feat: track duty email confirmations and add throttled account email tests

This commit is contained in:
2026-11-06 15:07:48 +08:00
parent 867443163a
commit 0a7a641430
11 changed files with 352 additions and 16 deletions
+9 -7
View File
@@ -168,7 +168,8 @@ def due_batches(schedule, now):
return batches
async def send_due(schedule, now, accounts, send_email, state_path, overrides=None):
async def send_due(schedule, now, accounts, send_email, state_path, overrides=None, base_url="http://127.0.0.1:37777"):
from .duty_receipts import send_notice
result = {"sent": 0, "failed": 0, "missing": {}}
if not schedule["enabled"]:
return result
@@ -180,28 +181,29 @@ async def send_due(schedule, now, accounts, send_email, state_path, overrides=No
if not await asyncio.to_thread(claim, state_path, key, email, now.timestamp()):
continue
clocks = schedule.get("slot_times", {})
lines = [f"{name}:" + "、".join(f"{slot}({clocks[slot]} 开始)" if slot in clocks else slot for slot in slots) for name, slots in names.items()]
body = f"{label}\n\n日期:{target.isoformat()}(周{'一二三四五六日'[target.weekday()]},{'单' if week == 'odd' else '双'}周)\n" + "\n".join(lines) + "\n\n以上时间均为北京时间。请准时值班;如需调班,请提前联系值班负责人。\nWorkLog"
slots = {slot for items in names.values() for slot in items}
ends = [datetime.combine(target, datetime.strptime(clocks[slot], "%H:%M").time(), BEIJING) + timedelta(minutes=schedule.get("duration_minutes", 105)) for slot in slots]
body = f"日期:{target.isoformat()}(周{'一二三四五六日'[target.weekday()]},{'单' if week == 'odd' else '双'}周)\n" + "、".join(f"{slot} {clocks[slot]} 开始" for slot in sorted(slots)) + "\n以上时间均为北京时间。请准时值班。"
try:
await send_email(email, f"{label}|{target.isoformat()}", body)
sent = await send_notice(state_path, target.isoformat(), names, email, max(ends).timestamp(), send_email, f"{label}|{target.isoformat()}", body, base_url, now.timestamp())
except Exception:
result["failed"] += 1
await asyncio.to_thread(finish, state_path, key, email, "failed")
log.exception("值班邮件发送失败")
else:
result["sent"] += 1
result["sent"] += int(sent)
await asyncio.to_thread(finish, state_path, key, email, "sent")
return result
async def reminder_loop(schedule_path, state_path, get_accounts, send_email, overrides_path=None):
async def reminder_loop(schedule_path, state_path, get_accounts, send_email, overrides_path=None, base_url="http://127.0.0.1:37777"):
previous_missing = None
while True:
try:
schedule = load_schedule(schedule_path)
if schedule["enabled"]:
overrides = json.loads(Path(overrides_path).read_text(encoding="utf-8-sig")) if overrides_path and Path(overrides_path).exists() else {}
result = await send_due(schedule, datetime.now(BEIJING), await get_accounts(), send_email, state_path, overrides)
result = await send_due(schedule, datetime.now(BEIJING), await get_accounts(), send_email, state_path, overrides, base_url)
if result["missing"] and result["missing"] != previous_missing:
log.warning("值班名单无法匹配邮箱:%s", result["missing"])
previous_missing = result["missing"]
+107
View File
@@ -0,0 +1,107 @@
"""值班提醒回执;独立 SQLite 保存每人每轮的发送次数和确认状态。"""
import hashlib
import json
import secrets
import sqlite3
import time
from contextlib import closing
from html import escape
def connect(path):
path.parent.mkdir(parents=True, exist_ok=True)
con = sqlite3.connect(path, timeout=10)
con.row_factory = sqlite3.Row
con.execute("CREATE TABLE IF NOT EXISTS duty_receipts (day TEXT, slot TEXT, name TEXT, attempts INTEGER DEFAULT 0, sent_count INTEGER DEFAULT 0, last_attempt REAL DEFAULT 0, last_sent REAL DEFAULT 0, confirmed REAL DEFAULT 0, PRIMARY KEY(day,slot,name))")
con.execute("CREATE TABLE IF NOT EXISTS duty_confirmations (digest TEXT PRIMARY KEY, targets TEXT NOT NULL, expires REAL NOT NULL)")
return con
def ensure(con, day, slot, name, email):
# 导入旧版成功发送记录;新版已有回执后不重复导入。
count, last = 0, 0
if email and con.execute("SELECT 1 FROM sqlite_master WHERE name='deliveries'").fetchone():
rows = con.execute("SELECT updated FROM deliveries WHERE email=? AND status='sent' AND day IN (?,?)", (email, day, f"{day}#before:{slot}")).fetchall()
count = len(rows)
last = max((r[0] for r in rows), default=0)
con.execute("INSERT OR IGNORE INTO duty_receipts(day,slot,name,attempts,sent_count,last_attempt,last_sent) VALUES (?,?,?,?,?,?,?)", (day, slot, name, count, count, last, last))
def status(path, day, slot, name, email, now):
with closing(connect(path)) as con:
ensure(con, day, slot, name, email)
row = dict(con.execute("SELECT * FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone())
con.commit()
return {"name": name, "attempts": row["attempts"], "sent_count": row["sent_count"], "last_sent_at": int(row["last_sent"] * 1000) or None, "confirmed_at": int(row["confirmed"] * 1000) or None, "can_remind": bool(email and not row["confirmed"] and row["attempts"] < 3 and now - row["last_attempt"] >= 60), "matched": bool(email)}
def reserve(path, day, names, email, expires, now):
selected = {}
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
for name, slots in names.items():
for slot in slots:
ensure(con, day, slot, name, email)
row = con.execute("SELECT * FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone()
if row["confirmed"] or row["attempts"] >= 3 or now - row["last_attempt"] < 60:
continue
con.execute("UPDATE duty_receipts SET attempts=attempts+1,last_attempt=? WHERE day=? AND slot=? AND name=?", (now, day, slot, name))
selected.setdefault(name, []).append(slot)
if not selected:
con.commit()
return None, {}
token = secrets.token_urlsafe(32)
targets = [(day, slot, name) for name, slots in selected.items() for slot in slots]
con.execute("INSERT INTO duty_confirmations VALUES (?,?,?)", (hashlib.sha256(token.encode()).hexdigest(), json.dumps(targets), expires))
con.commit()
return token, selected
def mark_sent(path, day, names, now):
with closing(connect(path)) as con:
for name, slots in names.items():
for slot in slots:
con.execute("UPDATE duty_receipts SET sent_count=sent_count+1,last_sent=? WHERE day=? AND slot=? AND name=?", (now, day, slot, name))
con.commit()
def confirmation(path, token, now, consume=False):
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
row = con.execute("SELECT * FROM duty_confirmations WHERE digest=?", (hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
if row is None or row["expires"] <= now:
return None
targets = json.loads(row["targets"])
if consume:
for day, slot, name in targets:
con.execute("UPDATE duty_receipts SET confirmed=CASE WHEN confirmed=0 THEN ? ELSE confirmed END WHERE day=? AND slot=? AND name=?", (now, day, slot, name))
con.commit()
return targets
def reserve_test(path, email, now):
with closing(connect(path)) as con:
con.execute("CREATE TABLE IF NOT EXISTS mail_test_limits (email TEXT PRIMARY KEY, last_attempt REAL NOT NULL)")
con.execute("BEGIN IMMEDIATE")
row = con.execute("SELECT last_attempt FROM mail_test_limits WHERE email=?", (email.strip().lower(),)).fetchone()
if row and now - row[0] < 120:
return False
con.execute("INSERT OR REPLACE INTO mail_test_limits VALUES (?,?)", (email.strip().lower(), now))
con.commit()
return True
async def send_notice(path, day, names, email, expires, send_email, subject, body, base_url, now=None):
import asyncio
now = time.time() if now is None else now
token, selected = await asyncio.to_thread(reserve, path, day, names, email, expires, now)
if not selected:
return False
url = base_url.rstrip('/') + '/duty-confirm/' + token
# 仅写入本次获得发送名额的同学和时段,避免再次提醒已确认的记录。
details = '\n'.join(f"{name}:{'、'.join(slots)}" for name, slots in selected.items())
plain = f"{subject}\n\n{body}\n{details}\n\n请点击以下链接确认已知晓本次值班安排:\n{url}\n\nWorkLog"
html = f'<div style="font-family:sans-serif;line-height:1.8;color:#263c35"><h2>{escape(subject)}</h2><p>{escape(body).replace(chr(10), "<br>")}</p><p>{escape(details).replace(chr(10), "<br>")}</p><a href="{escape(url, quote=True)}" style="display:inline-block;padding:12px 24px;background:#28664f;color:white;text-decoration:none;border-radius:8px">确认已知晓值班安排</a><p>打开后请在页面中确认。WorkLog</p></div>'
await send_email(email, subject, plain, html)
await asyncio.to_thread(mark_sent, path, day, selected, now)
return True
+75 -3
View File
@@ -38,6 +38,8 @@ from .models import activities, auth_limits, email_verifications, join_links, me
from .security import hash_password, new_token, token_digest, verify_password
from .backup import backup_loop, parse_time
from .duty import BEIJING, duty_status, load_schedule, reminder_loop
from .duty import resolve_recipients
from . import duty_receipts
BASE_DIR = Path(__file__).resolve().parent
PROJECT_DIR = BASE_DIR.parent
@@ -547,6 +549,7 @@ async def lifespan(_app: FastAPI):
duty_task = asyncio.create_task(reminder_loop(
duty_path, _db_path.with_name("duty-reminders.db"), duty_accounts, _send_email,
os.getenv("WORKLOG_DUTY_EMAILS", str(_db_path.parent / "duty-emails.json")),
_site_base_url(),
))
try:
yield
@@ -639,7 +642,7 @@ async def security_headers(request: Request, call_next):
"img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; "
"frame-ancestors 'none'; form-action 'self'"
)
if request.url.path.startswith(("/api/", "/join/")):
if request.url.path.startswith(("/api/", "/join/", "/duty-confirm/")):
response.headers["Cache-Control"] = "no-store"
return response
@@ -1147,15 +1150,84 @@ async def update_me(payload: ProfileIn, user: dict = Depends(current_user), db:
# ---------------------------------------------------------------- 成员
@app.get("/api/duty/current")
async def current_duty(_viewer: dict = Depends(current_user)) -> dict:
async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession = Depends(get_db)) -> dict:
path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json")))
if not path.exists():
return duty_status({"enabled": False}, datetime.now(BEIJING))
try:
return duty_status(load_schedule(path), datetime.now(BEIJING))
data = duty_status(load_schedule(path), datetime.now(BEIJING))
accounts = [dict(r) for r in (await db.execute(select(users.c.display_name, users.c.email))).mappings()]
overrides = _duty_overrides()
for shift in (data["current"], data["next"]):
if not shift:
continue
recipients, _ = resolve_recipients({name: [shift["slot"]] for name in shift["names"]}, accounts, overrides)
emails = {name: email for email, names in recipients.items() for name in names}
day = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING).date().isoformat()
shift["reminders"] = [await asyncio.to_thread(duty_receipts.status, _duty_state(), day, shift["slot"], name, emails.get(name), time.time()) for name in shift["names"]]
return data
except (ValueError, KeyError, TypeError, OSError) as exc:
raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc
def _duty_state():
return _db_path.with_name("duty-reminders.db")
@app.post("/api/auth/test-email")
async def test_account_email(viewer: dict = Depends(current_user)):
email = viewer.get("email", "").strip()
if not email:
raise HTTPException(status_code=409, detail="当前账号尚未绑定邮箱")
if not await asyncio.to_thread(duty_receipts.reserve_test, _duty_state(), email, time.time()):
raise HTTPException(status_code=429, detail="同一邮箱2分钟内只能测试一次,请稍后重试", headers={"Retry-After": "120"})
await _send_email(email, "【WorkLog】邮箱连通性测试", "这是一封由你在账号设置中主动发送的测试邮件。收到本邮件表示当前邮件发送服务可以向你的绑定邮箱投递邮件。\n\nWorkLog")
return {"ok": True, "retry_after": 120}
def _duty_overrides():
import json
path = Path(os.getenv("WORKLOG_DUTY_EMAILS", str(_db_path.parent / "duty-emails.json")))
return json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {}
class DutyRemindIn(BaseModel):
name: str = Field(min_length=1, max_length=64)
start_at: int
@app.post("/api/duty/remind")
async def remind_duty(payload: DutyRemindIn, viewer: dict = Depends(current_user), db: AsyncSession = Depends(get_db)):
data = await current_duty(viewer, db)
shift = next((s for s in (data["current"], data["next"]) if s and s["start_at"] == payload.start_at and payload.name in s["names"]), None)
if not shift:
raise HTTPException(status_code=409, detail="值班安排已变化,请刷新页面")
accounts = [dict(r) for r in (await db.execute(select(users.c.display_name, users.c.email))).mappings()]
recipients, _ = resolve_recipients({payload.name: [shift["slot"]]}, accounts, _duty_overrides())
if not recipients:
raise HTTPException(status_code=409, detail="未找到唯一的绑定邮箱,请核对姓名和账号")
email = next(iter(recipients))
start = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING)
try:
sent = await duty_receipts.send_notice(_duty_state(), start.date().isoformat(), {payload.name: [shift["slot"]]}, email, shift["end_at"] / 1000, _send_email, "值班提醒", f"日期:{start:%Y-%m-%d},{start:%H:%M} 开始(北京时间)", _site_base_url())
except HTTPException:
raise
if not sent:
raise HTTPException(status_code=429, detail="已确认、已达3次上限或距上次发送不足1分钟")
return {"ok": True}
@app.get("/duty-confirm/{token}", include_in_schema=False)
@app.post("/duty-confirm/{token}", include_in_schema=False)
async def confirm_duty(token: str, request: Request):
targets = await asyncio.to_thread(duty_receipts.confirmation, _duty_state(), token, time.time(), request.method == "POST")
if targets is None:
return HTMLResponse(_join_page("确认链接无效或本轮值班已结束。", "err"), status_code=410)
text = ";".join(f"{day} {slot} {name}" for day, slot, name in targets)
if request.method == "GET":
return HTMLResponse(_join_page("请确认已知晓:" + text, "confirm", extra='<form method="post"><button class="btn" type="submit">确认已知晓值班安排</button></form>'))
return HTMLResponse(_join_page("已确认值班安排,谢谢。", "ok"))
@app.get("/api/stats/overview")
async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(current_user)) -> dict:
members = int((await db.execute(select(func.count()).select_from(users))).scalar() or 0)