unis-oa/backend/app/api/notify_channels.py

355 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""消息渠道接口 -- 渠道配置的增删改、测试发送、投递记录与重发。
和字典、数据源一个口径:**改配置要权限码 ``system:notify``,看渠道列表只要登录**;
但投递记录里带收件人邮箱,那一份要和改配置同样的权限才能看。
"测试发送"真发一条,但只发给点按钮的人自己(邮件发到他自己邮箱,机器人往群里发一条
明写「测试」的消息)——配渠道的人必须先在自己身上验过,而不是配完就等用户来报"没收到"。
"""
from __future__ import annotations
import re
from datetime import datetime
from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from .. import models, schemas
from ..db import get_db
from ..deps import CurrentUser, client_ip, current_user, require_permission
from ..envelope import bad_request, not_found, ok
from .. import dbconfig
from ..service import channels
router = APIRouter(tags=["notify"])
CODE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
LIST_LIMIT = 300
KIND_LABELS = {
models.NotifyChannel.KIND_EMAIL: "邮件(SMTP)",
models.NotifyChannel.KIND_DINGTALK: "钉钉群机器人",
models.NotifyChannel.KIND_FEISHU: "飞书群机器人",
models.NotifyChannel.KIND_WECOM: "企业微信群机器人",
models.NotifyChannel.KIND_WEBHOOK: "自定义 HTTP 回调",
}
def _stamp(value: datetime | None) -> str:
return value.strftime("%Y-%m-%d %H:%M:%S") if value else ""
def _view(db: Session, row: models.NotifyChannel) -> dict:
"""渠道视图:密钥换成"已设置",并带上"现在还缺什么"和近一天的投递成败。"""
since = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
counts = dict(db.execute(
select(models.NotifyDelivery.status, func.count(models.NotifyDelivery.id))
.where(models.NotifyDelivery.channel == row.code, models.NotifyDelivery.create_time >= since)
.group_by(models.NotifyDelivery.status)
).all())
return {
"id": row.id,
"code": row.code,
"name": row.name,
"kind": row.kind,
"kindLabel": KIND_LABELS.get(row.kind, row.kind),
"enabled": row.enabled,
"events": list(row.events or []),
"config": channels.scrub_config(row.config or {}),
"textTemplate": row.text_template,
"timeoutSeconds": row.timeout_seconds,
"retries": row.retries,
"remark": row.remark,
"creatorName": row.creator_name,
"updateTime": _stamp(getattr(row, "update_time", None)),
"lastSentAt": _stamp(row.last_sent_at),
"lastError": row.last_error,
"problems": channels.problems(row),
"today": {
"success": int(counts.get(models.NotifyDelivery.STATUS_SUCCESS, 0)),
"failed": int(counts.get(models.NotifyDelivery.STATUS_FAILED, 0)
+ counts.get(models.NotifyDelivery.STATUS_DEAD, 0)),
"skipped": int(counts.get(models.NotifyDelivery.STATUS_SKIPPED, 0)),
},
}
def get_channel(db: Session, code: str) -> models.NotifyChannel | None:
return db.execute(
select(models.NotifyChannel).where(models.NotifyChannel.code == str(code).strip())
).scalar_one_or_none()
def _clean(body: schemas.NotifyChannelBody, *, kind: str) -> dict:
values = {
"name": str(body.name or "").strip(),
"kind": str(body.kind or "").strip(),
"enabled": bool(body.enabled),
"events": [str(item) for item in (body.events or []) if str(item) in channels.EVENT_KEYS],
"text_template": str(body.text_template or "").strip()[:512],
"timeout_seconds": int(body.timeout_seconds or 10),
"retries": int(body.retries or 3),
"remark": str(body.remark or "").strip(),
}
if not values["name"]:
raise bad_request("要给这个渠道起个名字,投递记录里认得出是哪个")
if values["kind"] not in models.NotifyChannel.KINDS:
raise bad_request("渠道类型不支持:" + str(body.kind))
if not values["events"]:
raise bad_request("至少勾一种要推送的消息")
if not 1 <= values["timeout_seconds"] <= 120:
raise bad_request("超时秒数需要在 1-120 之间")
if not 0 <= values["retries"] <= 10:
raise bad_request("重试次数需要在 0-10 之间")
config = dict(body.config or {})
if kind == models.NotifyChannel.KIND_EMAIL:
host = str(config.get("host") or "").strip()
if not host:
raise bad_request("要填 SMTP 服务器地址")
mail_from = str(config.get("mail_from") or "").strip()
if mail_from and not channels.EMAIL_RE.match(mail_from):
raise bad_request("发件人邮箱格式不对")
for key in ("host", "mail_from", "username", "security"):
config[key] = str(config.get(key) or "").strip()
# 口令是这里唯一的密钥:留空 = 不提交这一项,让 merge_config 把已存的那把留着。
# 早先这里无条件写 config["password"] = "",界面上"不改口令"的保存
# 反而把库里那把清空了——渠道看着是配好的,从此每封信都登录失败。
password = str(config.get("password") or "").strip()
if password:
config["password"] = password
else:
config.pop("password", None)
config["port"] = int(config.get("port") or 465)
if config["security"] not in ("ssl", "starttls", "none"):
config["security"] = "ssl"
else:
url = str(config.get("url") or "").strip()
if not url:
raise bad_request("要填推送地址")
if not url.startswith(("http://", "https://")):
raise bad_request("推送地址要以 http:// 或 https:// 开头")
config["url"] = url
config["secret"] = str(config.get("secret") or "").strip() or None
config = {key: value for key, value in config.items() if value is not None}
return values | {"config": config}
def _log(db: Session, user: CurrentUser, action: str, target: str, detail: str, request: Request | None) -> None:
db.add(models.OperationLog(
action=action, target=target, detail=detail, person=user.person_id,
person_name=user.display_name, identity=user.ref,
ip=client_ip(request) if request else "",
))
@router.get("/notify/meta")
def notify_meta(_: CurrentUser = Depends(current_user)) -> dict:
"""界面上要摊开成勾选框的下拉清单:渠道类型、事件、模板占位符、SMTP 常用端口。"""
return ok({
"kinds": [{"value": key, "label": label} for key, label in KIND_LABELS.items()],
"events": [{"value": key, "label": label} for key, label in channels.EVENTS],
"textVars": [{"value": "{" + name + "}", "label": label} for name, label in (
("title", "消息标题"), ("body", "消息正文"), ("url", "单据链接"),
("person", "收件人姓名"), ("time", "发生时间"), ("type", "消息类型"),
)],
"smtpPresets": [
{"label": "SSL(常用 465)", "port": 465, "security": "ssl"},
{"label": "STARTTLS(常用 587)", "port": 587, "security": "starttls"},
{"label": "不加密(仅限内网中继)", "port": 25, "security": "none"},
],
})
@router.get("/notify/channels")
def list_channels(db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
rows = list(db.execute(
select(models.NotifyChannel).order_by(models.NotifyChannel.code)
).scalars().all())
return ok({
"items": [_view(db, row) for row in rows],
"enabled": any(row.enabled for row in rows),
"masterSwitch": bool(dbconfig.value("notify_channels_enabled", True)),
})
@router.post("/notify/channels")
def create_channel(
body: schemas.NotifyChannelBody,
request: Request = None,
db: Session = Depends(get_db),
user: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
code = str(body.code or "").strip()
if not CODE_RE.match(code):
raise bad_request("渠道编码只允许字母、数字、下划线和短横线(1-64 位)")
if get_channel(db, code) is not None:
raise bad_request(f"渠道编码 {code} 已经存在")
values = _clean(body, kind=str(body.kind or ""))
row = models.NotifyChannel(code=code, creator=user.person_id, creator_name=user.display_name)
for key, value in values.items():
setattr(row, key, value)
db.add(row)
_log(db, user, "notify_channel_create", code, f"新增消息渠道:{row.name}", request)
db.commit()
db.refresh(row)
return ok(_view(db, row))
@router.put("/notify/channels/{code}")
def update_channel(
code: str,
body: schemas.NotifyChannelBody,
request: Request = None,
db: Session = Depends(get_db),
user: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
row = get_channel(db, code)
if row is None:
raise not_found("渠道不存在")
values = _clean(body, kind=str(body.kind or row.kind))
# 密钥字段留空 = 不改:界面上永远看不到明文,也就不可能"看一眼再原样提交"
incoming = dict(body.config or {})
merged = channels.merge_config(row.config or {}, incoming)
merged.update(values.pop("config"))
values["config"] = merged
for key, value in values.items():
setattr(row, key, value)
_log(db, user, "notify_channel_update", code, f"修改消息渠道:{row.name}", request)
db.commit()
db.refresh(row)
return ok(_view(db, row))
@router.delete("/notify/channels/{code}")
def delete_channel(
code: str,
request: Request = None,
db: Session = Depends(get_db),
user: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
row = get_channel(db, code)
if row is None:
raise not_found("渠道不存在")
db.delete(row)
_log(db, user, "notify_channel_delete", code, f"删除消息渠道:{row.name}", request)
db.commit()
return ok({"code": code})
@router.post("/notify/channels/{code}/test")
def test_channel(
code: str,
db: Session = Depends(get_db),
user: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
"""当场发一条测试消息给点按钮的人。失败原因原样带回界面,不让人去翻服务日志。"""
row = get_channel(db, code)
if row is None:
raise not_found("渠道不存在")
problems = channels.problems(row)
if problems:
raise bad_request("还缺:" + ";".join(problems))
delivery = models.NotifyDelivery(
channel=row.code, kind=row.kind, type=list(row.events or ["task"])[0],
identity=user.ref, person=user.person_id, person_name=user.display_name,
target=(channels.email_of(row, user.person)
if row.kind in models.NotifyChannel.SMTP_KINDS else str((row.config or {}).get("url") or "")),
title="[测试] 这是一条来自 OA 的测试消息",
body="看到这条说明渠道配置是对的。测试期间如果没收到,先确认这个人有没有邮箱。",
)
if not delivery.target:
raise bad_request("你的账号上没有邮箱,先到自己资料里补一个再测")
db.add(delivery)
db.commit()
result = channels.deliver(db, delivery, channel=row)
if result.status == models.NotifyDelivery.STATUS_SUCCESS:
return ok({"status": result.status, "detail": result.response, "delivery": _delivery_view(result)})
raise bad_request(f"没发出去:{result.last_error}", reason="NOTIFY_TEST_FAILED")
@router.get("/notify/deliveries")
def list_deliveries(
channel: str = Query(""),
status_filter: str = Query("", alias="status"),
type_filter: str = Query("", alias="type"),
keyword: str = Query(""),
limit: int = Query(80, ge=1, le=LIST_LIMIT),
db: Session = Depends(get_db),
_: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
stmt = select(models.NotifyDelivery).order_by(models.NotifyDelivery.id.desc()).limit(limit)
if channel:
stmt = stmt.where(models.NotifyDelivery.channel == channel)
if status_filter:
stmt = stmt.where(models.NotifyDelivery.status == status_filter)
if type_filter:
stmt = stmt.where(models.NotifyDelivery.type == type_filter)
if keyword:
like = f"%{keyword}%"
stmt = stmt.where(models.NotifyDelivery.title.like(like) | models.NotifyDelivery.person_name.like(like))
rows = list(db.execute(stmt).scalars().all())
counts = dict(db.execute(
select(models.NotifyDelivery.status, func.count(models.NotifyDelivery.id)).group_by(models.NotifyDelivery.status)
).all())
return ok({
"items": [_delivery_view(row) for row in rows],
"counts": {key: int(counts.get(key, 0)) for key in models.NotifyDelivery.STATUSES},
"events": [{"value": key, "label": label} for key, label in channels.EVENTS],
})
def _delivery_view(row: models.NotifyDelivery) -> dict:
return {
"id": row.id,
"channel": row.channel,
"kind": row.kind,
"type": row.type,
"typeLabel": channels.EVENT_LABELS.get(row.type, row.type),
"person": row.person,
"personName": row.person_name,
# 机器人地址里有 access_token,记录里只回打码后的地址
"target": channels.mask_target(row.target) if "://" in (row.target or "") else row.target,
"title": row.title,
"body": row.body,
"job": row.job,
"work": row.work,
"status": row.status,
"attempts": row.attempts,
"nextAttemptAt": _stamp(row.next_attempt_at),
"sentAt": _stamp(row.sent_at),
"createTime": _stamp(getattr(row, "create_time", None)),
"lastError": row.last_error,
"response": dict(row.response or {}),
"ms": row.ms,
}
@router.post("/notify/deliveries/{delivery_id}/resend")
def resend_delivery(
delivery_id: str,
db: Session = Depends(get_db),
_: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
row = channels.resend(db, delivery_id)
if row is None:
raise not_found("投递记录不存在")
return ok(_delivery_view(row))
@router.post("/notify/deliveries/{delivery_id}/send-now")
def send_delivery_now(
delivery_id: str,
db: Session = Depends(get_db),
_: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
"""不等下一轮调度,立刻发这一条(配完渠道想马上看到效果时用)。"""
row = db.get(models.NotifyDelivery, delivery_id)
if row is None:
raise not_found("投递记录不存在")
if row.status == models.NotifyDelivery.STATUS_SUCCESS:
raise bad_request("这条已经发成功了,再发一遍收件人会收到两封")
result = channels.deliver(db, row)
return ok(_delivery_view(result))