Files
worklog/server/duty_receipts.py

192 lines
10 KiB
Python
Raw Permalink 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.
"""值班提醒回执、确认表单nonce、邮件按钮测试和旧缺勤记录兼容。"""
import json
import secrets
import sqlite3
import time
from contextlib import closing
from html import escape
from .security import token_digest
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)")
con.execute("CREATE TABLE IF NOT EXISTS duty_confirmation_forms (digest TEXT PRIMARY KEY, nonce_hash TEXT NOT NULL)")
con.execute("CREATE TABLE IF NOT EXISTS mail_button_tests (digest TEXT PRIMARY KEY, kind TEXT NOT NULL, expires REAL NOT NULL, confirmed REAL NOT NULL DEFAULT 0)")
return con
def ensure(con, day, slot, name, email):
# 导入旧版成功发送记录;新版已有回执后不重复导入。
count, last = 0, 0
exists = con.execute("SELECT 1 FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone()
if not exists and email and con.execute("SELECT 1 FROM sqlite_master WHERE name='deliveries'").fetchone():
# 只有当前任务已发送的记录才能算作既有回执;旧表可能由当前调度器
# 预先写入 sending/failed,不能因为新行刚刚创建就把 slot 判成已发过。
rows = con.execute("SELECT updated FROM deliveries WHERE email=? AND status='sent' AND updated > 0 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 (?,?,?)", (token_digest(token), 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 confirm_on_site(path, day, slot, name, email, now, end_at):
if now >= end_at:
return None
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
ensure(con, day, slot, name, email)
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))
confirmed = con.execute("SELECT confirmed FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone()[0]
con.commit()
return int(confirmed * 1000)
def issue_confirmation_form(path, token, now):
with closing(connect(path)) as con:
digest = token_digest(token)
row = con.execute("SELECT expires FROM duty_confirmations WHERE digest=?", (digest,)).fetchone()
if row is None or row[0] <= now:
return None
nonce = secrets.token_urlsafe(32)
con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, token_digest(nonce)))
con.commit()
return nonce
def issue_activity_form(path, token, namespace='activity'):
digest = token_digest(namespace + ':' + token)
nonce = secrets.token_urlsafe(32)
with closing(connect(path)) as con:
con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, token_digest(nonce)))
con.commit()
return nonce
def validate_activity_form(path, token, nonce, namespace='activity'):
if not nonce:
return False
digest = token_digest(namespace + ':' + token)
with closing(connect(path)) as con:
row = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (digest,)).fetchone()
return bool(row and secrets.compare_digest(row[0], token_digest(nonce)))
def confirmation(path, token, now, consume=False, form_token=None, require_form=False):
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
row = con.execute("SELECT * FROM duty_confirmations WHERE digest=?", (token_digest(token),)).fetchone()
if row is None or row["expires"] <= now:
return None
if consume and require_form:
form = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (token_digest(token),)).fetchone()
if form is None or not form_token or not secrets.compare_digest(form[0], token_digest(form_token)):
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
def create_button_test(path, kind, now):
token = secrets.token_urlsafe(32)
with closing(connect(path)) as con:
con.execute("INSERT INTO mail_button_tests(digest,kind,expires) VALUES (?,?,?)", (token_digest(token), kind, now + 86400))
con.commit()
return token
def button_test(path, token, now, consume=False):
digest = token_digest(token)
with closing(connect(path)) as con:
row = con.execute("SELECT * FROM mail_button_tests WHERE digest=? AND expires>?", (digest, now)).fetchone()
if not row:
return None
if consume:
con.execute("UPDATE mail_button_tests SET confirmed=CASE WHEN confirmed=0 THEN ? ELSE confirmed END WHERE digest=?", (now, digest))
con.commit()
return row['kind']
def absence_records(path, limit=50, offset=0):
"""只读兼容历史缺勤记录,不再创建、生成或补记缺勤。"""
if not path.exists():
return []
with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True)) as con:
con.row_factory = sqlite3.Row
if not con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='duty_absences'").fetchone():
return []
rows = con.execute("SELECT * FROM duty_absences ORDER BY day DESC,end_at DESC,name LIMIT ? OFFSET ?", (limit, offset)).fetchall()
return [{"day": r['day'], "slot": r['slot'], "name": r['name'], "end_at": int(r['end_at'] * 1000), "recorded_at": int(r['recorded_at'] * 1000), "reason": "未确认缺勤"} for r in rows]
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