1469 lines
72 KiB
Python
1469 lines
72 KiB
Python
"""消息渠道 -- 站内信之外,把同一条消息送到邮箱与群机器人。
|
||
|
||
**为什么挂在 ``engine.notify()`` 上而不是各处加发送代码**:站内信、邮件、机器人提醒
|
||
说的是同一句话("您有一张单要处理")。写通知的唯一入口是 ``notify()``,渠道投递就
|
||
在同一个位置扇出;以后再加短信、企业微信工作通知,业务代码一行都不用改。
|
||
|
||
**为什么先入队再发送**:SMTP 和机器人网关都会抖,而"消息丢了"这件事必须看得见。
|
||
入队与站内信同一事务(业务定了消息就一定在),投递交给后台调度线程,失败按退避重试,
|
||
重试用满进死信——和写回发件箱是同一套底线(``docs/notification-channels-design.md``)。
|
||
|
||
``hub_wecom`` 是这一套里唯一的"转发型"渠道:消息不出到 SMTP,而是交给统一身份 Hub
|
||
代发企业微信应用消息(对接文档 9.6)。本系统不持有企微密钥、不碰 ``access_token``,
|
||
收件人按 Hub 账号解析,点开那张卡片回到的是**已经跑通的**免登回调,只是多带一个
|
||
``redirect``。所以这一路的配置比 SMTP 还薄——连地址都没有,只有"发什么形态的消息"。
|
||
|
||
配置尽量薄:一个渠道只有"发到哪 + 发什么事 + 用什么身份发"三格。收件人不做配置项,
|
||
**站内信发给谁这一路就发给谁**,邮箱从账号上取;账号没邮箱就在投递记录里留一条
|
||
``skipped`` 并写明原因,不静默丢。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import hmac
|
||
import json
|
||
import logging
|
||
import re
|
||
import smtplib
|
||
import time
|
||
import urllib.parse
|
||
import urllib.request
|
||
from datetime import datetime, timedelta
|
||
from email.message import EmailMessage
|
||
from typing import Any, Iterable
|
||
|
||
from sqlalchemy import case, func, or_, select, update
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import hubconfig, models, presence, readcache
|
||
from . import fetch, hub as hub_api, org, signing
|
||
from . import wake as wake_signal
|
||
|
||
logger = logging.getLogger("unisoa.channels")
|
||
|
||
#: 可订阅的通知事件:取值与 ``oa_notification.type`` 完全一致,界面上就是几个勾选框
|
||
EVENTS: tuple[tuple[str, str], ...] = (
|
||
("task", "新的待办"),
|
||
("press", "催办提醒"),
|
||
("read", "抄送 / 分享 / 评论"),
|
||
("completed", "办结结果"),
|
||
("expire", "待办超时"),
|
||
("meeting", "会议提醒"),
|
||
# 管理员干预改道:站内那条留痕叫 control,外发这一路单独一个事件名。分成两个是因为
|
||
# 挂起 / 恢复 / 改数据这类动作不值得往邮箱和群里刷,而改道**收走了别人手里的待办**——
|
||
# 那张卡片已经推出去了、又收不回来,管理员想对外说一句时得能只勾这一档。
|
||
# 存量渠道的 events 里没这个值,所以默认一句都不往外推。
|
||
("rerouted", "流程被干预改道"),
|
||
)
|
||
EVENT_LABELS = dict(EVENTS)
|
||
#: 界面上"全选"用的清单
|
||
EVENT_KEYS = tuple(key for key, _ in EVENTS)
|
||
|
||
BACKOFF_SECONDS = (60, 300, 1800)
|
||
BATCH_LIMIT = 40
|
||
#: 一轮最多发多久。刚入队那一条已被叫醒机制当场送到这一轮,可它排在谁的后面没有准:
|
||
#: 一个慢 SMTP 网关能把 40 条各顶满超时(渠道默认 10 秒),新消息就得陪着等完。
|
||
#: 到点收工,剩下没认领的行状态一动没动,下一轮(或被新消息叫醒的那一轮)照样取得到。
|
||
ROUND_BUDGET_SECONDS = 20.0
|
||
#: 正文进邮件/机器人时截这么长:机器人有长度墙,而且消息不该变成第二份表单
|
||
BODY_LIMIT = 1000
|
||
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||
#: 密钥类配置键:接口回显时只说"已设置",不回明文
|
||
SECRET_KEYS = ("password", "secret", "token")
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Hub 企业微信推送(对接文档 9.6)的预算与语义
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 两种消息形态:卡片(可点,跳转场景)与纯 markdown 提醒
|
||
HUB_MSGTYPES = ("textcard", "markdown")
|
||
HUB_MSGTYPE_CARD = "textcard"
|
||
HUB_MSGTYPE_MARKDOWN = "markdown"
|
||
#: Hub 在标题前强制加 ``【应用名称】``,两边合计 ≤128 字符。本系统不知道自己
|
||
#: 在 Hub 上叫什么(那是 Hub 侧登记的),所以默认只敢用一半,剩下留给应用名。
|
||
HUB_TITLE_DEFAULT = 64
|
||
HUB_TITLE_FLOOR = 8
|
||
#: ``description`` 上限(文档 9.6.2)
|
||
HUB_DESC_BYTES = 512
|
||
#: ``markdown`` 正文上限,单位是**字节**,且含 Hub 追加的 ``[查看详情](链接)`` 那一行
|
||
HUB_CONTENT_BYTES = 2048
|
||
#: 带深链时先给 Hub 那句追加留出的字节数:链接本身约 60~70 字节,留到 192 是
|
||
#: 给长域名与 ``auth/go/<24 位>`` 之外的写法兜底——超了是 Hub 直接 400,整批没人收到
|
||
HUB_LINK_RESERVE_BYTES = 192
|
||
#: 一次调用 200 人是 Hub 的上限;本系统一条投递记录只有一个人,用不到切批
|
||
HUB_RECEIVER_MAX = 200
|
||
#: 这几类消息点开是要**办事**的,深链落待办页(有同意/退回那一套),
|
||
#: 而不是只能看的单据页;办结与抄送落单据页,会议提醒压根没单据
|
||
HUB_TASK_EVENTS = ("task", "press", "expire")
|
||
#: 退成"不带链接的纯提醒"的两种来路,会记进 ``response.hub.degraded`` 给界面念:
|
||
#: 没有单据可指(会议提醒那类)/ Hub 上没登记本系统首页地址,深链拼不出来
|
||
HUB_DEGRADED_NO_LINK = "no_link"
|
||
HUB_DEGRADED_NO_HOME = "hub_no_home"
|
||
#: Hub 用 Go 写时间,没赋值时回的是零值 ``0001-01-01T00:00:00Z`` 而不是缺字段
|
||
HUB_ZERO_TIME = "0001-01-01"
|
||
|
||
#: 逐人失败原因 -> 本系统怎么办。三档:稍后同键重发(retry)/ 不算故障,等人补
|
||
#: 东西(skip)/ 再试也不会成,直接进死信喊人(dead)。表外的原因按 retry 处理,
|
||
#: 宁可多试三轮也别把一条本该送到的消息悄悄判死。
|
||
HUB_RETRY_REASONS = frozenset({"rate_limited", "api_error", "sending"})
|
||
HUB_SKIP_REASONS = frozenset({
|
||
"user_not_found", "user_disabled", "wecom_not_bound", "wecom_rejected", "unlicensed",
|
||
})
|
||
HUB_DEAD_REASONS = frozenset({"invalid_message", "quota_exceeded", "daily_limit_exceeded"})
|
||
|
||
#: 逐人原因翻成人话。这一列会直接进投递记录的 ``last_error``,运维不用翻文档
|
||
HUB_REASON_LABELS = {
|
||
"user_not_found": "统一身份里没有这个账号,等下一轮组织人员同步或核对账号",
|
||
"user_disabled": "这个账号在统一身份里已停用",
|
||
"wecom_not_bound": "这个账号还没绑定企业微信成员,请在企业微信里补上「Hub账号」等资料后重发",
|
||
"wecom_rejected": "企业微信判定成员无效,通常是这个人不在应用的可见范围",
|
||
"unlicensed": "这个成员缺企业微信基础接口许可,请联系企微管理员购买",
|
||
"rate_limited": "同一个成员收消息太频繁,稍后自动重发",
|
||
"quota_exceeded": "本应用当日的推送人次数配额已用尽,明天再重发或请 Hub 调高配额",
|
||
"daily_limit_exceeded": "这个人今天收到的推送已达上限(跨所有来源应用),明天再重发",
|
||
"invalid_message": "消息组装失败(通常是链接或正文太长),改短之后再发",
|
||
"api_error": "企业微信接口报错,按 Hub 返回的错误码排查(最常见是可信 IP 未放行)",
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 收件人标识:Hub 认哪几种、渠道上怎么选
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 对接文档 9.6.2 的 ``receivers`` 一项只认两种标识,多写一种会被 Hub 按参数不合法整条拒掉:
|
||
#:
|
||
#: * ``user_id`` —— Hub 的人员主键(本地 ``users.hub_user_id``)。账号能被别人注册走、
|
||
#: 姓名会改、登录名也会在 Hub 侧改,只有它从头到尾指向同一个人,所以默认押它。
|
||
#: * ``account`` —— 登录账号(本地 ``users.account``)。区分大小写的精确匹配,2026-10-20 起
|
||
#: 还会随企业微信「Hub账号」扩展属性被同步改写(9.5),押它迟早对不上;但主键没同步过来的
|
||
#: 环境(老库、手工建的本地账号)只有这一条路可走。
|
||
#:
|
||
#: 每一项是 ``(标识名, 界面上的叫法, 本地列)``。**要加一种标识只需在这里加一行**,
|
||
#: 渠道配置、入队、发送、回查、界面清单都跟着认它(取法见 :data:`HUB_RECEIVER_VALUES`)。
|
||
HUB_RECEIVER_FIELDS: tuple[tuple[str, str, str], ...] = (
|
||
("user_id", "Hub 用户 ID", "users.hub_user_id"),
|
||
("account", "登录账号", "users.account"),
|
||
)
|
||
HUB_RECEIVER_LABELS: dict[str, str] = {key: label for key, label, _column in HUB_RECEIVER_FIELDS}
|
||
HUB_RECEIVER_COLUMNS: dict[str, str] = {key: column for key, _label, column in HUB_RECEIVER_FIELDS}
|
||
#: 没配过这一项的渠道照这个顺序认人:主键优先、退回账号。存量渠道一字不差地沿用。
|
||
HUB_RECEIVER_DEFAULT: tuple[str, ...] = ("user_id", "account")
|
||
|
||
#: 界面上摊开成几档。顺序就是优先级;只有一项时**不退回**另一种——那是管理员明确说过
|
||
#: "只按这一列发",宁可跳过这个人,也别悄悄换成另一列把消息送到别人手机上。
|
||
HUB_RECEIVER_PRESETS: tuple[tuple[tuple[str, ...], str, str], ...] = (
|
||
(("user_id", "account"), "Hub 用户 ID 优先",
|
||
"先按 Hub 主键认人,主键没同步过来才退回登录账号,让 Hub 自己判一次 user_not_found。改名不丢消息。"),
|
||
(("account", "user_id"), "登录账号优先",
|
||
"主键不可信(比如同步回来的 id 与目录对不上)时按账号认,账号取不到再退主键。"),
|
||
(("user_id",), "只认 Hub 用户 ID",
|
||
"最严格:主键为空的人(本地自建号、还没同步的)直接跳过,绝不按账号猜。"),
|
||
(("account",), "只认登录账号",
|
||
"账号区分大小写、还会被企微「Hub账号」字段改写,一改账号这个人就收不到,直到主键补上。"),
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 配置校验与视图辅助
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def problems(row: models.NotifyChannel) -> list[str]:
|
||
"""渠道配置缺了什么。保存时不拦(配置到一半很常见),但界面上要一直挂着这句话。"""
|
||
out: list[str] = []
|
||
config = dict(row.config or {})
|
||
kind = row.kind
|
||
if kind in models.NotifyChannel.SMTP_KINDS:
|
||
if not str(config.get("host") or "").strip():
|
||
out.append("没填 SMTP 服务器地址")
|
||
if not str(config.get("mail_from") or "").strip():
|
||
out.append("没填发件人邮箱")
|
||
if not str(config.get("username") or "").strip():
|
||
out.append("没填 SMTP 登录账号")
|
||
if kind in models.NotifyChannel.URL_KINDS:
|
||
url = str(config.get("url") or "").strip()
|
||
if not url:
|
||
out.append("没填推送地址")
|
||
elif not url.startswith(("http://", "https://")):
|
||
out.append("推送地址要以 http:// 或 https:// 开头")
|
||
if kind == models.NotifyChannel.KIND_DINGTALK and not str(config.get("secret") or "").strip():
|
||
out.append("钉钉机器人建议填加签密钥(安全设置选「加签」),否则只能靠 IP 白名单")
|
||
if kind in models.NotifyChannel.HUB_KINDS:
|
||
cfg = hubconfig.get()
|
||
if not cfg.notify_on:
|
||
out.append("统一身份这边还发不出企业微信,缺:" + "、".join(cfg.notify_missing))
|
||
if str(config.get("msgtype") or "").strip().lower() not in ("", *HUB_MSGTYPES):
|
||
out.append(f"消息形态只认 {' / '.join(HUB_MSGTYPES)},现在填的是 {config.get('msgtype')}")
|
||
# 收件人标识写错一个字母,后果是"这个人静默收不到"而界面上一切正常;
|
||
# 认不出的值当场挂在这条渠道上,比让它长成一条 skipped 投递记录好查得多
|
||
if parse_hub_receiver_pref(config.get("receiver")) is None:
|
||
out.append("收件人标识只认 " + " / ".join(HUB_RECEIVER_LABELS.values())
|
||
+ f",现在填的是 {config.get('receiver')}")
|
||
# 点开那张卡片的那一趟不带 state(对接文档 9.6.5:推送链路签发的票据没有 state)。
|
||
# 「免登必须校验 state」开成强制档时会当场拒掉,而点卡片的人只会看到一句「免登
|
||
# 校验未通过」,不会回来说原因——这话得挂在这一页上。关掉深链的渠道不受影响。
|
||
if getattr(cfg, "hub_sso_state_required", False) and hub_wants_link(row):
|
||
out.append("「免登必须校验 state」开着:卡片点开那一路不带 state,会被拒在门外;"
|
||
"要么关掉这一项,要么确认 Hub 门户真会把 state 原样带回")
|
||
if not list(row.events or []):
|
||
out.append("还没勾选要推送哪些消息")
|
||
if str(row.text_template or "").strip():
|
||
bad = [t for t in re.findall(r"\{([^{}]*)\}", row.text_template) if t not in TEXT_VARS]
|
||
if bad:
|
||
out.append(f"正文模板里有不认识的占位符:{'、'.join(sorted(set(bad)))}")
|
||
return out
|
||
|
||
|
||
#: 正文模板能用的占位符
|
||
TEXT_VARS = ("title", "body", "url", "person", "time", "type")
|
||
|
||
|
||
#: 每一档种类**真正拥有**的配置键。换种类时靠它把上一档的参数筛掉:
|
||
#: 钉钉渠道改成 Hub 渠道之后,库里再拖着一个没人读的 url 只会让人以为还在发钉钉。
|
||
#: 也是渠道保存时唯一认收的键——界面上多传的东西(比如把回显的 xxxSet 又提交回来)
|
||
#: 不会跟着进库。
|
||
CONFIG_KEYS: dict[str, tuple[str, ...]] = {
|
||
models.NotifyChannel.KIND_EMAIL: ("host", "port", "security", "mail_from", "username", "password"),
|
||
models.NotifyChannel.KIND_DINGTALK: ("url", "secret"),
|
||
models.NotifyChannel.KIND_FEISHU: ("url", "secret"),
|
||
models.NotifyChannel.KIND_WECOM: ("url", "secret"),
|
||
models.NotifyChannel.KIND_WEBHOOK: ("url", "secret"),
|
||
models.NotifyChannel.KIND_HUB_WECOM: ("msgtype", "with_link", "title_limit", "receiver"),
|
||
}
|
||
|
||
|
||
def owned_config_keys(kind: str) -> tuple[str, ...]:
|
||
"""这一档种类认收的配置键;认不出的种类回空元组(一个键都不留)。"""
|
||
return CONFIG_KEYS.get(str(kind or "").strip(), ())
|
||
|
||
|
||
def scrub_config(config: dict) -> dict:
|
||
"""回显给界面的渠道参数:密钥换成"是否已设置",绝不出明文。"""
|
||
out = dict(config or {})
|
||
for key in SECRET_KEYS:
|
||
if key in out:
|
||
out[f"{key}Set"] = bool(str(out.get(key) or "").strip())
|
||
out.pop(key, None)
|
||
return out
|
||
|
||
|
||
def merge_config(old: dict, incoming: dict) -> dict:
|
||
"""保存时把界面上"留空表示不改"的密钥保留下来。"""
|
||
merged = dict(old or {})
|
||
for key, value in dict(incoming or {}).items():
|
||
if key in SECRET_KEYS and str(value or "").strip() == "":
|
||
continue
|
||
merged[key] = value
|
||
return merged
|
||
|
||
|
||
def mask_target(value: str) -> str:
|
||
"""机器人地址里有 access_token / key,列表里一律打码,只留能认出是哪一个的部分。"""
|
||
url = str(value or "")
|
||
if "://" not in url:
|
||
return url
|
||
parts = urllib.parse.urlsplit(url)
|
||
query = {k: ("***" if any(t in k.lower() for t in ("token", "key", "signature", "sig")) else v)
|
||
for k, v in urllib.parse.parse_qsl(parts.query)}
|
||
return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path,
|
||
urllib.parse.urlencode(query), ""))
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 入队
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def has_enabled_channel(db: Session) -> bool:
|
||
"""库里还有没有启用的通知渠道(:mod:`app.presence` 的那一个探针)。"""
|
||
return db.execute(
|
||
select(models.NotifyChannel.id).where(models.NotifyChannel.enabled.is_(True)).limit(1)
|
||
).first() is not None
|
||
|
||
|
||
def enabled_channels(db: Session) -> list[models.NotifyChannel]:
|
||
"""当前启用的通知渠道;一次流转要发待办、阅件、办结好几种通知,问一次就够。
|
||
|
||
一个渠道都没配时连库都不问(口径与作废规则见 :mod:`app.presence`);配上一个之后
|
||
写库那一趟就把结论作废了,下一趟通知照旧问库。
|
||
"""
|
||
if not presence.any_row(db, "oa_notify_channel", has_enabled_channel):
|
||
return []
|
||
return readcache.get(db, ("oa_notify_channel",), ("channels.enabled_channels",),
|
||
lambda: list_enabled_channels(db))
|
||
|
||
|
||
def list_enabled_channels(db: Session) -> list[models.NotifyChannel]:
|
||
"""真正问库的那一步。"""
|
||
return list(db.execute(
|
||
select(models.NotifyChannel).where(models.NotifyChannel.enabled.is_(True))
|
||
.order_by(models.NotifyChannel.code)
|
||
).scalars().all())
|
||
|
||
|
||
def channels_for(db: Session, event: str) -> list[models.NotifyChannel]:
|
||
rows = enabled_channels(db)
|
||
return [row for row in rows if event in list(row.events or [])]
|
||
|
||
|
||
def render_text(channel: models.NotifyChannel, delivery: models.NotifyDelivery, *, link: str) -> str:
|
||
template = str(channel.text_template or "").strip()
|
||
values = {
|
||
"title": delivery.title,
|
||
"body": (delivery.body or "")[:BODY_LIMIT],
|
||
"url": link,
|
||
"person": delivery.person_name or delivery.person,
|
||
"time": (delivery.create_time or datetime.now()).strftime("%Y-%m-%d %H:%M"),
|
||
"type": EVENT_LABELS.get(delivery.type, delivery.type),
|
||
}
|
||
if template:
|
||
text = template
|
||
for key, value in values.items():
|
||
text = text.replace("{" + key + "}", str(value))
|
||
return text.strip()
|
||
return "\n".join(part for part in (f"{delivery.title}", delivery.body[:BODY_LIMIT], link) if part)
|
||
|
||
|
||
def enqueue_for(
|
||
db: Session,
|
||
identities: list[str],
|
||
*,
|
||
event: str,
|
||
title: str,
|
||
body: str = "",
|
||
job: str = "",
|
||
work: str = "",
|
||
task: str = "",
|
||
process: str = "",
|
||
notification: str = "",
|
||
) -> int:
|
||
"""给这批收件人按订阅关系排上投递任务。**与站内信同一事务**,别在这里 commit。
|
||
|
||
渠道全关着时一个查询都不发(``channels_for`` 是唯一一次全表读,渠道数量是个位数),
|
||
所以打开这些功能不会给办结、提交这类热路径增加负担。
|
||
"""
|
||
wanted = [row for row in channels_for(db, event) if row.enabled]
|
||
if not wanted:
|
||
return 0
|
||
people = []
|
||
for identity in [str(item) for item in identities if item]:
|
||
person = org.person_by_identity(db, identity)
|
||
if person is not None:
|
||
people.append((identity, person))
|
||
if not people:
|
||
return 0
|
||
added = 0
|
||
for channel in wanted:
|
||
if channel.kind in models.NotifyChannel.HUB_KINDS:
|
||
# **Hub 代发是一人一条**:卡片要点开就是"我的那条待办",收件人必须在
|
||
# 这条消息里唯一确定;合并成一条会让逐人失败原因(谁没绑企微、谁不在
|
||
# 可见范围)无处可记,也就没法自动补发。
|
||
links = hub_task_links(db, task, [identity for identity, _person in people])
|
||
pref = hub_receiver_pref(channel.config)
|
||
for identity, person in people:
|
||
receiver, target = hub_receiver(person, pref)
|
||
row = _pending(channel, event, identity=identity, person=person, target=target,
|
||
target_field=hub_receiver_field(receiver),
|
||
title=title, body=body, job=job, work=work,
|
||
task=links.get(identity, ""),
|
||
process=process, notification=notification)
|
||
if not target:
|
||
row.status = models.NotifyDelivery.STATUS_SKIPPED
|
||
row.last_error = hub_no_receiver_reason(pref)
|
||
db.add(row)
|
||
added += 1
|
||
continue
|
||
if channel.kind in models.NotifyChannel.SMTP_KINDS:
|
||
for identity, person in people:
|
||
target = email_of(channel, person)
|
||
row = _pending(channel, event, identity=identity, person=person, target=target,
|
||
title=title, body=body, job=job, work=work, task=task,
|
||
process=process, notification=notification)
|
||
if not target:
|
||
row.status = models.NotifyDelivery.STATUS_SKIPPED
|
||
row.last_error = "这个账号没有邮箱,去「组织人员」里补上之后可以重发"
|
||
db.add(row)
|
||
added += 1
|
||
continue
|
||
# **群机器人一批发一条**:三个人会签就往群里甩三条一模一样的"您有一张待办",
|
||
# 群里的人两天就会把这个群设成免打扰,等于这个渠道白配。收件人合并成一条,
|
||
# 名字写进正文与 person_name,群里才知道这条在提醒谁;邮件仍是一人一封。
|
||
url = str((channel.config or {}).get("url") or "")
|
||
names = "、".join(str(person.display_name) for _identity, person in people)
|
||
identity, person = people[0]
|
||
row = _pending(channel, event, identity=identity, person=person, target=url,
|
||
title=title, body=f"提醒:{names}" if not body else f"{body}\n提醒:{names}",
|
||
job=job, work=work, task=task, process=process,
|
||
notification=notification, person_name=names)
|
||
if not url:
|
||
row.status = models.NotifyDelivery.STATUS_SKIPPED
|
||
row.last_error = "渠道还没填推送地址"
|
||
db.add(row)
|
||
added += 1
|
||
if added:
|
||
db.flush()
|
||
# 站内信落库那一刻就把投递线程叫起来。渠道提醒晚 30 秒到人,人的读法不是
|
||
# "渠道有点慢"而是"OA 根本不通知我"——这一句把等待从"最多一个轮询周期
|
||
# (实测 28~60 秒)"压到当下,通路本身见 :mod:`service.wake`。
|
||
wake_signal.mark(db)
|
||
return added
|
||
|
||
|
||
def _pending(
|
||
channel: models.NotifyChannel,
|
||
event: str,
|
||
*,
|
||
identity: str,
|
||
person,
|
||
target: str,
|
||
target_field: str = "",
|
||
title: str,
|
||
body: str,
|
||
job: str,
|
||
work: str,
|
||
task: str,
|
||
process: str,
|
||
notification: str,
|
||
person_name: str = "",
|
||
) -> models.NotifyDelivery:
|
||
"""排一条待发记录(不落库,调用方决定 add 与跳过原因)。"""
|
||
return models.NotifyDelivery(
|
||
channel=channel.code,
|
||
kind=channel.kind,
|
||
type=event,
|
||
identity=identity,
|
||
person=str(person.id),
|
||
person_name=person_name or str(person.display_name),
|
||
target=target,
|
||
target_field=target_field,
|
||
title=title[:500],
|
||
body=body or "",
|
||
job=job,
|
||
work=work,
|
||
task=task,
|
||
process=process,
|
||
notification=notification,
|
||
)
|
||
|
||
|
||
def email_of(channel: models.NotifyChannel, person) -> str:
|
||
value = str(getattr(person, "email", "") or "").strip()
|
||
return value if EMAIL_RE.match(value) else ""
|
||
|
||
|
||
def _hub_user_id_of(person) -> str:
|
||
"""Hub 人员主键:只认纯数字(``users.hub_user_id`` 那一列本来就是整数)。"""
|
||
text = str(getattr(person, "hub_user_id", None) or "").strip()
|
||
return text if text.isdigit() else ""
|
||
|
||
|
||
def _hub_account_of(person) -> str:
|
||
return str(getattr(person, "account", "") or "").strip()
|
||
|
||
|
||
#: 每种收件标识从本地哪一列取值。:data:`HUB_RECEIVER_FIELDS` 加一种,这里就得配一个取法。
|
||
HUB_RECEIVER_VALUES: dict[str, Any] = {
|
||
"user_id": _hub_user_id_of,
|
||
"account": _hub_account_of,
|
||
}
|
||
|
||
|
||
def parse_hub_receiver_pref(value: object) -> tuple[str, ...] | None:
|
||
"""把渠道上配的 ``receiver`` 解析成认人的顺序;出现认不出的标识回 ``None``。
|
||
|
||
认列表也认逗号串(``"account,user_id"``),顺序即优先级,重复去掉。没配或配了个空
|
||
→ 默认那一档。保存渠道时靠 ``None`` 这一支把错别字当场挡下来,别让它在投递记录里
|
||
长成一句"取不到收件标识"。
|
||
"""
|
||
if value is None:
|
||
return HUB_RECEIVER_DEFAULT
|
||
if isinstance(value, str):
|
||
items: list[object] = value.replace(",", " ").split()
|
||
elif isinstance(value, (list, tuple, set)):
|
||
items = list(value)
|
||
else:
|
||
return None
|
||
out: list[str] = []
|
||
for item in items:
|
||
key = str(item or "").strip().lower()
|
||
if not key:
|
||
continue
|
||
if key not in HUB_RECEIVER_VALUES:
|
||
return None
|
||
if key not in out:
|
||
out.append(key)
|
||
return tuple(out) or HUB_RECEIVER_DEFAULT
|
||
|
||
|
||
def hub_receiver_pref(config: dict | None) -> tuple[str, ...]:
|
||
"""渠道上配的收件人标识顺序。取配置的一路不炸:配歪了就按默认走。"""
|
||
return parse_hub_receiver_pref((config or {}).get("receiver")) or HUB_RECEIVER_DEFAULT
|
||
|
||
|
||
def hub_receiver_field(receiver: dict) -> str:
|
||
"""Hub 那一项用的是哪种标识(``receivers`` 的一项只有一个键)。"""
|
||
return str(next(iter(receiver or {}), ""))
|
||
|
||
|
||
def hub_receiver_value(field: str, text: object) -> dict[str, object]:
|
||
"""把记在投递记录里的标识还原成 Hub 要的那一项;``user_id`` 必须是整数。"""
|
||
value = str(text or "").strip()
|
||
if not value or field not in HUB_RECEIVER_VALUES:
|
||
return {}
|
||
return {field: int(value)} if field == "user_id" and value.isdigit() else {field: value}
|
||
|
||
|
||
def hub_receiver(person, pref: Iterable[str] | None = None) -> tuple[dict[str, object], str]:
|
||
"""这个人在 Hub 上是谁:``(receivers 里那一项, 记到投递记录里的收件标识)``。
|
||
|
||
按 ``pref`` 给的顺序逐个认,取到第一个非空就收工。不传就是默认的
|
||
**"主键优先、退回账号"**(:data:`HUB_RECEIVER_DEFAULT`)——押主键是因为改名、改登录名
|
||
都不动它,而 ``account`` 是区分大小写的精确匹配、2026-10-20 起还会随企业微信
|
||
「Hub账号」扩展属性被同步改写;主键为空(本地账号还没被统一身份认领)时才退回账号,
|
||
让 Hub 自己判一次 ``user_not_found``,它比我们猜得准,也比"本地直接不发"多一条
|
||
能被管理员看懂的理由。
|
||
|
||
渠道把某一种单独勾出来时**不退回**另一种:那是管理员明确说过"只按这一列发",
|
||
宁可跳过这个人并写明原因,也别悄悄换成另一列把人送错。
|
||
"""
|
||
for field in tuple(pref) if pref else HUB_RECEIVER_DEFAULT:
|
||
take = HUB_RECEIVER_VALUES.get(str(field or "").strip().lower())
|
||
if take is None:
|
||
continue
|
||
text = str(take(person) or "").strip()
|
||
if not text:
|
||
continue
|
||
return hub_receiver_value(str(field).strip().lower(), text), text
|
||
return {}, ""
|
||
|
||
|
||
def hub_no_receiver_reason(pref: Iterable[str] | None = None) -> str:
|
||
"""取不到收件标识时写给管理员的那句话:点名按哪几列找过、该去哪儿补。"""
|
||
fields = tuple(pref) if pref else HUB_RECEIVER_DEFAULT
|
||
named = "、".join(HUB_RECEIVER_LABELS.get(field, field) for field in fields)
|
||
columns = "、".join(HUB_RECEIVER_COLUMNS.get(field, field) for field in fields)
|
||
return (f"这个账号在统一身份里对不上号:按渠道配的收件人标识({named},取自 {columns})"
|
||
"在这个人身上取不到值,这条没发出去。要么到「组织人员」里给这个人补上,"
|
||
"要么把渠道的收件人标识换成另一种。")
|
||
|
||
|
||
#: 每种收件标识"这个人到底有没有"的库内判据,口径与 :data:`HUB_RECEIVER_VALUES` 一致
|
||
HUB_RECEIVER_SQL: dict[str, Any] = {
|
||
"user_id": lambda: models.User.hub_user_id.is_not(None),
|
||
"account": lambda: models.User.account != "",
|
||
}
|
||
|
||
|
||
def hub_receiver_coverage(db: Session) -> dict[str, Any]:
|
||
"""在职账号里各收件标识能覆盖多少人:换标识之前先看这一眼。
|
||
|
||
换成"只认登录账号"而库里三成是本地自建号,界面上怎么选都对,要等投出一堆
|
||
``skipped`` 才知道坏事。这一条聚合把话提到保存之前说:``fields`` 是每一种**各自**
|
||
能发到多少人,``any`` 是几种都试一遍(默认那一档)能发到的人数,
|
||
``none`` 是怎么配都发不到的那批人——最后这一档才是运维该盯着补的数。
|
||
"""
|
||
fields = [field for field in HUB_RECEIVER_SQL if field in HUB_RECEIVER_VALUES]
|
||
if not fields:
|
||
return {"active": 0, "fields": {}, "any": 0, "none": 0}
|
||
row = db.execute(
|
||
select(
|
||
func.count(models.User.id),
|
||
*[func.sum(case((HUB_RECEIVER_SQL[field](), 1), else_=0)) for field in fields],
|
||
func.sum(case((or_(*[HUB_RECEIVER_SQL[field]() for field in fields]), 1), else_=0)),
|
||
).where(models.User.status == models.UserStatus.ACTIVE)
|
||
).one()
|
||
active = int(row[0] or 0)
|
||
return {
|
||
"active": active,
|
||
"fields": {field: int(row[index + 1] or 0) for index, field in enumerate(fields)},
|
||
"any": int(row[len(fields) + 1] or 0),
|
||
"none": active - int(row[len(fields) + 1] or 0),
|
||
}
|
||
|
||
|
||
def hub_task_links(db: Session, task: str, identities: list[str]) -> dict[str, str]:
|
||
"""这批人各自能拿到哪条待办深链:只有这条待办的持有人拿得到。
|
||
|
||
``engine.notify()`` 对**整批**收件人只传一个 ``task=``,而 ``/todo/<task>`` 是个人
|
||
页面。眼下多收件人还带 task 的只有"外部审批那一环超时"(待办持有人 + 兜底管理员
|
||
一起收,见 ``engine.py`` 里那处 ``[task.identity, _fallback_admin_ref(db)]``),
|
||
照原样发给管理员,他点开的是"不是我的那条待办"——审批页只读、按钮全灰。所以一人
|
||
一条在这里按人分一次:不是持有人就把 task 抹掉,深链退回 ``/work/<job>``,
|
||
那一页管理员本来就看得懂也动得了。
|
||
|
||
单收件人批次不查库(待办到达是热路径,每单都要走一遍,多一次 ``SELECT`` 不值);
|
||
查不到待办行也一并抹掉——那条待办多半已经被办掉了,``/todo/<task>`` 点开会是一句
|
||
"待办不存在或已被处理",不如去看单据。
|
||
"""
|
||
if not task:
|
||
return {}
|
||
if len(identities) < 2:
|
||
return {identity: task for identity in identities}
|
||
row = db.get(models.Task, task)
|
||
holder = str(getattr(row, "identity", "") or "").strip()
|
||
return {identity: task for identity in identities if holder and identity == holder}
|
||
|
||
|
||
def hub_target_for(
|
||
db: Session, row: models.NotifyDelivery, channel: models.NotifyChannel | None = None,
|
||
) -> dict[str, object]:
|
||
"""发送这一刻的收件人标识,按渠道配的 :func:`hub_receiver_pref` 顺序认。
|
||
|
||
取的值以人为准、不以 :attr:`NotifyDelivery.target` 为准:入队之后可能又跑了一趟
|
||
组织人员同步(``hub_user_id`` 补上了),管理员也可能刚把这一路的收件人标识换成
|
||
登录账号,这条排队里的记录就该按**发送这一刻的口径**发。
|
||
|
||
人查不到(账号被删)才回落到记录里那一对 ``(target_field, target)``;升级之前的
|
||
老记录没写过是哪一列,只能按值猜——纯数字只可能是 Hub 主键,口径与改造前一字不差。
|
||
"""
|
||
pref = hub_receiver_pref(getattr(channel, "config", None))
|
||
person_id = str(row.person or "").strip()
|
||
if person_id.isdigit():
|
||
person = db.get(models.User, int(person_id))
|
||
if person is not None:
|
||
receiver, _target = hub_receiver(person, pref)
|
||
if receiver:
|
||
return receiver
|
||
value = str(row.target or "").strip()
|
||
if not value:
|
||
return {}
|
||
field = str(row.target_field or "").strip().lower()
|
||
if field:
|
||
return hub_receiver_value(field, value)
|
||
return {"user_id": int(value)} if value.isdigit() else {"account": value}
|
||
|
||
|
||
def _clip_chars(text: str, limit: int) -> str:
|
||
"""按**字符**截断(Hub 的标题与 description 限的是字符数)。"""
|
||
value = str(text or "")
|
||
if len(value) <= limit:
|
||
return value
|
||
return value[:max(0, limit - 1)].rstrip() + "…"
|
||
|
||
|
||
def _clip_bytes(text: str, limit: int) -> str:
|
||
"""按 **UTF-8 字节**截断:``markdown`` 的 2048 是字节数,中文一个字占三个字节。
|
||
|
||
``errors="ignore"`` 吃掉切一半的那个多字节字符,末尾再补一个省略号(省略号自己
|
||
也是 3 字节,所以先让出 3 字节的位置)。
|
||
"""
|
||
raw = str(text or "").encode("utf-8")
|
||
if len(raw) <= limit:
|
||
return str(text or "")
|
||
keep = raw[:max(0, limit - 3)].decode("utf-8", "ignore").rstrip()
|
||
return keep + "…"
|
||
|
||
|
||
def hub_msgtype(channel: models.NotifyChannel) -> str:
|
||
value = str((channel.config or {}).get("msgtype") or HUB_MSGTYPE_CARD).strip().lower()
|
||
return value if value in HUB_MSGTYPES else HUB_MSGTYPE_CARD
|
||
|
||
|
||
def hub_wants_link(channel: models.NotifyChannel) -> bool:
|
||
"""这条渠道要不要带单据深链。关掉之后发出的是纯提醒,不占用 Hub 的深链。"""
|
||
value = (channel.config or {}).get("with_link", True)
|
||
if isinstance(value, str):
|
||
return value.strip().lower() not in ("", "0", "false", "no", "off")
|
||
return bool(value)
|
||
|
||
|
||
def hub_title_limit(channel: models.NotifyChannel) -> int:
|
||
try:
|
||
value = int((channel.config or {}).get("title_limit") or HUB_TITLE_DEFAULT)
|
||
except (TypeError, ValueError):
|
||
value = HUB_TITLE_DEFAULT
|
||
return max(HUB_TITLE_FLOOR, min(120, value))
|
||
|
||
|
||
def hub_msg_key(row: models.NotifyDelivery, *, variant: str = "") -> str:
|
||
"""这一条业务通知的幂等键:**跨重试保持不变**,只有人工补发时才换世代。
|
||
|
||
文档 9.6.4 把重试姿势压成一句话——超时之后用同一个 ``msg_key`` 原样重发。投递记录
|
||
的 ``id`` 天生满足这件事:同一条记录退避重发、进程重启重发,键都不变,Hub 会把
|
||
"已经投过"的那次回成 ``duplicate``。反过来,``partial`` / ``sent`` 之后人工点重发,
|
||
同键只会命中缓存拿到旧明细(人不会重复收到,但运维会以为没发出去),所以那种
|
||
重发要换世代号 ``-r2``、``-r3``,让它变成一条真的新消息。
|
||
"""
|
||
base = f"oa-{row.channel}-{row.id}"
|
||
try:
|
||
seq = int((row.response or {}).get("msgKeySeq") or 0)
|
||
except (TypeError, ValueError):
|
||
seq = 0
|
||
if seq > 0:
|
||
base = f"{base}-r{seq}"
|
||
#: ``variant`` 是"同一条通知换了内容还得再发一次"留的口子(Hub 拼不出深链时摘掉
|
||
#: 链接改发纯提醒,见 :func:`_hub_send`)。那是一条**内容不同**的消息,同键只会
|
||
#: 命中 Hub 的缓存拿回旧明细;后缀先给 128 留出位置,免得截断把后缀截掉。
|
||
tail = f"-{variant}" if variant else ""
|
||
return f"{base[:128 - len(tail)]}{tail}"
|
||
|
||
|
||
def hub_payload(
|
||
db: Session, channel: models.NotifyChannel, row: models.NotifyDelivery, *,
|
||
link: str = "", force_no_link: bool = False,
|
||
) -> tuple[dict, str]:
|
||
"""照文档 9.6.2 组一次请求体,回 ``(请求体, 降级说明)``。
|
||
|
||
截断全在这里:Hub 那边是 400 硬拒(不是替你截断),超了就是整批没人收到。
|
||
降级说明现在是 ``no_link`` 一种:卡片配了但没有单据可指,改发纯文本提醒。
|
||
``force_no_link`` 是同一条退路的另一半——Hub 认得出深链但拼不出(没登记
|
||
``home_url``)时由 :func:`_hub_send` 传 True:文档 9.6.2 说 ``target_path`` 留空
|
||
就是纯文字提醒,宁可朴素也别让整条消息判死、一个人收不到。
|
||
"""
|
||
receiver = hub_target_for(db, row, channel)
|
||
# 渠道把深链关掉时,测试发送也不该擅自带一条出去
|
||
if force_no_link:
|
||
path = ""
|
||
else:
|
||
path = link if (link and hub_wants_link(channel)) else hub_target_path(channel, row)
|
||
# 卡片没有链接就是一张点不动的卡片:没有单据可指(meeting 这类)就退成纯文本提醒,
|
||
# 与"群里那条不带链接的机器人消息"同一立场——宁可朴素,别给一个点开白屏的东西。
|
||
msgtype = hub_msgtype(channel)
|
||
degraded = ""
|
||
if msgtype == HUB_MSGTYPE_CARD and not path:
|
||
msgtype = HUB_MSGTYPE_MARKDOWN
|
||
degraded = HUB_DEGRADED_NO_LINK
|
||
# 深链照旧喂给模板里的 {url}(有人就想在正文里写"详情见 xxx"),但默认模板
|
||
# 把它当第三行拼出来的那一句要抹掉:卡片上它是那颗按钮,markdown 里 Hub 自己
|
||
# 追加 "[查看详情](链接)",正文里再抄一遍路径只是占字数
|
||
text = _strip_link_line(render_text(channel, row, link=path), path)
|
||
payload: dict[str, object] = {
|
||
"msg_key": hub_msg_key(row),
|
||
"msgtype": msgtype,
|
||
"receivers": [receiver] if receiver else [],
|
||
}
|
||
if path:
|
||
payload["target_path"] = path
|
||
if msgtype == HUB_MSGTYPE_CARD:
|
||
# 标题与正文都得有东西:Hub 对 textcard 的 title/description 是必填,
|
||
# 空一个是 400 整条被拒,而"正文被模板清空"这种事只有发的时候才发现
|
||
description = _strip_title(text, row.title) or str(row.body or "").strip() or str(row.title or "")
|
||
payload["title"] = _clip_chars(row.title, hub_title_limit(channel))
|
||
payload["description"] = _clip_chars(description, HUB_DESC_BYTES)
|
||
else:
|
||
budget = HUB_CONTENT_BYTES - (HUB_LINK_RESERVE_BYTES if path else 0)
|
||
content = str(text or "").strip() or str(row.title or "")
|
||
payload["content"] = _clip_bytes(content, budget)
|
||
return payload, degraded
|
||
|
||
|
||
def _strip_link_line(text: str, path: str) -> str:
|
||
"""抹掉默认模板拼在最后一行的那条深链路径(自定义模板写在中间的 ``{url}`` 不动)。"""
|
||
value = str(text or "").strip()
|
||
tail = str(path or "").strip()
|
||
if not tail:
|
||
return value
|
||
if value == tail:
|
||
return ""
|
||
if value.endswith("\n" + tail):
|
||
return value[: -len(tail) - 1].rstrip()
|
||
return value
|
||
|
||
|
||
def _strip_title(text: str, title: str) -> str:
|
||
"""默认模板渲染出来的第一行就是标题,卡片上标题会单独显示,正文里别再来一遍。"""
|
||
value = str(text or "").strip()
|
||
head = str(title or "").strip()
|
||
if head and value.startswith(head):
|
||
value = value[len(head):].strip()
|
||
return value
|
||
|
||
|
||
def hub_outcome(recipient_status: str, reason: str) -> tuple[str, str]:
|
||
"""逐人结果 -> ``(本系统状态, 给人看的一句话)``。
|
||
|
||
返回的状态取 :data:`models.NotifyDelivery` 那几个常量。分档表在
|
||
:data:`HUB_RETRY_REASONS` / :data:`HUB_SKIP_REASONS` / :data:`HUB_DEAD_REASONS`。
|
||
"""
|
||
slug = str(reason or "").strip()
|
||
if str(recipient_status or "").strip().lower() == "sent":
|
||
return models.NotifyDelivery.STATUS_SUCCESS, ""
|
||
label = HUB_REASON_LABELS.get(slug, "")
|
||
if slug in HUB_RETRY_REASONS or slug not in (HUB_SKIP_REASONS | HUB_DEAD_REASONS):
|
||
return models.NotifyDelivery.STATUS_FAILED, f"Hub 暂未投出({slug or '未知原因'}):{label or '稍后自动重试'}"
|
||
if slug in HUB_SKIP_REASONS:
|
||
return models.NotifyDelivery.STATUS_SKIPPED, label or f"这个人收不到({slug})"
|
||
return models.NotifyDelivery.STATUS_DEAD, label or f"投递失败({slug})"
|
||
|
||
|
||
def work_path(job: str) -> str:
|
||
"""单据在站内的相对路径(``/work/<job>``),没有单据就回空串。
|
||
|
||
Hub 推送要的是 ``target_path``:**站内相对路径**,绝对地址由 Hub 按本系统登记的
|
||
``home_url`` 在点击时刻现拼(文档 9.6.6)。所以这一路绝不能把 ``site_front_url``
|
||
拼进去——那等于把域名写死进一条永久有效的链接里,以后换域名历史消息全成死链。
|
||
"""
|
||
return f"/work/{str(job).strip()}" if str(job or "").strip() else ""
|
||
|
||
|
||
def hub_target_path(channel: models.NotifyChannel, row: models.NotifyDelivery) -> str:
|
||
"""这条消息的深链(``target_path``):站内相对路径,不带域名。
|
||
|
||
待办 / 催办 / 超时落 ``/todo/<task>``——那是审批人自己的页面,"点开即批"就靠它;
|
||
其余(办结、抄送、评论)落 ``/work/<job>``。没有单据可指就回空串,
|
||
Hub 那边发出的是不带链接的纯提醒。
|
||
|
||
``row.task`` 已经是"这个人的那条待办":入队时由 :func:`hub_task_links` 按人分过,
|
||
同批里不是持有人的那几条根本不带 task,所以这里不必再问库。
|
||
|
||
落点对不对、这个人有没有权限看,本系统自己判(Hub 只负责把路径原样带到
|
||
``redirect``,见文档 9.6.5 与 9.6.8)。
|
||
"""
|
||
if not hub_wants_link(channel):
|
||
return ""
|
||
if str(row.type or "") in HUB_TASK_EVENTS and str(row.task or "").strip():
|
||
return f"/todo/{str(row.task).strip()}"
|
||
return work_path(row.job)
|
||
|
||
|
||
def work_link(job: str, *, base: str = "") -> str:
|
||
"""消息里带的单据链接。站点地址取「系统设置 → 站点信息 → 系统访问地址」,没配就只留相对路径。"""
|
||
from .. import dbconfig
|
||
|
||
site = str(dbconfig.value("site_front_url", "") or "").strip().rstrip("/")
|
||
path = work_path(job)
|
||
if not path:
|
||
return site
|
||
if base:
|
||
return f"{base.rstrip('/')}{path}"
|
||
return f"{site}{path}" if site else path
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 投递
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class SendError(Exception):
|
||
"""一次可重试的发送失败(连不上、超时、对方返回非 2xx)。"""
|
||
|
||
|
||
def _smtp_send(config: dict, to: str, subject: str, text: str, timeout: int) -> str:
|
||
host = str(config.get("host") or "").strip()
|
||
port = int(config.get("port") or 465)
|
||
if not host:
|
||
raise SendError("渠道没填 SMTP 服务器地址")
|
||
message = EmailMessage()
|
||
message["From"] = str(config.get("mail_from") or config.get("username") or "")
|
||
message["To"] = to
|
||
message["Subject"] = subject
|
||
message.set_content(text)
|
||
security = str(config.get("security") or "ssl").strip().lower()
|
||
try:
|
||
if security == "ssl":
|
||
client = smtplib.SMTP_SSL(host, port, timeout=timeout)
|
||
else:
|
||
client = smtplib.SMTP(host, port, timeout=timeout)
|
||
except Exception as exc:
|
||
raise SendError(f"连不上邮件服务器 {host}:{port}:{fetch.friendly_error(exc)}") from exc
|
||
try:
|
||
with client:
|
||
if security == "starttls":
|
||
try:
|
||
client.starttls()
|
||
except Exception as exc:
|
||
raise SendError(f"和邮件服务器协商 STARTTLS 失败:{fetch.friendly_error(exc)}") from exc
|
||
username = str(config.get("username") or "").strip()
|
||
password = str(config.get("password") or "").strip()
|
||
if username:
|
||
try:
|
||
client.login(username, password)
|
||
except smtplib.SMTPAuthenticationError as exc:
|
||
# 账号密码错不值得重试:重试一百次也是错,直接给人看
|
||
raise _Fatal(f"SMTP 登录被拒(账号或口令不对):{exc}") from exc
|
||
try:
|
||
client.send_message(message)
|
||
except smtplib.SMTPRecipientsRefused as exc:
|
||
raise _Fatal(f"邮件服务器拒收这个收件人:{exc}") from exc
|
||
except smtplib.SMTPResponseException as exc:
|
||
raise SendError(f"邮件服务器返回 {exc.smtp_code}:{exc.smtp_error}") from exc
|
||
except smtplib.SMTPException as exc:
|
||
raise SendError(f"发送失败:{exc}") from exc
|
||
except OSError as exc:
|
||
raise SendError(f"发送中断:{exc}") from exc
|
||
return f"已投递给 {to}"
|
||
|
||
|
||
class _Fatal(Exception):
|
||
"""再重试也不会成功的失败(口令错、收件人被拒),直接进死信喊人。"""
|
||
|
||
|
||
class _Skipped(Exception):
|
||
"""**这个人现在收不到,但不是故障**:没有邮箱、没绑企业微信、账号没认领。
|
||
|
||
与 :class:`_Fatal` 分开记,是为了让"投递交付失败"和"收件人缺一块资料"在
|
||
投递记录的统计里各归各的——后者混进失败里,运维就永远看不出到底谁在掉队。
|
||
"""
|
||
|
||
|
||
def hub_key_seq(row: models.NotifyDelivery) -> int:
|
||
"""当前这个 ``msg_key`` 是第几世(0 = 首次那一版)。存在 ``response`` 里,
|
||
人工补发已投出去的消息时由 :func:`resend` 加一。"""
|
||
try:
|
||
return int((row.response or {}).get("msgKeySeq") or 0)
|
||
except (TypeError, ValueError):
|
||
return 0
|
||
|
||
|
||
def _hub_client(timeout: int):
|
||
"""发送用的 Hub 客户端:站点、熔断、在飞闸门都跟统一身份共用一套。
|
||
|
||
超时用**渠道自己那一格**:推送是后台调度里跑的,和登录那条在线链路不同一条命,
|
||
配渠道的人知道自家 Hub 有多慢。熔断照旧共享——Hub 真的不理人时,这一路也不该
|
||
把调度线程一条条排上去干等。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
return hub_api.HubClient(cfg.hub_base_url, timeout=max(1, int(timeout)))
|
||
|
||
|
||
def _hub_request_error(exc: hub_api.HubError) -> Exception:
|
||
"""请求级失败翻成本系统的处置。分类只看 HTTP 状态码与 ``code``(文档 9.6.4 明确
|
||
说了别拿 ``message`` 的中文文案做判断),文案只作为给人看的那半句。
|
||
"""
|
||
code = str(exc.code or "").strip()
|
||
status = int(getattr(exc, "status", 0) or 0)
|
||
message = str(exc.message or "").strip()
|
||
if status == 409:
|
||
# 同一个 msg_key 上一次还在发送中:并发保护,不是失败,稍后同键再来
|
||
return SendError(f"Hub 上这一条还在发送中,稍后自动重试:{message}")
|
||
if status == 401 or code == hub_api.CODE_UNAUTHORIZED:
|
||
if not code.isdigit():
|
||
# 网关式的裸 ``{"error":"unauthorized"}``:这台 Hub 对"这条路径压根没注册"
|
||
# 也回同一种 401,光说密钥会让人白换一把。两种可能都得报出去(真环境两种都遇到过)。
|
||
return _Fatal(
|
||
"企业微信推送这一步 Hub 没认这次请求(401 unauthorized),两种可能都要查:"
|
||
"①这把免登应用密钥不被本 Hub 认(系统设置 → 统一身份 里换一把有效的);"
|
||
f"②这台 Hub 上还没有推送这个接口、或它前面的网关没放行这条路径"
|
||
f"({hubconfig.get().hub_path_notify_wecom})。对方原话:{message}"
|
||
)
|
||
return _Fatal(f"统一身份不认这把应用密钥(或本系统已停用),发不出企业微信:{message or code}")
|
||
if status == 403 or code == hub_api.CODE_FORBIDDEN:
|
||
return _Fatal(
|
||
"企业微信推送开关没开:全局开关与本应用的推送开关都在 Hub 侧,"
|
||
f"要找 Hub 管理员开闸。对方原话:{message}"
|
||
)
|
||
if status == 400 or code == hub_api.CODE_BAD_REQUEST:
|
||
hint = ";Hub 上没登记本系统的首页地址(home_url),深链拼不出来,请 Hub 管理员补填" \
|
||
if "首页" in message else ""
|
||
return _Fatal(f"Hub 认为这条消息不合法,重发也一样:{message}{hint}")
|
||
if status == 503:
|
||
return SendError(f"Hub 那边企业微信还没配好,修好就能发:{message}")
|
||
return SendError(f"统一身份这一步没走通,稍后自动重试:{message or exc}")
|
||
|
||
|
||
def hub_home_url_missing(exc: hub_api.HubError) -> bool:
|
||
"""这次 400 是不是"Hub 上没登记本系统的首页地址"(深链拼不出来)。
|
||
|
||
文档 9.6.4 把参数类错误全塞进同一个 ``400001``,能分辨的只有文案,所以这里
|
||
**只决定要不要摘掉深链再试一次**:认不出就照旧判死,认错也只是多发一条纯提醒,
|
||
两种失败方向都比"整条丢掉、一个人收不到"轻。
|
||
"""
|
||
if int(getattr(exc, "status", 0) or 0) != 400:
|
||
return False
|
||
message = str(exc.message or "")
|
||
return "首页" in message or "home_url" in message
|
||
|
||
|
||
def hub_time(value: object) -> str:
|
||
"""Hub 的 ``sent_at``:零值当没填。Hub 那边这个字段常常没赋值,
|
||
直接抄进界面就会出现"发送于 0001-01-01"这种鬼话。"""
|
||
text = str(value or "").strip()
|
||
return "" if not text or text.startswith(HUB_ZERO_TIME) else text
|
||
|
||
|
||
def hub_enterprise_hint(data: dict) -> str:
|
||
"""企业微信自己回的那句(``wecom_errcode`` / ``wecom_errmsg``),只挂在失败上。
|
||
|
||
逐人 ``reason`` 说的是"哪一类问题",企微那句才是"具体哪一处":
|
||
``81013 user & party & tag all invalid`` 就是这个人不在应用可见范围(或成员已离职),
|
||
运维照着那个码去企微的 devtool 一查就到底,比在我们这句"通常是可见范围问题"里猜快。
|
||
"""
|
||
code = str(data.get("wecom_errcode") or "").strip()
|
||
message = _brief(str(data.get("wecom_errmsg") or ""), 160)
|
||
if not (code or message):
|
||
return ""
|
||
return f"(企业微信:{code} {message})"
|
||
|
||
|
||
def _match_recipient(recipients: list[dict], receiver: dict) -> dict | None:
|
||
"""从逐人明细里找出**这条记录对应的那个人**。
|
||
|
||
文档 9.6.3 说得很清楚:别按数组下标对应请求,按 ``receiver`` 回显值对应。
|
||
本系统一次只发一个人,所以回显对不上时(Hub 换了写法)退化成"就一条,是它"。
|
||
"""
|
||
want = str(next(iter(receiver.values()), "")).strip()
|
||
for item in recipients:
|
||
if str(item.get("receiver") or "").strip() == want:
|
||
return item
|
||
return recipients[0] if len(recipients) == 1 else None
|
||
|
||
|
||
def _hub_send(
|
||
db: Session, row: models.NotifyDelivery, channel: models.NotifyChannel, timeout: int,
|
||
*, link: str = "",
|
||
) -> tuple[str, int, dict[str, Any]]:
|
||
"""发一条给 Hub 代发。返回 ``(给人看的一句话, HTTP 状态, 要并进 response 的东西)``。
|
||
|
||
三条来自文档 9.6 的硬规矩:
|
||
|
||
* **不自己重试**:幂等靠 ``msg_key``,超时之后由调度退避、原样同键重发,
|
||
Hub 会三选一(已投过回缓存 / 整批没投过重发 / 还在发回 409);
|
||
* **逐人结果才算数**:HTTP 200 且 ``code=="200"`` 只说明 Hub 听懂了,
|
||
这个人到底收到没有看 ``recipients[].status``;
|
||
* **原因要留住**:``reason`` 原样存进 ``response.hub``,界面上直接看得见,
|
||
补发时不用回来翻 Hub 的日志。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
if not cfg.notify_on:
|
||
raise SendError("统一身份现在发不出企业微信,缺:" + "、".join(cfg.notify_missing))
|
||
payload, degraded = hub_payload(db, channel, row, link=link)
|
||
receivers = payload.get("receivers") or []
|
||
if not receivers:
|
||
raise _Skipped(hub_no_receiver_reason(hub_receiver_pref(channel.config)))
|
||
receiver = receivers[0]
|
||
# 记录里那一对标识要跟**真正发出去**的那一对一致:入队之后人可能被同步改了主键、
|
||
# 渠道也可能被换成按账号发,「回查送达」是拿记录里的标识去对 Hub 的回显的,
|
||
# 对不上就找不到人(本系统一次只发一个人,靠"就一条"兜得住,但界面会念错是谁)。
|
||
used_field = hub_receiver_field(receiver)
|
||
used_value = str(receiver.get(used_field, "")) if used_field else ""
|
||
if used_field and (row.target_field != used_field or row.target != used_value):
|
||
row.target_field = used_field
|
||
row.target = used_value
|
||
seq = hub_key_seq(row)
|
||
client = _hub_client(timeout)
|
||
try:
|
||
data = client.notify_wecom(payload)
|
||
except hub_api.HubError as exc:
|
||
if not payload.get("target_path") or not hub_home_url_missing(exc):
|
||
raise _hub_request_error(exc) from exc
|
||
# Hub 应用没登记 home_url:带深链的那一条整批被 400 拒掉,谁都没收到。
|
||
# 摘掉深链换纯提醒重发一次(内容变了,所以换个键,同键只会命中缓存),
|
||
# 人至少知道有单子要处理;至于点开那一跳,等管理员补上 home_url 之后
|
||
# 新消息自动就带回链接了(文档 9.6.6:深链基址是点击时刻现拼的)。
|
||
payload, _ignored = hub_payload(db, channel, row, link=link, force_no_link=True)
|
||
payload["msg_key"] = hub_msg_key(row, variant="nolink")
|
||
degraded = HUB_DEGRADED_NO_HOME
|
||
try:
|
||
data = client.notify_wecom(payload)
|
||
except hub_api.HubError as retry_exc:
|
||
raise _hub_request_error(retry_exc) from retry_exc
|
||
|
||
recipients = [item for item in (data.get("recipients") or []) if isinstance(item, dict)]
|
||
mine = _match_recipient(recipients, receiver)
|
||
status = str(data.get("status") or "").strip().lower()
|
||
summary: dict[str, Any] = {
|
||
"msgKey": str(payload.get("msg_key") or ""),
|
||
"msgKeySeq": seq,
|
||
"status": status,
|
||
"attempt": data.get("attempt"),
|
||
"sentAt": hub_time(data.get("sent_at")),
|
||
"duplicate": bool(data.get("duplicate")),
|
||
"link": str(data.get("link") or ""),
|
||
"grant": str(data.get("grant") or ""),
|
||
"reason": str((mine or {}).get("reason") or ""),
|
||
"wecomUserId": str((mine or {}).get("wecom_userid") or ""),
|
||
"recipients": recipients[:HUB_RECEIVER_MAX],
|
||
}
|
||
if degraded:
|
||
summary["degraded"] = degraded
|
||
if data.get("wecom_errcode") is not None:
|
||
summary["wecomErrcode"] = data.get("wecom_errcode")
|
||
if data.get("wecom_errmsg"):
|
||
summary["wecomErrmsg"] = str(data.get("wecom_errmsg"))
|
||
detail = _brief(json.dumps({k: v for k, v in summary.items() if k != "recipients"},
|
||
ensure_ascii=False), 380)
|
||
# 先落一份带 hub 明细的 response:下面无论走成功还是抛异常,界面上都看得见
|
||
# 对方到底说了什么(失败路径上 deliver() 不会再动 response)
|
||
row.response = {"httpStatus": 200, "detail": detail, "hub": summary}
|
||
|
||
if mine is None:
|
||
# 没有逐人明细 = 整批就没投出去(文档 9.6.3:请求级原因看 wecom_errmsg)
|
||
if status in ("sent", "partial"):
|
||
return detail, 200, {"hub": summary}
|
||
why = str(data.get("wecom_errmsg") or data.get("wecom_errcode") or "没回逐人结果")
|
||
raise SendError(f"Hub 说这一条没投出去:{_brief(why, 300)}")
|
||
|
||
outcome, message = hub_outcome(str(mine.get("status") or ""), str(mine.get("reason") or ""))
|
||
if outcome != models.NotifyDelivery.STATUS_SUCCESS:
|
||
message = f"{message}{hub_enterprise_hint(data)}"
|
||
if outcome == models.NotifyDelivery.STATUS_SUCCESS:
|
||
notes = []
|
||
if summary["duplicate"]:
|
||
# 同键命中缓存:这个人之前收到过,没重复收到。当作成功,但要说清楚
|
||
notes.append("Hub 命中幂等缓存,这条此前已投出")
|
||
if summary.get("degraded") == HUB_DEGRADED_NO_HOME:
|
||
notes.append("Hub 上没登记本系统首页地址(home_url),这条退成了不带链接的"
|
||
"纯提醒;请 Hub 管理员补填,补好之后新消息自动带回深链")
|
||
return (f"{detail}({';'.join(notes)})" if notes else detail), 200, {"hub": summary}
|
||
if outcome == models.NotifyDelivery.STATUS_SKIPPED:
|
||
raise _Skipped(message)
|
||
if outcome == models.NotifyDelivery.STATUS_DEAD:
|
||
raise _Fatal(message)
|
||
raise SendError(message)
|
||
|
||
|
||
def _robot_body(kind: str, text: str, delivery: models.NotifyDelivery) -> tuple[bytes, dict[str, str]]:
|
||
"""按平台要求的 JSON 结构组包。三家机器人的文本消息结构不一样,这里一次对齐。"""
|
||
headers = {"Content-Type": "application/json"}
|
||
if kind == models.NotifyChannel.KIND_DINGTALK:
|
||
return json.dumps({"msgtype": "text", "text": {"content": text}}, ensure_ascii=False).encode(), headers
|
||
if kind == models.NotifyChannel.KIND_FEISHU:
|
||
return json.dumps({"msg_type": "text", "content": {"text": text}}, ensure_ascii=False).encode(), headers
|
||
if kind == models.NotifyChannel.KIND_WECOM:
|
||
return json.dumps({"msgtype": "text", "text": {"content": text}}, ensure_ascii=False).encode(), headers
|
||
body = json.dumps({
|
||
"event": delivery.type,
|
||
"title": delivery.title,
|
||
"body": delivery.body,
|
||
"person": delivery.person_name,
|
||
"job": delivery.job,
|
||
"work": delivery.work,
|
||
"url": work_link(delivery.job),
|
||
}, ensure_ascii=False).encode("utf-8")
|
||
headers["X-Unisoa-Event"] = delivery.type or ""
|
||
return body, headers
|
||
|
||
|
||
def _signed_url(kind: str, config: dict, url: str, body: bytes) -> str:
|
||
"""加签:钉钉和飞书的群机器人要求带时间戳与签名,防止地址泄露后被别人往群里发。"""
|
||
secret = str(config.get("secret") or "").strip()
|
||
if not secret:
|
||
return url
|
||
stamp = str(int(time.time() * 1000))
|
||
if kind == models.NotifyChannel.KIND_DINGTALK:
|
||
sign = signing.dingtalk_sign(secret, stamp)
|
||
joiner = "&" if "?" in url else "?"
|
||
return f"{url}{joiner}timestamp={stamp}&sign={urllib.parse.quote(sign, safe='')}"
|
||
if kind == models.NotifyChannel.KIND_FEISHU:
|
||
sign = signing.feishu_sign(secret, stamp)
|
||
parts = urllib.parse.urlsplit(url)
|
||
query = dict(urllib.parse.parse_qsl(parts.query))
|
||
query.update({"timestamp": stamp, "sign": sign})
|
||
return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path,
|
||
urllib.parse.urlencode(query), ""))
|
||
return url
|
||
|
||
|
||
def deliver(
|
||
db: Session,
|
||
row: models.NotifyDelivery,
|
||
*,
|
||
channel: models.NotifyChannel | None = None,
|
||
hub_link: str = "",
|
||
) -> models.NotifyDelivery:
|
||
"""发一条。成功记 ``success``,可重试的失败按退避重排,判死的直接进 ``dead``。
|
||
|
||
``hub_link`` 只给"测试发送"用:那一条没有真实单据可指,指到待办列表才能把点开
|
||
那一跳(Hub 认人 + ``redirect``)一起验掉;正常投递一律留空,深链按记录自己算。
|
||
"""
|
||
channel = channel or db.execute(
|
||
select(models.NotifyChannel).where(models.NotifyChannel.code == row.channel)
|
||
).scalar_one_or_none()
|
||
if channel is None or not channel.enabled:
|
||
row.status = models.NotifyDelivery.STATUS_DEAD
|
||
row.last_error = "渠道已被删掉或停用,这条没发出去;需要发就重新配一个渠道再重发"
|
||
db.commit()
|
||
return row
|
||
link = work_link(row.job)
|
||
text = render_text(channel, row, link=link)
|
||
config = dict(channel.config or {})
|
||
timeout = max(1, int(channel.timeout_seconds or 10))
|
||
extra: dict[str, Any] = {}
|
||
started = time.perf_counter()
|
||
try:
|
||
if row.kind in models.NotifyChannel.HUB_KINDS:
|
||
detail, status_code, extra = _hub_send(db, row, channel, timeout, link=hub_link)
|
||
elif row.kind in models.NotifyChannel.SMTP_KINDS:
|
||
detail = _smtp_send(config, row.target, row.title, text, timeout)
|
||
status_code = 200
|
||
else:
|
||
body, headers = _robot_body(row.kind, text, row)
|
||
url = _signed_url(row.kind, config, str(config.get("url") or ""), body)
|
||
status_code, response_text = fetch.http_request("POST", url, body, headers, timeout)
|
||
if status_code >= 400:
|
||
raise SendError(f"对方返回 {status_code}:{_brief(response_text)}")
|
||
# 钉钉/飞书/企微连不上时报的是 200 + 业务错误码,只看 HTTP 状态会把失败当成功
|
||
detail = _brief(response_text)
|
||
error = _robot_error(row.kind, response_text)
|
||
if error:
|
||
raise _Fatal(error)
|
||
row.ms = int((time.perf_counter() - started) * 1000)
|
||
row.status = models.NotifyDelivery.STATUS_SUCCESS
|
||
row.sent_at = datetime.now()
|
||
row.response = {"httpStatus": status_code, "detail": detail, **extra}
|
||
row.last_error = ""
|
||
channel.last_sent_at = datetime.now()
|
||
channel.last_error = ""
|
||
except _Skipped as exc:
|
||
row.ms = int((time.perf_counter() - started) * 1000)
|
||
row.status = models.NotifyDelivery.STATUS_SKIPPED
|
||
row.last_error = str(exc)[:500]
|
||
except _Fatal as exc:
|
||
row.ms = int((time.perf_counter() - started) * 1000)
|
||
row.status = models.NotifyDelivery.STATUS_DEAD
|
||
row.last_error = str(exc)[:500]
|
||
channel.last_error = str(exc)[:500]
|
||
except SendError as exc:
|
||
row.ms = int((time.perf_counter() - started) * 1000)
|
||
_fail(db, row, str(exc), retries=int(channel.retries or 3))
|
||
except Exception as exc: # 网络层的一切意外都当可重试
|
||
row.ms = int((time.perf_counter() - started) * 1000)
|
||
_fail(db, row, f"发送时出错了:{fetch.friendly_error(exc)}", retries=int(channel.retries or 3))
|
||
db.flush()
|
||
db.commit()
|
||
return row
|
||
|
||
|
||
def _robot_error(kind: str, text: str) -> str:
|
||
"""机器人接口的业务错误码。这几类重试无意义:地址里的 token 失效、被限流之外的封禁。"""
|
||
try:
|
||
data = json.loads(text or "{}")
|
||
except ValueError:
|
||
return ""
|
||
code = data.get("errcode", data.get("code", 0))
|
||
if str(code) in ("0", ""):
|
||
return ""
|
||
message = str(data.get("errmsg") or data.get("msg") or "")
|
||
if kind == models.NotifyChannel.KIND_WEBHOOK:
|
||
return ""
|
||
return f"机器人拒收({code}):{message}"
|
||
|
||
|
||
def _brief(text: str, limit: int = 400) -> str:
|
||
value = str(text or "").strip().replace("\r", " ").replace("\n", " ")
|
||
return value[:limit]
|
||
|
||
|
||
def _fail(db: Session, row: models.NotifyDelivery, message: str, *, retries: int) -> None:
|
||
row.attempts = int(row.attempts or 0)
|
||
row.last_error = message[:500]
|
||
if row.attempts >= max(1, retries):
|
||
row.status = models.NotifyDelivery.STATUS_DEAD
|
||
row.last_error = f"{message[:440]}(已重试 {row.attempts} 次,不再自动发)"
|
||
return
|
||
delay = BACKOFF_SECONDS[min(len(BACKOFF_SECONDS) - 1, max(0, row.attempts - 1))]
|
||
row.status = models.NotifyDelivery.STATUS_FAILED
|
||
# 抹掉微秒再写库:DATETIME 列的秒级四舍五入会把"现在能发"抬成"一秒后才能发"
|
||
row.next_attempt_at = datetime.now().replace(microsecond=0) + timedelta(seconds=delay)
|
||
|
||
|
||
def hub_recheck(db: Session, row: models.NotifyDelivery) -> str:
|
||
"""找 Hub 回查这一条的逐人投递结果,按对方口径改写本地状态,回一句给人看的话。
|
||
|
||
这是文档 9.6 的第 3 件事。用得上的两个时刻:一是 ``rate_limited`` / 超时之后
|
||
不确定到底投没投出去,二是管理员想知道"这条卡片现在是什么下场"。回查只读、
|
||
可反复调(文档明说无副作用),所以界面上给一条记录配一个按钮不心疼。
|
||
"""
|
||
if row.kind not in models.NotifyChannel.HUB_KINDS:
|
||
raise ValueError("只有走统一身份 Hub 的渠道才有投递明细可回查")
|
||
# 认记录里那个键,不重算:摘掉深链重发的那一条用的是 ``-nolink`` 变体,
|
||
# 重算出来的键在 Hub 那边根本没有推送记录
|
||
hub = dict((row.response or {}).get("hub") or {})
|
||
key = str(hub.get("msgKey") or "").strip() or hub_msg_key(row)
|
||
if not key:
|
||
raise ValueError("这条记录没有幂等键,回不了查(大概是换世代之前发出去的)")
|
||
data = hub_api.client().notify_wecom_status(key)
|
||
recipients = [item for item in (data.get("recipients") or []) if isinstance(item, dict)]
|
||
status = str(data.get("status") or "").strip().lower()
|
||
mine = None
|
||
want = str(row.target or "").strip()
|
||
for item in recipients:
|
||
if str(item.get("receiver") or "").strip() == want:
|
||
mine = item
|
||
break
|
||
if mine is None and len(recipients) == 1:
|
||
mine = recipients[0]
|
||
|
||
hub.update({
|
||
"msgKey": key,
|
||
"status": status or str(hub.get("status") or ""),
|
||
"attempt": data.get("attempt", hub.get("attempt")),
|
||
"sentAt": hub_time(data.get("sent_at")) or str(hub.get("sentAt") or ""),
|
||
"duplicate": bool(data.get("duplicate")),
|
||
"link": str(data.get("link") or hub.get("link") or ""),
|
||
"grant": str(data.get("grant") or hub.get("grant") or ""),
|
||
"recipients": recipients[:HUB_RECEIVER_MAX],
|
||
"recheckedAt": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||
})
|
||
if data.get("wecom_errmsg"):
|
||
hub["wecomErrmsg"] = str(data.get("wecom_errmsg"))
|
||
if data.get("wecom_errcode") is not None:
|
||
hub["wecomErrcode"] = data.get("wecom_errcode")
|
||
|
||
if mine is not None:
|
||
outcome, message = hub_outcome(str(mine.get("status") or ""), str(mine.get("reason") or ""))
|
||
if outcome != models.NotifyDelivery.STATUS_SUCCESS:
|
||
message = f"{message}{hub_enterprise_hint(data)}"
|
||
hub["reason"] = str(mine.get("reason") or "")
|
||
hub["wecomUserId"] = str(mine.get("wecom_userid") or hub.get("wecomUserId") or "")
|
||
elif status in ("sent", "partial"):
|
||
outcome, message = models.NotifyDelivery.STATUS_SUCCESS, ""
|
||
else:
|
||
outcome, message = models.NotifyDelivery.STATUS_FAILED, \
|
||
f"Hub 那边这一条还是没投出去:{_brief(str(data.get('wecom_errmsg') or '没回逐人结果'), 300)}"
|
||
|
||
row.response = {"httpStatus": 200, "detail": _brief(json.dumps(
|
||
{k: v for k, v in hub.items() if k != "recipients"}, ensure_ascii=False), 380), "hub": hub}
|
||
if outcome == models.NotifyDelivery.STATUS_SUCCESS:
|
||
row.status = outcome
|
||
row.last_error = ""
|
||
if not row.sent_at:
|
||
row.sent_at = _parse_hub_time(str(hub.get("sentAt") or "")) or datetime.now()
|
||
return "Hub 确认这个人已经收到了"
|
||
if outcome == models.NotifyDelivery.STATUS_SKIPPED:
|
||
row.status = outcome
|
||
row.last_error = message
|
||
return message or "这个人收不到"
|
||
if outcome == models.NotifyDelivery.STATUS_DEAD:
|
||
row.status = outcome
|
||
row.last_error = message
|
||
return message
|
||
# 还是没投出去:留原状态,让调度按退避继续试
|
||
row.last_error = message
|
||
return message or "Hub 那边还没投出去,稍后按退避继续重试"
|
||
|
||
|
||
def _parse_hub_time(value: str) -> datetime | None:
|
||
"""Hub 回传的 ``sent_at`` 是 UTC 的 RFC3339,本地那几列存的是不带时区的本地时间。"""
|
||
text = hub_time(value)
|
||
if not text:
|
||
return None
|
||
try:
|
||
stamp = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||
except ValueError:
|
||
return None
|
||
if stamp.tzinfo is not None:
|
||
stamp = stamp.astimezone().replace(tzinfo=None)
|
||
return stamp
|
||
|
||
|
||
def claim(db: Session, delivery_id: str) -> bool:
|
||
"""把一条待头发给自己。多副本时靠这条 UPDATE 的 rowcount 决定谁发,避免同一封邮件发两遍。
|
||
|
||
参数是 id 不是 ORM 对象:认领带的 ``commit()`` 会把 :func:`due` 那批对象全部过期,
|
||
下一圈再摸 ``row.id`` 就是回库,行被清理脚本删掉时抛的是 ``ObjectDeletedError``,
|
||
整轮投递跟着断(写回发件箱与事件订阅两路同此理,那边一并改了)。
|
||
"""
|
||
result = db.execute(
|
||
update(models.NotifyDelivery)
|
||
.where(models.NotifyDelivery.id == delivery_id)
|
||
.where(models.NotifyDelivery.status.in_(models.NotifyDelivery.STATUS_OPEN))
|
||
.where(models.NotifyDelivery.next_attempt_at <= datetime.now())
|
||
.values(status=models.NotifyDelivery.STATUS_SENDING,
|
||
attempts=models.NotifyDelivery.attempts + 1,
|
||
next_attempt_at=datetime.now() + timedelta(minutes=10)),
|
||
execution_options={"synchronize_session": False},
|
||
)
|
||
db.commit()
|
||
return int(result.rowcount or 0) == 1
|
||
|
||
|
||
def due(db: Session, *, limit: int = BATCH_LIMIT) -> list[models.NotifyDelivery]:
|
||
moment = datetime.now()
|
||
return list(db.execute(
|
||
select(models.NotifyDelivery)
|
||
.where(models.NotifyDelivery.status.in_(models.NotifyDelivery.STATUS_OPEN))
|
||
.where(models.NotifyDelivery.next_attempt_at <= moment)
|
||
.order_by(models.NotifyDelivery.next_attempt_at, models.NotifyDelivery.id)
|
||
.limit(limit)
|
||
).scalars().all())
|
||
|
||
|
||
def due_now(db: Session) -> bool:
|
||
return db.execute(
|
||
select(models.NotifyDelivery.id)
|
||
.where(models.NotifyDelivery.status.in_(models.NotifyDelivery.STATUS_OPEN))
|
||
.where(models.NotifyDelivery.next_attempt_at <= datetime.now())
|
||
.limit(1)
|
||
).first() is not None
|
||
|
||
|
||
#: 停在 sending 超过这个时长就认定进程死在半路(发送超时上限远小于它)
|
||
SENDING_TIMEOUT_SECONDS = 600
|
||
|
||
|
||
def recover_stuck(db: Session) -> int:
|
||
"""把卡在 ``sending`` 的记录放回队列。
|
||
|
||
和写回发件箱不一样:这里**不需要**"结果未知"这个状态。少发一封提醒的代价是用户
|
||
晚一点知道,多发的代价只是邮箱里多一封重复邮件——所以默认重来,不把人拉来确认。
|
||
"""
|
||
cutoff = datetime.now() - timedelta(seconds=SENDING_TIMEOUT_SECONDS)
|
||
result = db.execute(
|
||
update(models.NotifyDelivery)
|
||
.where(models.NotifyDelivery.status == models.NotifyDelivery.STATUS_SENDING)
|
||
.where(models.NotifyDelivery.next_attempt_at < cutoff)
|
||
.values(status=models.NotifyDelivery.STATUS_FAILED,
|
||
last_error="上一次发送没有走完(进程可能重启过),已重新排队",
|
||
next_attempt_at=datetime.now()),
|
||
execution_options={"synchronize_session": False},
|
||
)
|
||
db.commit()
|
||
return int(result.rowcount or 0)
|
||
|
||
|
||
def run_due(db: Session, *, limit: int = BATCH_LIMIT) -> dict:
|
||
"""后台调度每轮调一次:先收尸,再认领,一条发一条;单条失败不带崩整轮。"""
|
||
recover_stuck(db)
|
||
sent = ok = dead = 0
|
||
started = time.perf_counter()
|
||
# 先抄下 id 再进循环:认领与投递各自 commit,过期对象摸一次属性就回读一次库
|
||
queued = [row.id for row in due(db, limit=limit)]
|
||
for index, delivery_id in enumerate(queued):
|
||
if index and time.perf_counter() - started > ROUND_BUDGET_SECONDS:
|
||
logger.info("消息渠道这一轮发满 %.0f 秒先收工,剩下 %d 条下一轮接着发",
|
||
ROUND_BUDGET_SECONDS, len(queued) - index)
|
||
break
|
||
if not claim(db, delivery_id):
|
||
continue # 别的进程已经认领了这条
|
||
fresh = db.get(models.NotifyDelivery, delivery_id)
|
||
if fresh is None:
|
||
continue
|
||
sent += 1
|
||
result = deliver(db, fresh)
|
||
if result.status == models.NotifyDelivery.STATUS_SUCCESS:
|
||
ok += 1
|
||
elif result.status == models.NotifyDelivery.STATUS_DEAD:
|
||
dead += 1
|
||
return {"sent": sent, "success": ok, "dead": dead}
|
||
|
||
|
||
def resend(db: Session, delivery_id: str) -> models.NotifyDelivery | None:
|
||
"""人工重发一条(补完邮箱、补完企微绑定之后点这个)。"""
|
||
row = db.get(models.NotifyDelivery, delivery_id)
|
||
if row is None:
|
||
return None
|
||
row.status = models.NotifyDelivery.STATUS_PENDING
|
||
row.attempts = 0
|
||
row.next_attempt_at = datetime.now()
|
||
row.last_error = ""
|
||
if row.kind in models.NotifyChannel.HUB_KINDS:
|
||
# 收件人重认一次:这一次重发多半就是"同步之后 hub_user_id 补上了 / 停用被取消",
|
||
# 拿着旧的收件标识重发等于把同一个错误再犯一遍。
|
||
person = db.get(models.User, int(row.person or 0) or 0)
|
||
if person is not None:
|
||
_receiver, target = hub_receiver(person)
|
||
if target:
|
||
row.target = target
|
||
# 已经投出去过的那一条(sent / partial)同键重发只会命中 Hub 的幂等缓存,
|
||
# 对方原样回一份旧明细、一个人也不会再收到——换个世代号才是真补发(文档 9.6.4)。
|
||
hub = dict(row.response or {}).get("hub") or {}
|
||
if str(hub.get("status") or "").lower() in ("sent", "partial"):
|
||
response = dict(row.response or {})
|
||
response["msgKeySeq"] = hub_key_seq(row) + 1
|
||
response["hub"] = {**hub, "msgKey": "", "status": "queued"}
|
||
row.response = response
|
||
if row.kind == models.NotifyChannel.KIND_EMAIL:
|
||
person = db.get(models.User, int(row.person or 0) or 0)
|
||
if person is not None:
|
||
row.target = email_of(models.NotifyChannel(kind=models.NotifyChannel.KIND_EMAIL), person)
|
||
if not row.target:
|
||
row.status = models.NotifyDelivery.STATUS_SKIPPED
|
||
row.last_error = "这个账号还是没有邮箱"
|
||
# 人点「重发」就是现在想看结果:别让他再等一个轮询周期(写回那边同此口径)
|
||
wake_signal.mark(db)
|
||
db.commit()
|
||
return row
|