unis-oa/backend/app/service/channels.py

588 lines
25 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.

"""消息渠道 -- 站内信之外,把同一条消息送到邮箱与群机器人。
**为什么挂在 ``engine.notify()`` 上而不是各处加发送代码**:站内信、邮件、机器人提醒
说的是同一句话("您有一张单要处理")。写通知的唯一入口是 ``notify()``,渠道投递就
在同一个位置扇出;以后再加短信、企业微信工作通知,业务代码一行都不用改。
**为什么先入队再发送**:SMTP 和机器人网关都会抖,而"消息丢了"这件事必须看得见。
入队与站内信同一事务(业务定了消息就一定在),投递交给后台调度线程,失败按退避重试,
重试用满进死信——和写回发件箱是同一套底线(``docs/notification-channels-design.md``)。
配置尽量薄:一个渠道只有"发到哪 + 发什么事 + 用什么身份发"三格。收件人不做配置项,
**站内信发给谁这一路就发给谁**,邮箱从账号上取;账号没邮箱就在投递记录里留一条
``skipped`` 并写明原因,不静默丢。
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
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
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from .. import models, presence, readcache
from . import fetch, org, signing
#: 可订阅的通知事件:取值与 ``oa_notification.type`` 完全一致,界面上就是几个勾选框
EVENTS: tuple[tuple[str, str], ...] = (
("task", "新的待办"),
("press", "催办提醒"),
("read", "抄送 / 分享 / 评论"),
("completed", "办结结果"),
("expire", "待办超时"),
("meeting", "会议提醒"),
)
EVENT_LABELS = dict(EVENTS)
#: 界面上"全选"用的清单
EVENT_KEYS = tuple(key for key, _ in EVENTS)
BACKOFF_SECONDS = (60, 300, 1800)
BATCH_LIMIT = 40
#: 正文进邮件/机器人时截这么长:机器人有长度墙,而且消息不该变成第二份表单
BODY_LIMIT = 1000
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
#: 密钥类配置键:接口回显时只说"已设置",不回明文
SECRET_KEYS = ("password", "secret", "token")
# ---------------------------------------------------------------------------
# 配置校验与视图辅助
# ---------------------------------------------------------------------------
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 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")
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.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()
return added
def _pending(
channel: models.NotifyChannel,
event: str,
*,
identity: str,
person,
target: 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,
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 work_link(job: str, *, base: str = "") -> str:
"""消息里带的单据链接。站点地址取「系统设置 → 站点信息 → 系统访问地址」,没配就只留相对路径。"""
from .. import dbconfig
site = str(dbconfig.value("site_front_url", "") or "").strip().rstrip("/")
if not job:
return site
path = f"/work/{job}"
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):
"""再重试也不会成功的失败(口令错、收件人被拒),直接进死信喊人。"""
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) -> models.NotifyDelivery:
"""发一条。成功记 ``success``,可重试的失败按退避重排,判死的直接进 ``dead``。"""
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))
started = time.perf_counter()
try:
if 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}
row.last_error = ""
channel.last_sent_at = datetime.now()
channel.last_error = ""
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
row.next_attempt_at = datetime.now() + timedelta(seconds=delay)
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
# 先抄下 id 再进循环:认领与投递各自 commit,过期对象摸一次属性就回读一次库
for delivery_id in [row.id for row in due(db, limit=limit)]:
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 == 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 = "这个账号还是没有邮箱"
db.commit()
return row