Peach: Local-first video metadata scraper and media manager.
feat: reconcile deleted media and generated caches
longmeidaoef2fcd639136
diff --git a/README.md b/README.mdindex a9c75f51e..a9df6c72b 100644--- a/README.md+++ b/README.md@@ -95,12 +95,15 @@ macOS/Linux 用 `./scripts/test.sh follow`。可选域为 `follow`、`catalog`| `/follow` | 关注观看 || `/follow-manage` | 关注管理与凭据状态 || `/review` | 人工复核 |+| `/resource-sync` | 网盘资源同步与孤立缓存清理 || `/trash` | 回收站 || `/stats` | 统计 || `/taste` | 品味画像与浏览记录管理 |`/healthz` 提供无副作用健康状态,`/api/sources` 提供来源可达性。其他 API 契约以实现和测试为准,不在 README 维护容易漂移的端点全集。+在网盘或本地资源目录手动删除文件后,进入「管理 → 资源同步」先扫描差异。Peach 只核对已挂载来源;缺失条目先进入回收站,可恢复的账本元数据不会立即丢失。确认同步时会同时清理不再被正常馆藏使用的截图、海报、图片缩略图、封面和播放缓存;候选 CSV、来源证据、女优头像和厂牌 Logo 不作缓存删除。+## 关注与候选关注管理支持粘贴链接、名称或 ID,也可直接登记 FANBOX、Patreon 和 SubscribeStar 的diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex a0e9211c9..ff6ef7d67 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -143,6 +143,7 @@ Gofile token 是另一份本机可选凭据,只进 Gofile 请求头,不进 U- FastAPI 是唯一 Web server。不得恢复平行 `http.server` 或动态 legacy loader。配置 `--token` 时通过 `/login` POST 取得 HttpOnly cookie;旧 `?t=` 只做一次兼容重定向,dependency 统一 JSON contract 鉴权但不替代登录流程。- FFmpeg/ffprobe 依次从显式环境变量、本机 `peach-data/tools/ffmpeg/bin`、`PATH` 解析;不得回退到 Stash 私有目录。- **生成产物走 Syncthing 单向同步,和账本、和 Git 是三条互不兜底的链路**。Windows send-only、Mac receive-only,五个文件夹 `snapshots`、`posters`、`avatars`、`logos`、`covers`;Mac 侧根目录在 `peach-data/artifacts/`(`generated` 是指向它的符号链接,不要把符号链接本身设成同步目录),Trash Can 版本保留 30 天。`.stignore` 不跨设备同步,两端每个目录各放一份。方向是固定的:Mac 不发布正式产物,在 Mac 上生成的图片不会回到 Windows。+- 网盘目录由人在 CloudDrive 外部整理后,必须经「管理 → 资源同步」显式对账,不做后台静默删除。扫描只核对已挂载的 `local`/`115`/`pikpak`;离线来源整源跳过。源文件缺失的 asset 先进入 Peach 回收站,清空回收站才永久删除账本行。同步可清理无正常馆藏引用的 snapshots、posters、photo-thumbs、transcodes、stream-segments、按 asset 生成的头像和共享番号封面;候选 CSV、provider evidence、实体头像与 Logo 不在自动清理边界。- 长任务只停止自己拥有且命令行匹配的 Python/FFmpeg 进程树,禁止全机终止 FFmpeg。- 导入运维脚本不得触发文件、网络或数据库副作用。`scrape_codes.py` 默认写可续跑复核 CSV;`clean_names.py` 先预览,`--apply` 前备份 SQLite。- 切换服务前检查 80、443、8900、9999 端口和实际进程归属。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 34005dc0e..500a0a345 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -36,6 +36,7 @@## 本批修正与验证+- 0.7.6 新增「管理 → 资源同步」:只读扫描逐来源核对 `local`、115、PikPak,整源离线时跳过;确认应用会重新核对,把网盘上已删除的 asset 先移入 Peach 回收站,并清理没有正常馆藏引用的截图、海报、图片缩略图、转码、流媒体片段、按 asset 生成的头像和共享番号封面。候选 CSV、来源证据、实体头像和 Logo 明确排除。详情页原有目录同步也改为先入回收站,不再直接删账本;清空回收站后统一清理派生缓存。共享封面、离线整源、临时测试库不触碰真实 generated 根均有数据层门槛;桌面和 390×844 响应式源码契约已覆盖。正式 Windows 全量测试 1157 项通过、13 项按平台跳过;尚未在生产执行资源扫描或应用清理,真实 ledger 和 generated 目录未写。- 艺人、厂牌、创作者、系列资料页的作品区统一复用首页排序:换一批、推荐顺序、每日轮换、随机、评分、高潮计数、观看次数、时长、体积、最近入库、最近看的;照片瀑布流和管理队列不添加无适用语义的排序。资料页 API 继续保留完整别名供搜索,但页面不再展示本地化规范名的纯拉丁转写;番号卡片优先显示规范女优实体,不再被旧 `asset.creator` 罗马字投影抢占。实体解析改为精确规范名优先、仅接受唯一别名,修复 `飯岡かなこ` 被 `森泽佳奈` 同名别名抢走的问题。390×844 实测页面宽 380、无横向溢出,排序行 348/710 px 可横滚;艺人、厂牌、创作者、系列均有 10 个排序按钮,JAV 厂牌另保留 3 个版式按钮。集成后正式 Windows 全量测试 1145 项通过、13 项按平台跳过。生产托盘已重启并重新拥有 80/443;项目 CA 严格 HTTPS 返回 0.7.5、writer、非只读,`释爱丽丝` 的纯拉丁别名不再展示,`飯岡かなこ` 路由到实体 8559。- 系列规范名已按 271 个代表番号重新读取 r18dev 同一响应中的官方日文翻译:261 个请求成功、10 个明确返回 404、0 个可重试错误或限流。真实 ledger 写入前用 SQLite Backup API 建立 `database/ledger.pre-series-name-localization-20260828-205228.db`,SHA-256 为 `07AAFBA70B08936D77DF98BAD5DA792617D707794EDBA3922C00207280A783D3`;253 个系列改名、1 个英文实体并入已存在的日文实体、425 条 `asset.series` 兼容投影同步,旧英文名保留为不展示但可搜索的别名。另有 7 个官方日文值与当前值相同、14 个没有可验证日文证据,均未猜译。asset 81555、asset_entity 152990 保持不变,series 289→288、entity 8178→8177、entity_alias 1526→1781;备份和现库均 `integrity_check=ok`、外键违规 0,现库系列投影不一致为 0。项目 CA 严格 HTTPS 已确认 0.7.5、writer、非只读;旧英文路由 `Raw Creampies`、`Aesthetics of a Facial`、`FALENO Compilation` 分别解析到 `なまなかだし`、`顔射の美学`、`FALENO総集編`,英文别名不进入展示列表。- 最近 12 小时 Windows 应用日志没有 Peach 的 1000/1001 崩溃事件;本轮 18:31 的 `Peach.exe` 退出是为加载已测试源码而执行的受控重启。重启后托盘与两个服务进程持续存在,80/443 正常监听;当前没有异常自动退出证据。diff --git a/src/peach/__init__.py b/src/peach/__init__.pyindex faa9948ef..2392673b5 100644--- a/src/peach/__init__.py+++ b/src/peach/__init__.py@@ -1,3 +1,3 @@"""Peach application package."""-__version__ = "0.7.5"+__version__ = "0.7.6"diff --git a/src/peach/api.py b/src/peach/api.pyindex 85d36b5e9..aa5652377 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -131,6 +131,10 @@ def create_app(cover_root=settings.cover_root,avatar_root=settings.avatar_root,logo_root=settings.logo_root,+ poster_root=settings.poster_root,+ photo_root=settings.photo_root,+ transcode_root=settings.transcode_root,+ stream_root=settings.stream_root,follow_state_root=settings.follow_state_root,taste_history_root=settings.taste_history_output_root,taste_history_store=settings.taste_history_store,diff --git a/src/peach/web_contract.py b/src/peach/web_contract.pyindex f35773c1d..e6dde6896 100644--- a/src/peach/web_contract.py+++ b/src/peach/web_contract.py@@ -11,6 +11,7 @@ import hashlibimport jsonimport randomimport re+import shutilimport threadingimport timeimport uuid@@ -108,6 +109,10 @@ class WebContract:cover_root: Path | None = None,avatar_root: Path | None = None,logo_root: Path | None = None,+ poster_root: Path | None = None,+ photo_root: Path | None = None,+ transcode_root: Path | None = None,+ stream_root: Path | None = None,follow_sources_root: Path | None = None,follow_secrets_root: Path | None = None,follow_state_root: Path | None = None,@@ -123,6 +128,15 @@ class WebContract:self.avatar_root = Path(avatar_root) if avatar_root is not None else GENERATED_DIR / "avatars"# `/logo` 就是从这里读;批准候选等于把图装进这个目录。self.logo_root = Path(logo_root) if logo_root is not None else GENERATED_DIR / "logos"+ self.poster_root = Path(poster_root) if poster_root is not None else GENERATED_DIR / "posters"+ self.photo_root = Path(photo_root) if photo_root is not None else GENERATED_DIR / "photo-thumbs"+ self.transcode_root = (Path(transcode_root) if transcode_root is not None+ else GENERATED_DIR / "transcodes")+ self.stream_root = Path(stream_root) if stream_root is not None else GENERATED_DIR / "stream-segments"+ # API construction passes every managed cache root. A bare WebContract is also used+ # by isolated unit tests; it must never wander into the machine's real generated tree.+ self.resource_cleanup_enabled = any(+ root is not None for root in (poster_root, photo_root, transcode_root, stream_root))# 追更的原始证据与本机凭据目录同样做成实例属性,测试才能落在临时目录里。self.follow_sources_root = (Path(follow_sources_root)if follow_sources_root is not None else SOURCES_DIR)@@ -1351,7 +1365,6 @@ def q_stats(contract: WebContract):"FROM asset WHERE last_played IS NOT NULL ORDER BY last_played DESC LIMIT 12")]c.close()try:- import shutilvolume = system_volume()du = shutil.disk_usage(volume)out["system_disk"] = {"root": str(volume), "free": du.free, "total": du.total}@@ -2495,7 +2508,9 @@ def w_empty_trash(contract: WebContract):if outcome is not None:_restore_staged_media(outcome["_staged"])raise- return {"ok": True, "operation": "empty-trash", **_finish_purge(outcome)}+ result = {"ok": True, "operation": "empty-trash", **_finish_purge(outcome)}+ result.update(_clean_resource_orphans(contract))+ return resultdef source_is_online(location: str) -> bool:@@ -2507,11 +2522,191 @@ def source_is_online(location: str) -> bool:return not is_unmapped(resolved) and root_online(resolved)+def _scan_missing_resources(contract: WebContract) -> dict:+ """Read-only reconciliation against every mounted filesystem source."""+ with contract.read_connection() as connection:+ rows = connection.execute(+ "SELECT id,location,path FROM asset "+ "WHERE path IS NOT NULL AND COALESCE(disposal,'')!='trash' "+ "AND location IN ('local','115','pikpak') ORDER BY location,id",+ ).fetchall()+ grouped: dict[str, list] = {}+ for row in rows:+ grouped.setdefault(row["location"], []).append(row)+ missing_ids: list[int] = []+ sources = []+ for location in LOCATION_ROOT_DECLARATIONS:+ items = grouped.get(location, [])+ online = source_is_online(location)+ missing = []+ if online:+ for row in items:+ if not translate_ledger_path(row["path"]).is_file():+ missing.append(row["id"])+ missing_ids.extend(missing)+ sources.append({+ "location": location, "online": online, "checked": len(items) if online else 0,+ "total": len(items), "missing": len(missing),+ })+ return {"sources": sources, "missing_ids": missing_ids}+++def _cache_file(path: Path, kind: str, output: list[tuple[str, Path, int]]) -> None:+ try:+ size = path.stat().st_size+ except OSError:+ return+ output.append((kind, path, size))+++def _resource_orphan_plan(contract: WebContract, excluded_ids: Sequence[int] = ()) -> dict:+ """Find only reproducible generated files that no active asset still owns.++ Review CSVs, provider evidence, logos and entity portraits are deliberately outside this+ boundary: they are provenance or shared identity assets, not disposable per-asset caches.+ """+ if not contract.resource_cleanup_enabled:+ return {"files": [], "dirs": set(), "summary": {},+ "total_files": 0, "total_bytes": 0}+ with contract.read_connection() as connection:+ rows = connection.execute(+ "SELECT id,code,snapshot_path FROM asset WHERE COALESCE(disposal,'')!='trash'",+ ).fetchall()+ excluded = {int(item) for item in excluded_ids}+ rows = [row for row in rows if int(row["id"]) not in excluded]+ active_ids = {int(row["id"]) for row in rows}+ active_codes = {normalise_code_key(row["code"]) for row in rows if row["code"]}+ active_codes.discard("")+ active_snapshots = set()+ for row in rows:+ raw = row["snapshot_path"]+ if raw:+ active_snapshots.add(remap_managed_path(+ raw, contract.snapshot_root, contract.legacy_snapshot_roots,+ ) if contract.snapshot_root is not None else Path(raw))++ files: list[tuple[str, Path, int]] = []+ cleanup_dirs: set[Path] = set()+ if contract.snapshot_root and contract.snapshot_root.is_dir():+ for path in contract.snapshot_root.rglob("*"):+ if path.is_file() and path not in active_snapshots:+ _cache_file(path, "snapshots", files)++ patterns = (+ (contract.poster_root, "posters", re.compile(r"^(\d+)_\d+\.jpg$")),+ (contract.photo_root, "photo-thumbs", re.compile(r"^(\d+)\.jpg$")),+ (contract.transcode_root, "transcodes", re.compile(r"^(\d+)-.+\.mp4$")),+ )+ for root, kind, pattern in patterns:+ if not root.is_dir():+ continue+ for path in root.iterdir():+ match = pattern.match(path.name)+ if match and int(match.group(1)) not in active_ids and path.is_file():+ _cache_file(path, kind, files)++ if contract.stream_root.is_dir():+ for directory in contract.stream_root.iterdir():+ if not directory.is_dir() or not directory.name.isdigit():+ continue+ if int(directory.name) in active_ids:+ continue+ cleanup_dirs.add(directory)+ for path in directory.rglob("*"):+ if path.is_file():+ _cache_file(path, "stream-segments", files)++ if contract.avatar_root.is_dir():+ for path in contract.avatar_root.iterdir():+ match = re.match(r"^(\d+)\.jpg$", path.name)+ if match and int(match.group(1)) not in active_ids and path.is_file():+ _cache_file(path, "asset-avatars", files)++ if contract.cover_root.is_dir():+ for path in contract.cover_root.iterdir():+ key = ""+ if path.name.endswith(".face.json"):+ key = path.name[:-10]+ elif path.suffix.lower() == ".jpg":+ key = path.stem+ if key and normalise_code_key(key) not in active_codes and path.is_file():+ _cache_file(path, "covers", files)++ summary: dict[str, dict[str, int]] = {}+ for kind, _path, size in files:+ bucket = summary.setdefault(kind, {"files": 0, "bytes": 0})+ bucket["files"] += 1+ bucket["bytes"] += size+ return {+ "files": files, "dirs": cleanup_dirs, "summary": summary,+ "total_files": len(files), "total_bytes": sum(item[2] for item in files),+ }+++def _clean_resource_orphans(contract: WebContract) -> dict:+ plan = _resource_orphan_plan(contract)+ removed = 0+ reclaimed = 0+ blocked = []+ for kind, path, size in plan["files"]:+ try:+ path.unlink(missing_ok=True)+ removed += 1+ reclaimed += size+ except OSError as error:+ blocked.append({"kind": kind, "name": path.name,+ "reason": error.strerror or str(error)})+ for directory in sorted(plan["dirs"], key=lambda item: len(item.parts), reverse=True):+ try:+ shutil.rmtree(directory)+ except FileNotFoundError:+ pass+ except OSError:+ # Individual file failures above already carry useful detail; a non-empty cache+ # directory is harmless and will be reconsidered on the next scan.+ pass+ return {"cache_removed": removed, "bytes_reclaimed": reclaimed,+ "cache_blocked": blocked}+++def w_resource_sync_scan(contract: WebContract, _body=None):+ scan = _scan_missing_resources(contract)+ caches = _resource_orphan_plan(contract, scan["missing_ids"])+ return {+ "ok": True, "sources": scan["sources"],+ "missing": len(scan["missing_ids"]),+ "cache": {"files": caches["total_files"], "bytes": caches["total_bytes"],+ "by_kind": caches["summary"]},+ }+++def w_resource_sync_apply(contract: WebContract, body):+ if body.get("confirm") is not True:+ raise ValueError("resource sync requires confirmation")+ # Apply never trusts an earlier browser result. Mount state and file existence are+ # checked again immediately before the bounded ledger write.+ scan = _scan_missing_resources(contract)+ missing_ids = scan["missing_ids"]+ if missing_ids:+ with contract.write_transaction() as connection:+ stamp = time.time()+ connection.executemany(+ "UPDATE asset SET disposal='trash',feedback_at=? WHERE id=?",+ [(stamp, asset_id) for asset_id in missing_ids],+ )+ contract.cache_bust()+ cleanup = _clean_resource_orphans(contract) if body.get("clean_cache", True) else {+ "cache_removed": 0, "bytes_reclaimed": 0, "cache_blocked": [],+ }+ return {"ok": True, "moved_to_trash": len(missing_ids),+ "sources": scan["sources"], **cleanup}++def w_purge_missing(contract: WebContract, body):- """按目录对账:文件已经在磁盘上删掉的,账本行一并删掉。+ """按目录对账:文件已经在磁盘上删掉的,账本行移入回收站。这条路径服务的是「我在资源管理器里整理网盘目录」——删掉的就是不要的,所以- 不进复核、不进回收站、不可恢复,播放历史等衍生行跟着一起走。+ 不进复核;账本记录仍先进入回收站,源文件恢复后还能还原。真正危险的不是删得太干净,而是把「盘没挂上」误判成「文件没了」:R: 掉线时整条来源 2,552 行都会看起来像被删。所以先做来源级在线判定,整源不在线就@@ -2549,21 +2744,13 @@ def w_purge_missing(contract: WebContract, body):contract.cache_bust()ids = [item["id"] for item in missing]- marks = ",".join("?" * len(ids))with contract.write_transaction() as connection:- connection.execute(- f"UPDATE playlist SET current_asset_id=NULL WHERE current_asset_id IN ({marks})",- ids,- )- connection.execute(- f"UPDATE playlist SET source_seed_asset_id=NULL WHERE source_seed_asset_id IN ({marks})",- ids,+ stamp = time.time()+ connection.executemany(+ "UPDATE asset SET disposal='trash',feedback_at=? WHERE id=?",+ [(stamp, asset_id) for asset_id in ids],)- for table in ASSET_REFERENCE_TABLES:- connection.execute(- f"DELETE FROM {table} WHERE asset_id IN ({marks})", ids)- # asset_search 交给 0004 的删除触发器,这里再删一遍只会重复。- connection.execute(f"DELETE FROM asset WHERE id IN ({marks})", ids)+ contract.cache_bust()return {"ok": True, "directory": photo_set_title(directory),"checked": len(rows), "removed": len(missing), "items": missing,@@ -2629,7 +2816,9 @@ def w_batch(contract: WebContract, body):_restore_staged_media(purge_outcome["_staged"])raiseif purge_outcome is not None:- return {"ok": True, "operation": operation, **_finish_purge(purge_outcome)}+ result = {"ok": True, "operation": operation, **_finish_purge(purge_outcome)}+ result.update(_clean_resource_orphans(contract))+ return resultreturn {"ok": True, "operation": operation, "changed": len(valid_ids)}@@ -2855,6 +3044,8 @@ POST_HANDLERS = {"/api/taste/source": w_taste_source,"/api/trash/empty": _post_empty_trash,"/api/purge-missing": w_purge_missing,+ "/api/resource-sync/scan": w_resource_sync_scan,+ "/api/resource-sync/apply": w_resource_sync_apply,"/api/review/auto-apply": w_review_auto_apply,"/api/review/decision": w_review_decision,}@@ -2865,7 +3056,7 @@ POST_HANDLERS = {#: 追更的「查找」在只读端被拦成 409 是实测踩到的。READ_ONLY_POST_ROUTES = frozenset({"/api/follow/resolve", "/api/follow/credential",- "/api/taste/refresh", "/api/taste/source",+ "/api/taste/refresh", "/api/taste/source", "/api/resource-sync/scan",})diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 4cfac9bc3..80fc9e1ae 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -498,6 +498,7 @@ class WebDataTests(unittest.TestCase):"/api/preference", "/api/quality-goal", "/api/item-tag", "/api/batch","/api/search-history", "/api/trash/empty", "/api/review/decision","/api/purge-missing", "/api/review/auto-apply",+ "/api/resource-sync/scan", "/api/resource-sync/apply","/api/follow/check", "/api/follow/status", "/api/follow/save","/api/follow/source", "/api/follow/resolve", "/api/follow/credential","/api/follow/author-alias", "/api/follow/schedule",@@ -2236,24 +2237,104 @@ class PurgeMissingTests(unittest.TestCase):self.assertEqual(result["error"], "source offline")self.assertEqual(self.ids(), [1, 2, 3, 4])- def test_missing_files_are_removed_with_their_derived_rows(self):+ def test_missing_files_move_to_trash_without_losing_metadata(self):result = self._run()self.assertTrue(result["ok"])self.assertEqual(result["checked"], 3)self.assertEqual(result["removed"], 2)self.assertEqual(sorted(x["id"] for x in result["items"]), [2, 3])- # 另一个目录的 4 必须原样留下。- self.assertEqual(self.ids(), [1, 4])+ # 另一个目录的 4 必须原样留下;缺失项先进入回收站,恢复源文件后仍可还原。+ self.assertEqual(self.ids(), [1, 2, 3, 4])con = sqlite3.connect(self.db_path)try:- # 衍生行跟着走:用户要的是「删干净」,不是留一堆孤儿。self.assertEqual(- [r[0] for r in con.execute("SELECT asset_id FROM asset_tag")], [4])+ con.execute("SELECT disposal FROM asset WHERE id=2").fetchone()[0], "trash")+ self.assertEqual(+ con.execute("SELECT disposal FROM asset WHERE id=3").fetchone()[0], "trash")+ # 元数据等到清空回收站才随账本行一起删。self.assertEqual(- [r[0] for r in con.execute("SELECT asset_id FROM asset_preference")], [4])+ [r[0] for r in con.execute("SELECT asset_id FROM asset_tag")], [2, 4])+ self.assertEqual(+ [r[0] for r in con.execute("SELECT asset_id FROM asset_preference")], [2, 4])finally:con.close()+ def test_full_sync_scans_all_online_assets_and_cleans_only_rebuildable_caches(self):+ roots = {}+ for name in ("snapshots", "posters", "photo-thumbs", "transcodes",+ "stream-segments", "avatars", "covers"):+ roots[name] = self.root / name+ roots[name].mkdir()+ cache_files = [+ roots["snapshots"] / "2.jpg",+ roots["posters"] / "2_4.jpg",+ roots["photo-thumbs"] / "2.jpg",+ roots["transcodes"] / "2-10-20.mp4",+ roots["stream-segments"] / "2" / "10-20-6" / "0.ts",+ roots["avatars"] / "2.jpg",+ roots["covers"] / "hey-002.jpg",+ ]+ for path in cache_files:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"cache")+ evidence = self.root / "candidate.csv"+ evidence.write_text("review evidence", encoding="utf-8")+ con = sqlite3.connect(self.db_path)+ con.execute("UPDATE asset SET code='HEY-002',snapshot_path=? WHERE id=2",+ (str(cache_files[0]),))+ con.commit();con.close()+ self.contract.snapshot_root = roots["snapshots"]+ self.contract.poster_root = roots["posters"]+ self.contract.photo_root = roots["photo-thumbs"]+ self.contract.transcode_root = roots["transcodes"]+ self.contract.stream_root = roots["stream-segments"]+ self.contract.avatar_root = roots["avatars"]+ self.contract.cover_root = roots["covers"]+ self.contract.resource_cleanup_enabled = True++ def online(location):+ return location == "115"+ with mock.patch.object(rm_web, "translate_ledger_path", self._translate), \+ mock.patch.object(rm_web, "source_is_online", online):+ preview = rm_web.w_resource_sync_scan(self.contract)+ self.assertEqual(preview["missing"], 2)+ self.assertEqual(preview["cache"]["files"], len(cache_files))+ result = rm_web.w_resource_sync_apply(+ self.contract, {"confirm": True, "clean_cache": True})++ self.assertEqual(result["moved_to_trash"], 2)+ self.assertEqual(result["cache_removed"], len(cache_files))+ self.assertTrue(all(not path.exists() for path in cache_files))+ self.assertTrue(evidence.is_file(), "候选证据不属于可删除缓存")+ con = sqlite3.connect(self.db_path)+ try:+ self.assertEqual(+ con.execute("SELECT count(*) FROM asset WHERE disposal='trash'").fetchone()[0], 2)+ finally:+ con.close()++ def test_full_sync_keeps_a_cover_shared_by_an_active_asset(self):+ covers = self.root / "covers"+ covers.mkdir()+ shared = covers / "hey-002.jpg"+ shared.write_bytes(b"cover")+ con = sqlite3.connect(self.db_path)+ con.execute("UPDATE asset SET code='HEY-002' WHERE id IN (1,2)")+ con.commit();con.close()+ self.contract.cover_root = covers+ self.contract.avatar_root = self.root / "avatars"+ self.contract.poster_root = self.root / "posters"+ self.contract.photo_root = self.root / "photo-thumbs"+ self.contract.transcode_root = self.root / "transcodes"+ self.contract.stream_root = self.root / "stream-segments"+ self.contract.resource_cleanup_enabled = True+ with mock.patch.object(rm_web, "translate_ledger_path", self._translate), \+ mock.patch.object(rm_web, "source_is_online", lambda loc: loc == "115"):+ preview = rm_web.w_resource_sync_scan(self.contract)+ self.assertEqual(preview["missing"], 2)+ self.assertTrue(shared.is_file())+ self.assertNotIn("covers", preview["cache"]["by_kind"])+def test_intact_directory_reports_no_change(self):for name in ("002.jpg", "003.jpg"):(self.root / name).write_bytes(b"x")diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 64eb4336e..5e673c075 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -545,7 +545,7 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("const MANAGE_SECTIONS=[")for section in ("'stats','统计'", "'ads','疑似广告'", "'dupes','重复文件'","'quality','高清版'", "'trash','回收站'", "'review','人工复核'",- "'taste','品味'"):+ "'taste','品味'", "'resources','资源同步'"):self.assertPageContains(section)self.assertPageContains("function manageSection()")self.assertPageContains("function buildManageBar()")@@ -571,7 +571,7 @@ class WebUiSourceTests(unittest.TestCase):sections = self.page.split("const MANAGE_SECTIONS=[", 1)[1].split("];", 1)[0]order = [line.split("'")[1] for line in sections.splitlines() if line.strip().startswith("['")]self.assertEqual(- order, ["stats", "taste", "review", "ads", "dupes", "trash", "follow", "quality"],+ order, ["stats", "taste", "review", "ads", "dupes", "resources", "trash", "follow", "quality"],"管理导航的顺序是语义契约:现状 → 复核 → 清理 → 回收站 → 往外拿",)@@ -1230,7 +1230,7 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains('data-nav="${k}" draggable="true"')self.assertPageContains("data-sidebar-hide")self.assertPageContains("data-sidebar-add-select")- self.assertPageContains("const OPTIONAL_SIDEBAR_KEYS=['stats','review','ads','dupes','trash','follow-manage','quality']")+ self.assertPageContains("const OPTIONAL_SIDEBAR_KEYS=['stats','review','ads','dupes','resources','trash','follow-manage','quality']")self.assertPageContains("if(DIRECT_MANAGE_NAV[k]){openManage(DIRECT_MANAGE_NAV[k]);return}")self.assertPageContains(".settingscard{width:min(520px,100%);max-height:min(720px,90vh);max-height:min(720px,90dvh);overflow:hidden")self.assertPageContains(".settingsscroll{max-height:inherit;overflow-y:auto")@@ -1544,6 +1544,14 @@ class WebUiSourceTests(unittest.TestCase):# 在线资产是 URL,没有本地文件可定位。self.assertPageContains("it.location==='online'?'':sourceTools(it.id)")+ def test_resource_sync_is_preview_first_and_keeps_offline_sources_safe(self):+ self.assertPageContains("if(path==='/resource-sync'){await openResourceSync(false);return}")+ self.assertPageContains("api('/api/resource-sync/scan',{method:'POST',body:'{}'})")+ self.assertPageContains("api('/api/resource-sync/apply',{method:'POST'")+ self.assertPageContains("来源离线时整库跳过")+ self.assertPageContains("同步到回收站并清理缓存")+ self.assertPageContains("候选 CSV、来源证据、女优头像和厂牌 Logo 不属于缓存")+def test_source_tool_icons_declare_stroke_and_no_fill(self):self.assertPageContains(".srctools button svg{width:15px;height:15px;stroke:currentColor;fill:none")diff --git a/web/app.css b/web/app.cssindex 17cd4525d..7d6d2c75a 100644--- a/web/app.css+++ b/web/app.css@@ -525,6 +525,7 @@ button.serieslink.entitylink:hover{color:var(--tungsten);text-decoration:none}.revieworigin>div button{display:inline-flex;align-items:center;gap:6px;border:0;border-radius:7px;background:var(--hover);padding:6px 9px;color:var(--ink-2);cursor:pointer}.revieworigin>div button:hover{color:var(--tungsten)}.revieworigin>div button svg{width:15px;height:15px;stroke:currentColor;fill:none;stroke-width:2}@media(max-width:640px){.qualitylist{grid-template-columns:1fr}.qualityitem{grid-template-columns:110px minmax(0,1fr)}.qualitycover{width:110px}.reviewcompare{grid-template-columns:1fr}.revieworigin{grid-template-columns:110px minmax(0,1fr)}.revieworigincover{width:110px}}+@media(max-width:640px){.resourcesync{padding:14px}.resourcesynchead{display:grid;gap:14px}.resourcesynchead button{width:100%;justify-content:center}.resourcesources{grid-template-columns:1fr}.resourcecache{grid-template-columns:1fr}.resourcesync #resourceApply{width:100%}}.indexmore[hidden],.entitymore[hidden]{display:none}.indexmore,.entitymore{display:flex;align-items:center;justify-content:center;margin:20px auto 0;min-width:124px;@@ -559,6 +560,8 @@ main{position:relative;z-index:1;padding:14px 16px 90px}display:flex;align-items:center;gap:10px;flex-wrap:nowrap;background:transparent;border-bottom:1px solid transparent}.count.manage-static{position:relative;top:auto;z-index:1}+.resourcesync{display:grid;gap:16px;padding:18px;border:1px solid var(--line-soft);border-radius:14px;background:var(--surface)}+.resourcesynchead{display:flex;align-items:flex-start;justify-content:space-between;gap:24px}.resourcesynchead h3{margin:0 0 6px;font-size:var(--fs-xl)}.resourcesynchead p{max-width:780px;margin:0;color:var(--muted);line-height:1.6}.resourcesynchead button{display:inline-flex;align-items:center;gap:8px;flex:none}.resourcesynchead button svg{width:17px;height:17px;stroke:currentColor;fill:none}.resourcesyncnote{padding:11px 13px;border-radius:9px;background:var(--overlay-5);color:var(--muted);font-size:var(--fs-sm);line-height:1.55}.resourcesources{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.resourcesources article{display:grid;gap:5px;padding:14px;border:1px solid var(--line-soft);border-radius:10px}.resourcesources article>b{font-size:var(--fs-lg)}.resourcesources article>span{font-size:var(--fs-xs)}.resourcesources .online{color:var(--success)}.resourcesources .offline,.resourceerror{color:var(--drop)}.resourcesources strong{margin-top:8px;font-size:var(--fs-lg)}.resourcesources small,.resourcecache small{color:var(--muted)}.resourcecache{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.resourcecache>div{display:grid;gap:3px;padding:16px;border-radius:10px;background:var(--overlay-5)}.resourcecache b{font-size:var(--fs-2xl)}.resourcecache span{font-weight:650}.resourcesync #resourceApply{justify-self:start}.resourcesyncok{margin:0;color:var(--success)}.resourcescanning,.resourceerror{margin:0}.tagbar,.count{transition:background-color .16s ease,border-color .16s ease}.tagbar.is-stuck,.count.is-stuck{background:color-mix(in srgb,#020408 84%,transparent);border-bottom-color:var(--line-soft);backdrop-filter:saturate(1.35) blur(16px);diff --git a/web/app.js b/web/app.jsindex c965b8e7d..3db911872 100644--- a/web/app.js+++ b/web/app.js@@ -79,7 +79,7 @@ function dropOfflineFromDefaultLoc(){const DURATION_TAGS=new Set(['短片-2分内','中片-10分内','长片-30分内','超长片-30分上']);const SETTINGS_KEY='peach.settings.v1';const DEFAULT_SIDEBAR_ORDER=['','performers','tags','jav','flagged','playlists','follow','immerse','manage'];-const OPTIONAL_SIDEBAR_KEYS=['stats','review','ads','dupes','trash','follow-manage','quality'];+const OPTIONAL_SIDEBAR_KEYS=['stats','review','ads','dupes','resources','trash','follow-manage','quality'];const ALL_SIDEBAR_KEYS=[...DEFAULT_SIDEBAR_ORDER,...OPTIONAL_SIDEBAR_KEYS];const DEFAULT_SETTINGS={rotateMinutes:0,batchSize:60,defaultSort:'seed',hoverDelaySeconds:5,seekSeconds:10,searchHistoryLimit:10,relatedLimit:20,javLayout:'big',sidebarOrder:DEFAULT_SIDEBAR_ORDER};let appSettings={...DEFAULT_SETTINGS};@@ -1033,6 +1033,49 @@ function showHomeSurfaces(){}function closeStats(push=true){if(push)route('/');showHomeSurfaces();load(true)}+async function openResourceSync(push=true){+ releaseHoverPreviews();+ if(push)route('/resource-sync');+ enterManagementSurface();disposeStage(false);+ $('#stats').hidden=false;$('#index').hidden=true;$('#grid').innerHTML='';buildManageBar();+ $('#count').textContent='';$('#loadSentinel').hidden=true;$('#shortsSec').hidden=true;+ $('#stats').innerHTML=`<section class="resourcesync">+ <div class="resourcesynchead"><div><h3>网盘与账本对账</h3>+ <p>只检查已挂载来源。网盘上已删除的条目先进入 Peach 回收站;封面、截图、海报、图片缩略图和播放缓存只清理没有在用的副本。</p></div>+ <button class="primary" id="resourceScan">${icon('refresh-cw')}扫描差异</button></div>+ <div class="resourcesyncnote">来源离线时整库跳过,避免把“网盘没挂上”误判成“文件已删除”。候选 CSV、来源证据、女优头像和厂牌 Logo 不属于缓存,不会删除。</div>+ <div id="resourceSyncResult" aria-live="polite"></div></section>`;+ const scan=$('#resourceScan'),result=$('#resourceSyncResult');+ const render=payload=>{+ const sources=payload.sources||[];+ const cache=payload.cache||{files:0,bytes:0};+ result.innerHTML=`<div class="resourcesources">${sources.map(source=>`<article>+ <b>${esc(LOC[source.location]||source.location)}</b><span class="${source.online?'online':'offline'}">${source.online?'已挂载':'离线,已跳过'}</span>+ <strong>${source.online?`${source.missing.toLocaleString()} 项已从网盘删除`:'—'}</strong>+ <small>${source.online?`已核对 ${source.checked.toLocaleString()} 项`:`账本有 ${source.total.toLocaleString()} 项`}</small></article>`).join('')}</div>+ <div class="resourcecache"><div><b>${cache.files.toLocaleString()}</b><span>个孤立缓存</span><small>${fmtSize(cache.bytes||0)}</small></div>+ <div><b>${Number(payload.missing||0).toLocaleString()}</b><span>项待同步</span><small>应用后进入回收站</small></div></div>+ ${(payload.missing||cache.files)?`<button class="danger" id="resourceApply">同步到回收站并清理缓存</button>`:+ '<p class="resourcesyncok">账本与已挂载来源一致,没有孤立缓存。</p>'}`;+ $('#resourceApply')?.addEventListener('click',async event=>{+ const button=event.currentTarget;+ if(!confirm(`把 ${payload.missing||0} 项移入回收站,并清理 ${cache.files||0} 个可重建缓存?`))return;+ button.disabled=true;button.textContent='正在重新核对并应用…';+ try{+ const applied=await api('/api/resource-sync/apply',{method:'POST',body:JSON.stringify({confirm:true,clean_cache:true})});+ result.innerHTML=`<p class="resourcesyncok">已把 ${applied.moved_to_trash.toLocaleString()} 项移入回收站,清理 ${applied.cache_removed.toLocaleString()} 个缓存,释放 ${fmtSize(applied.bytes_reclaimed||0)}。</p>`;+ }catch(error){button.disabled=false;button.textContent='重试同步';result.insertAdjacentHTML('beforeend',`<p class="resourceerror">${esc(error.message)}</p>`)}+ });+ };+ scan.onclick=async()=>{+ scan.disabled=true;scan.innerHTML=`${icon('refresh-cw')}正在扫描…`;result.innerHTML='<p class="resourcescanning">正在核对网盘元数据,不会读取视频内容。</p>';+ try{render(await api('/api/resource-sync/scan',{method:'POST',body:'{}'}))}+ catch(error){result.innerHTML=`<p class="resourceerror">扫描失败:${esc(error.message)}</p>`}+ finally{scan.disabled=false;scan.innerHTML=`${icon('refresh-cw')}重新扫描`}+ };+ window.scrollTo({top:0,behavior:'smooth'});+}+let tasteWindow='all';const tasteDate=value=>value?new Date(value).toLocaleDateString('zh-CN'):'—';const tasteHours=seconds=>seconds>=3600?(seconds/3600).toFixed(1)+' 小时':Math.round(seconds/60)+' 分钟';@@ -2796,7 +2839,7 @@ function renderPhotoWall(kind,name,filters,data,append=false){标题旁两个按钮,服务的是「跳过去自己整理网盘目录」这条来回:定位打开源文件所在目录(A:/B: 是 CloudDrive 挂上来的盘符,在资源管理器里和本地目录没区别),在那边删掉不要的,回来点一下同步,账本跟着对齐。- 删除不进复核也不可恢复——手动删掉的就是不要的。真正要防的是把「盘没挂上」当成+ 删除不进复核,但账本记录先放进回收站。真正要防的是把「盘没挂上」当成「文件没了」,那个闸门在服务端:整条来源不在线时直接拒绝,一行都不动。路径始终由服务端按 asset id 查,前端拿不到也不该拿到 `path`。 ── */const SOURCE_HINTS={@@ -2822,7 +2865,7 @@ async function syncMissing(id,status,done){const r=await api('/api/purge-missing',{method:'POST',body:JSON.stringify({id})});if(r.ok===false){status.textContent=sourceHint(r.error);return}status.textContent=r.removed- ? `已从账本移除 ${r.removed} 项(核对 ${r.checked} 项)`+ ? `已把 ${r.removed} 项移入回收站(核对 ${r.checked} 项)`: `目录内 ${r.checked} 项都还在,无需改动`;if(r.removed&&done)done(r);}catch(e){status.textContent=sourceHint(e.message)}@@ -2832,7 +2875,7 @@ async function syncMissing(id,status,done){const sourceTools=id=>`<div class="srctools"><button type="button" data-reveal="${id}" title="在文件管理器里打开源文件所在目录"aria-label="定位源文件">${icon('folder-open')}</button>- <button type="button" data-sync="${id}" title="核对该目录:磁盘上已删除的,从账本一并移除"+ <button type="button" data-sync="${id}" title="核对该目录:磁盘上已删除的,移入 Peach 回收站"aria-label="同步删除">${icon('refresh-cw')}</button><span class="srcstate" aria-live="polite"></span></div>`;@@ -3044,6 +3087,7 @@ const MANAGE_SECTIONS=[['review','人工复核','square-check-big'],['ads','疑似广告','alert'],['dupes','重复文件','hard-drive'],+ ['resources','资源同步','refresh-cw'],['trash','回收站','trash'],['follow','关注','rss'],['quality','高清版','sparkles'],@@ -3051,7 +3095,7 @@ const MANAGE_SECTIONS=[const OPTIONAL_EDGE_ICONS=MANAGE_SECTIONS.map(([key,label,ic])=>key==='follow'?['follow-manage','关注管理',ic]:[key,label,ic]);const NAV_CATALOG=[...EDGE_ICONS,...OPTIONAL_EDGE_ICONS];-const DIRECT_MANAGE_NAV={stats:'stats',review:'review',ads:'ads',dupes:'dupes',trash:'trash','follow-manage':'follow',quality:'quality'};+const DIRECT_MANAGE_NAV={stats:'stats',review:'review',ads:'ads',dupes:'dupes',resources:'resources',trash:'trash','follow-manage':'follow',quality:'quality'};function orderedEdgeIcons(){const byKey=new Map(NAV_CATALOG.map(item=>[item[0],item]));return appSettings.sidebarOrder.map(key=>byKey.get(key)).filter(Boolean);@@ -3158,6 +3202,7 @@ function manageSection(){if(path==='/review')return 'review';if(path==='/trash')return 'trash';if(path==='/duplicates')return 'dupes';+ if(path==='/resource-sync')return 'resources';if(path==='/quality-goals')return 'quality';if(path==='/follow-manage')return 'follow';return state.state==='ads'?'ads':'';@@ -3202,6 +3247,7 @@ function openManage(section='stats'){if(section==='taste'){openTaste();return}if(section==='review'){openReview();return}if(section==='dupes'){openDuplicates();return}+ if(section==='resources'){openResourceSync();return}if(section==='quality'){openQualityGoals();return}if(section==='follow'){openFollowManage();return}state.orient='';state.state=section==='trash'?'trash':'ads';@@ -4335,6 +4381,7 @@ async function restoreRoute(){if(path==='/taste'){await openTaste(false);return}if(path==='/review'){await openReview(false);return}if(path==='/duplicates'){await openDuplicates(false);return}+ if(path==='/resource-sync'){await openResourceSync(false);return}if(path==='/quality-goals'){await openQualityGoals(false);return}if(path==='/follow'){await openFollow(false);return}if(path==='/follow-manage'){await openFollowManage(false);return}