Peach: Local-first video metadata scraper and media manager.
feat(wants): 想要清单的数据层、入库对账与撤回
longmeidao5672fe8f6cd7
diff --git a/migrations/0042_want_list.sql b/migrations/0042_want_list.sqlnew file mode 100644index 000000000..98cfd1105--- /dev/null+++ b/migrations/0042_want_list.sql@@ -0,0 +1,69 @@+-- 「想要」清单:用户登记「这部我想要」的作品,按番号或关注条目认(待办第 40 条)。+--+-- 为什么另起一张表:三处来源形状不同。Feed 壳按番号唯一、关注条目按 `follow_item.id`、库外番号+-- 只有一个字符串;寻找更好版本(`asset_quality_goal`)的主键含 `asset_id`,只能挂在已入库的作品上。+-- 往其中任何一张加列都要给另外两种来源各开一个例外。+--+-- `code` 是登记时的写法,`code_key` 是 `normalise_code_key` 的结果,入库对账与去重都按它比。+-- 关注条目没有番号,按 `follow_item_id` 认;条目随来源一起删掉时置空,行上的快照还认得出是哪一部。+--+-- 快照列(标题、链接、封面地址、发行日、厂牌、女优)取自 Feed 壳、关注条目或取资料那一步,+-- 都是「某个来源这么说」的展示值,不是真相字段。`scraped_at`/`scrape_error` 记取资料那一步。+--+-- `state`:`wanted` 待找,`given_up` 老片查满次数无果暂时放弃,`acquired` 已入库。未发售不是一种+-- 状态,按 `release_date` 读的时候现算,到了发售日自然回到待找。+-- 查找计数(`search_count`、`last_search_*`、`given_up_at`)由下载模块每查一次记一笔,新片不计数。+--+-- 入库对账是代码判据确定的结果,按 ADR-0052 直接落库:`acquired_source` 是归属串,+-- `acquired_batch` 是批次号 `<source>@<登记时刻>`,整批撤回时按它认。`acquired_asset_id` 不挂外键:+-- 搬运接回与资源同步会删掉 `asset` 行,而扫描那条连接不开外键约束,挂了也拦不住悬空,+-- 对账记录本身要留着(同 `record_rehome` 的两个 asset id)。+CREATE TABLE want_item(+ id INTEGER PRIMARY KEY,+ code TEXT,+ code_key TEXT,+ follow_item_id INTEGER REFERENCES follow_item(id) ON DELETE SET NULL,+ origin TEXT NOT NULL CHECK(origin IN ('code','feed','follow')),+ title TEXT,+ link TEXT,+ cover_url TEXT,+ release_date TEXT,+ studio TEXT,+ performers TEXT,+ scraped_at TEXT,+ scrape_error TEXT,+ state TEXT NOT NULL DEFAULT 'wanted' CHECK(state IN ('wanted','given_up','acquired')),+ search_count INTEGER NOT NULL DEFAULT 0,+ last_search_at TEXT,+ last_search_outcome TEXT CHECK(last_search_outcome IN ('found','none','error')),+ last_search_note TEXT,+ given_up_at TEXT,+ acquired_asset_id INTEGER,+ acquired_at TEXT,+ acquired_source TEXT,+ acquired_batch TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+);++-- 同一个番号、同一条关注条目只登记一次;登记、对账、Feed 卡上的「想要过没有」都按这两个键查。+CREATE UNIQUE INDEX idx_want_item_code_key ON want_item(code_key) WHERE code_key IS NOT NULL;+CREATE UNIQUE INDEX idx_want_item_follow ON want_item(follow_item_id) WHERE follow_item_id IS NOT NULL;++-- 清单页按状态分段、段内按登记时间倒序;整批撤回按归属串找。+CREATE INDEX idx_want_item_state ON want_item(state, created_at);+CREATE INDEX idx_want_item_acquired_source ON want_item(acquired_source) WHERE acquired_source IS NOT NULL;++INSERT INTO ledger_revision(tbl) VALUES ('want_item');++CREATE TRIGGER rev_want_item_insert AFTER INSERT ON want_item BEGIN+ UPDATE ledger_revision SET n=n+1 WHERE tbl='want_item';+END;++CREATE TRIGGER rev_want_item_update AFTER UPDATE ON want_item BEGIN+ UPDATE ledger_revision SET n=n+1 WHERE tbl='want_item';+END;++CREATE TRIGGER rev_want_item_delete AFTER DELETE ON want_item BEGIN+ UPDATE ledger_revision SET n=n+1 WHERE tbl='want_item';+END;diff --git a/scripts/revert_auto_landing.py b/scripts/revert_auto_landing.pyindex 474c560c6..237baaa4b 100644--- a/scripts/revert_auto_landing.py+++ b/scripts/revert_auto_landing.py@@ -26,6 +26,9 @@id 或路径已被别的行占用时那一批拒绝撤回。登记时自动接回记 `auto:vanished-reattach`,孤儿记录列表里由人接回记 `user:reattach`。+「想要」清单的入库对账记在 `want_item.acquired_source` 与 `acquired_batch`(批次号+`auto:want-acquired@<登记时刻>`)。撤回把那几条改回待找,查找计数原样留着。+revert_auto_landing.py --source auto:performer-aliasrevert_auto_landing.py --source auto:performer-alias --batch auto:performer-alias@812revert_auto_landing.py --source auto:performer-profile@@ -34,6 +37,7 @@ id 或路径已被别的行占用时那一批拒绝撤回。登记时自动接revert_auto_landing.py --source adr-0079-fc2-descriptive-performerrevert_auto_landing.py --source auto:metadata-tagsrevert_auto_landing.py --source auto:vanished-reattach --batch auto:vanished-reattach@3+ revert_auto_landing.py --source auto:want-acquired默认只列计划;`--apply` 必须同时给 `--backup`,删文件在账本行之后、同一次运行里完成。"""@@ -46,7 +50,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))-from peach import record_rehome, sample_images # noqa: E402+from peach import record_rehome, sample_images, wants # noqa: E402from peach.config import GENERATED_DIR # noqa: E402from peach.metadata_auto_apply import UNION_TAGS_SOURCE # noqa: E402from peach.scripting import add_ledger_write_args, open_for_write, verify_after_write # noqa: E402@@ -229,6 +233,13 @@ def planned_files(logo_root: Path, source: str, batch: str) -> list[Path]:return found+def print_acquired(planned: list[dict]) -> None:+ """想要清单里对账标了已入库的那几条,一条一行。"""+ for item in planned:+ label = item["code"] or item["title"] or f"#{item['id']}"+ print(f" - 想要 {label[:40]:<40} 资产 {item['acquired_asset_id']} {item['acquired_batch']}")++def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description=__doc__)add_ledger_write_args(parser)@@ -254,6 +265,8 @@ def main(argv: list[str] | None = None) -> int:rejections = planned_rejections(connection, args.source, args.batch)tags = planned_tags(connection, args.source, args.batch)rehomes = record_rehome.planned_revert(connection, args.source, args.batch)+ acquired = wants.planned_revert(connection, args.source, args.batch)+ print_acquired(acquired)for link in links:print(f" - 链接 {link['entity'][:20]:<20} {link['url'][:56]} {link['batch']}")for alias in aliases:@@ -280,7 +293,7 @@ def main(argv: list[str] | None = None) -> int:print({"链接": len(links), "别名": len(aliases), "资料": len(profiles), "编号": len(refs),"归属": len(memberships), "片商": len(makers), "标识文件": len(files),"样张": sum(sample["count"] for sample in samples), "否决": len(rejections),- "标签": len(tags), "接回": len(rehomes)})+ "标签": len(tags), "接回": len(rehomes), "想要入库": len(acquired)})if not args.apply:print("dry-run;确认无误后加 --apply --backup <路径>")return 0@@ -316,6 +329,7 @@ def main(argv: list[str] | None = None) -> int:(tag["asset_id"], tag["tag"], tag["source"])).rowcount or 0 for tag in tags)reopened = reopen_extended_decisions(connection, {tag["item_key"] for tag in tags})restored = record_rehome.revert(connection, args.source, args.batch)+ reopened_wants = wants.revert(connection, args.source, args.batch)integrity, orphans = verify_after_write(connection)finally:connection.close()@@ -329,7 +343,7 @@ def main(argv: list[str] | None = None) -> int:"删除编号": len(refs), "删除归属": len(memberships), "删除片商": len(makers),"删除样张": removed_samples, "删除否决": len(rejections),"删除标签": len(tags), "删除扁平标签": removed_tag_rows, "重开决定": reopened,- "撤回接回": restored, "删除文件": removed,+ "撤回接回": restored, "想要回到待找": reopened_wants, "删除文件": removed,"integrity_check": integrity, "foreign_key_check": orphans})return 0diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 4dc5b270c..46e263a7e 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -52,7 +52,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_studio_followup.py", "test_sample_images.py","test_jav_code_domain.py","test_taste_history.py", "test_web_ui.py", "test_web_js.py",- "test_web_perf.py", "test_web_resource_sync.py", "test_record_rehome.py",+ "test_web_perf.py", "test_web_resource_sync.py", "test_record_rehome.py", "test_wants.py","test_web_orphan_records.py","test_web_review.py", "test_web_settings.py"),# 任务中心的两个文件跟着 `test_jobs.py` 走:`jobs.py` 与 `task_runs.py` 是同一条@@ -100,7 +100,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_agency_entity.py", "test_agency_reject.py", "test_label_maker.py","test_seed_pack.py", "test_seed_followup.py"),"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_script_policy.py",- "test_scan.py", "test_record_rehome.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",+ "test_scan.py", "test_record_rehome.py", "test_wants.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py","test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py","test_version_bump.py", "test_changelog.py", "test_release_due.py","test_restart_windows_tray.py", "test_deploy_windows_tray.py",diff --git a/src/peach/scan.py b/src/peach/scan.pyindex 658c3b0a5..4a61e1c94 100644--- a/src/peach/scan.py+++ b/src/peach/scan.py@@ -6,6 +6,7 @@文件消失、带着个人记录的行由资源同步标 `disposal='vanished'`(ADR-0087)。登记时把它们接回:同一路径的文件回来了,upsert 清掉那一行的 `disposal`;新登记的行由 `record_rehome.reattach`按番号或「创作者 + 文件名主干 + 时长」找它的旧行,把记录搬过来、删掉旧行,记一个可撤回的批次。+接着由 `wants.reconcile` 按番号对一遍「想要」清单,命中的标「已入库」,同样记可撤回的批次。两条不变量都在这里守:@@ -37,7 +38,7 @@ from collections.abc import Callable, Mapping, Sequencefrom dataclasses import dataclassfrom pathlib import Path, PureWindowsPath-from . import record_rehome, subtitles+from . import record_rehome, subtitles, wantsfrom .platform import is_windows_path, resolve_location, resolve_rootVIDEO = {".mp4", ".m4v", ".mkv", ".avi", ".wmv", ".mov", ".ts", ".flv", ".rmvb", ".mpg",@@ -200,6 +201,8 @@ class IngestResult:new: bool = False#: 新行接回了几条已消失作品的个人记录(`record_rehome`)。reattached: int = 0+ #: 新行让几条「想要」标了已入库(`wants.reconcile`)。+ acquired: int = 0def _directory_stats(directory: Path) -> dict[str, tuple[int, str]]:@@ -287,11 +290,12 @@ def ingest_path((location, str(ledger_path))).fetchone()new = first_seen == nowreattached = len(record_rehome.reattach(connection, [asset_id] if new else [], now=now))+ acquired = len(wants.reconcile(connection, [asset_id] if new else []))connection.commit()finally:connection.close()return IngestResult(location, str(ledger_path), True, stat.st_size, tracks,- asset_id=asset_id, new=new, reattached=reattached)+ asset_id=asset_id, new=new, reattached=reattached, acquired=acquired)@dataclass(frozen=True)@@ -312,6 +316,8 @@ class ScanResult:new_ids: tuple[int, ...] = ()#: 本次接回了几条已消失作品的个人记录。reattached: int = 0+ #: 本次让几条「想要」标了已入库。+ acquired: int = 0def summary(self) -> str:return (f"✓ {self.location}: {self.files:,} 文件 / "@@ -425,13 +431,14 @@ def scan_location(new_ids = tuple(row[0] for row in connection.execute("SELECT id FROM asset WHERE location=? AND first_seen=? ORDER BY id", (location, now)))reattached = len(record_rehome.reattach(connection, new_ids, now=now))+ acquired = len(wants.reconcile(connection, new_ids))connection.commit()- gone = connection.execute(+ gone =connection.execute("SELECT COUNT(*) FROM asset WHERE location=? AND last_seen<?",(location, now)).fetchone()[0]finally:connection.close()result = ScanResult(location, root, files, total, time.time() - started, gone,- tracks, orphans, skipped, new_ids, reattached)+ tracks, orphans, skipped, new_ids, reattached, acquired)report(result.summary())return resultdiff --git a/src/peach/wants.py b/src/peach/wants.pynew file mode 100644index 000000000..53250d6b1--- /dev/null+++ b/src/peach/wants.py@@ -0,0 +1,427 @@+"""「想要」清单:登记「这部我想要」,入库时自动对账(待办第 40 条)。++关注一位女优只是持续知道她出了什么,「想要」说的是要这一部。能登记三种东西:Feed 发现的番号壳、+关注条目、用户直接输入的库外番号。番号一律按 `normalise_code_key` 归一,关注条目没有番号,按+`follow_item.id` 认。++**与屏蔽互斥。** Peach 的「屏蔽」是 Feed 卡上的「不想看」(`feed_discovery.ignored_at`)与关注条目的+「忽略」(`follow_item.status='ignored'`)。登记想要时清掉对应的屏蔽;屏蔽时撤掉对应的想要+(`drop_codes`、`drop_follow_items`)。两边的写入口各调这里一个函数,SQL 只写在这一处。++**入库自动对账。** 扫描登记新文件(`scan.scan_location` 与 `scan.ingest_path` 两条路径)和关注条目+保存进账本时调 `reconcile`:新行的番号键命中一条想要,就标「已入库」。番号键的判据是代码给的,+同样输入同样输出,按 ADR-0052 直接落库,记归属串 `AUTO_SOURCE` 与批次 `<source>@<登记时刻>`,+`revert` 按它们整批撤回成待找。++**查找状态。** 真正的查资源归第 41–43 条的下载模块;这里留状态与计数,给它一个记账入口+`record_search`。照 SakuraMedia 的口径:发售 90 天内的新片查不到也不计数,一直待找;老片+(发行日缺失也按老片算)查满 `STALE_ATTEMPT_LIMIT` 次无果标「暂时放弃」,`reset_search` 手动重置。+还没发售的不催:`phase` 按发行日现算出「未发售」,`pending_targets` 不交出它。++调用方负责事务:这里的函数只在给定连接上写,不提交。+"""+from __future__ import annotations++from collections.abc import Iterable, Sequence+from dataclasses import dataclass+from datetime import date, datetime, timedelta, timezone++from .catalog_rules import normalise_code_key, release_code_from_text+from .record_rehome import code_key as asset_code_key++#: 入库自动对账写下的归属串。+AUTO_SOURCE = "auto:want-acquired"++#: 发售多少天之内算新片:查不到也不计数,持续待找。+FRESH_DAYS = 90+#: 老片查满几次无果就暂时放弃。+STALE_ATTEMPT_LIMIT = 3++#: 三种状态,含义见迁移 0042。+WANTED, GIVEN_UP, ACQUIRED = "wanted", "given_up", "acquired"+#: 清单上的四段:待找、未发售、暂时放弃、已入库。未发售是按发行日现算的,不是存下的状态。+SEARCHING, UNRELEASED = "searching", "unreleased"+PHASES = (SEARCHING, UNRELEASED, GIVEN_UP, ACQUIRED)++#: 一次查找的三种结果。`error` 是网络或索引器失败,不算这一部查过。+SEARCH_OUTCOMES = ("found", "none", "error")++#: 一次 `IN (...)` 最多带多少个参数,留在 SQLite 默认上限之内。+_CHUNK = 400++_COLUMNS = ("id,code,code_key,follow_item_id,origin,title,link,cover_url,release_date,studio,"+ "performers,scraped_at,scrape_error,state,search_count,last_search_at,"+ "last_search_outcome,last_search_note,given_up_at,acquired_asset_id,acquired_at,"+ "acquired_source,acquired_batch,created_at,updated_at")+++def stamp(moment: datetime | None = None) -> str:+ """ISO-8601 UTC 文本,与 `feed_discovery`、`task_run` 同一种写法。"""+ return (moment or datetime.now(timezone.utc)).astimezone(+ timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")+++def _rows(connection, sql: str, params: Sequence = ()) -> list[dict]:+ """查询结果按列名转成字典,不依赖调用方连接上的 `row_factory`。"""+ cursor = connection.execute(sql, tuple(params))+ names = [column[0] for column in cursor.description]+ return [dict(zip(names, row)) for row in cursor.fetchall()]+++def _chunks(values: list) -> Iterable[list]:+ for offset in range(0, len(values), _CHUNK):+ yield values[offset:offset + _CHUNK]+++def _register(connection) -> None:+ """扫描那条连接是裸 `sqlite3.connect`,没有挂 `normalise_code_key`;补上同一份实现。"""+ connection.create_function("normalise_code_key", 1, normalise_code_key, deterministic=True)+++def parse_code(text: str | None) -> tuple[str, str]:+ """一段文字里的番号与它的键;认不出就抛,消息直接给人看。"""+ code = release_code_from_text(str(text or "").strip())+ key = normalise_code_key(code) if code else ""+ if not key:+ raise ValueError(f"认不出番号:{str(text or '').strip() or '(空)'}")+ return code, key+++def _day(value: str | None) -> date | None:+ try:+ return date.fromisoformat(str(value or "")[:10])+ except ValueError:+ return None+++def is_unreleased(release_date: str | None, today: date) -> bool:+ released = _day(release_date)+ return released is not None and released > today+++def is_fresh(release_date: str | None, today: date) -> bool:+ """发售 `FRESH_DAYS` 天之内(含还没发售的)。发行日缺失按老片算:不知道多新就不当新片。"""+ released = _day(release_date)+ return released is not None and released > today - timedelta(days=FRESH_DAYS)+++def phase(row: dict, today: date | None = None) -> str:+ """清单上的那一段:已入库、未发售、暂时放弃、待找。"""+ if row["state"] == ACQUIRED:+ return ACQUIRED+ if is_unreleased(row.get("release_date"), today or date.today()):+ return UNRELEASED+ if row["state"] == GIVEN_UP:+ return GIVEN_UP+ return SEARCHING+++def get(connection, want_id: int) -> dict | None:+ found = _rows(connection, f"SELECT {_COLUMNS} FROM want_item WHERE id=?", (int(want_id),))+ return found[0] if found else None+++def by_code_key(connection, key: str) -> dict | None:+ found = _rows(connection, f"SELECT {_COLUMNS} FROM want_item WHERE code_key=?", (key,))+ return found[0] if found else None+++def wanted_keys(connection, keys: Iterable[str]) -> set[str]:+ """这些番号键里登记了想要、还没入库的那几个。Feed 卡上「想要」键的按下状态按它给。"""+ wanted = sorted({key for key in keys if key})+ found: set[str] = set()+ for batch in _chunks(wanted):+ found.update(str(row[0]) for row in connection.execute(+ f"SELECT code_key FROM want_item WHERE state<>'acquired' AND code_key IN "+ f"({','.join('?' * len(batch))})", batch))+ return found+++def in_library(connection, key: str) -> bool:+ """这个番号键在库里有没有一部:与 `feeds.in_library` 同一口径,已消失的不算,回收站里的算。"""+ _register(connection)+ return connection.execute(+ "SELECT 1 FROM asset WHERE code IS NOT NULL AND COALESCE(disposal,'')<>'vanished'"+ " AND normalise_code_key(code)=? LIMIT 1", (key,)).fetchone() is not None+++def _shell(connection, key: str) -> dict | None:+ """同一个番号的 Feed 壳:登记时把它取到的资料抄一份快照。"""+ _register(connection)+ found = _rows(connection, "SELECT id,code,title,link,cover_url,release_date,studio,performers,"+ "scraped_at,scrape_error FROM feed_discovery WHERE normalise_code_key(code)=?"+ " ORDER BY id LIMIT 1", (key,))+ return found[0] if found else None+++def add_code(connection, text: str, *, origin: str = "code", now: str | None = None) -> dict:+ """按番号登记想要,返回那一行(带 `created`)。已登记的原样返回,幂等。++ 已经在库里的拒绝:那部已经到手了,要换更好的版本走「寻找更好版本」。同一个番号的 Feed 壳+ 要是被「不想看」收起了,这里取消那次忽略(想要与屏蔽互斥),并把壳上的资料抄进快照。+ """+ if origin not in ("code", "feed"):+ raise ValueError(f"unknown want origin: {origin}")+ code, key = parse_code(text)+ if in_library(connection, key):+ raise ValueError(f"{code} 已经在库里")+ moment = now or stamp()+ shell = _shell(connection, key)+ if shell is not None:+ connection.execute("UPDATE feed_discovery SET ignored_at=NULL WHERE id=?", (shell["id"],))+ existing = by_code_key(connection, key)+ if existing is not None:+ if existing["state"] == ACQUIRED:+ # 对上的那部又不在库里了(已消失或被删):重新算待找。+ connection.execute(+ "UPDATE want_item SET state='wanted',acquired_asset_id=NULL,acquired_at=NULL,"+ "acquired_source=NULL,acquired_batch=NULL,updated_at=? WHERE id=?",+ (moment, existing["id"]))+ if shell is not None:+ _fill_snapshot(connection, existing["id"], shell, moment)+ return {**get(connection, existing["id"]), "created": False}+ snapshot = shell or {}+ want_id = int(connection.execute(+ "INSERT INTO want_item(code,code_key,origin,title,link,cover_url,release_date,studio,"+ "performers,scraped_at,scrape_error,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",+ (code, key, origin, snapshot.get("title"), snapshot.get("link"), snapshot.get("cover_url"),+ snapshot.get("release_date"), snapshot.get("studio"), snapshot.get("performers"),+ snapshot.get("scraped_at"), snapshot.get("scrape_error"), moment, moment)).lastrowid)+ return {**get(connection, want_id), "created": True}+++def _fill_snapshot(connection, want_id: int, values: dict, moment: str) -> None:+ """快照只补空格:用户登记之后壳上才取到的资料补进来,已经有的不覆盖。"""+ connection.execute(+ "UPDATE want_item SET title=COALESCE(title,?),link=COALESCE(link,?),"+ "cover_url=COALESCE(cover_url,?),release_date=COALESCE(release_date,?),"+ "studio=COALESCE(studio,?),performers=COALESCE(performers,?),updated_at=? WHERE id=?",+ (values.get("title"), values.get("link"), values.get("cover_url"),+ values.get("release_date"), values.get("studio"), values.get("performers"),+ moment, int(want_id)))+++def add_feed(connection, discovery_id: int, *, now: str | None = None) -> dict:+ """Feed 卡上的「想要」:按壳的番号登记。"""+ found = connection.execute(+ "SELECT code FROM feed_discovery WHERE id=?", (int(discovery_id),)).fetchone()+ if found is None:+ raise ValueError("找不到这条新作")+ return add_code(connection, found[0], origin="feed", now=now)+++def add_follow(connection, item_id: int, *, now: str | None = None) -> dict:+ """关注条目的「想要」。条目被忽略过的拉回已看(想要与屏蔽互斥)。"""+ found = _rows(connection, "SELECT id,title,url,published_at,status FROM follow_item WHERE id=?",+ (int(item_id),))+ if not found:+ raise ValueError("找不到这条关注条目")+ item = found[0]+ if item["status"] == "ignored":+ connection.execute("UPDATE follow_item SET status='seen' WHERE id=?", (item["id"],))+ existing = _rows(connection, "SELECT id FROM want_item WHERE follow_item_id=?", (item["id"],))+ if existing:+ return {**get(connection, existing[0]["id"]), "created": False}+ moment = now or stamp()+ want_id = int(connection.execute(+ "INSERT INTO want_item(follow_item_id,origin,title,link,release_date,created_at,updated_at)"+ " VALUES(?,'follow',?,?,?,?,?)",+ (item["id"], item["title"], item["url"], (item["published_at"] or "")[:10] or None,+ moment, moment)).lastrowid)+ return {**get(connection, want_id), "created": True}+++def remove(connection, want_ids: Iterable[int]) -> int:+ """用户在清单上移除。已入库的也能移除:那只是这份清单不再列它。"""+ ids = sorted({int(value) for value in want_ids})+ removed = 0+ for batch in _chunks(ids):+ removed += connection.execute(+ f"DELETE FROM want_item WHERE id IN ({','.join('?' * len(batch))})", batch).rowcount or 0+ return removed+++def drop_codes(connection, codes: Iterable[str]) -> int:+ """屏蔽了这几个番号(Feed 卡上「不想看」):撤掉还没入库的想要。"""+ keys = sorted({normalise_code_key(code) for code in codes if code} - {""})+ dropped = 0+ for batch in _chunks(keys):+ dropped += connection.execute(+ f"DELETE FROM want_item WHERE state<>'acquired' AND code_key IN "+ f"({','.join('?' * len(batch))})", batch).rowcount or 0+ return dropped+++def drop_follow_items(connection, item_ids: Iterable[int]) -> int:+ """忽略了这几条关注条目:撤掉还没入库的想要。"""+ ids = sorted({int(value) for value in item_ids})+ dropped = 0+ for batch in _chunks(ids):+ dropped += connection.execute(+ f"DELETE FROM want_item WHERE state<>'acquired' AND follow_item_id IN "+ f"({','.join('?' * len(batch))})", batch).rowcount or 0+ return dropped+++def reconcile(connection, asset_ids: Iterable[int], *, now: str | None = None) -> list[int]:+ """新登记的这几行命中了哪些想要,标「已入库」并返回它们的 id。++ 番号键用 `record_rehome.code_key`:刚登记的行 `code` 还空着,从文件名解析。判在库与+ `feeds.in_library` 同一口径,只看 `disposal` 为空的行。关注条目按 `follow_item.asset_id`+ 认:保存进账本的那条就是它。同一个批次号记这一轮的时刻,整批撤回按它认。+ """+ ids = sorted({int(value) for value in asset_ids})+ if not ids or connection.execute(+ "SELECT 1 FROM want_item WHERE state<>'acquired' LIMIT 1").fetchone() is None:+ return []+ moment = now or stamp()+ batch_id = f"{AUTO_SOURCE}@{moment}"+ by_key: dict[str, int] = {}+ by_follow: dict[int, int] = {}+ for batch in _chunks(ids):+ marks = ",".join("?" * len(batch))+ for row in _rows(connection, f"SELECT id,code,name FROM asset WHERE id IN ({marks})"+ " AND disposal IS NULL", batch):+ key = asset_code_key(row)+ if key:+ by_key.setdefault(key, int(row["id"]))+ for item_id, asset_id in connection.execute(+ f"SELECT id,asset_id FROM follow_item WHERE asset_id IN ({marks})", batch):+ by_follow.setdefault(int(item_id), int(asset_id))+ hits: list[tuple[int, int]] = []+ for key_batch in _chunks(sorted(by_key)):+ hits += [(int(want_id), by_key[key]) for want_id, key in connection.execute(+ f"SELECT id,code_key FROM want_item WHERE state<>'acquired' AND code_key IN "+ f"({','.join('?' * len(key_batch))})", key_batch)]+ for item_batch in _chunks(sorted(by_follow)):+ hits += [(int(want_id), by_follow[int(item_id)]) for want_id, item_id in connection.execute(+ f"SELECT id,follow_item_id FROM want_item WHERE state<>'acquired' AND follow_item_id IN "+ f"({','.join('?' * len(item_batch))})", item_batch)]+ for want_id, asset_id in hits:+ connection.execute(+ "UPDATE want_item SET state='acquired',acquired_asset_id=?,acquired_at=?,"+ "acquired_source=?,acquired_batch=?,updated_at=? WHERE id=?",+ (asset_id, moment, AUTO_SOURCE, batch_id, moment, want_id))+ return sorted(want_id for want_id, _asset in hits)+++def planned_revert(connection, source: str, batch: str = "") -> list[dict]:+ """这个来源(或其中一批)对账写下的「已入库」。"""+ clause, values = (" AND acquired_batch=?", (batch,)) if batch else ("", ())+ return _rows(connection, "SELECT id,code,title,acquired_asset_id,acquired_batch FROM want_item"+ f" WHERE state='acquired' AND acquired_source=?{clause} ORDER BY id",+ (source, *values))+++def revert(connection, source: str, batch: str = "") -> int:+ """撤回对账:标「已入库」的那几条回到待找,查找计数原样留着。返回撤了几条。"""+ planned = planned_revert(connection, source, batch)+ moment = stamp()+ for item in planned:+ connection.execute(+ "UPDATE want_item SET state=CASE WHEN given_up_at IS NULL THEN 'wanted' ELSE 'given_up' END,"+ "acquired_asset_id=NULL,acquired_at=NULL,acquired_source=NULL,acquired_batch=NULL,"+ "updated_at=? WHERE id=?", (moment, item["id"]))+ return len(planned)+++def record_search(connection, want_id: int, outcome: str, *, note: str = "",+ now: str | None = None, today: date | None = None) -> str:+ """下载模块查了一次资源,记一笔,返回这一条现在的段(`phase`)。++ `found` 清零计数、取消暂时放弃;`error` 只记下这次失败,不算查过;`none` 只给老片计数,+ 满 `STALE_ATTEMPT_LIMIT` 次标暂时放弃。已入库的不再记。+ """+ if outcome not in SEARCH_OUTCOMES:+ raise ValueError(f"unknown search outcome: {outcome}")+ row = get(connection, want_id)+ if row is None:+ raise ValueError("找不到这条想要")+ day = today or date.today()+ if row["state"] == ACQUIRED:+ return ACQUIRED+ moment = now or stamp()+ count, state, given_up = int(row["search_count"] or 0), row["state"], row["given_up_at"]+ if outcome == "found":+ count, state, given_up = 0, WANTED, None+ elif outcome == "none" and not is_fresh(row["release_date"], day):+ count += 1+ if count >= STALE_ATTEMPT_LIMIT and state != GIVEN_UP:+ state, given_up = GIVEN_UP, moment+ connection.execute(+ "UPDATE want_item SET search_count=?,state=?,given_up_at=?,last_search_at=?,"+ "last_search_outcome=?,last_search_note=?,updated_at=? WHERE id=?",+ (count, state, given_up, moment, outcome, note[:500] or None, moment, int(want_id)))+ return phase({**row, "state": state}, day)+++def reset_search(connection, want_ids: Iterable[int], *, now: str | None = None) -> int:+ """手动重置:暂时放弃的回到待找,计数清零。已入库的不动。"""+ ids = sorted({int(value) for value in want_ids})+ moment = now or stamp()+ changed = 0+ for batch in _chunks(ids):+ changed += connection.execute(+ "UPDATE want_item SET state='wanted',search_count=0,given_up_at=NULL,updated_at=?"+ f" WHERE state<>'acquired' AND id IN ({','.join('?' * len(batch))})",+ (moment, *batch)).rowcount or 0+ return changed+++@dataclass(frozen=True)+class WantTarget:+ """交给下载模块的一条待找:拿什么去搜、去哪个关注条目取。"""++ id: int+ #: 番号与它的键;关注条目没有番号时两项都是 None。+ code: str | None+ code_key: str | None+ title: str | None+ release_date: str | None+ studio: str | None+ performers: str | None+ #: 登记时来源给的作品页或帖子地址。+ link: str | None+ #: 关注条目的 id 与帖子地址;按番号登记的为 None。+ follow_item_id: int | None+ follow_url: str | None+ #: 发售 `FRESH_DAYS` 天之内:查不到不计数。+ fresh: bool+ search_count: int+ last_search_at: str | None+++def pending_targets(connection, *, today: date | None = None) -> list[WantTarget]:+ """第 41 条云下载与第 42 条本地下载读的入口:全部「待找」的条目,新片在前。++ 不交出未发售的、暂时放弃的、已入库的;番号已经在库里、只是对账没走到的(文件名解析不出+ 番号、刮削后才补上 `asset.code`)也不交出,免得把已有的再下一遍。+ """+ day = today or date.today()+ _register(connection)+ rows = _rows(+ connection,+ "SELECT w.id,w.code,w.code_key,w.title,w.release_date,w.studio,w.performers,w.link,"+ "w.follow_item_id,f.url AS follow_url,w.search_count,w.last_search_at,w.state"+ " FROM want_item w LEFT JOIN follow_item f ON f.id=w.follow_item_id"+ " WHERE w.state='wanted' AND (w.code_key IS NULL OR NOT EXISTS"+ " (SELECT 1 FROM asset a WHERE a.code IS NOT NULL AND COALESCE(a.disposal,'')<>'vanished'"+ " AND normalise_code_key(a.code)=w.code_key))"+ " ORDER BY w.created_at, w.id")+ targets = [WantTarget(+ id=int(row["id"]), code=row["code"], code_key=row["code_key"], title=row["title"],+ release_date=row["release_date"], studio=row["studio"], performers=row["performers"],+ link=row["link"], follow_item_id=row["follow_item_id"], follow_url=row["follow_url"],+ fresh=is_fresh(row["release_date"], day), search_count=int(row["search_count"] or 0),+ last_search_at=row["last_search_at"])+ for row in rows if phase(row, day) == SEARCHING]+ return sorted(targets, key=lambda target: not target.fresh)+++def list_rows(connection) -> list[dict]:+ """清单页的全部行,带关注条目的来源与状态。"""+ return _rows(connection, f"SELECT {', '.join('w.' + name for name in _COLUMNS.split(','))},"+ " s.provider AS follow_provider, f.status AS follow_status"+ " FROM want_item w LEFT JOIN follow_item f ON f.id=w.follow_item_id"+ " LEFT JOIN follow_source s ON s.id=f.source_id"+ " ORDER BY w.created_at DESC, w.id DESC")diff --git a/tests/test_migrations.py b/tests/test_migrations.pyindex 9a4a6526c..5ec80d970 100644--- a/tests/test_migrations.py+++ b/tests/test_migrations.py@@ -25,7 +25,7 @@ class MigrationTests(unittest.TestCase):backup = self.root / "before.db"done = upgrade(self.db, MIGRATIONS, backup)self.assertEqual([m.version for m in done],- ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039", "0040", "0041", "0043"])+ ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039", "0040", "0041", "0042", "0043"])self.assertTrue(backup.exists())con = sqlite3.connect(self.db)tables = {row[0] for row in con.execute(@@ -43,7 +43,7 @@ class MigrationTests(unittest.TestCase):"asset_tag_preference", "asset_search", "follow_playback","genre_decision", "asset_subtitle", "task_run", "performer_profile", "code_sample_image","schema_migration"} <= tables)- self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039", "0040", "0041", "0043"])+ self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039", "0040", "0041", "0042", "0043"])self.assertEqual(upgrade(self.db, MIGRATIONS), [])self.assertEqual(plan(self.db, MIGRATIONS)[1], [])@@ -325,10 +325,10 @@ class MigrationTests(unittest.TestCase):for path in sorted(MIGRATIONS.glob("*.sql")):# 0024 重建 follow_playback,必须与建表的 0022 一起排除;0038 给每张表挂# 版本号触发器、0039 清 follow_playback 的孤儿行、0040 给墓碑表登记版本号、0041 给新表挂- # 版本号触发器、0043 建下载任务表并挂版本号触发器,被排除的迁移建的表这时还不存在,- # 它们也要等到后面一起应用。+ # 版本号触发器、0042 的想要清单挂版本号触发器、0043 建下载任务表并挂版本号触发器,+ # 被排除的迁移建的表这时还不存在,它们也要等到后面一起应用。if not path.name.startswith(("0020_", "0021_", "0022_", "0024_", "0038_", "0039_", "0040_",- "0041_", "0043_")):+ "0041_", "0042_", "0043_")):shutil.copyfile(path, base_migrations / path.name)sqlite3.connect(self.db).close()upgrade(self.db, base_migrations)diff --git a/tests/test_wants.py b/tests/test_wants.pynew file mode 100644index 000000000..04606bd23--- /dev/null+++ b/tests/test_wants.py@@ -0,0 +1,271 @@+"""「想要」清单的数据层:登记、与屏蔽互斥、入库对账与撤回、查找状态(待办第 40 条)。++对账那一侧走真的 `scan.scan_location` 与 `scan.ingest_path`:全量扫描与推送发现是两条登记路径,+对账要在两条上都发生。声明根写成 `R:\\media`、挂载表指向临时目录,哪台机器上都跑。+"""+from __future__ import annotations++import importlib.util+import io+import sqlite3+import tempfile+import unittest+from contextlib import closing, redirect_stdout+from datetime import date+from pathlib import Path++from peach import scan, wants+from peach.migrations import upgrade++ROOT = Path(__file__).resolve().parents[1]+DECLARED = {"local": ("R:\\media",)}+TODAY = date(2026, 10, 1)+++class WantFixture(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name).resolve()+ self.db = self.root / "ledger.db"+ upgrade(self.db, ROOT / "migrations")+ self.media = self.root / "media"+ self.media.mkdir()+ self.mounts = {"local": (str(self.media),)}++ def write(self, fn):+ with closing(sqlite3.connect(self.db)) as connection:+ result = fn(connection)+ connection.commit()+ return result++ def query(self, sql, params=()):+ with closing(sqlite3.connect(self.db)) as connection:+ return connection.execute(sql, params).fetchall()++ def put(self, relative: str) -> str:+ path = self.media.joinpath(*relative.split("/"))+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"0" * 10)+ return "R:\\media\\" + relative.replace("/", "\\")++ def scan_all(self):+ with redirect_stdout(io.StringIO()):+ return scan.scan_location(self.db, "local", "R:\\media", declared_roots=DECLARED,+ mounts=self.mounts, windows=False)++ def ingest(self, path):+ return scan.ingest_path(self.db, "local", path, declared_roots=DECLARED, mounts=self.mounts,+ windows=False)++ def add_asset(self, asset_id, code, *, disposal=None):+ self.write(lambda connection: connection.execute(+ "INSERT INTO asset(id,location,path,name,medium,size,code,disposal)"+ " VALUES(?,'local',?,?,'video',10,?,?)",+ (asset_id, f"R:\\media\\old\\{code}.mp4", f"{code}.mp4", code, disposal)))++ def add_follow_item(self, item_id=9, status="new"):+ def insert(connection):+ connection.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')")+ connection.execute(+ "INSERT INTO follow_item(id,source_id,external_id,title,url,release_key,status,"+ "published_at,first_seen_at,last_seen_at) VALUES(?,2,?,'帖子标题',"+ "'https://rule34video.com/video/9/x/','r',?,'2026-09-20T10:00:00Z','x','x')",+ (item_id, str(item_id), status))+ self.write(insert)+++class RegisterTests(WantFixture):+ def test_a_typed_code_is_normalised_and_registered_once(self):+ first = self.write(lambda connection: wants.add_code(connection, "ssis00950"))+ again = self.write(lambda connection: wants.add_code(connection, "SSIS-950"))+ self.assertTrue(first["created"])+ self.assertFalse(again["created"])+ self.assertEqual(again["id"], first["id"])+ self.assertEqual(self.query("SELECT code,code_key,origin,state FROM want_item"),+ [("SSIS-950", "SSIS-950", "code", "wanted")])++ def test_text_without_a_code_is_refused(self):+ with self.assertRaisesRegex(ValueError, "认不出番号"):+ self.write(lambda connection: wants.add_code(connection, "hello"))++ def test_a_code_already_in_the_library_is_refused_but_a_vanished_one_is_not(self):+ self.add_asset(1, "ABP-123")+ self.add_asset(2, "ABP-124", disposal="vanished")+ with self.assertRaisesRegex(ValueError, "已经在库里"):+ self.write(lambda connection: wants.add_code(connection, "abp123"))+ self.assertTrue(self.write(lambda connection: wants.add_code(connection, "ABP-124"))["created"])++ def test_wanting_a_feed_shell_takes_its_details_and_lifts_its_ignore(self):+ self.write(lambda connection: connection.execute(+ "INSERT INTO feed_discovery(id,code,title,link,cover_url,release_date,studio,performers,"+ "discovered_at,ignored_at) VALUES(5,'HMN-071','作品标题','https://javdb.com/v/Ab1',"+ "'https://images.example.test/c.jpg','2026-09-20','示例厂牌','深田えいみ','x','x')"))+ row = self.write(lambda connection: wants.add_feed(connection, 5))+ self.assertEqual((row["origin"], row["title"], row["link"], row["studio"], row["release_date"]),+ ("feed", "作品标题", "https://javdb.com/v/Ab1", "示例厂牌", "2026-09-20"))+ self.assertEqual(self.query("SELECT ignored_at FROM feed_discovery"), [(None,)])++ def test_ignoring_a_feed_shell_drops_its_want_but_not_an_acquired_one(self):+ self.write(lambda connection: wants.add_code(connection, "HMN-071"))+ self.write(lambda connection: wants.add_code(connection, "HMN-072"))+ self.write(lambda connection: connection.execute(+ "UPDATE want_item SET state='acquired' WHERE code_key='HMN-072'"))+ dropped = self.write(lambda connection: wants.drop_codes(connection, ["hmn071", "HMN-072"]))+ self.assertEqual(dropped, 1)+ self.assertEqual(self.query("SELECT code_key FROM want_item"), [("HMN-072",)])++ def test_wanting_an_ignored_follow_item_brings_it_back_and_ignoring_drops_it(self):+ self.add_follow_item(status="ignored")+ row = self.write(lambda connection: wants.add_follow(connection, 9))+ self.assertEqual((row["origin"], row["follow_item_id"], row["title"], row["release_date"]),+ ("follow", 9, "帖子标题", "2026-09-20"))+ self.assertEqual(self.query("SELECT status FROM follow_item"), [("seen",)])+ self.assertEqual(self.write(lambda connection: wants.drop_follow_items(connection, [9])), 1)+ self.assertEqual(self.query("SELECT count(*) FROM want_item"), [(0,)])+++class ReconcileTests(WantFixture):+ def test_a_full_scan_marks_the_want_acquired_with_source_and_batch(self):+ self.write(lambda connection: wants.add_code(connection, "SSIS-950"))+ path = self.put("SSIS-950.mp4")+ self.put("OTHER-001.mp4")+ result = self.scan_all()+ asset_id = self.query("SELECT id FROM asset WHERE path=?", (path,))[0][0]+ self.assertEqual(result.acquired, 1)+ state, acquired_asset, source, batch = self.query(+ "SELECT state,acquired_asset_id,acquired_source,acquired_batch FROM want_item")[0]+ self.assertEqual((state, acquired_asset, source), ("acquired", asset_id, wants.AUTO_SOURCE))+ self.assertTrue(batch.startswith(wants.AUTO_SOURCE + "@"))++ def test_push_discovery_ingest_marks_the_want_acquired_too(self):+ self.write(lambda connection: wants.add_code(connection, "ABW-358"))+ result = self.ingest(self.put("[site.cc]abw358-C.mp4"))+ self.assertEqual(result.acquired, 1)+ self.assertEqual(self.query("SELECT state,acquired_asset_id FROM want_item"),+ [("acquired", result.asset_id)])++ def test_a_file_seen_again_does_not_reconcile(self):+ path = self.put("ABW-358.mp4")+ self.ingest(path)+ # 「新」按 first_seen 等于这一次的时刻判,精度是秒;把首见挪早,第二次就一定是重见。+ self.write(lambda connection: connection.execute("UPDATE asset SET first_seen='2026-01-01 00:00:00'"))+ self.write(lambda connection: connection.execute(+ "INSERT INTO want_item(code,code_key,origin,created_at,updated_at)"+ " VALUES('ABW-358','ABW-358','code','x','x')"))+ self.assertEqual(self.ingest(path).acquired, 0)+ self.assertEqual(self.query("SELECT state FROM want_item"), [("wanted",)])++ def test_saving_a_follow_item_reconciles_its_want(self):+ self.add_follow_item()+ self.write(lambda connection: wants.add_follow(connection, 9))+ self.add_asset(40, "X")+ self.write(lambda connection: connection.execute("UPDATE follow_item SET asset_id=40"))+ self.assertEqual(self.write(lambda connection: wants.reconcile(connection, [40])), [1])+ self.assertEqual(self.query("SELECT state,acquired_asset_id FROM want_item"), [("acquired", 40)])++ def test_revert_puts_the_batch_back_to_searching(self):+ self.write(lambda connection: wants.add_code(connection, "SSIS-950"))+ self.write(lambda connection: wants.add_code(connection, "SSIS-951"))+ self.write(lambda connection: connection.execute(+ "UPDATE want_item SET state='given_up',given_up_at='x',search_count=3 WHERE code_key='SSIS-951'"))+ self.put("SSIS-950.mp4")+ self.put("SSIS-951.mp4")+ self.scan_all()+ with closing(sqlite3.connect(self.db)) as connection:+ planned = wants.planned_revert(connection, wants.AUTO_SOURCE)+ self.assertEqual(wants.planned_revert(connection, "user:other"), [])+ self.assertEqual([item["code"] for item in planned], ["SSIS-950", "SSIS-951"])+ spec = importlib.util.spec_from_file_location(+ "revert_auto_landing_under_test", ROOT / "scripts" / "revert_auto_landing.py")+ script = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(script)+ with redirect_stdout(io.StringIO()) as printed:+ self.assertEqual(script.main([+ "--db", str(self.db), "--logo-root", str(self.root / "logos"),+ "--source", wants.AUTO_SOURCE, "--batch", planned[0]["acquired_batch"],+ "--apply", "--backup", str(self.root / "backup.db")]), 0)+ self.assertIn("'想要回到待找': 2", printed.getvalue())+ self.assertEqual(self.query(+ "SELECT code,state,search_count,acquired_asset_id,acquired_batch FROM want_item ORDER BY id"),+ [("SSIS-950", "wanted", 0, None, None), ("SSIS-951", "given_up", 3, None, None)])+++class SearchStateTests(WantFixture):+ def want(self, code, release_date):+ row = self.write(lambda connection: wants.add_code(connection, code))+ self.write(lambda connection: connection.execute(+ "UPDATE want_item SET release_date=? WHERE id=?", (release_date, row["id"])))+ return row["id"]++ def record(self, want_id, outcome):+ return self.write(lambda connection: wants.record_search(+ connection, want_id, outcome, today=TODAY))++ def test_an_old_release_gives_up_after_three_empty_searches_and_can_be_reset(self):+ want_id = self.want("ABP-100", "2025-01-01")+ self.assertEqual([self.record(want_id, "none") for _ in range(3)],+ [wants.SEARCHING, wants.SEARCHING, wants.GIVEN_UP])+ self.assertEqual(self.query("SELECT state,search_count FROM want_item"), [("given_up", 3)])+ self.assertEqual(self.write(lambda connection: wants.reset_search(connection, [want_id])), 1)+ self.assertEqual(self.query("SELECT state,search_count,given_up_at FROM want_item"),+ [("wanted", 0, None)])++ def test_a_missing_release_date_counts_as_an_old_release(self):+ want_id = self.want("ABP-101", None)+ for _ in range(3):+ self.record(want_id, "none")+ self.assertEqual(self.query("SELECT state FROM want_item"), [("given_up",)])++ def test_a_fresh_release_keeps_searching_and_errors_never_count(self):+ fresh = self.want("ABP-102", "2026-08-01")+ old = self.want("ABP-103", "2025-01-01")+ for _ in range(5):+ self.assertEqual(self.record(fresh, "none"), wants.SEARCHING)+ self.record(old, "error")+ self.assertEqual(self.query("SELECT search_count,state,last_search_outcome FROM want_item ORDER BY id"),+ [(0, "wanted", "none"), (0, "wanted", "error")])++ def test_finding_something_clears_the_count(self):+ want_id = self.want("ABP-104", "2025-01-01")+ self.record(want_id, "none")+ self.record(want_id, "none")+ self.assertEqual(self.record(want_id, "found"), wants.SEARCHING)+ self.assertEqual(self.query("SELECT search_count FROM want_item"), [(0,)])++ def test_pending_targets_skip_unreleased_given_up_acquired_and_owned(self):+ old = self.want("ABP-110", "2025-01-01")+ fresh = self.want("ABP-111", "2026-09-15")+ self.want("ABP-112", "2026-12-24")+ given_up = self.want("ABP-113", "2025-01-01")+ self.write(lambda connection: connection.execute(+ "UPDATE want_item SET state='given_up' WHERE id=?", (given_up,)))+ self.want("ABP-114", "2025-01-01")+ self.add_asset(1, "ABP-114")+ self.add_follow_item()+ follow = self.write(lambda connection: wants.add_follow(connection, 9))["id"]+ with closing(sqlite3.connect(self.db)) as connection:+ targets = wants.pending_targets(connection, today=TODAY)+ self.assertEqual([target.id for target in targets], [fresh, follow, old])+ self.assertEqual([target.fresh for target in targets], [True, True, False])+ self.assertEqual((targets[1].code, targets[1].follow_url),+ (None, "https://rule34video.com/video/9/x/"))++ def test_the_list_carries_the_follow_provider(self):+ self.add_follow_item()+ self.write(lambda connection: wants.add_follow(connection, 9))+ with closing(sqlite3.connect(self.db)) as connection:+ rows = wants.list_rows(connection)+ self.assertEqual((rows[0]["follow_provider"], rows[0]["follow_status"]), ("rule34video", "new"))++ def test_phase_reads_unreleased_from_the_release_date(self):+ row = {"state": "given_up", "release_date": "2026-12-01"}+ self.assertEqual(wants.phase(row, TODAY), wants.UNRELEASED)+ self.assertEqual(wants.phase({**row, "release_date": "2026-09-01"}, TODAY), wants.GIVEN_UP)+ self.assertEqual(wants.phase({**row, "state": "acquired"}, TODAY), wants.ACQUIRED)+++if __name__ == "__main__":+ unittest.main()