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

507 lines
24 KiB
Python
Raw Permalink 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 hubconfig, models, schemas, serializers
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 ..query import count_of
from ..service import channels
from ..service import hub as hub_api
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 回调",
models.NotifyChannel.KIND_HUB_WECOM: "企业微信(经统一身份 Hub 推送)",
}
#: Hub 这一路的两种消息形态,界面上是个分段选择
HUB_MSGTYPE_LABELS = {
channels.HUB_MSGTYPE_CARD: "卡片(可点开直达待办)",
channels.HUB_MSGTYPE_MARKDOWN: "纯文本提醒(不带链接)",
}
#: 测试发送没有真实单据可指,深链指到待办列表:点开那一跳(Hub 认人 + redirect)
#: 才能一起验掉,否则只验到"消息发出去了"这一半
HUB_TEST_PATH = "/todo"
def receiver_labels(pref: list[str] | tuple[str, ...]) -> str:
"""把收件人标识的顺序翻成一句人话:``Hub 用户 ID → 登录账号``。"""
return " → ".join(channels.HUB_RECEIVER_LABELS.get(field, field) for field in pref)
def hub_no_receiver_hint(pref: tuple[str, ...]) -> str:
"""测试发送时点按钮的人自己取不到收件标识:这话要对着"你的账号"说。"""
named = "、".join(channels.HUB_RECEIVER_LABELS.get(field, field) for field in pref)
return (f"你的账号在统一身份里对不上号:按这个渠道配的收件人标识({named})取不到值,"
"这一路发不到你手机上。要么给自己补上,要么把渠道的收件人标识换成另一种。")
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())
is_hub = row.kind in models.NotifyChannel.HUB_KINDS
receiver_pref = channels.hub_receiver_pref(row.config or {})
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 {}),
# 这一路按哪一列认人(只有 Hub 渠道有意义):收件人标识现在是渠道上可配的一项,
# 列表里就得说清当前用的是哪种、按什么顺序退回,不然出问题时连"该看哪一列"都对不上
"receiverPref": list(receiver_pref) if is_hub else [],
"receiverLabel": receiver_labels(receiver_pref) if is_hub else "",
"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"
elif kind == models.NotifyChannel.KIND_HUB_WECOM:
# 这一路没有地址也没有密钥要填:站点和应用密钥都跟着「系统设置 → 统一身份」
msgtype = str(config.get("msgtype") or channels.HUB_MSGTYPE_CARD).strip().lower()
if msgtype not in channels.HUB_MSGTYPES:
raise bad_request("消息形态只认 textcard(卡片)或 markdown(纯文本提醒)")
config["msgtype"] = msgtype
config["with_link"] = bool(config.get("with_link", True))
try:
title_limit = int(config.get("title_limit") or channels.HUB_TITLE_DEFAULT)
except (TypeError, ValueError):
raise bad_request("标题字数上限要填个数字")
if not channels.HUB_TITLE_FLOOR <= title_limit <= 120:
raise bad_request(f"标题字数上限需要在 {channels.HUB_TITLE_FLOOR}-120 之间")
config["title_limit"] = title_limit
# 收件人标识:Hub 只认那两种(``user_id`` / ``account``),顺序就是认人的优先级。
# 存成规范化后的列表,界面上提交 ""/"account"/["account","user_id"] 都收,
# 但库里只留一种写法,免得同一个配置有三种长相。
receiver = channels.parse_hub_receiver_pref(config.get("receiver"))
if receiver is None:
raise bad_request("收件人标识只认 "
+ " / ".join(f"{key}({channels.HUB_RECEIVER_LABELS[key]})"
for key in channels.HUB_RECEIVER_VALUES))
config["receiver"] = list(receiver)
# 密钥不在渠道上,但别的渠道传来的 url/secret 也不该跟着种类切换还留在库里
config = {key: value for key, value in config.items()
if key in ("msgtype", "with_link", "title_limit", "receiver")}
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}
# 只收这一档种类认得的键:界面上多传的东西(密钥回显的 xxxSet 之类)不进库
owned = channels.owned_config_keys(kind)
config = {key: value for key, value in config.items() if not owned or key in owned}
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 常用端口。"""
hub = hubconfig.get()
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],
# Hub 代发这一路的"底"配在哪、还缺什么:配渠道的人最常撞的是密钥没领、
# 以及 Hub 侧那两道推送开关没开,先在界面上看得见,别等投递记录里报错
"hub": {
"ready": hub.notify_on,
"missing": hub.notify_missing,
"baseUrl": hub.hub_base_url,
"appCode": hub.hub_app_code,
"keySet": bool(hub.hub_integration_key.strip()),
"pushPath": hub.hub_path_notify_wecom,
"forcedOff": hub.forced_off,
"timeoutSeconds": hub.hub_timeout_seconds,
},
"hubMsgtypes": [{"value": key, "label": label} for key, label in HUB_MSGTYPE_LABELS.items()],
# 收件人标识:Hub 只认这几种(渠道 config.receiver 的取值),界面照这张表摊开成
# 优先级选项;``hubReceiverPresets`` 是常用的几种组合,每一档都带一句"什么时候用它"
"hubReceivers": [{"value": key, "label": label, "column": column}
for key, label, column in channels.HUB_RECEIVER_FIELDS
if key in channels.HUB_RECEIVER_VALUES],
"hubReceiverPresets": [{"value": list(pref), "label": label, "hint": hint}
for pref, label, hint in channels.HUB_RECEIVER_PRESETS],
"hubReceiverDefault": list(channels.HUB_RECEIVER_DEFAULT),
"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())
hub_rows = [row for row in rows if row.kind in models.NotifyChannel.HUB_KINDS]
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)),
# 换收件人标识之前得先看见代价:每一种各能覆盖多少在职账号、怎么配都发不到的是几个。
# 只在真有 Hub 渠道时问这一条聚合,邮件/机器人那一档用不上
"hubCoverage": channels.hub_receiver_coverage(db) if hub_rows else None,
})
@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("渠道不存在")
kind = str(body.kind or row.kind)
values = _clean(body, kind=kind)
# 密钥字段留空 = 不改:界面上永远看不到明文,也就不可能"看一眼再原样提交"
incoming = dict(body.config or {})
merged = channels.merge_config(row.config or {}, incoming)
merged.update(values.pop("config"))
# 种类换过一档,库里那一档留下的参数就得清掉,不然旧的推送地址会一直躺在
# 新渠道的配置里,看着像它还生效
owned = channels.owned_config_keys(kind)
values["config"] = {key: value for key, value in merged.items()
if not owned or key in owned}
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))
hub_kind = row.kind in models.NotifyChannel.HUB_KINDS
if row.kind in models.NotifyChannel.SMTP_KINDS:
target = channels.email_of(row, user.person)
elif hub_kind:
receiver_pref = channels.hub_receiver_pref(row.config)
receiver, target = channels.hub_receiver(user.person, receiver_pref)
else:
target = str((row.config or {}).get("url") or "")
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=target,
target_field=channels.hub_receiver_field(receiver) if hub_kind else "",
title="[测试] 这是一条来自 OA 的测试消息",
body="看到这条说明渠道配置是对的。测试期间如果没收到,先确认这个人有没有邮箱。"
if not hub_kind else "收到这条说明 OA → Hub → 企业微信这一段是通的。"
"点开应该落到本系统的待办列表;落在首页说明 Hub 上没登记首页地址(home_url)。",
)
if not delivery.target:
raise bad_request(
hub_no_receiver_hint(receiver_pref) if hub_kind
else "你的账号上没有邮箱,先到自己资料里补一个再测"
)
db.add(delivery)
db.commit()
result = channels.deliver(db, delivery, channel=row, hub_link=HUB_TEST_PATH if hub_kind else "")
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(""),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=LIST_LIMIT),
db: Session = Depends(get_db),
_: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
"""投递记录:按页翻,不再只给"最近 80 条"那一刀。
跳过和失败的都是几百上千行堆在这儿,只截最近 80 条等于把"上周那批为什么没发出去"
直接翻不到,所以这里和待办、操作日志一个口径:``page`` / ``page_size`` 分页,
回 ``total`` / ``pages`` 给分页器。
``counts`` 跟着渠道 / 消息类型 / 关键词走,但不跟着状态走——状态就是那排徽标本身,
跟着走会让当前选中的那一档永远等于"全部"。``''`` 那一项是这些筛选下的总数,
界面上「全部」那一格读它(以前它压根没值,永远显示 0)。
"""
filters = []
if channel:
filters.append(models.NotifyDelivery.channel == channel)
if type_filter:
filters.append(models.NotifyDelivery.type == type_filter)
if keyword:
like = f"%{keyword}%"
filters.append(models.NotifyDelivery.title.like(like) | models.NotifyDelivery.person_name.like(like))
stmt = select(models.NotifyDelivery).where(*filters)
if status_filter:
stmt = stmt.where(models.NotifyDelivery.status == status_filter)
total = count_of(db, stmt)
rows = list(db.execute(
stmt.order_by(models.NotifyDelivery.id.desc()).offset((page - 1) * page_size).limit(page_size)
).scalars().all())
counts = dict(db.execute(
select(models.NotifyDelivery.status, func.count(models.NotifyDelivery.id))
.where(*filters)
.group_by(models.NotifyDelivery.status)
).all())
payload = serializers.page([_delivery_view(row) for row in rows], total, page, page_size)
payload["counts"] = {key: int(counts.get(key, 0)) for key in models.NotifyDelivery.STATUSES}
payload["counts"][""] = sum(payload["counts"].values())
payload["events"] = [{"value": key, "label": label} for key, label in channels.EVENTS]
return ok(payload)
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,
# 走 Hub 的那一路要看得清"这串是 Hub 主键还是登录账号"——10086 与 zhangsan
# 在收件人排查上是两回事:前者跟着同步走,后者会被企微字段改写
"targetField": row.target_field,
"targetFieldLabel": channels.HUB_RECEIVER_LABELS.get(row.target_field, ""),
"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}/recheck")
def recheck_delivery(
delivery_id: str,
db: Session = Depends(get_db),
_: CurrentUser = Depends(require_permission("system:notify")),
) -> dict:
"""问 Hub 回查这一条的逐人投递结果(文档 9.6.7),按对方口径改写本地状态。
只读、可反复点:回查不改 Hub 上任何东西,也就不存在"多点一次多发一条"。
超时之后不确定到底投没投出去、或者想看看某个人的失败原因变了没有,用它。
"""
row = db.get(models.NotifyDelivery, delivery_id)
if row is None:
raise not_found("投递记录不存在")
try:
detail = channels.hub_recheck(db, row)
except ValueError as exc:
raise bad_request(str(exc))
except hub_api.HubError as exc:
# 404 = 这条记录已经出了 Hub 的保留期(或压根没投出去过),话要说成这样
raise bad_request(f"问不到 Hub 的投递明细:{exc.message}")
db.commit()
db.refresh(row)
return ok(_delivery_view(row) | {"detail": detail})
@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))