789 lines
32 KiB
Python
789 lines
32 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""HTTP 层(零依赖):http.server + 手写路由。
|
||
|
||
启动:
|
||
python -m backend.app # 默认 http://127.0.0.1:8000
|
||
python -m backend.app --port 8080
|
||
打开 http://127.0.0.1:8000/ 就是接口控制台(可一键跑完整流程)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import base64
|
||
import json
|
||
import mimetypes
|
||
import os
|
||
import re
|
||
import sys
|
||
import traceback
|
||
from dataclasses import dataclass, field
|
||
from http import HTTPStatus
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
from pathlib import Path
|
||
from urllib.parse import parse_qs, urlparse
|
||
|
||
from . import db as dbm
|
||
from . import kp_graph, ocr_budget, qr, tencent_ocr
|
||
from . import scanflow, services as svc
|
||
from .services import ApiError
|
||
|
||
HERE = Path(__file__).resolve().parent
|
||
ROOT = HERE.parent
|
||
WORKBENCH = ROOT / "prototype" / "workbench" / "index.html"
|
||
BRAND_DIR = ROOT / "brand"
|
||
ROUTES: list[tuple[str, re.Pattern, object, str]] = []
|
||
|
||
# 生产环境(QINGLING_ENV=prod)不注册这两组路由:
|
||
# /api/dev/* 能清库、能签年卡、能伪造扫码登录,只该在本地存在;
|
||
# /api/auth/sms-* 这一版没接短信服务商,验证码是随响应回显的,
|
||
# 线上等于「任意手机号都能直接注册并登录」。
|
||
PROD = os.environ.get("QINGLING_ENV", "dev").strip().lower() in ("prod", "production")
|
||
DEV_ONLY_PREFIXES = ("/api/dev/", "/api/auth/sms-")
|
||
MAX_BODY = 16 * 1024 * 1024 # 与 Caddy 的 request_body max_size 对齐
|
||
|
||
# 只有「要贴到新标签页/发给他人的链接」才允许把令牌放在 query 里。
|
||
# 其它接口一律走 Authorization 头——令牌进 URL 会被反代 access log 明文记下来。
|
||
QUERY_TOKEN_PATHS = (
|
||
re.compile(r"^/api/export/csv$"),
|
||
re.compile(r"^/api/print/weekly$"),
|
||
)
|
||
|
||
|
||
def query_token_ok(path: str) -> bool:
|
||
return any(p.match(path) for p in QUERY_TOKEN_PATHS)
|
||
CORS_ORIGINS = [o.strip() for o in
|
||
(os.environ.get("QINGLING_CORS") or ("*" if not PROD else "")).split(",")
|
||
if o.strip()]
|
||
|
||
|
||
def route(method: str, pattern: str, auth: str = "parent"):
|
||
"""auth: parent | child_ok | none
|
||
|
||
生产环境里 DEV_ONLY_PREFIXES 命中的路由直接不注册——请求会落到 404,
|
||
而不是「注册了但返回 403」,这样连「这个接口存在」都不泄漏。
|
||
"""
|
||
def deco(fn):
|
||
if PROD and pattern.startswith(DEV_ONLY_PREFIXES):
|
||
return fn
|
||
ROUTES.append((method, re.compile("^" + pattern + "$"), fn, auth))
|
||
return fn
|
||
return deco
|
||
|
||
|
||
@dataclass
|
||
class Ctx:
|
||
conn: object
|
||
method: str
|
||
path: str
|
||
query: dict
|
||
body: dict
|
||
headers: dict
|
||
token: str | None = None
|
||
guardian_id: str | None = None
|
||
raw_body: bytes = b""
|
||
|
||
def q(self, name: str, default: str = "") -> str:
|
||
v = self.query.get(name)
|
||
return v[0] if v else default
|
||
|
||
@property
|
||
def gid(self) -> str:
|
||
if not self.guardian_id:
|
||
raise ApiError(401, "UNAUTHORIZED", "没有登录")
|
||
return self.guardian_id
|
||
|
||
|
||
# ------------------------------------------------------------------ 路由
|
||
|
||
@route("GET", "/api/health", auth="none")
|
||
def health(ctx: Ctx, **kw):
|
||
try: # 顺手清理过期的删号申请与会话(各一次索引查询,很便宜)
|
||
svc.purge_due(ctx.conn)
|
||
svc.purge_expired_sessions(ctx.conn)
|
||
svc.sweep_uploads(ctx.conn) # 上传目录按 90 天清,内部自己限每天一次
|
||
except Exception:
|
||
pass
|
||
# 上线自查用:OCR 凭据配没配、这个月还剩多少次、缓存开没开。
|
||
# 故意不暴露密钥本身,只说「有没有」。
|
||
try:
|
||
ocr_state = {
|
||
"configured": tencent_ocr.available(),
|
||
"mode": tencent_ocr.mode(),
|
||
"cache": os.environ.get("OCR_CACHE", "") not in ("0", "false", "no", "off"),
|
||
"used": ocr_budget.used(),
|
||
"limit": ocr_budget.limit() or None,
|
||
"remaining": ocr_budget.remaining(),
|
||
}
|
||
except Exception:
|
||
ocr_state = {"configured": None}
|
||
return {"ok": True, "service": "qingling-primary", "version": "1.2.0", "time": dbm.now(),
|
||
"wx_mode": svc.wechat.mode(), "routes": len(ROUTES), "ocr": ocr_state}
|
||
|
||
|
||
@route("POST", "/api/auth/wx-login", auth="none")
|
||
def wx_login(ctx: Ctx, **kw):
|
||
code = str(ctx.body.get("code") or "").strip()
|
||
return svc.login(ctx.conn, code)
|
||
|
||
|
||
@route("POST", "/api/auth/sms-code", auth="none")
|
||
def sms_code(ctx: Ctx, **kw):
|
||
return svc.send_sms_code(ctx.conn, ctx.body.get("phone"))
|
||
|
||
|
||
@route("POST", "/api/auth/sms-login", auth="none")
|
||
def sms_login(ctx: Ctx, **kw):
|
||
return svc.login_phone(ctx.conn, ctx.body.get("phone"), ctx.body.get("code"))
|
||
|
||
|
||
@route("GET", "/api/notifications", auth="parent")
|
||
def notifications(ctx: Ctx, **kw):
|
||
return svc.list_notifications(ctx.conn, ctx.gid, int(ctx.q("limit") or 10))
|
||
|
||
|
||
@route("POST", "/api/auth/web-ticket", auth="parent")
|
||
def web_ticket(ctx: Ctx, **kw):
|
||
return svc.create_web_ticket(ctx.conn, ctx.gid, str(ctx.body.get("base_url") or ""))
|
||
|
||
|
||
@route("POST", "/api/auth/ticket-login", auth="none")
|
||
def ticket_login(ctx: Ctx, **kw):
|
||
return svc.login_ticket(ctx.conn, ctx.body.get("ticket"))
|
||
|
||
|
||
@route("POST", "/api/auth/scan-start", auth="none")
|
||
def scan_start(ctx: Ctx, **kw):
|
||
base = str(ctx.body.get("base_url") or "").strip()
|
||
if not base:
|
||
host = ctx.headers.get("Host") or "127.0.0.1:8000"
|
||
proto = ctx.headers.get("X-Forwarded-Proto") or "http"
|
||
base = f"{proto}://{host}"
|
||
return svc.scan_start(ctx.conn, base)
|
||
|
||
|
||
@route("GET", "/api/auth/scan-status", auth="none")
|
||
def scan_status(ctx: Ctx, **kw):
|
||
return svc.scan_status(ctx.conn, ctx.q("code"))
|
||
|
||
|
||
@route("POST", "/api/auth/scan-confirm", auth="parent")
|
||
def scan_confirm(ctx: Ctx, **kw):
|
||
return svc.scan_confirm(ctx.conn, ctx.gid, ctx.body.get("code"))
|
||
|
||
|
||
@route("GET", "/api/auth/scan-qr.svg", auth="none")
|
||
def scan_qr_svg(ctx: Ctx, **kw):
|
||
code = (ctx.q("code") or "").strip().upper()
|
||
if not code:
|
||
raise ApiError(400, "BAD_CODE", "缺少登录码")
|
||
try:
|
||
matrix = qr.encode(code)
|
||
except ValueError as e:
|
||
raise ApiError(400, "BAD_CODE", str(e))
|
||
return ("svg", qr.svg(matrix, scale=10, margin=4))
|
||
|
||
|
||
@route("GET", "/api/auth/scan-qr.png", auth="none")
|
||
def scan_qr(ctx: Ctx, **kw):
|
||
ok, data, why = svc.wechat.wxacode(ctx.q("code"))
|
||
if not ok:
|
||
raise ApiError(404, "NO_QRCODE", why)
|
||
return ("png", data)
|
||
|
||
|
||
@route("POST", "/api/dev/scan-confirm", auth="none")
|
||
def dev_scan_confirm(ctx: Ctx, **kw):
|
||
return svc.dev_scan_confirm(ctx.conn, ctx.body.get("code"))
|
||
|
||
|
||
@route("POST", "/api/auth/logout", auth="parent")
|
||
def logout(ctx: Ctx, **kw):
|
||
ctx.conn.execute("DELETE FROM sessions WHERE token=?", (ctx.token,))
|
||
return {"ok": True}
|
||
|
||
|
||
@route("GET", "/api/me", auth="parent")
|
||
def me(ctx: Ctx, **kw):
|
||
row = ctx.conn.execute("SELECT * FROM guardians WHERE id=?", (ctx.gid,)).fetchone()
|
||
return {"guardian": dbm.row_to_dict(row),
|
||
"children": svc.list_children(ctx.conn, ctx.gid),
|
||
"consent": svc.consent_status(ctx.conn, ctx.gid),
|
||
"deletion": svc.deletion_status(ctx.conn, ctx.gid)}
|
||
|
||
|
||
@route("DELETE", "/api/me", auth="parent")
|
||
def delete_me(ctx: Ctx, **kw):
|
||
"""删号:进 7 天冷静期,可撤销;到期由 purge_due 真删。
|
||
|
||
立刻作废所有令牌,所以调用方要自己清本地登录态。
|
||
"""
|
||
return svc.request_deletion(ctx.conn, ctx.gid, str(ctx.body.get("reason") or ""))
|
||
|
||
|
||
@route("POST", "/api/me/cancel-deletion", auth="parent")
|
||
def cancel_delete_me(ctx: Ctx, **kw):
|
||
return svc.cancel_deletion(ctx.conn, ctx.gid)
|
||
|
||
|
||
@route("GET", "/api/consent", auth="parent")
|
||
def get_consent(ctx: Ctx, **kw):
|
||
return svc.consent_status(ctx.conn, ctx.gid)
|
||
|
||
|
||
@route("POST", "/api/consent", auth="parent")
|
||
def post_consent(ctx: Ctx, **kw):
|
||
return svc.give_consent(ctx.conn, ctx.gid, str(ctx.body.get("version") or svc.CONSENT_VERSION))
|
||
|
||
|
||
@route("POST", "/api/consent/revoke", auth="parent")
|
||
def post_consent_revoke(ctx: Ctx, **kw):
|
||
return svc.revoke_consent(ctx.conn, ctx.gid)
|
||
|
||
|
||
@route("GET", "/api/children", auth="parent")
|
||
def get_children(ctx: Ctx, **kw):
|
||
return {"items": svc.list_children(ctx.conn, ctx.gid)}
|
||
|
||
|
||
@route("POST", "/api/children", auth="parent")
|
||
def post_children(ctx: Ctx, **kw):
|
||
return svc.create_child(ctx.conn, ctx.gid,
|
||
nickname=ctx.body.get("nickname"),
|
||
grade=int(ctx.body.get("grade") or 0),
|
||
subjects=ctx.body.get("subjects") or ("math", "chinese"),
|
||
remind_at=ctx.body.get("remind_at") or "19:30")
|
||
|
||
|
||
@route("GET", r"/api/children/(?P<cid>[^/]+)", auth="parent")
|
||
def get_child(ctx: Ctx, cid: str, **kw):
|
||
return svc.get_child(ctx.conn, ctx.gid, cid)
|
||
|
||
|
||
@route("DELETE", r"/api/children/(?P<cid>[^/]+)", auth="parent")
|
||
def del_child(ctx: Ctx, cid: str, **kw):
|
||
return svc.delete_child(ctx.conn, ctx.gid, cid)
|
||
|
||
|
||
@route("POST", r"/api/children/(?P<cid>[^/]+)/session", auth="parent")
|
||
def child_session(ctx: Ctx, cid: str, **kw):
|
||
svc.get_child(ctx.conn, ctx.gid, cid)
|
||
token = svc.make_token(cid, kind="child", ttl=svc.CHILD_TOKEN_TTL)
|
||
return {"child_token": token, "expires_in": svc.CHILD_TOKEN_TTL, "child_id": cid}
|
||
|
||
|
||
@route("POST", "/api/papers", auth="parent")
|
||
def post_paper(ctx: Ctx, **kw):
|
||
return svc.create_paper(ctx.conn, ctx.gid, str(ctx.body.get("child_id") or ""),
|
||
str(ctx.body.get("subject") or "math"),
|
||
int(ctx.body.get("image_count") or 1))
|
||
|
||
|
||
def _decode_image(ctx: Ctx) -> bytes:
|
||
raw = str(ctx.body.get("image_b64") or "")
|
||
if "," in raw[:80] and raw.lstrip().startswith("data:"):
|
||
raw = raw.split(",", 1)[1]
|
||
try:
|
||
return base64.b64decode(raw, validate=False)
|
||
except Exception: # noqa: BLE001
|
||
raise svc.ApiError(400, "BAD_IMAGE", "图片不是合法的 base64")
|
||
|
||
|
||
@route("POST", "/api/papers/scan/detect", auth="parent")
|
||
def post_scan_detect(ctx: Ctx, **kw):
|
||
"""整页拍 → 切块 → 返回每块的框,让家长在图上点「哪几道错了」。"""
|
||
image = _decode_image(ctx)
|
||
return scanflow.detect(image, str(ctx.body.get("filename") or "page.jpg"))
|
||
|
||
|
||
@route("POST", "/api/papers/scan/prepare", auth="parent")
|
||
def post_scan_prepare(ctx: Ctx, **kw):
|
||
"""入库前预览:勾中的块里到底有哪几道(口算卡一块十几道,要逐条勾)。"""
|
||
picks = ctx.body.get("picks") or []
|
||
if not isinstance(picks, list):
|
||
raise svc.ApiError(400, "BAD_PICKS", "picks 要是数组")
|
||
return svc.prepare_scan_picks(
|
||
ctx.conn, ctx.gid, str(ctx.body.get("child_id") or ""),
|
||
str(ctx.body.get("subject") or "math"), str(ctx.body.get("draft_id") or ""), picks)
|
||
|
||
|
||
@route("POST", "/api/papers/scan/import", auth="parent")
|
||
def post_scan_import(ctx: Ctx, **kw):
|
||
"""家长勾完 → 只把选中的块裁出来单独识别并入库。"""
|
||
picks = ctx.body.get("picks") or []
|
||
if not isinstance(picks, list):
|
||
raise svc.ApiError(400, "BAD_PICKS", "picks 要是数组")
|
||
return svc.import_scan_picks(
|
||
ctx.conn, ctx.gid, str(ctx.body.get("child_id") or ""),
|
||
str(ctx.body.get("subject") or "math"), str(ctx.body.get("draft_id") or ""), picks)
|
||
|
||
|
||
@route("POST", "/api/papers/ocr", auth="parent")
|
||
def post_paper_ocr(ctx: Ctx, **kw):
|
||
"""真拍照:图片 base64 → OCR → 切题 → 入库。OCR 不可用时按参数退回演示题库。"""
|
||
raw = str(ctx.body.get("image_b64") or "")
|
||
if "," in raw[:80] and raw.lstrip().startswith("data:"):
|
||
raw = raw.split(",", 1)[1]
|
||
try:
|
||
image = base64.b64decode(raw, validate=False)
|
||
except Exception: # noqa: BLE001
|
||
raise svc.ApiError(400, "BAD_IMAGE", "图片不是合法的 base64")
|
||
return svc.create_paper_from_image(
|
||
ctx.conn, ctx.gid, str(ctx.body.get("child_id") or ""),
|
||
str(ctx.body.get("subject") or "math"), image,
|
||
filename=str(ctx.body.get("filename") or "page.jpg"),
|
||
fallback_demo=bool(ctx.body.get("fallback_demo", True)))
|
||
|
||
|
||
@route("GET", r"/api/papers/(?P<pid>[^/]+)", auth="parent")
|
||
def get_paper(ctx: Ctx, pid: str, **kw):
|
||
return svc.get_paper(ctx.conn, ctx.gid, ctx.q("child_id"), pid)
|
||
|
||
|
||
@route("PATCH", r"/api/questions/(?P<qid>[^/]+)", auth="parent")
|
||
def patch_question(ctx: Ctx, qid: str, **kw):
|
||
return svc.set_verdict(ctx.conn, ctx.gid, qid, str(ctx.body.get("verdict") or ""))
|
||
|
||
|
||
@route("POST", "/api/mistakes/import", auth="parent")
|
||
def import_mistakes(ctx: Ctx, **kw):
|
||
return svc.import_mistakes(ctx.conn, ctx.gid, str(ctx.body.get("child_id") or ""),
|
||
list(ctx.body.get("question_ids") or []))
|
||
|
||
|
||
@route("POST", "/api/mistakes/manual", auth="parent")
|
||
def add_manual(ctx: Ctx, **kw):
|
||
return svc.add_manual_mistake(
|
||
ctx.conn, ctx.gid, str(ctx.body.get("child_id") or ""),
|
||
str(ctx.body.get("subject") or "math"), str(ctx.body.get("stem") or ""),
|
||
ctx.body.get("answer"), ctx.body.get("judge_type"),
|
||
ctx.body.get("options"), str(ctx.body.get("wrong_code") or "E4"))
|
||
|
||
|
||
@route("GET", "/api/mistakes", auth="parent")
|
||
def get_mistakes(ctx: Ctx, **kw):
|
||
return svc.list_mistakes(ctx.conn, ctx.gid, ctx.q("child_id"),
|
||
ctx.q("status") or None)
|
||
|
||
|
||
@route("GET", "/api/today", auth="parent")
|
||
def get_today(ctx: Ctx, **kw):
|
||
return svc.today_queue(ctx.conn, ctx.gid, ctx.q("child_id"),
|
||
ctx.q("subject") or None)
|
||
|
||
|
||
def _child_id(ctx: Ctx) -> str:
|
||
"""允许孩子令牌:令牌里绑的就是 child_id,忽略请求体里的。"""
|
||
if ctx.token and ctx.token.startswith("child:"):
|
||
return ctx.token.split(":", 1)[1]
|
||
return str(ctx.body.get("child_id") or ctx.q("child_id"))
|
||
|
||
|
||
@route("POST", r"/api/mistakes/(?P<mid>[^/]+)/attempt", auth="child_ok")
|
||
def post_attempt(ctx: Ctx, mid: str, **kw):
|
||
return svc.attempt(ctx.conn, ctx.gid, _child_id(ctx), mid,
|
||
str(ctx.body.get("answer") or ""),
|
||
ctx.body.get("cost_ms"))
|
||
|
||
|
||
@route("POST", r"/api/mistakes/(?P<mid>[^/]+)/self-judge", auth="child_ok")
|
||
def post_self_judge(ctx: Ctx, mid: str, **kw):
|
||
"""没有标准答案的题:孩子自己判对错。"""
|
||
return svc.self_judge(ctx.conn, ctx.gid, _child_id(ctx), mid,
|
||
bool(ctx.body.get("correct")),
|
||
str(ctx.body.get("note") or ""))
|
||
|
||
|
||
@route("POST", r"/api/mistakes/(?P<mid>[^/]+)/skip", auth="child_ok")
|
||
def post_skip(ctx: Ctx, mid: str, **kw):
|
||
return svc.skip(ctx.conn, ctx.gid, _child_id(ctx), mid)
|
||
|
||
|
||
@route("GET", r"/api/mistakes/(?P<mid>[^/]+)/similar", auth="parent")
|
||
def get_similar(ctx: Ctx, mid: str, **kw):
|
||
"""举一反三:这道错题的同类变式(工作台「再练一道」用)。"""
|
||
n = int(ctx.q("n") or 3)
|
||
return svc.similar_mistakes(ctx.conn, ctx.gid, ctx.q("child_id"), mid, n=max(1, min(n, 5)))
|
||
|
||
|
||
@route("POST", r"/api/mistakes/(?P<mid>[^/]+)/explain", auth="child_ok")
|
||
def post_explain(ctx: Ctx, mid: str, **kw):
|
||
return svc.explain(ctx.conn, ctx.gid, _child_id(ctx), mid,
|
||
str(ctx.body.get("channel") or "ai_voice"),
|
||
str(ctx.body.get("text") or ""))
|
||
|
||
|
||
@route("GET", r"/api/kp-graph/(?P<kp>[^/]+)", auth="none")
|
||
def kp_detail(ctx: Ctx, kp: str, **kw):
|
||
"""知识点 + 前置 + 退一层建议(工作台「学情分析」与「讲一遍」用)。"""
|
||
t = kp_graph.topic(kp)
|
||
if not t:
|
||
raise ApiError(404, "NO_KP", "没有这个知识点")
|
||
return {"topic": t, "parents": kp_graph.parents(kp),
|
||
"chain": kp_graph.chain(kp), "retreat": kp_graph.retreat(kp)}
|
||
|
||
|
||
@route("GET", "/api/report/weekly", auth="parent")
|
||
def weekly(ctx: Ctx, **kw):
|
||
return svc.weekly_report(ctx.conn, ctx.gid, ctx.q("child_id"),
|
||
ctx.q("week_of") or None)
|
||
|
||
|
||
@route("GET", "/api/export/csv", auth="none")
|
||
def export_csv(ctx: Ctx, **kw):
|
||
cid = ctx.q("child_id")
|
||
return ("csv", svc.export_csv(ctx.conn, ctx.gid, cid), "qingling-export.csv")
|
||
|
||
|
||
@route("GET", "/api/print/weekly", auth="none")
|
||
def print_weekly(ctx: Ctx, **kw):
|
||
return ("html", svc.weekly_sheet_html(ctx.conn, ctx.gid, ctx.q("child_id"),
|
||
ctx.q("week_of") or None))
|
||
|
||
|
||
@route("GET", "/api/entitlement", auth="parent")
|
||
def get_entitlement(ctx: Ctx, **kw):
|
||
return svc.entitlement(ctx.conn, ctx.gid)
|
||
|
||
|
||
@route("POST", "/api/entitlement/redeem", auth="parent")
|
||
def post_redeem(ctx: Ctx, **kw):
|
||
return svc.redeem_code(ctx.conn, ctx.gid, ctx.body.get("code") or "")
|
||
|
||
|
||
@route("POST", "/api/dev/issue-codes", auth="none")
|
||
def dev_issue_codes(ctx: Ctx, **kw):
|
||
codes = svc.issue_codes(ctx.conn, int(ctx.body.get("count") or 1),
|
||
ctx.body.get("kind") or "trial7")
|
||
return {"codes": codes, "kind": ctx.body.get("kind") or "trial7"}
|
||
|
||
|
||
@route("POST", "/api/dev/demo-data", auth="parent")
|
||
def dev_demo_data(ctx: Ctx, **kw):
|
||
"""给当前家长装一份演示数据(小程序里「填充演示数据」按钮用)。"""
|
||
return svc.demo_data(ctx.conn, ctx.gid,
|
||
nickname=ctx.body.get("nickname") or "皮皮",
|
||
grade=int(ctx.body.get("grade") or 2))
|
||
|
||
|
||
@route("GET", "/api/wx/config", auth="none")
|
||
def wx_config(ctx: Ctx, **kw):
|
||
"""前端判断要不要显示「微信登录 / 订阅消息」的真实状态。"""
|
||
return {
|
||
"mode": svc.wechat.mode(),
|
||
"appid": svc.wechat.appid(),
|
||
"appid_set": bool(svc.wechat.appid()),
|
||
"secret_set": bool(svc.wechat.secret()),
|
||
"daily_template": svc.wechat.TMPL_DAILY,
|
||
"daily_template_set": bool(svc.wechat.TMPL_DAILY),
|
||
"pay_enabled": False,
|
||
"pay_reason": "个人主体小程序不能开通微信支付",
|
||
}
|
||
|
||
|
||
@route("POST", "/api/notify/subscribe", auth="parent")
|
||
def subscribe(ctx: Ctx, **kw):
|
||
"""用户点完 requestSubscribeMessage(同意了几条就传几个模板 ID)。"""
|
||
ids = ctx.body.get("template_ids") or ctx.body.get("tmpl_ids") or []
|
||
if isinstance(ids, str):
|
||
ids = [ids]
|
||
return svc.record_subscribe(ctx.conn, ctx.gid, list(ids))
|
||
|
||
|
||
@route("GET", "/api/notify/quota", auth="parent")
|
||
def quota(ctx: Ctx, **kw):
|
||
return svc.subscribe_quota(ctx.conn, ctx.gid)
|
||
|
||
|
||
@route("POST", "/api/orders", auth="parent")
|
||
def post_order(ctx: Ctx, **kw):
|
||
return svc.create_order(ctx.conn, ctx.gid, ctx.body.get("sku") or "term")
|
||
|
||
|
||
@route("GET", r"/api/orders/(?P<oid>[^/]+)", auth="parent")
|
||
def get_order(ctx: Ctx, oid: str, **kw):
|
||
return svc.get_order(ctx.conn, ctx.gid, oid)
|
||
|
||
|
||
@route("POST", r"/api/orders/(?P<oid>[^/]+)/pay", auth="parent")
|
||
def pay_order(ctx: Ctx, oid: str, **kw):
|
||
"""演示用「人工确认到账」。真实环境由支付回调或后台运营触发。"""
|
||
return svc.pay_order(ctx.conn, ctx.gid, oid)
|
||
|
||
|
||
@route("POST", "/api/wechat/pay-notify", auth="none")
|
||
def pay_notify(ctx: Ctx, **kw):
|
||
"""微信支付回调。个人主体没配 WX_PAY_KEY 时返回 501,不假装成功。"""
|
||
return svc.pay_notify(ctx.conn, ctx.headers, ctx.raw_body)
|
||
|
||
|
||
@route("GET", "/api/stats", auth="parent")
|
||
def get_stats(ctx: Ctx, **kw):
|
||
return svc.stats(ctx.conn, ctx.gid, ctx.q("child_id"))
|
||
|
||
|
||
@route("POST", "/api/dev/advance", auth="none")
|
||
def dev_advance(ctx: Ctx, **kw):
|
||
return svc.dev_advance(ctx.conn, int(ctx.body.get("days") or 1))
|
||
|
||
|
||
@route("POST", "/api/dev/notify-tick", auth="none")
|
||
def dev_notify(ctx: Ctx, **kw):
|
||
return svc.notifications_tick(ctx.conn, ctx.body.get("date"))
|
||
|
||
|
||
@route("POST", "/api/dev/reseed", auth="none")
|
||
def dev_reseed(ctx: Ctx, **kw):
|
||
from . import seed
|
||
ctx.conn.execute("PRAGMA foreign_keys=OFF")
|
||
dbm.reset_db(ctx.conn)
|
||
ctx.conn.execute("PRAGMA foreign_keys=ON")
|
||
return seed.seed(ctx.conn)
|
||
|
||
|
||
# ------------------------------------------------------------------ 服务器
|
||
|
||
class App(BaseHTTPRequestHandler):
|
||
server_version = "QinglingHTTP/1.0"
|
||
protocol_version = "HTTP/1.1"
|
||
|
||
def log_message(self, fmt, *args): # 安静一点
|
||
if os.environ.get("QINGLING_VERBOSE"):
|
||
sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))
|
||
|
||
# -- 工具
|
||
def _send(self, status: int, body: bytes, ctype: str, extra: dict | None = None):
|
||
self.send_response(status)
|
||
self.send_header("Content-Type", ctype)
|
||
self.send_header("Content-Length", str(len(body)))
|
||
# 开发默认 *(file:// 打开的原型要能访问本机服务);生产默认不发这个头,
|
||
# 需要跨域就把域名写进 QINGLING_CORS。
|
||
if CORS_ORIGINS:
|
||
origin = self.headers.get("Origin") or ""
|
||
if "*" in CORS_ORIGINS or origin in CORS_ORIGINS:
|
||
self.send_header("Access-Control-Allow-Origin", "*" if "*" in CORS_ORIGINS else origin)
|
||
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||
self.send_header("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||
# 让 file:// 打开的原型也能访问本机服务(Chrome 的 Private Network Access)
|
||
self.send_header("Access-Control-Allow-Private-Network", "true")
|
||
for k, v in (extra or {}).items():
|
||
self.send_header(k, v)
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
|
||
def _json(self, status: int, payload: dict):
|
||
body = json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8")
|
||
self._send(status, body, "application/json; charset=utf-8")
|
||
|
||
def _read_body(self) -> tuple[dict, bytes]:
|
||
try:
|
||
n = int(self.headers.get("Content-Length") or 0)
|
||
except (TypeError, ValueError):
|
||
raise ApiError(400, "BAD_LENGTH", "Content-Length 不是数字")
|
||
if n < 0:
|
||
raise ApiError(400, "BAD_LENGTH", "Content-Length 不能是负数")
|
||
if n > MAX_BODY:
|
||
# 直连 8000 时没有 Caddy 的 16MB 兜底,这里自己拦一道
|
||
raise ApiError(413, "BODY_TOO_LARGE", f"请求体太大了(上限 {MAX_BODY // (1024 * 1024)}MB)")
|
||
raw = self.rfile.read(n) if n else b""
|
||
if not raw:
|
||
return {}, raw
|
||
ctype = (self.headers.get("Content-Type") or "").lower()
|
||
if "application/json" in ctype or raw[:1] in (b"{", b"["):
|
||
try:
|
||
data = json.loads(raw.decode("utf-8"))
|
||
return (data if isinstance(data, dict) else {"items": data}), raw
|
||
except json.JSONDecodeError:
|
||
raise ApiError(400, "BAD_JSON", "请求体不是合法 JSON")
|
||
# 表单
|
||
form = parse_qs(raw.decode("utf-8"), keep_blank_values=True)
|
||
return {k: v[0] for k, v in form.items()}, raw
|
||
|
||
def _resolve_auth(self, ctx: Ctx, mode: str):
|
||
if mode == "none":
|
||
return
|
||
auth = self.headers.get("Authorization") or ""
|
||
token = auth[7:].strip() if auth.lower().startswith("bearer ") else None
|
||
if not token and query_token_ok(ctx.path):
|
||
token = (ctx.query.get("token") or [None])[0]
|
||
if not token:
|
||
raise ApiError(401, "UNAUTHORIZED", "缺少 Authorization: Bearer <token>")
|
||
ctx.token = token
|
||
# 先按家长令牌解
|
||
try:
|
||
sub = svc.parse_token(token, kind="parent")
|
||
except ApiError:
|
||
sub = None
|
||
if sub:
|
||
# 令牌本身是自签名的,但退出登录 / 申请删号要能立刻失效,
|
||
# 所以每次都要在 sessions 里对上号(一次主键查询,很便宜)。
|
||
alive = ctx.conn.execute("SELECT 1 FROM sessions WHERE token=?", (token,)).fetchone()
|
||
if alive is None:
|
||
raise ApiError(401, "SESSION_REVOKED", "登录已失效,请重新登录")
|
||
ctx.guardian_id = sub
|
||
return
|
||
if mode == "child_ok":
|
||
cid = svc.parse_token(token, kind="child") # 15 分钟的孩子会话
|
||
row = ctx.conn.execute("SELECT * FROM children WHERE id=? AND deleted_at IS NULL", (cid,)).fetchone()
|
||
if row is None:
|
||
raise ApiError(401, "UNAUTHORIZED", "孩子档案不存在")
|
||
ctx.guardian_id = row["guardian_id"]
|
||
ctx.token = "child:" + cid
|
||
return
|
||
# 不是家长令牌:如果是孩子令牌,明确告诉它「不能做家长操作」
|
||
try:
|
||
svc.parse_token(token, kind="child")
|
||
except ApiError:
|
||
raise ApiError(401, "UNAUTHORIZED", "登录已失效,请重新登录")
|
||
raise ApiError(403, "FORBIDDEN", "这是孩子会话,不能做家长操作")
|
||
|
||
def _dispatch(self, method: str):
|
||
parsed = urlparse(self.path)
|
||
path = parsed.path.rstrip("/") or "/"
|
||
query = parse_qs(parsed.query)
|
||
conn = dbm.connect()
|
||
try:
|
||
if method == "GET" and path in ("/", "/demo"):
|
||
return self._static("demo.html", "text/html; charset=utf-8")
|
||
if method == "GET" and path in ("/workbench", "/app"):
|
||
# 电脑 / 平板上的工作台(做题与反馈都在这边)
|
||
return self._file(WORKBENCH, "text/html; charset=utf-8")
|
||
if method == "GET" and (path == "/workbench.html" or path.startswith("/brand/")):
|
||
name = path.split("/")[-1]
|
||
target = BRAND_DIR / name if path.startswith("/brand/") else WORKBENCH
|
||
ctype = mimetypes.guess_type(str(target))[0] or "application/octet-stream"
|
||
return self._file(target, ctype)
|
||
if method == "GET" and path == "/docs":
|
||
return self._docs()
|
||
if method == "OPTIONS":
|
||
return self._json(204, {"ok": True})
|
||
body, raw = (self._read_body() if method in ("POST", "PATCH", "PUT") else ({}, b""))
|
||
ctx = Ctx(conn=conn, method=method, path=path, query=query,
|
||
body=body, headers=dict(self.headers), raw_body=raw)
|
||
if path.startswith("/api/print/") or path.startswith("/api/export/"):
|
||
# 打印与导出给的是免登录 token 链接(家长把链接发到电脑上打开)
|
||
t = (query.get("token") or [None])[0]
|
||
if not t:
|
||
raise ApiError(401, "UNAUTHORIZED", "链接缺少 token")
|
||
ctx.token = t
|
||
try:
|
||
ctx.guardian_id = svc.parse_token(t, kind="parent")
|
||
except ApiError:
|
||
cid = svc.parse_token(t, kind="child")
|
||
row = conn.execute("SELECT guardian_id FROM children WHERE id=?", (cid,)).fetchone()
|
||
if row is None:
|
||
raise ApiError(401, "UNAUTHORIZED", "链接已失效")
|
||
ctx.guardian_id = row["guardian_id"]
|
||
for m, pat, fn, mode in ROUTES:
|
||
if m != method:
|
||
continue
|
||
hit = pat.match(path)
|
||
if not hit:
|
||
continue
|
||
if not (path.startswith("/api/print/") or path.startswith("/api/export/")):
|
||
self._resolve_auth(ctx, mode)
|
||
if mode == "parent" and ctx.token and ctx.token.startswith("child:"):
|
||
raise ApiError(403, "FORBIDDEN", "这是孩子会话,不能做家长操作")
|
||
result = fn(ctx, **hit.groupdict())
|
||
if isinstance(result, dict):
|
||
return self._json(200, {"ok": True, "data": result})
|
||
if isinstance(result, tuple) and result and result[0] == "html":
|
||
return self._send(200, result[1].encode("utf-8"), "text/html; charset=utf-8")
|
||
if isinstance(result, tuple) and result and result[0] == "svg":
|
||
return self._send(200, result[1].encode("utf-8"), "image/svg+xml",
|
||
{"Cache-Control": "no-store"})
|
||
if isinstance(result, tuple) and result and result[0] == "png":
|
||
return self._send(200, result[1], "image/png", {"Cache-Control": "no-store"})
|
||
if isinstance(result, tuple) and result and result[0] == "jpg":
|
||
return self._send(200, result[1], "image/jpeg", {"Cache-Control": "no-store"})
|
||
if isinstance(result, tuple) and result and result[0] == "csv":
|
||
name = result[2] if len(result) > 2 else "export.csv"
|
||
return self._send(200, ("\ufeff" + result[1]).encode("utf-8"),
|
||
"text/csv; charset=utf-8",
|
||
{"Content-Disposition": f'attachment; filename="{name}"'})
|
||
return self._json(200, {"ok": True, "data": result})
|
||
raise ApiError(404, "NOT_FOUND", f"没有这个接口:{method} {path}")
|
||
except ApiError as e:
|
||
self._json(e.status, {"ok": False, "error": {"code": e.code, "message": e.message}})
|
||
except BrokenPipeError:
|
||
pass
|
||
except Exception as e: # noqa: BLE001
|
||
traceback.print_exc()
|
||
# 生产环境不把异常原文回给前端(会带出 SQL 和路径)
|
||
msg = "服务器内部错误,稍后再试" if PROD else str(e)
|
||
self._json(500, {"ok": False, "error": {"code": "INTERNAL", "message": msg}})
|
||
finally:
|
||
try:
|
||
conn.close()
|
||
except Exception:
|
||
pass
|
||
|
||
def _static(self, name: str, ctype: str):
|
||
p = HERE / "static" / name
|
||
if not p.exists():
|
||
return self._json(404, {"ok": False, "error": {"code": "NOT_FOUND", "message": name}})
|
||
self._send(200, p.read_bytes(), ctype)
|
||
|
||
def _file(self, p: Path, ctype: str):
|
||
if not p.exists() or not p.is_file():
|
||
return self._json(404, {"ok": False, "error": {"code": "NOT_FOUND", "message": p.name}})
|
||
self._send(200, p.read_bytes(), ctype)
|
||
|
||
def _docs(self):
|
||
rows = []
|
||
for m, pat, fn, mode in ROUTES:
|
||
rows.append(f"<tr><td><b>{m}</b></td><td><code>{pat.pattern[1:-1]}</code></td>"
|
||
f"<td>{mode}</td><td>{fn.__doc__ or ''}</td></tr>")
|
||
html = ("<!doctype html><meta charset='utf-8'><title>错题毕业 · 接口文档</title>"
|
||
"<style>body{font-family:system-ui,'Microsoft YaHei';margin:32px;color:#24211f}"
|
||
"table{border-collapse:collapse;width:100%;font-size:13px}"
|
||
"th,td{border-bottom:1px solid #e6dfd8;padding:8px;text-align:left}"
|
||
"th{background:#b3272d;color:#fff}code{background:#f5f1ed;padding:2px 5px;border-radius:3px}"
|
||
"h1{font-size:20px}</style>"
|
||
"<h1>错题毕业 · 小学版接口</h1>"
|
||
"<p>所有接口返回 <code>{ok:true,data:…}</code> 或 <code>{ok:false,error:{code,message}}</code>。"
|
||
"带 <code>Authorization: Bearer <token></code>。试跑:<a href='/'>接口控制台</a></p>"
|
||
"<table><tr><th>方法</th><th>路径</th><th>鉴权</th><th>说明</th></tr>"
|
||
+ "".join(rows) + "</table>")
|
||
self._send(200, html.encode("utf-8"), "text/html; charset=utf-8")
|
||
|
||
def do_GET(self):
|
||
self._dispatch("GET")
|
||
|
||
def do_POST(self):
|
||
self._dispatch("POST")
|
||
|
||
def do_PATCH(self):
|
||
self._dispatch("PATCH")
|
||
|
||
def do_DELETE(self):
|
||
self._dispatch("DELETE")
|
||
|
||
def do_OPTIONS(self):
|
||
self._dispatch("OPTIONS")
|
||
|
||
|
||
def serve(host: str = "127.0.0.1", port: int = 8000, db_path: str | None = None):
|
||
conn = dbm.connect(db_path)
|
||
dbm.init_db(conn)
|
||
conn.close()
|
||
httpd = ThreadingHTTPServer((host, port), App)
|
||
print(f"错题毕业 · 小学版后端已启动:http://{host}:{port}")
|
||
print(f" 接口控制台: http://{host}:{port}/")
|
||
print(f" 接口文档: http://{host}:{port}/docs")
|
||
print(f" 数据库: {db_path or dbm.DB_PATH}")
|
||
try:
|
||
httpd.serve_forever()
|
||
except KeyboardInterrupt:
|
||
print("\n已停止")
|
||
finally:
|
||
httpd.server_close()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
ap = argparse.ArgumentParser(description="错题毕业 · 小学版后端")
|
||
ap.add_argument("--host", default="127.0.0.1")
|
||
ap.add_argument("--port", type=int, default=8000)
|
||
ap.add_argument("--db", default=None)
|
||
a = ap.parse_args()
|
||
serve(a.host, a.port, a.db)
|