210 lines
8.5 KiB
Python
210 lines
8.5 KiB
Python
"""信号分发:四类用户过滤(SQL 层)→ notifications 行 → JPush 下发。
|
||
|
||
enqueue:在扫描事务内调用(与 signals/checkpoint 同事务提交)。
|
||
push_pending:事务外执行。2026-12-03 起:每轮扫描每个用户只发一条聚合推送,
|
||
失败不重试,但把原因写入 push_batches/push_log 供排查与统计。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import secrets
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
from ..db import execute, query
|
||
|
||
|
||
def _now() -> datetime:
|
||
return datetime.now(timezone(timedelta(hours=8)))
|
||
|
||
|
||
def _in_dnd(user: dict, now: datetime) -> bool:
|
||
if not user["dnd_enabled"]:
|
||
return False
|
||
hm = now.strftime("%H:%M")
|
||
start, end = user["dnd_start"], user["dnd_end"]
|
||
if not start or not end or start == end:
|
||
return False
|
||
if start > end: # 跨午夜
|
||
return hm >= start or hm < end
|
||
return start <= hm < end
|
||
|
||
|
||
def _targets(conn) -> list[dict]:
|
||
"""已激活 + 未封禁 + 推送开 + 非免打扰 的用户列表。
|
||
|
||
注意:App 内通知列表面向所有激活用户,不依赖 JPush 设备注册——
|
||
RID 为空只影响 push_pending 能否推送,不影响通知行生成。
|
||
(原实现 JOIN devices 且要求 jpush_rid 非空,导致未接 JPush 时
|
||
所有用户的通知列表永远为空。)"""
|
||
now = _now()
|
||
now_s = now.strftime("%Y-%m-%d %H:%M:%S")
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT u.id AS user_id,
|
||
COALESCE(s.push_enabled,1) AS push_enabled,
|
||
COALESCE(s.dnd_enabled,0) AS dnd_enabled,
|
||
s.dnd_start, s.dnd_end
|
||
FROM users u
|
||
LEFT JOIN user_settings s ON s.user_id = u.id
|
||
WHERE u.is_banned = 0 AND u.active_until >= ?
|
||
""",
|
||
(now_s,),
|
||
).fetchall()
|
||
return [r for r in rows if not _in_dnd(r, now)]
|
||
|
||
|
||
def enqueue(conn, signal_ids: list[int]) -> int:
|
||
"""为每个目标用户创建 notification(UNIQUE 去重),push_status='pending'。"""
|
||
targets = _targets(conn)
|
||
created = _now().strftime("%Y-%m-%d %H:%M:%S")
|
||
n = 0
|
||
for sig in signal_ids:
|
||
for t in targets:
|
||
cur = conn.execute(
|
||
"INSERT OR IGNORE INTO notifications(user_id, signal_id, created_at, push_status)"
|
||
" VALUES(?,?,?,?)",
|
||
(t["user_id"], sig, created, "pending"),
|
||
)
|
||
n += cur.rowcount
|
||
# 激活后的新用户:激活时间点之前不补建(§12.3 激活补建走独立流程)
|
||
if n:
|
||
# 累计通知数只增不减(归档不影响):按用户各自新增数累加,同一事务内
|
||
conn.execute(
|
||
"INSERT INTO user_counters(user_id, notified_total, updated_at) "
|
||
"SELECT user_id, COUNT(*), ? FROM notifications WHERE signal_id IN (%s) GROUP BY user_id "
|
||
"ON CONFLICT(user_id) DO UPDATE SET notified_total = notified_total + excluded.notified_total,"
|
||
" updated_at = excluded.updated_at" % ",".join("?" * len(signal_ids)),
|
||
tuple([created] + signal_ids),
|
||
)
|
||
return n
|
||
|
||
|
||
def send_signal_sms() -> None:
|
||
"""背离点短信提醒(PRD §11.2):已激活 + sms_enabled + 非免打扰,日频控 20 条。"""
|
||
from ..notify.sms import send_signal_sms
|
||
|
||
rows = query(
|
||
"""
|
||
SELECT u.id AS user_id, u.phone, s.sms_enabled, s.dnd_enabled, s.dnd_start, s.dnd_end,
|
||
u.active_until, u.is_banned
|
||
FROM users u LEFT JOIN user_settings s ON s.user_id=u.id
|
||
WHERE u.is_banned=0 AND u.active_until >= ?
|
||
AND COALESCE(s.sms_enabled,0)=1
|
||
""",
|
||
(_now().strftime("%Y-%m-%d %H:%M:%S"),),
|
||
)
|
||
if not rows:
|
||
return
|
||
users = [r for r in rows if not _in_dnd(r, _now())]
|
||
if not users:
|
||
return
|
||
ids = ",".join("?" * len(users))
|
||
signals = query(
|
||
f"""
|
||
SELECT n.id AS nid, u.id AS user_id, u.phone, s.symbol, s.interval, s.divergence_time,
|
||
s.trigger_close
|
||
FROM notifications n
|
||
JOIN signals s ON s.id = n.signal_id
|
||
JOIN users u ON u.id = n.user_id
|
||
WHERE n.sms_status IS NULL AND u.id IN ({ids})
|
||
AND s.created_at >= date('now', '-1 day')
|
||
LIMIT 200
|
||
""",
|
||
tuple([u["user_id"] for u in users]),
|
||
)
|
||
if not signals:
|
||
return
|
||
by_user = {}
|
||
for s in signals:
|
||
by_user.setdefault(s["user_id"], []).append(s)
|
||
for uid, items in by_user.items():
|
||
urow = next(u for u in users if u["user_id"] == uid)
|
||
sent = query(
|
||
"SELECT COUNT(*) c FROM sms_log WHERE phone=? AND sent_at LIKE ? AND status='success'",
|
||
(urow["phone"], _now().strftime("%Y-%m-%d") + "%"),
|
||
)[0]["c"]
|
||
now_str = _now().strftime("%Y-%m-%d %H:%M:%S")
|
||
for it in items:
|
||
if sent >= 20:
|
||
break
|
||
ok = send_signal_sms(urow["phone"], it["symbol"], it["interval"], it["divergence_time"], it["trigger_close"])
|
||
execute("UPDATE notifications SET sms_status=? WHERE id=?", ("success" if ok else "failed", it["nid"]))
|
||
execute(
|
||
"INSERT INTO sms_log(phone, scene, sent_at, status) VALUES(?,?,?,?)",
|
||
(urow["phone"], "signal", now_str, "success" if ok else "failed"),
|
||
)
|
||
if ok:
|
||
sent += 1
|
||
|
||
|
||
def push_pending() -> None:
|
||
"""把 pending 通知推出去:每轮每个用户一条聚合推送。
|
||
|
||
- 旧信号闸门(2026-11-24):divergence_time 距今 >30 分钟不弹推送(skipped)
|
||
- >30 分钟仍未发出的 pending 置 expired
|
||
- 失败不重试(用户 2026-12-03 要求),原因写入 push_batches.error / push_log.error
|
||
- 每条推送生成 push_batches 批次行并带 receipt_token,客户端回执后写 received_at
|
||
"""
|
||
from ..notify.push import send_round_push # 延迟导入,避免无凭证时报错
|
||
|
||
gate = (_now() - timedelta(minutes=30)).strftime("%Y-%m-%d %H:%M:%S")
|
||
execute(
|
||
"UPDATE notifications SET push_status='skipped' "
|
||
"WHERE push_status='pending' AND signal_id IN "
|
||
"(SELECT id FROM signals WHERE divergence_time < ?)",
|
||
(gate,),
|
||
)
|
||
expire_before = (_now() - timedelta(minutes=30)).strftime("%Y-%m-%d %H:%M:%S")
|
||
execute(
|
||
"UPDATE notifications SET push_status='expired' "
|
||
"WHERE push_status='pending' AND created_at < ?",
|
||
(expire_before,),
|
||
)
|
||
rows = query(
|
||
"""
|
||
SELECT n.id, n.user_id, n.signal_id, s.symbol, s.interval, s.divergence_time, s.kind,
|
||
d.jpush_rid
|
||
FROM notifications n JOIN signals s ON s.id = n.signal_id
|
||
JOIN devices d ON d.user_id = n.user_id AND d.rid_invalid = 0
|
||
AND d.jpush_rid IS NOT NULL
|
||
WHERE n.push_status = 'pending' AND s.kind != 'long_ignition'
|
||
ORDER BY s.divergence_time
|
||
LIMIT 5000
|
||
"""
|
||
)
|
||
if not rows:
|
||
return
|
||
|
||
# JOIN devices 会把同一通知按设备行放大:按通知 id 去重,同时收集该用户的全部有效 rid
|
||
by_user: dict[int, dict] = {}
|
||
for r in rows:
|
||
u = by_user.setdefault(r["user_id"], {"items": {}, "rids": []})
|
||
u["items"][r["id"]] = {
|
||
"id": r["id"], "signal_id": r["signal_id"], "symbol": r["symbol"],
|
||
"interval": r["interval"], "divergence_time": r["divergence_time"], "kind": r["kind"],
|
||
}
|
||
rid = r["jpush_rid"]
|
||
if rid and rid not in u["rids"]:
|
||
u["rids"].append(rid)
|
||
|
||
now_str = _now().strftime("%Y-%m-%d %H:%M:%S")
|
||
for user_id, u in by_user.items():
|
||
items = sorted(u["items"].values(), key=lambda x: x["divergence_time"])
|
||
rids = u["rids"]
|
||
token = secrets.token_urlsafe(24)
|
||
# 先落批次再发送:发送途中进程崩溃也留有记录
|
||
execute(
|
||
"INSERT INTO push_batches(user_id, rid, signal_ids, item_count, status, receipt_token, sent_at)"
|
||
" VALUES(?,?,?,?,?,?,?)",
|
||
(user_id, ",".join(rids), ",".join(str(it["signal_id"]) for it in items),
|
||
len(items), "pending", token, now_str),
|
||
)
|
||
batch = query("SELECT id, receipt_token FROM push_batches WHERE receipt_token=?", (token,))[0]
|
||
status, error = send_round_push(items, rids, batch)
|
||
execute("UPDATE push_batches SET status=?, error=? WHERE id=?", (status, error, batch["id"]))
|
||
for it in items:
|
||
execute("UPDATE notifications SET push_status=? WHERE id=?", (status, it["id"]))
|
||
execute(
|
||
"INSERT INTO push_log(notification_id, provider, status, error, sent_at) VALUES(?,?,?,?,?)",
|
||
(it["id"], "jpush", status, error, now_str),
|
||
)
|