Peach: Local-first video metadata scraper and media manager.
feat(wants): 想要清单的接口、Feed 与关注条目上的想要、取资料任务
longmeidaob1138cb191d8
diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 46e263a7e..7db758c61 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -32,7 +32,7 @@ COMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py", "test_coSCOPES: dict[str, tuple[str, ...]] = {"checks": ("test_copy_final_state.py", "test_dependency_policy.py", "test_repo_hygiene.py", "test_test_planning.py","test_complexity_ratchet.py", "test_source_assertion_ratchet.py"),- "follow": ("test_follow*.py", "test_http.py", "test_migrations.py"),+ "follow": ("test_follow*.py", "test_http.py", "test_migrations.py", "test_wants_web.py"),"catalog": ("test_ad_judgement.py", "test_composite_name_split.py", "test_media_libraries.py","test_content_region.py","test_duplicate_identity_merge.py",@@ -40,7 +40,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_migrations.py","test_review_mirror.py", "test_rm_web.py","test_entity_link_install.py", "test_web_links.py", "test_entry_links.py",- "test_feeds.py", "test_feeds_web.py",+ "test_feeds.py", "test_feeds_web.py", "test_wants_web.py","test_link_marks.py", "test_site_icons.py", "test_site_logos.py","test_avatar_face.py","test_brand_marks.py", "test_studio_icon_variants.py",diff --git a/src/peach/feed_followup.py b/src/peach/feed_followup.pyindex 891900353..22d74959b 100644--- a/src/peach/feed_followup.py+++ b/src/peach/feed_followup.py@@ -187,7 +187,7 @@ def fetch_cover(contract, code: str,return data, size, evidence-def _install_cover(contract, code: str, cover_url: str | None = None) -> bool:+def ensure_cover(contract, code: str, cover_url: str | None = None) -> bool:"""本机还没有这个番号的封面就去取来装上。返回这一部现在有没有封面。"""from .catalog_rules import is_korean_mib_codefrom .cover_artwork import install_cover@@ -202,7 +202,7 @@ def _install_cover(contract, code: str, cover_url: str | None = None) -> bool:return True-def _performer_names(value: object) -> list[str]:+def performer_names(value: object) -> list[str]:if isinstance(value, list):return [str(item.get("name") or "") if isinstance(item, dict) else str(item)for item in value]@@ -220,7 +220,7 @@ def _scrape_fields(contract, provider, row) -> bool:"UPDATE feed_discovery SET scrape_error=?,scraped_at=? WHERE id=?",(str(error), feeds.stamp(), int(row["id"])))return False- names = _performer_names(fields.get("performers"))+ names = performer_names(fields.get("performers"))with contract.database.write_transaction() as connection:connection.execute("UPDATE feed_discovery SET title=COALESCE(?,title),cover_url=COALESCE(?,cover_url),"@@ -269,7 +269,7 @@ def run(contract, key: str, handle) -> dict:cover_url = connection.execute("SELECT cover_url FROM feed_discovery WHERE id=?", (int(row["id"]),)).fetchone()try:- covers += _install_cover(contract, code, cover_url[0] if cover_url else None)+ covers += ensure_cover(contract, code, cover_url[0] if cover_url else None)except (CoverConnectError, httpx.TransportError):unreachable += 1except Exception: # noqa: BLE001 - 取不到封面这一部照样有资料,下一轮再试diff --git a/src/peach/task_runs.py b/src/peach/task_runs.pyindex c75911444..5ec0a1553 100644--- a/src/peach/task_runs.py+++ b/src/peach/task_runs.py@@ -90,6 +90,7 @@ TASK_LABELS = {"code-samples": "补番号样张","feed-check": "订阅源拉取","feed-scrape": "取新作资料",+ "want-scrape": "取想要的资料","timeline-thumbnails": "视频缩略图采集","seed-import": "导入实体种子",}diff --git a/src/peach/web_feeds.py b/src/peach/web_feeds.pyindex 940c981ad..b48902098 100644--- a/src/peach/web_feeds.py+++ b/src/peach/web_feeds.py@@ -16,8 +16,9 @@ from urllib.parse import quotefrom . import (entities, entry_links, feed_followup, feeds, javdb, performer_alias_followup as alias,- performer_profile_followup, web_catalog, web_settings,+ performer_profile_followup, wants, web_catalog, web_settings, web_wants,)+from .catalog_rules import normalise_code_keyfrom .jobs import TaskRunConflictfrom .http import HttpRequest, public_https_url@@ -205,6 +206,8 @@ def w_feed_check(contract, body) -> dict:result = _execute_check(contract, body, job_id)contract.feed_job.update(job_id, **result, status="complete",current=None, completed_at=time.time())+ # 「想要」里取不到资料或封面的,跟着每一轮拉取再试(隔 `web_wants.RETRY_AFTER`)。+ web_wants.start_scrape(contract, trigger="scheduled" if body.get("automatic") else "manual")finally:finished.set()@@ -486,6 +489,7 @@ def q_feed_discoveries(contract, args) -> dict:" LIMIT ?", (*params, limit + 1)).fetchall()studios = {name: _studio_name(connection, name)for name in {row["studio"] for row in rows[:limit]} if name}+ wanted = wants.wanted_keys(connection, (normalise_code_key(row["code"]) for row in rows[:limit]))more = len(rows) > limit# 最近一轮取新作资料里封面断在连接上的部数。只看最近这一轮:换了线路之后下一轮取到,# 提示就该跟着消失,而不是让一次旧故障一直挂在页面上。@@ -507,6 +511,7 @@ def q_feed_discoveries(contract, args) -> dict:"source_name": row["source_name"],"read": bool(row["read_at"]),"ignored": bool(row["ignored_at"]),+ "wanted": normalise_code_key(row["code"]) in wanted,"scrape_error": row["scrape_error"],} for row in rows[:limit]]}@@ -542,17 +547,36 @@ def _studio_name(connection, name: str) -> str:ACTIONS = {"read": ("read_at", True), "unread": ("read_at", False),"ignore": ("ignored_at", True), "unignore": ("ignored_at", False)}+#: 「想要」与取消想要:写的是 `want_item`,不是壳上的列。忽略与想要互斥,两边都由 `wants` 收口。+WANT_ACTIONS = ("want", "unwant")+++def _want(connection, action: str, ids: list[int]) -> int:+ if action == "want":+ return sum(int(wants.add_feed(connection, value)["created"]) for value in ids)+ marks = ",".join("?" for _ in ids)+ codes = [row[0] for row in connection.execute(+ f"SELECT code FROM feed_discovery WHERE id IN ({marks})", ids)]+ return wants.drop_codes(connection, codes)+def w_feed_discovery(contract, body) -> dict:- """把一条或几条新作标成已读/未读、忽略/取消忽略。幂等。"""+ """把一条或几条新作标成已读/未读、忽略/取消忽略、想要/取消想要。幂等。"""action = str(body.get("action") or "")- if action not in ACTIONS:+ if action not in ACTIONS and action not in WANT_ACTIONS:raise ValueError(f"unknown feed discovery action: {action}")raw = body.get("ids")ids = [value for value in (raw if isinstance(raw, list) else [raw])if type(value) is int]if not ids:raise ValueError("ids must be a nonempty list of feed discovery ids")+ if action in WANT_ACTIONS:+ with contract.database.write_transaction() as connection:+ affected = _want(connection, action, ids)+ contract.cache_bust()+ if action == "want":+ web_wants.start_scrape(contract)+ return {"ok": True, "action": action, "affected": affected}column, setting = ACTIONS[action]value = feeds.stamp() if setting else Nonemarks = ",".join("?" for _ in ids)@@ -560,5 +584,7 @@ def w_feed_discovery(contract, body) -> dict:cursor = connection.execute(f"UPDATE feed_discovery SET {column}=? WHERE id IN ({marks})",(value, *ids))+ if action == "ignore":+ _want(connection, "unwant", ids)contract.cache_bust()return {"ok": True, "action": action, "affected": int(cursor.rowcount or 0)}diff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex 03d60689a..5f4b875cb 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -18,7 +18,7 @@ import urllib.parsefrom pathlib import Path-from . import avatar_face, follow_assets, follow_providers+from . import avatar_face, follow_assets, follow_providers, wantsfrom .follow import FollowSourceErrorfrom .follow_faces import annotate_groupfrom .follow_check import plan_check, run_check@@ -822,6 +822,17 @@ def _media_items(item) -> list[dict]:return _media_projection(item)[0]+def item_thumbs(contract, connection, item_ids) -> dict[int, str | None]:+ """别处列出关注条目时用的缩略图,与关注卡同一份投影(`_thumb_url`)。"""+ store = _store(contract, connection)+ found: dict[int, str | None] = {}+ for item_id in item_ids:+ item = store.item(int(item_id))+ if item is not None:+ found[int(item_id)] = _thumb_url(item)+ return found++def _thumb_url(item) -> str | None:"""卡片上用哪个缩略图。@@ -1902,6 +1913,9 @@ def w_follow_status(contract, body) -> dict:store = _store(contract, connection)for item_id in item_ids:store.set_status(item_id, status)+ if status == "ignored":+ # 忽略与「想要」互斥:忽略了的条目撤掉还没入库的想要。+ wants.drop_follow_items(connection, item_ids)result = {"ok": True, "items": item_ids, "status": status}if len(item_ids) == 1:result["item"] = item_ids[0]@@ -1995,6 +2009,8 @@ def w_follow_save(contract, body) -> dict:with contract.database.write_transaction() as connection:store = _store(contract, connection)asset_ids = [store.save_asset(item_id, confirm=True) for item_id in item_ids]+ # 保存进账本就是入库:想要这一条的标「已入库」(`wants.reconcile` 按 asset_id 认)。+ wants.reconcile(connection, asset_ids)result = {"ok": True, "items": item_ids, "asset_ids": asset_ids}if len(item_ids) == 1:result.update({"item": item_ids[0], "asset_id": asset_ids[0]})diff --git a/src/peach/web_router.py b/src/peach/web_router.pyindex 0f36fa93c..5151749e0 100644--- a/src/peach/web_router.py+++ b/src/peach/web_router.py@@ -95,6 +95,7 @@ from .web_scraping import (from .web_state import WebContract, path_versionfrom .web_tasks import q_tasksfrom .web_timeline_thumbnails import q_thumbnail_jobs, q_timeline, w_thumbnail_jobs+from .web_wants import q_wants, w_wantsfrom .web_stats import (q_quality_goals,q_search_history,@@ -345,6 +346,7 @@ GET_HANDLERS = {"/api/index": _get_index,"/api/duplicates": q_duplicates,"/api/quality-goals": q_quality_goals,+ "/api/wants": q_wants,"/api/stats": _get_stats,"/api/tops": _get_tops,"/api/ads": _get_ads,@@ -391,6 +393,7 @@ POST_HANDLERS = {"/api/playlist": w_playlist,"/api/preference": w_preference,"/api/quality-goal": w_quality_goal,+ "/api/wants": w_wants,"/api/item-tag": w_item_tag,"/api/batch": w_batch,"/api/search-history": w_search_history,diff --git a/src/peach/web_state.py b/src/peach/web_state.pyindex cee1818eb..fdb53880b 100644--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@ -184,6 +184,7 @@ class WebContract:self.followups = FollowupRunner(self)self.follow_job = self._job("PeachFollowCheckJob", "follow-check")self.feed_job = self._job("PeachFeedCheckJob", "feed-check")+ self.want_job = self._job("PeachWantScrapeJob", "want-scrape")self.follow_resolve_job = self._job("PeachFollowResolveJob", "follow-resolve")self.taste_refresh_job = self._job("PeachTasteRefreshJob", "taste-refresh")self.link_prune_job = self._job("PeachLinkPruneJob", "link-prune")@@ -321,6 +322,7 @@ class WebContract:self.resource_apply_job.stop()self.link_check.stop()self.feed_job.stop()+ self.want_job.stop()self.followups.stop()def cache_bust(self):diff --git a/src/peach/web_wants.py b/src/peach/web_wants.pynew file mode 100644index 000000000..f15da4e67--- /dev/null+++ b/src/peach/web_wants.py@@ -0,0 +1,223 @@+"""「想要」清单的读写契约与取资料任务(待办第 40 条)。++数据层与对账在 `wants`;这里是 `/api/wants` 的读写,以及给按番号登记的想要取一份资料和封面。++**取资料复用 Feed 那一套。** 问来源链是 `feed_followup.collect`,取图与落盘是+`feed_followup.ensure_cover`:封面按番号装进本机封面目录,Feed 卡、想要清单和文件入库后的+资产卡用的是同一张。Feed 壳已经取到的资料在登记时抄进快照,这里只补库外番号和壳上还缺的。+关注条目没有番号,缩略图沿用关注卡那份投影(`web_follow.item_thumbs`)。++**两处起跑。** 登记一条缺资料或缺封面的想要,当场起一轮 `want_job`;Feed 每拉一轮订阅,+跑完顺带再起一轮,作为取不到时的重试。两处读同一份 `backlog`,隔 `RETRY_AFTER` 才重试,+取不到的原因写在行上的 `scrape_error`。+"""+from __future__ import annotations++import time+from datetime import date, datetime, timedelta, timezone+from urllib.parse import quote++from . import feed_followup, wants, web_follow+from .jobs import TaskRunConflict++#: 取不到资料或封面的想要,隔多久再试一次;与 Feed 壳同一个间隔。+RETRY_AFTER = feed_followup.RETRY_AFTER++#: 一轮最多取几部。按番号登记是一部一部点的,一轮撞上这么多已经是积压。+MAX_PER_RUN = 48+++def backlog(connection, cover_root, *, exclude=(), now: datetime | None = None,+ retry_after: timedelta = RETRY_AFTER) -> list[int]:+ """有番号、还没入库、缺资料或缺本机封面、上次尝试已经过了 `retry_after` 的想要。"""+ cutoff = wants.stamp((now or datetime.now(timezone.utc)) - retry_after)+ skip = set(exclude)+ found: list[int] = []+ for want_id, code, scraped_at, scrape_error in connection.execute(+ "SELECT id,code,scraped_at,scrape_error FROM want_item WHERE state<>'acquired'"+ " AND code IS NOT NULL AND (scraped_at IS NULL OR scraped_at<?) ORDER BY created_at, id",+ (cutoff,)):+ if int(want_id) in skip:+ continue+ needs_fields = scraped_at is None or scrape_error is not None+ if needs_fields or not feed_followup.has_local_cover(cover_root, code):+ found.append(int(want_id))+ return found+++def _scrape_one(contract, provider_factory, want_id: int) -> tuple[bool, bool]:+ """取一部:缺资料先问来源链,再装封面。返回 (取到资料, 现在有封面)。"""+ with contract.database.read_connection() as connection:+ row = wants.get(connection, want_id)+ if row is None or row["state"] == wants.ACQUIRED or not row["code"]:+ return False, False+ fetched = False+ if row["scraped_at"] is None or row["scrape_error"] is not None:+ try:+ fields, cover_url = feed_followup.collect(provider_factory(), row["code"])+ except Exception as error: # noqa: BLE001 - 原因写到行上给人看+ with contract.database.write_transaction() as connection:+ connection.execute("UPDATE want_item SET scrape_error=?,scraped_at=?,updated_at=?"+ " WHERE id=?", (str(error)[:500], wants.stamp(), wants.stamp(),+ want_id))+ else:+ names = feed_followup.performer_names(fields.get("performers"))+ with contract.database.write_transaction() as connection:+ connection.execute(+ "UPDATE want_item SET title=COALESCE(title,?),cover_url=COALESCE(cover_url,?),"+ "studio=COALESCE(studio,?),release_date=COALESCE(release_date,?),"+ "performers=COALESCE(performers,?),scrape_error=NULL,scraped_at=?,updated_at=?"+ " WHERE id=?",+ (fields.get("title") or None, cover_url, fields.get("studio") or None,+ fields.get("release_date") or None,+ "、".join(name for name in names if name) or None,+ wants.stamp(), wants.stamp(), want_id))+ fetched = True+ with contract.database.read_connection() as connection:+ cover_url = (wants.get(connection, want_id) or {}).get("cover_url")+ try:+ covered = feed_followup.ensure_cover(contract, row["code"], cover_url)+ except Exception: # noqa: BLE001 - 取不到封面这一部照样有资料,隔一阵再试+ covered = False+ with contract.database.write_transaction() as connection:+ connection.execute("UPDATE want_item SET scraped_at=? WHERE id=?", (wants.stamp(), want_id))+ return fetched, covered+++def _provider(contract):+ holder: list = []++ def get():+ if not holder:+ from .library_processing import LibraryMetadataProvider+ holder.append(LibraryMetadataProvider(contract.follow_secrets_root))+ return holder[0]+ return get+++def scrape(contract, job_id: str | None = None) -> dict:+ """把积压的想要取一遍。一轮里新登记的也会接着取到:每取完一批再读一次积压。"""+ done: set[int] = set()+ fetched = covers = 0+ provider = _provider(contract)+ while len(done) < MAX_PER_RUN:+ with contract.database.read_connection() as connection:+ batch = backlog(connection, contract.cover_root, exclude=done)[:MAX_PER_RUN - len(done)]+ if not batch:+ break+ for want_id in batch:+ if job_id:+ contract.want_job.update(job_id, checked=len(done), total=len(done) + len(batch),+ current=want_id)+ got, covered = _scrape_one(contract, provider, want_id)+ fetched += got+ covers += covered+ done.add(want_id)+ contract.cache_bust()+ return {"ok": True, "total": len(done), "fetched": fetched, "covers": covers}+++def start_scrape(contract, *, trigger: str = "manual") -> dict | None:+ """有积压就起一轮 `want_job`;没有就不起,任务中心里不留空跑的一行。"""+ with contract.database.read_connection() as connection:+ if not backlog(connection, contract.cover_root):+ return None++ def work(job_id):+ result = scrape(contract, job_id)+ contract.want_job.update(job_id, **result, status="complete", current=None,+ completed_at=time.time())+ try:+ return contract.want_job.start(work, restart=True, trigger=trigger,+ initial={"ok": True, "checked": 0, "total": 0, "current": None})+ except TaskRunConflict:+ # 另一个进程占着这把互斥键:登记已经落库,资料留给下一轮。+ return None+++def _cover(contract, row: dict, thumbs: dict) -> tuple[str | None, bool]:+ """(封面地址, 是不是远程图)。本机封面优先,其次关注卡的缩略图,最后是来源给的地址。"""+ code = row["code"]+ if code and contract.has_cover(code):+ return f"/cover?code={quote(code)}&thumb=1", False+ thumb = thumbs.get(row["follow_item_id"]) if row["follow_item_id"] else None+ if thumb:+ return thumb, False+ return row["cover_url"], bool(row["cover_url"])+++def _payload(contract, row: dict, today: date, thumbs: dict) -> dict:+ cover, remote = _cover(contract, row, thumbs)+ return {+ "id": int(row["id"]), "code": row["code"], "origin": row["origin"],+ "title": row["title"], "link": row["link"], "release_date": row["release_date"],+ "studio": row["studio"], "performers": row["performers"],+ "phase": wants.phase(row, today), "fresh": wants.is_fresh(row["release_date"], today),+ "search_count": int(row["search_count"] or 0), "last_search_at": row["last_search_at"],+ "last_search_outcome": row["last_search_outcome"], "given_up_at": row["given_up_at"],+ "acquired_asset_id": row["acquired_asset_id"], "acquired_at": row["acquired_at"],+ "follow_item_id": row["follow_item_id"], "follow_provider": row.get("follow_provider"),+ "cover": cover, "remote_cover": remote,+ "scraped": row["scraped_at"] is not None, "scrape_error": row["scrape_error"],+ "created_at": row["created_at"],+ }+++def q_wants(contract, args) -> dict:+ """清单页的全部行与四段计数;带 `follow=<条目 id>` 只回这一条关注条目的想要。"""+ today = date.today()+ follow = str(args.get("follow") or "")+ with contract.database.read_connection() as connection:+ rows = wants.list_rows(connection)+ if follow.isdigit():+ rows = [row for row in rows if row["follow_item_id"] == int(follow)]+ thumbs = web_follow.item_thumbs(+ contract, connection, [row["follow_item_id"] for row in rows if row["follow_item_id"]])+ items = [_payload(contract, row, today, thumbs) for row in rows]+ if follow:+ return {"ok": True, "want": items[0] if items else None}+ counts = {name: 0 for name in wants.PHASES}+ for item in items:+ counts[item["phase"]] += 1+ snapshot = contract.want_job.snapshot() or {}+ return {"ok": True, "items": items, "counts": counts,+ "scraping": snapshot.get("status") == "running"}+++def _ids(body) -> list[int]:+ raw = body.get("ids")+ ids = [value for value in (raw if isinstance(raw, list) else [raw]) if type(value) is int]+ if not ids:+ raise ValueError("ids must be a nonempty list of want ids")+ return ids+++def _add(connection, body) -> dict:+ if type(body.get("feed")) is int:+ return wants.add_feed(connection, body["feed"])+ if type(body.get("follow")) is int:+ return wants.add_follow(connection, body["follow"])+ return wants.add_code(connection, str(body.get("code") or ""))+++def w_wants(contract, body) -> dict:+ """登记(`add`:`code`、`feed` 或 `follow` 三选一)、移除、重置查找(`remove`/`reset` 带 `ids`)。"""+ action = str(body.get("action") or "")+ if action == "add":+ with contract.database.write_transaction() as connection:+ row = _add(connection, body)+ contract.cache_bust()+ start_scrape(contract)+ with contract.database.read_connection() as connection:+ listed = [item for item in wants.list_rows(connection) if item["id"] == row["id"]]+ thumbs = web_follow.item_thumbs(contract, connection,+ [row["follow_item_id"]] if row["follow_item_id"] else [])+ return {"ok": True, "created": row["created"],+ "want": _payload(contract, listed[0], date.today(), thumbs)}+ if action not in ("remove", "reset"):+ raise ValueError(f"unknown want action: {action}")+ ids = _ids(body)+ with contract.database.write_transaction() as connection:+ changed = (wants.remove if action == "remove" else wants.reset_search)(connection, ids)+ contract.cache_bust()+ return {"ok": True, "action": action, "affected": changed}diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex a5bd7c367..63c88fef4 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -997,6 +997,7 @@ class WebDataTests(unittest.TestCase):"/api/taste", "/api/settings", "/api/links", "/api/organize", "/api/orphan-records","/api/feeds", "/api/feeds/check", "/api/feeds/discoveries", "/api/feeds/lookup","/api/downloads",+ "/api/wants",})self.assertEqual(set(rm_web.POST_HANDLERS), {"/api/downloads", "/api/downloads/cancel",@@ -1020,6 +1021,7 @@ class WebDataTests(unittest.TestCase):"/api/entity-name", "/api/entity-alias","/api/organize/preview", "/api/organize/apply", "/api/organize/rollback","/api/feeds/check", "/api/feeds/source", "/api/feeds/discovery",+ "/api/wants",})with self.assertRaises(rm_web.ContractRouteNotFound):rm_web.dispatch_api_get(self.contract, "/api/typo", {})diff --git a/tests/test_wants_web.py b/tests/test_wants_web.pynew file mode 100644index 000000000..6c4f2c12b--- /dev/null+++ b/tests/test_wants_web.py@@ -0,0 +1,177 @@+"""「想要」的接口与入口:清单读写、Feed 卡与关注条目上的想要、互斥、取资料任务(待办第 40 条)。"""+from __future__ import annotations++import io+import sys+import tempfile+import unittest+from datetime import datetime, timedelta, timezone+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))+sys.path.insert(0, str(Path(__file__).resolve().parent))++from peach import feed_followup, wants, web_wants # noqa: E402+from peach.web_contract import WebContract # noqa: E402+from peach.web_router import dispatch_api_get, dispatch_api_post # noqa: E402+from support.ledger import fresh_ledger # noqa: E402+++class WantWebFixture(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.contract = WebContract(fresh_ledger(self.temporary.name))+ self.addCleanup(self.contract.stop_background_jobs)+ self.contract.followups.stop()+ self.contract.cover_root = Path(self.temporary.name) / "covers"+ # 取资料与取图都替掉:番号是假的,配额是真的。+ self.collected: list[str] = []+ self.collect_misses: set[str] = set()+ original_collect, original_fetch = feed_followup.collect, feed_followup.fetch_cover+ feed_followup.collect = self._collect+ feed_followup.fetch_cover = self._fetch_cover+ self.addCleanup(lambda: setattr(feed_followup, "collect", original_collect))+ self.addCleanup(lambda: setattr(feed_followup, "fetch_cover", original_fetch))+ original_provider = web_wants._provider+ web_wants._provider = lambda contract: (lambda: None)+ self.addCleanup(lambda: setattr(web_wants, "_provider", original_provider))++ def _collect(self, provider, code):+ self.collected.append(code)+ if code in self.collect_misses:+ raise ValueError("来源链上都没有这个番号的资料")+ return ({"title": f"{code} 的标题", "studio": "示例厂牌", "release_date": "2026-09-20",+ "performers": [{"name": "深田えいみ"}]}, "https://images.example.test/cover.jpg")++ def _fetch_cover(self, contract, code, cover_url=None):+ from PIL import Image+ buffer = io.BytesIO()+ Image.new("RGB", (800, 538), (40, 40, 40)).save(buffer, format="JPEG")+ return buffer.getvalue(), (800, 538), {"code": code, "source": "test"}++ def get(self, path="/api/wants", **args):+ return dispatch_api_get(self.contract, path, args)++ def post(self, path, body):+ return dispatch_api_post(self.contract, path, body)++ def settle(self):+ thread = self.contract.want_job.thread+ if thread is not None:+ thread.join(10)++ def execute(self, sql, params=()):+ with self.contract.database.write_transaction() as connection:+ connection.execute(sql, params)++ def shell(self, discovery_id=5, code="HMN-071", ignored=None):+ self.execute(+ "INSERT INTO feed_discovery(id,code,title,cover_url,release_date,discovered_at,scraped_at,ignored_at)"+ " VALUES(?,?,'作品标题','https://images.example.test/c.jpg','2026-09-20','x','x',?)",+ (discovery_id, code, ignored))++ def follow_item(self, item_id=9, status="new"):+ self.execute("INSERT OR IGNORE INTO follow_source(id,provider,ref,label,url,semantics,created_at,"+ "updated_at) VALUES(2,'rule34video','r34/1','Creator','https://rule34video.com/u',"+ "'work','x','x')")+ self.execute("INSERT INTO follow_item(id,source_id,external_id,title,url,media_url,release_key,"+ "status,first_seen_at,last_seen_at) VALUES(?,2,?,'帖子标题',"+ "'https://rule34video.com/video/9/x/','https://rule34video.com/get_file/9.mp4',"+ "'r',?,'x','x')", (item_id, str(item_id), status))+++class WantListTests(WantWebFixture):+ def test_adding_a_typed_code_fetches_its_details_and_cover(self):+ result = self.post("/api/wants", {"action": "add", "code": "ssis950"})+ self.settle()+ self.assertTrue(result["created"])+ self.assertEqual(self.collected, ["SSIS-950"])+ listed = self.get()+ item = listed["items"][0]+ self.assertEqual((item["code"], item["title"], item["studio"], item["performers"], item["phase"]),+ ("SSIS-950", "SSIS-950 的标题", "示例厂牌", "深田えいみ", wants.SEARCHING))+ self.assertEqual((item["cover"], item["remote_cover"]), ("/cover?code=SSIS-950&thumb=1", False))+ self.assertTrue((self.contract.cover_root / "SSIS-950.jpg").is_file())+ self.assertEqual(listed["counts"], {"searching": 1, "unreleased": 0, "given_up": 0, "acquired": 0})++ def test_a_failed_lookup_is_recorded_and_retried_only_after_the_interval(self):+ self.collect_misses.add("SSIS-951")+ self.post("/api/wants", {"action": "add", "code": "SSIS-951"})+ self.settle()+ item = self.get()["items"][0]+ self.assertEqual(item["scrape_error"], "来源链上都没有这个番号的资料")+ with self.contract.database.read_connection() as connection:+ self.assertEqual(web_wants.backlog(connection, self.contract.cover_root), [])+ later = datetime.now(timezone.utc) + web_wants.RETRY_AFTER + timedelta(minutes=1)+ self.assertEqual(web_wants.backlog(connection, self.contract.cover_root, now=later), [item["id"]])++ def test_a_code_already_in_the_library_or_unreadable_text_is_refused(self):+ self.execute("INSERT INTO asset(id,location,path,name,medium,code) VALUES(1,'local','R:\\a.mp4',"+ "'a.mp4','video','ABP-123')")+ with self.assertRaisesRegex(ValueError, "已经在库里"):+ self.post("/api/wants", {"action": "add", "code": "ABP-123"})+ with self.assertRaisesRegex(ValueError, "认不出番号"):+ self.post("/api/wants", {"action": "add", "code": "hello"})+ with self.assertRaisesRegex(ValueError, "unknown want action"):+ self.post("/api/wants", {"action": "drop", "ids": [1]})++ def test_remove_and_reset_act_on_the_listed_ids(self):+ first = self.post("/api/wants", {"action": "add", "code": "ABP-100"})["want"]["id"]+ second = self.post("/api/wants", {"action": "add", "code": "ABP-101"})["want"]["id"]+ self.settle()+ self.execute("UPDATE want_item SET state='given_up',search_count=3,given_up_at='x' WHERE id=?",+ (second,))+ self.assertEqual(self.post("/api/wants", {"action": "reset", "ids": [second]})["affected"], 1)+ self.assertEqual(self.post("/api/wants", {"action": "remove", "ids": [first]})["affected"], 1)+ self.assertEqual([(item["id"], item["phase"], item["search_count"]) for item in self.get()["items"]],+ [(second, wants.SEARCHING, 0)])+++class FeedEntryTests(WantWebFixture):+ def wanted(self):+ return {item["id"]: item["wanted"] for item in self.get("/api/feeds/discoveries", state="all")["items"]}++ def test_a_feed_card_can_be_wanted_and_unwanted(self):+ self.shell()+ self.assertEqual(self.wanted(), {5: False})+ self.post("/api/feeds/discovery", {"action": "want", "ids": [5]})+ self.settle()+ self.assertEqual(self.wanted(), {5: True})+ item = self.get()["items"][0]+ self.assertEqual((item["origin"], item["title"]), ("feed", "作品标题"))+ self.post("/api/feeds/discovery", {"action": "unwant", "ids": [5]})+ self.assertEqual(self.get()["items"], [])++ def test_ignoring_a_feed_card_drops_its_want_and_wanting_lifts_the_ignore(self):+ self.shell()+ self.post("/api/feeds/discovery", {"action": "want", "ids": [5]})+ self.post("/api/feeds/discovery", {"action": "ignore", "ids": [5]})+ self.assertEqual(self.get()["items"], [])+ self.post("/api/feeds/discovery", {"action": "want", "ids": [5]})+ self.settle()+ self.assertEqual(self.get("/api/feeds/discoveries", state="ignored")["items"], [])+ self.assertEqual(self.wanted(), {5: True})+++class FollowEntryTests(WantWebFixture):+ def test_a_follow_item_can_be_wanted_and_ignoring_it_drops_the_want(self):+ self.follow_item(status="ignored")+ self.assertIsNone(self.get(follow="9")["want"])+ want = self.post("/api/wants", {"action": "add", "follow": 9})["want"]+ self.assertEqual((want["origin"], want["follow_item_id"], want["follow_provider"]),+ ("follow", 9, "rule34video"))+ self.assertEqual(self.get(follow="9")["want"]["id"], want["id"])+ self.post("/api/follow/status", {"item": 9, "to": "ignored"})+ self.assertIsNone(self.get(follow="9")["want"])++ def test_saving_a_wanted_follow_item_marks_it_acquired(self):+ self.follow_item()+ self.post("/api/wants", {"action": "add", "follow": 9})+ saved = self.post("/api/follow/save", {"item": 9})+ item = self.get(follow="9")["want"]+ self.assertEqual((item["phase"], item["acquired_asset_id"]), (wants.ACQUIRED, saved["asset_id"]))+++if __name__ == "__main__":+ unittest.main()