Peach: Local-first video metadata scraper and media manager.
refactor: isolate web contract application state
Peach local maintenance994c41a570d5
diff --git a/src/peach/api.py b/src/peach/api.pyindex 860076f4c..8420ed61a 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -35,8 +35,9 @@ def _authorized(request: Request, token: str, args: dict[str, str]) -> bool:def create_app(settings: PeachSettings | None = None) -> FastAPI:settings = settings or PeachSettings()- web_contract.DB = str(settings.db_path)- web_contract.cache_bust()+ contract = web_contract.WebContract(+ settings.db_path, settings.snapshot_root, settings.legacy_snapshot_roots,+ )repository = LedgerRepository(settings.db_path)resolver = FFmpegResolver(settings.ffmpeg_root)media_service = FilesystemMediaService(@@ -75,7 +76,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:openapi_url="/openapi.json" if settings.docs_enabled else None,)app.state.settings = settings- app.state.web_contract = web_contract+ app.state.web_contract = contractapp.state.repository = repositoryapp.state.media_service = media_serviceapp.state.preview_service = preview_service@@ -206,7 +207,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:if not _authorized(request, settings.token, args):return JSONResponse({"error": "unauthorized"}, status_code=401)try:- return web_contract.dispatch_api_get(f"/api/{route}", args)+ return web_contract.dispatch_api_get(contract, f"/api/{route}", args)except KeyError:return JSONResponse({"error": "not found"}, status_code=404)except (TypeError, ValueError) as exc:@@ -220,7 +221,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:if not _authorized(request, settings.token, args):return JSONResponse({"error": "unauthorized"}, status_code=401)try:- return web_contract.dispatch_api_post(f"/api/{route}", body)+ return web_contract.dispatch_api_post(contract, f"/api/{route}", body)except KeyError:return JSONResponse({"error": "not found"}, status_code=404)except (TypeError, ValueError) as exc:diff --git a/src/peach/web_contract.py b/src/peach/web_contract.pyindex d48c65e1a..40f467890 100644--- a/src/peach/web_contract.py+++ b/src/peach/web_contract.py@@ -11,45 +11,64 @@ import sqlite3import threadingimport timefrom pathlib import Path+from typing import Sequence-from .config import DATABASE_PATH---DB = str(DATABASE_PATH)+from .media import remap_managed_pathCOST = {"local": "free", "115": "free", "pikpak": "metered", "online": "metered"}FAVICON = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0B0B0D"/><defs><linearGradient id="pg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FF9A76"/><stop offset="1" stop-color="#F2557B"/></linearGradient></defs><path d="M16 28c-5.7 0-9.7-3.6-9.7-8.6 0-4.3 2.8-7.6 6.5-7.6 1.4 0 2.4.5 3.2 1.1.8-.6 1.8-1.1 3.2-1.1 3.7 0 6.5 3.3 6.5 7.6C25.7 24.4 21.7 28 16 28z" fill="url(#pg)"/><path d="M16 13.4V27" stroke="#0B0B0D" stroke-width="1.1" opacity=".3" stroke-linecap="round"/><path d="M17.1 11.7c.6-2.8 2.8-4.6 5.6-4.8-.2 2.8-2.2 4.7-5.6 4.8z" fill="#5FB95F"/><path d="M16 11.9c0-1.9.5-3.4 1.5-4.5" stroke="#8A5A3B" stroke-width="1.5" stroke-linecap="round" fill="none"/></svg>')-_lock = threading.Lock()--# 聚合类查询(facets / tops / stats)是多个全表 GROUP BY,索引帮不上,-# 但它们的结果变化很慢 —— 缓存 90 秒,写入操作主动失效。-_CACHE, _CACHE_LOCK = {}, threading.Lock()CACHE_TTL = 90-def cached(key, fn):- now = time.time()- with _CACHE_LOCK:- hit = _CACHE.get(key)- if hit and now - hit[0] < CACHE_TTL:- return hit[1]- val = fn()- with _CACHE_LOCK:- _CACHE[key] = (now, val)- return val-def cache_bust():- with _CACHE_LOCK:- _CACHE.clear()--def db(write=False):- target = DB if write else Path(DB).resolve().as_uri() + "?mode=ro"- c = sqlite3.connect(target, timeout=30, check_same_thread=False, uri=not write)- c.row_factory = sqlite3.Row- return c+++class WebContract:+ """单个应用实例的数据库、写锁和聚合缓存;不共享模块级可变状态。"""++ def __init__(self, db_path: Path, snapshot_root: Path | None = None,+ legacy_snapshot_roots: Sequence[Path] = ()):+ self.db_path = Path(db_path)+ self.snapshot_root = Path(snapshot_root) if snapshot_root is not None else None+ self.legacy_snapshot_roots = tuple(Path(path) for path in legacy_snapshot_roots)+ self.write_lock = threading.Lock()+ self.cache: dict[str, tuple[float, object]] = {}+ self.cache_lock = threading.Lock()++ def cached(self, key, fn):+ now = time.time()+ with self.cache_lock:+ hit = self.cache.get(key)+ if hit and now - hit[0] < CACHE_TTL:+ return hit[1]+ value = fn()+ with self.cache_lock:+ self.cache[key] = (now, value)+ return value++ def cache_bust(self):+ with self.cache_lock:+ self.cache.clear()++ def db(self, write=False):+ target = (str(self.db_path) if write else+ self.db_path.resolve().as_uri() + "?mode=ro")+ connection = sqlite3.connect(+ target, timeout=30, check_same_thread=False, uri=not write,+ )+ connection.row_factory = sqlite3.Row+ return connection++ def has_snapshot(self, raw_path: str | None) -> bool:+ if not raw_path:+ return False+ path = (remap_managed_path(+ raw_path, self.snapshot_root, self.legacy_snapshot_roots,+ ) if self.snapshot_root is not None else Path(raw_path))+ return path.is_file()# ────────────────────────────── 查询 ──────────────────────────────-def q_items(args):+def q_items(contract: WebContract, args):where, par = ["a.medium='video'"], []if args.get("loc"):locs = [x for x in args["loc"].split(",") if x]@@ -105,7 +124,7 @@ def q_items(args):"a.duration,a.width,a.height,a.ctx_length,a.ctx_orient,a.snapshot_path,""a.play_count,a.leave_ratio,a.feedback,a.disposal,a.rating,a.o_count,""a.play_seconds,a.max_reached,a.seek_count ""FROM asset a WHERE " + " AND ".join(where) + f" ORDER BY {order} LIMIT ? OFFSET ?")- c = db()+ c = contract.db()rows = [dict(r) for r in c.execute(sql, par + [lim, off])]cnt = c.execute("SELECT count(*) FROM asset a WHERE " + " AND ".join(where), par).fetchone()[0]c.close()@@ -114,7 +133,7 @@ def q_items(args):ids = [r["id"] for r in rows]qm = ",".join("?" * len(ids))tmap = {}- for aid, tag in con_tags(ids, qm):+ for aid, tag in con_tags(contract, ids, qm):tmap.setdefault(aid, []).append(tag)for r in rows:ts = tmap.get(r["id"], [])@@ -122,26 +141,26 @@ def q_items(args):r["performers"] = [t[3:] for t in ts if t.startswith("演员:")][:3]for r in rows:r["cost"] = COST.get(r["location"], "metered")- r["has_thumb"] = bool(r["snapshot_path"] and os.path.exists(r["snapshot_path"]))+ r["has_thumb"] = contract.has_snapshot(r["snapshot_path"])r.pop("snapshot_path", None)r.pop("path", None) # 路径不外发,串流走 idreturn {"total": cnt, "items": rows}-def con_tags(ids, qm):- c = db()+def con_tags(contract: WebContract, ids, qm):+ c = contract.db()try:return c.execute(f"SELECT asset_id, tag FROM asset_tag WHERE asset_id IN ({qm})", ids).fetchall()finally:c.close()-def q_item(aid):+def q_item(contract: WebContract, aid):"""按 id 直取。⚠️ 第一版没有这个接口,前端用「带筛选条件再查一遍然后 find」的绕法,limit 被覆盖成 1 → find 必然失败 → 走兜底 items[0],于是**每次点击都打开同一个默认列表首项**(一个 12.6 GB 的 PikPak 文件),既显示错条目,又反复拉计费流量。教训:按 id 取就按 id 取。"""- c = db()+ c = contract.db()r = c.execute("SELECT id,location,path,name,creator,studio,code,size,duration,width,height,""ctx_length,ctx_orient,snapshot_path,play_count,leave_ratio,feedback,disposal,"@@ -154,7 +173,7 @@ def q_item(aid):d["performers"] = [t[3:] for t in _ts if t.startswith("演员:")]c.close()d["cost"] = COST.get(d["location"], "metered")- d["has_thumb"] = bool(d["snapshot_path"] and os.path.exists(d["snapshot_path"]))+ d["has_thumb"] = contract.has_snapshot(d["snapshot_path"])d.pop("snapshot_path", None); d.pop("path", None)return d@@ -175,13 +194,13 @@ def tag_cat(t):if re.search(r"(ちゃん|さん|酱|娘)$", t) and len(t) <= 8: return "character"return "general"-def q_ads(limit=200):+def q_ads(contract: WebContract, limit=200):"""疑似广告复核队列 —— **不自动删**,只排队让人看接触印相确认。没有可靠的单一判据(试过「同番号短版」会误伤 CD2/part1 分卷,试过「同名扩散」会误伤 001.mp4 这类通用名的真文件)。所以给的是**嫌疑分**,按分排序,人工看图定夺,确认的走既定 CSV 删除流程。"""- c = db()+ c = contract.db()rows = c.execute("SELECT id,location,name,creator,code,size,duration,width,height,snapshot_path,""feedback,disposal,play_count,leave_ratio,o_count,studio,ctx_orient "@@ -212,17 +231,17 @@ def q_ads(limit=200):if s >= 40:d["score"] = s; d["why"] = " · ".join(why)d["cost"] = COST.get(d["location"], "metered")- d["has_thumb"] = bool(d["snapshot_path"] and os.path.exists(d["snapshot_path"]))+ d["has_thumb"] = contract.has_snapshot(d["snapshot_path"])d.pop("snapshot_path", None)out.append(d)c.close()out.sort(key=lambda x: (-x["score"], -(x["size"] or 0)))return {"total": len(out), "items": out[:limit]}-def q_related(aid, limit=24):+def q_related(contract: WebContract, aid, limit=24):"""接着看 —— 把口味接近的串成播放列表。优先级:同创作者 > 共享标签最多 > 同厂牌。全部排除已标记不合口味的。"""- c = db()+ c = contract.db()r = c.execute("SELECT creator,studio,code,ctx_orient FROM asset WHERE id=?", (aid,)).fetchone()if not r:c.close(); return {"items": []}@@ -256,16 +275,16 @@ def q_related(aid, limit=24):c.close()for d in picked:d["cost"] = COST.get(d["location"], "metered")- d["has_thumb"] = bool(d["snapshot_path"] and os.path.exists(d["snapshot_path"]))+ d["has_thumb"] = contract.has_snapshot(d["snapshot_path"])d.pop("snapshot_path", None)return {"items": picked[:limit]}-def q_tops(n=28):+def q_tops(contract: WebContract, n=28):"""顶部三层用的数据:女优圆头像 / 厂牌 / 内容标签。头像不额外造图 —— 取该创作者一张有接触印相的代表作,前端用 background-position:50% 50% 裁中心格做圆头像。"""- c = db()+ c = contract.db()def rep(field, val):r = c.execute(f"SELECT id FROM asset WHERE medium='video' AND {field}=? ""AND snapshot_path IS NOT NULL "@@ -285,9 +304,9 @@ def q_tops(n=28):c.close()return out-def q_index(kind, q="", limit=600):+def q_index(contract: WebContract, kind, q="", limit=600):"""全部创作者 / 全部标签的索引页数据。"""- c = db()+ c = contract.db()if kind == "creators":sql = ("SELECT creator k, count(*) n FROM asset WHERE medium='video' ""AND creator IS NOT NULL AND creator<>'' ")@@ -311,9 +330,9 @@ def q_index(kind, q="", limit=600):c.close()return {"kind": kind, "items": rows}-def q_stats():+def q_stats(contract: WebContract):"""统计页:库存 / 归属 / 标签 / 消费 / 磁盘。原来挤在顶栏右上角,信息量太小又碍眼。"""- c = db()+ c = contract.db()out = {}out["by_loc"] = [dict(r) for r in c.execute("SELECT location k, count(*) n, COALESCE(sum(size),0) bytes, "@@ -365,8 +384,8 @@ def q_stats():out["disk_c"] = Nonereturn out-def q_facets():- c = db()+def q_facets(contract: WebContract):+ c = contract.db()out = {}out["locations"] = [dict(r) for r in c.execute("SELECT location AS k, count(*) AS n, "@@ -400,7 +419,7 @@ def q_facets():# ────────────────────────────── 写入 ──────────────────────────────-def w_activity(body):+def w_activity(contract: WebContract, body):"""播放埋点。「看完」不等于真看完 —— 快进扫过去也会到片尾。所以记两个互相独立的量:@@ -411,8 +430,8 @@ def w_activity(body):aid = int(body["id"]); pos = float(body.get("position", 0))dur = float(body.get("duration", 0)); add = float(body.get("delta", 0))ended = bool(body.get("ended")); seeks = int(body.get("seeks", 0))- with _lock:- c = db(write=True)+ with contract.write_lock:+ c = contract.db(write=True)row = c.execute("SELECT play_seconds,max_reached,seek_count FROM asset WHERE id=?",(aid,)).fetchone()secs = (row["play_seconds"] or 0) + max(add, 0)@@ -427,22 +446,22 @@ def w_activity(body):return {"ok": True, "play_seconds": secs, "leave_ratio": ratio,"max_reached": mx, "seek_count": sk, "real_ratio": real}-def w_play(body):- cache_bust()+def w_play(contract: WebContract, body):+ contract.cache_bust()aid = int(body["id"])- with _lock:- c = db(write=True)+ with contract.write_lock:+ c = contract.db(write=True)c.execute("UPDATE asset SET play_count=COALESCE(play_count,0)+1, last_played=? ""WHERE id=?", (time.time(), aid))c.commit(); c.close()return {"ok": True}-def w_feedback(body):- cache_bust()+def w_feedback(contract: WebContract, body):+ contract.cache_bust()"""四级反馈,前三级只打标记(见方案 §5.4)。第四级删除不在本服务里。"""aid = int(body["id"]); kind = body.get("kind")- with _lock:- c = db(write=True)+ with contract.write_lock:+ c = contract.db(write=True)if kind in ("dislike", "seen"):cur = c.execute("SELECT feedback FROM asset WHERE id=?", (aid,)).fetchone()["feedback"]c.execute("UPDATE asset SET feedback=?, feedback_at=? WHERE id=?",@@ -462,33 +481,33 @@ def w_feedback(body):return {"ok": True, **r}-def dispatch_api_get(path, args):+def dispatch_api_get(contract: WebContract, path, args):"""Dispatch the stable JSON read contract used by the current web client."""if path == "/api/items":- return q_items(args)+ return q_items(contract, args)if path == "/api/item":- return q_item(int(args["id"]))+ return q_item(contract, int(args["id"]))if path == "/api/index":- return q_index(args.get("kind", "tags"), args.get("q", ""))+ return q_index(contract, args.get("kind", "tags"), args.get("q", ""))if path == "/api/stats":- return cached("stats", q_stats)+ return contract.cached("stats", lambda: q_stats(contract))if path == "/api/tops":n = min(int(args.get("n", "28")), 60)- return cached(f"tops{n}", lambda: q_tops(n))+ return contract.cached(f"tops{n}", lambda: q_tops(contract, n))if path == "/api/ads":- return q_ads(min(int(args.get("limit", "200")), 400))+ return q_ads(contract, min(int(args.get("limit", "200")), 400))if path == "/api/related":- return q_related(int(args["id"]), min(int(args.get("limit", "24")), 60))+ return q_related(contract, int(args["id"]), min(int(args.get("limit", "24")), 60))if path == "/api/facets":- return cached("facets", q_facets)+ return contract.cached("facets", lambda: q_facets(contract))raise KeyError(path)-def dispatch_api_post(path, body):+def dispatch_api_post(contract: WebContract, path, body):if path == "/api/activity":- return w_activity(body)+ return w_activity(contract, body)if path == "/api/play":- return w_play(body)+ return w_play(contract, body)if path == "/api/feedback":- return w_feedback(body)+ return w_feedback(contract, body)raise KeyError(path)diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 7d4879ca4..978e917fe 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -35,6 +35,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.db = self.root / "ledger.db"self.media_root = self.root / "media"self.snapshot_root = self.root / "snapshots"+ self.legacy_snapshot_root = self.root / "legacy-snapshots"self.poster_root = self.root / "posters"self.avatar_root = self.root / "avatars"self.logo_root = self.root / "logos"@@ -43,8 +44,10 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):path.mkdir()self.media_file = self.media_root / "one.mp4"self.media_file.write_bytes(b"0123456789")- self.snapshot_file = self.snapshot_root / "one.jpg"+ self.snapshot_file = self.snapshot_root / "cloud" / "local" / "one.jpg"+ self.snapshot_file.parent.mkdir(parents=True)self.snapshot_file.write_bytes(b"snapshot")+ self.legacy_snapshot_file = self.legacy_snapshot_root / "cloud" / "local" / "one.jpg"(self.poster_root / "1_4.jpg").write_bytes(b"poster")(self.avatar_root / "1.jpg").write_bytes(b"avatar")(self.logo_root / "Studio_A.img").write_bytes(b"logo")@@ -58,7 +61,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):width,height,snapshot_path,first_seen)VALUES(1,'local',?,'one.mp4','video',100,'Alice','Studio A',100,1920,1080,?,'2026-08-14')""",- (str(self.media_file), str(self.snapshot_file)),+ (str(self.media_file), str(self.legacy_snapshot_file)),)con.execute("INSERT INTO asset_tag(asset_id,tag,source) VALUES(1,'Tag A','test')")con.commit()@@ -66,6 +69,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):app = create_app(PeachSettings(db_path=self.db, token="secret", page_path=self.page,allowed_media_roots=(self.media_root,), snapshot_root=self.snapshot_root,+ legacy_snapshot_roots=(self.legacy_snapshot_root,),poster_root=self.poster_root, avatar_root=self.avatar_root, logo_root=self.logo_root,ffmpeg_root=self.root / "ffmpeg",))@@ -97,6 +101,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(response.status_code, 200)data = response.json()self.assertEqual(data["total"], 1)+ self.assertTrue(data["items"][0]["has_thumb"])self.assertNotIn("path", data["items"][0])self.assertEqual(response.headers["cache-control"], "no-store")diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 2e2100c0b..6ec08f655 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -75,12 +75,9 @@ class WebDataTests(unittest.TestCase):)con.commit()con.close()- self.old_db = rm_web.DB- rm_web.DB = self.db_path- rm_web.cache_bust()+ self.contract = rm_web.WebContract(Path(self.db_path))def tearDown(self):- rm_web.DB = self.old_dbself.tmp.cleanup()def row(self, aid=1):@@ -91,13 +88,15 @@ class WebDataTests(unittest.TestCase):return rowdef test_default_database_connection_is_readonly(self):- con = rm_web.db()+ con = self.contract.db()with self.assertRaises(sqlite3.OperationalError):con.execute("UPDATE asset SET name='must-not-write' WHERE id=1")con.close()def test_items_are_filtered_and_do_not_expose_paths(self):- result = rm_web.q_items({"loc": "local", "sort": "new", "limit": "10"})+ result = rm_web.q_items(+ self.contract, {"loc": "local", "sort": "new", "limit": "10"},+ )self.assertEqual(result["total"], 1)self.assertEqual(result["items"][0]["id"], 1)self.assertEqual(result["items"][0]["performers"], ["Alice"])@@ -105,21 +104,34 @@ class WebDataTests(unittest.TestCase):self.assertNotIn("snapshot_path", result["items"][0])def test_activity_accumulates_real_play_time_and_max_position(self):- first = rm_web.w_activity({"id": 1, "position": 50, "duration": 100,- "delta": 12, "seeks": 2})- second = rm_web.w_activity({"id": 1, "position": 20, "duration": 100,- "delta": 3, "seeks": 1})+ first = rm_web.w_activity(self.contract, {+ "id": 1, "position": 50, "duration": 100, "delta": 12, "seeks": 2,+ })+ second = rm_web.w_activity(self.contract, {+ "id": 1, "position": 20, "duration": 100, "delta": 3, "seeks": 1,+ })self.assertEqual(first["max_reached"], 0.5)self.assertEqual(second["play_seconds"], 15)self.assertEqual(second["max_reached"], 0.5)self.assertEqual(second["seek_count"], 3)def test_feedback_and_disposal_toggle_independently(self):- self.assertEqual(rm_web.w_feedback({"id": 1, "kind": "dislike"})["feedback"], "dislike")- self.assertEqual(rm_web.w_feedback({"id": 1, "kind": "dispose"})["disposal"], "pending")+ self.assertEqual(rm_web.w_feedback(+ self.contract, {"id": 1, "kind": "dislike"},+ )["feedback"], "dislike")+ self.assertEqual(rm_web.w_feedback(+ self.contract, {"id": 1, "kind": "dispose"},+ )["disposal"], "pending")self.assertEqual(self.row()["feedback"], "dislike")- self.assertIsNone(rm_web.w_feedback({"id": 1, "kind": "dislike"})["feedback"])+ self.assertIsNone(rm_web.w_feedback(+ self.contract, {"id": 1, "kind": "dislike"},+ )["feedback"])self.assertEqual(self.row()["disposal"], "pending")+ def test_application_contract_instances_do_not_share_cache(self):+ other = rm_web.WebContract(Path(self.tmp.name) / "other.db")+ self.assertEqual(self.contract.cached("same", lambda: "first"), "first")+ self.assertEqual(other.cached("same", lambda: "second"), "second")+if __name__ == "__main__":unittest.main()