Files
worklog/server/duty_receipts.py
T

108 lines
5.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""值班提醒回执;独立 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