Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix: run resource reconciliation in background

longmeidao77c5a8ef5f59
diff --git a/README.md b/README.md
index a9df6c72b..d653bf15a 100644
--- a/README.md
+++ b/README.md
@@ -102,7 +102,7 @@ macOS/Linux 用 `./scripts/test.sh follow`。可选域为 `follow`、`catalog`
`/healthz` 提供无副作用健康状态,`/api/sources` 提供来源可达性。其他 API 契约以实现和测试为准,不在 README 维护容易漂移的端点全集。
-在网盘或本地资源目录手动删除文件后,进入「管理 → 资源同步」先扫描差异。Peach 只核对已挂载来源;缺失条目先进入回收站,可恢复的账本元数据不会立即丢失。确认同步时会同时清理不再被正常馆藏使用的截图、海报、图片缩略图、封面和播放缓存;候选 CSV、来源证据、女优头像和厂牌 Logo 不作缓存删除。
+在网盘或本地资源目录手动删除文件后,进入「管理 → 资源同步」先扫描差异。扫描在后台运行并逐来源显示进度,离开页面不会中断;Peach 只核对已挂载来源,暂时不可读的目录会跳过而不是判成删除。缺失条目先进入回收站,可恢复的账本元数据不会立即丢失。确认同步时会再次核对候选项,并清理不再被正常馆藏使用的截图、海报、图片缩略图、封面和播放缓存;候选 CSV、来源证据、女优头像和厂牌 Logo 不作缓存删除。
## 关注与候选
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 234e49011..32c3e3877 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -144,7 +144,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 不在自动清理边界。
+- 网盘目录由人在 CloudDrive 外部整理后,必须经「管理 → 资源同步」显式对账,不做后台静默删除。扫描只核对已挂载的 `local`/`115`/`pikpak`;离线来源整源跳过,单个目录不可读时保留账本行并回报。真实账本约 8 万条、3673 个目录,逐文件或同步 HTTP 请求实测 5 分钟仍未返回;因此全库扫描必须使用后台作业并逐来源回报进度,同一目录只枚举一次,目录元数据并发固定为 8。应用不得重跑全库或盲信旧结果,只重新核对本次发现的缺失候选。源文件缺失的 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.md
index 0077f20cc..72b62886d 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -40,7 +40,7 @@
- 0.7.9 将 Rule34.xxx 封面从 250×141 `preview_url` 升级为官方 `sample_url`,历史行按同一 bucket/hash 只读升级,不改 ledger;Rule34 Paheal 图片直接读原图,视频按需双并发抽取并缓存最大 1280px JPEG。抽帧在开头 30 秒用 FFmpeg `blackframe` 选第一张黑色像素低于 98% 的帧,版本化缓存键会自动淘汰旧黑帧,全黑或超时继续回退低清封面。真实生产样本:Rule34.xxx 为 1080×1920,Paheal 图片为 1920×2964,Paheal 视频封面为 1280×720、黑像素占 28.9%,旧缓存已在请求后原子替换。关注域 410 项、Windows 正式全量 1176 项通过,分别有 1/13 项按平台跳过。正式 EXE SHA-256 为 `2719F6D3CC9951DC11FB387A49CFEF1ED19DC4A7CCEF27100C44A47A53833F65`,上版备份为 `dist/Peach/Peach.pre-0.7.9-20260828-224816.exe`;22 个迁移、0 待处理,80/443 已恢复,项目 CA 严格 HTTPS 返回 0.7.9、writer、非只读。生产浏览器首屏实测 Rule34.xxx 3840×2160、Paheal 1280×720,无横向溢出与控制台错误。未触发关注检查,ledger SHA-256 保持 `A03E3B450B2721B7FB8078D4A3751C498750B1A8608C66F49CCBD96AE949BF6F`。
- 0.7.8 修复 JAV 大图的两个同批回归:Mix 卡片现在与同一网格里的作品共用大图比例和官方封面,不再单独掉回 16:9;生成缓存清理新增数据库所属 data root 边界,临时数据库即使漏配默认缓存根也不能越界删除真实 `peach-data/generated`。事故复核确认 0.7.6 开发期的 FastAPI 清空回收站测试虽然使用临时 ledger,却漏传 `cover_root`/`stream_root`,因此把真实 `covers` 当成孤立缓存;目录在 2026-08-28 21:12 被清空。旧抓取日志仍有 484 条证据,其中 243 张成功、241 张未取得;新增 `fetch_jav_covers.py --restore-successes` 只按成功记录的原 URL、原尺寸原子恢复,不重新探测来源、不写 ledger。与并发关注封面改动重放后,Windows 正式全量测试 1175 项通过、13 项按平台跳过。243 张成功记录已全部按原尺寸恢复,日志 SHA-256 仍为 `EED7DA6D1D522260BBF060C0B47FDF22E98FDDF202AE4DA65FB435A5FE309B39`,ledger SHA-256 仍为 `A03E3B450B2721B7FB8078D4A3751C498750B1A8608C66F49CCBD96AE949BF6F`。用户手动重启服务后,项目 CA 严格 HTTPS 返回 0.7.8、writer、非只读;`ABP-993` 封面返回 200 `image/jpeg`。生产页面桌面实测 Mix 与普通 JAV 卡片均为 383.3×547.6、比例 0.7;390×844 下 `ABP-993` 为 348×497.1、无横向溢出,浏览器错误 0。生产 EXE 未在本批替换。
-- 0.7.6 新增「管理 → 资源同步」:只读扫描逐来源核对 `local`、115、PikPak,整源离线时跳过;确认应用会重新核对,把网盘上已删除的 asset 先移入 Peach 回收站,并清理没有正常馆藏引用的截图、海报、图片缩略图、转码、流媒体片段、按 asset 生成的头像和共享番号封面。候选 CSV、来源证据、实体头像和 Logo 明确排除。详情页原有目录同步也改为先入回收站,不再直接删账本;清空回收站后统一清理派生缓存。共享封面、离线整源、临时测试库不触碰真实 generated 根均有数据层门槛;桌面和 390×844 响应式源码契约已覆盖。正式 Windows 全量测试 1157 项通过、13 项按平台跳过;未在生产执行资源扫描或应用清理,真实 ledger 未写,但正式测试的缓存根隔离缺口实际清空了真实 `generated/covers`,更正与修复见 0.7.8。
+- 0.7.6 新增「管理 → 资源同步」:只读扫描逐来源核对 `local`、115、PikPak,整源离线时跳过;确认应用会重新核对,把网盘上已删除的 asset 先移入 Peach 回收站,并清理没有正常馆藏引用的截图、海报、图片缩略图、转码、流媒体片段、按 asset 生成的头像和共享番号封面。候选 CSV、来源证据、实体头像和 Logo 明确排除。详情页原有目录同步也改为先入回收站,不再直接删账本;清空回收站后统一清理派生缓存。共享封面、离线整源、临时测试库不触碰真实 generated 根均有数据层门槛;桌面和 390×844 响应式源码契约已覆盖。正式 Windows 全量测试 1157 项通过、13 项按平台跳过;未在生产执行应用清理,真实 ledger 未写,但正式测试的缓存根隔离缺口实际清空了真实 `generated/covers`,更正与修复见 0.7.8。后续生产只读扫描因约 8 万条记录和 3673 个目录在 5 分钟后超时,现改为可离页的后台作业、逐来源进度、同目录单次枚举和固定 8 路目录元数据读取;应用只重查本轮缺失候选,目录暂时不可读不进入回收站。
- 艺人、厂牌、创作者、系列资料页的作品区统一复用首页排序:换一批、推荐顺序、每日轮换、随机、评分、高潮计数、观看次数、时长、体积、最近入库、最近看的;照片瀑布流和管理队列不添加无适用语义的排序。资料页 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/web_contract.py b/src/peach/web_contract.py
index fc9289b47..32eaece4f 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -15,9 +15,10 @@ import shutil
import threading
import time
import uuid
+from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime, timedelta
from pathlib import Path, PurePosixPath
-from typing import Sequence
+from typing import Callable, Sequence
from urllib.parse import quote, urlsplit
from .config import (
@@ -169,6 +170,9 @@ class WebContract:
self.cache_lock = threading.Lock()
self.follow_check_lock = threading.Lock()
self.follow_scheduler = None
+ self.resource_scan_lock = threading.Lock()
+ self.resource_scan_state: dict | None = None
+ self.resource_scan_thread: threading.Thread | None = None
self._fts_available: bool | None = None
def cached(self, key, fn):
@@ -2522,7 +2526,74 @@ def source_is_online(location: str) -> bool:
return not is_unmapped(resolved) and root_online(resolved)
-def _scan_missing_resources(contract: WebContract) -> dict:
+RESOURCE_SCAN_WORKERS = 8
+
+
+def _scan_resource_directory(
+ item: tuple[Path, dict[str, list[int]]],
+) -> tuple[list[int], int]:
+ parent, expected = item
+ present: set[str] = set()
+ unreadable = 0
+ try:
+ with os.scandir(parent) as entries:
+ for entry in entries:
+ key = entry.name.casefold()
+ if key not in expected:
+ continue
+ try:
+ if entry.is_file():
+ present.add(key)
+ except OSError:
+ # The name was returned but its type could not be read. Preserve the
+ # ledger row and report it as unreadable instead of declaring deletion.
+ present.add(key)
+ unreadable += len(expected[key])
+ except FileNotFoundError:
+ return [asset_id for ids in expected.values() for asset_id in ids], 0
+ except OSError:
+ return [], sum(len(ids) for ids in expected.values())
+ return (
+ [asset_id for key, ids in expected.items() if key not in present for asset_id in ids],
+ unreadable,
+ )
+
+
+def _missing_resource_ids(rows: Sequence) -> tuple[list[int], int]:
+ """Compare ledger paths one directory listing at a time.
+
+ Cloud mounts make one ``stat`` request per path painfully slow. ``scandir`` reuses the
+ directory enumeration that the filesystem already returns, while retaining the same
+ case-insensitive Windows path semantics. An unreadable directory is skipped rather than
+ being mistaken for a directory that the user deleted.
+ """
+ directories: dict[Path, dict[str, list[int]]] = {}
+ for row in rows:
+ path = translate_ledger_path(row["path"])
+ expected = directories.setdefault(path.parent, {})
+ expected.setdefault(path.name.casefold(), []).append(int(row["id"]))
+
+ directory_items = list(directories.items())
+ if len(directory_items) <= 1:
+ results = [_scan_resource_directory(item) for item in directory_items]
+ else:
+ # CloudDrive directory reads are latency-bound metadata requests. Keep concurrency
+ # deliberately small: enough to hide round trips without turning a scan into a media
+ # download or overwhelming either mounted provider.
+ with ThreadPoolExecutor(
+ max_workers=min(RESOURCE_SCAN_WORKERS, len(directory_items)),
+ thread_name_prefix="PeachResourceScan",
+ ) as executor:
+ results = list(executor.map(_scan_resource_directory, directory_items))
+ missing = [asset_id for ids, _unreadable in results for asset_id in ids]
+ unreadable = sum(count for _ids, count in results)
+ return missing, unreadable
+
+
+def _scan_missing_resources(
+ contract: WebContract,
+ progress: Callable[[dict], None] | None = None,
+) -> dict:
"""Read-only reconciliation against every mounted filesystem source."""
with contract.read_connection() as connection:
rows = connection.execute(
@@ -2539,15 +2610,18 @@ def _scan_missing_resources(contract: WebContract) -> dict:
items = grouped.get(location, [])
online = source_is_online(location)
missing = []
+ unreadable = 0
if online:
- for row in items:
- if not translate_ledger_path(row["path"]).is_file():
- missing.append(row["id"])
+ missing, unreadable = _missing_resource_ids(items)
missing_ids.extend(missing)
- sources.append({
- "location": location, "online": online, "checked": len(items) if online else 0,
- "total": len(items), "missing": len(missing),
- })
+ source = {
+ "location": location, "online": online,
+ "checked": max(0, len(items) - unreadable) if online else 0,
+ "total": len(items), "missing": len(missing), "unreadable": unreadable,
+ }
+ sources.append(source)
+ if progress is not None:
+ progress(source)
return {"sources": sources, "missing_ids": missing_ids}
@@ -2691,7 +2765,77 @@ def _clean_resource_orphans(contract: WebContract) -> dict:
"cache_blocked": blocked}
-def w_resource_sync_scan(contract: WebContract, _body=None):
+def _resource_scan_public(state: dict) -> dict:
+ if state["status"] == "complete":
+ return {**state["result"], "status": "complete", "scan_id": state["scan_id"]}
+ return {
+ "ok": state["status"] != "failed",
+ "status": state["status"],
+ "scan_id": state["scan_id"],
+ "sources": [dict(source) for source in state["sources"]],
+ "completed_sources": len(state["sources"]),
+ "total_sources": len(LOCATION_ROOT_DECLARATIONS),
+ **({"error": state["error"]} if state["status"] == "failed" else {}),
+ }
+
+
+def _run_resource_scan(contract: WebContract, scan_id: str) -> None:
+ def progress(source: dict) -> None:
+ with contract.resource_scan_lock:
+ state = contract.resource_scan_state
+ if state is not None and state["scan_id"] == scan_id:
+ state["sources"].append(dict(source))
+
+ try:
+ scan = _scan_missing_resources(contract, progress)
+ caches = _resource_orphan_plan(contract, scan["missing_ids"])
+ result = {
+ "ok": True, "sources": scan["sources"],
+ "missing": len(scan["missing_ids"]),
+ "cache": {"files": caches["total_files"], "bytes": caches["total_bytes"],
+ "by_kind": caches["summary"]},
+ }
+ with contract.resource_scan_lock:
+ state = contract.resource_scan_state
+ if state is not None and state["scan_id"] == scan_id:
+ state.update(status="complete", result=result,
+ missing_ids=list(scan["missing_ids"]), completed_at=time.time())
+ except Exception as error: # Background failures must become a pollable state.
+ with contract.resource_scan_lock:
+ state = contract.resource_scan_state
+ if state is not None and state["scan_id"] == scan_id:
+ state.update(status="failed", error=f"{type(error).__name__}: {error}",
+ completed_at=time.time())
+
+
+def _background_resource_scan(contract: WebContract, restart: bool = False) -> dict:
+ thread = None
+ with contract.resource_scan_lock:
+ state = contract.resource_scan_state
+ if state is not None and state["status"] == "running":
+ return _resource_scan_public(state)
+ if state is not None and not restart:
+ return _resource_scan_public(state)
+ scan_id = uuid.uuid4().hex
+ state = {
+ "scan_id": scan_id, "status": "running", "sources": [],
+ "started_at": time.time(), "result": None, "missing_ids": [], "error": "",
+ }
+ contract.resource_scan_state = state
+ thread = threading.Thread(
+ target=_run_resource_scan, args=(contract, scan_id), daemon=True,
+ name="PeachResourceScanJob",
+ )
+ contract.resource_scan_thread = thread
+ response = _resource_scan_public(state)
+ thread.start()
+ return response
+
+
+def w_resource_sync_scan(contract: WebContract, body=None):
+ body = body or {}
+ if body.get("background") is True:
+ return _background_resource_scan(contract, restart=body.get("restart") is True)
scan = _scan_missing_resources(contract)
caches = _resource_orphan_plan(contract, scan["missing_ids"])
return {
@@ -2702,13 +2846,52 @@ def w_resource_sync_scan(contract: WebContract, _body=None):
}
+def _recheck_resource_scan_ids(contract: WebContract, asset_ids: Sequence[int]) -> list[int]:
+ if not asset_ids:
+ return []
+ rows = []
+ with contract.read_connection() as connection:
+ for offset in range(0, len(asset_ids), 400):
+ batch = list(asset_ids[offset:offset + 400])
+ marks = ",".join("?" for _item in batch)
+ rows.extend(connection.execute(
+ "SELECT id,location,path FROM asset "
+ f"WHERE id IN ({marks}) AND path IS NOT NULL "
+ "AND COALESCE(disposal,'')!='trash'",
+ batch,
+ ).fetchall())
+ grouped: dict[str, list] = {}
+ for row in rows:
+ grouped.setdefault(row["location"], []).append(row)
+ missing = []
+ for location, items in grouped.items():
+ if not source_is_online(location):
+ continue
+ source_missing, _unreadable = _missing_resource_ids(items)
+ missing.extend(source_missing)
+ return missing
+
+
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"]
+ scan_id = str(body.get("scan_id") or "")
+ if scan_id:
+ with contract.resource_scan_lock:
+ state = contract.resource_scan_state
+ if (state is None or state["scan_id"] != scan_id
+ or state["status"] != "complete"):
+ raise ValueError("resource scan expired; scan again")
+ candidates = list(state["missing_ids"])
+ sources = [dict(source) for source in state["result"]["sources"]]
+ # Do not trust the background result at write time. Recheck only its bounded
+ # candidate set; online sources and unreadable directories retain the safe skip.
+ missing_ids = _recheck_resource_scan_ids(contract, candidates)
+ scan = {"sources": sources, "missing_ids": missing_ids}
+ else:
+ # Compatibility path for non-browser callers: still perform a fresh full scan.
+ scan = _scan_missing_resources(contract)
+ missing_ids = scan["missing_ids"]
if missing_ids:
with contract.write_transaction() as connection:
stamp = time.time()
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index f597dbd5b..7aa3c34e0 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -1,7 +1,9 @@
import csv
import json
+import os
import sqlite3
import tempfile
+import time
import unittest
from contextlib import contextmanager
from pathlib import Path
@@ -2313,6 +2315,58 @@ class PurgeMissingTests(unittest.TestCase):
finally:
con.close()
+ def test_full_sync_lists_each_directory_once_instead_of_stating_every_file(self):
+ real_scandir = os.scandir
+ with mock.patch.object(rm_web, "translate_ledger_path", self._translate), \
+ mock.patch.object(rm_web, "source_is_online", lambda loc: loc == "115"), \
+ mock.patch.object(rm_web.os, "scandir", wraps=real_scandir) as scandir:
+ preview = rm_web.w_resource_sync_scan(self.contract)
+
+ self.assertEqual(preview["missing"], 2)
+ self.assertEqual(scandir.call_count, 1)
+ source = next(row for row in preview["sources"] if row["location"] == "115")
+ self.assertEqual(source["checked"], 4)
+ self.assertEqual(source["unreadable"], 0)
+
+ def test_full_sync_skips_an_unreadable_directory_instead_of_trashing_it(self):
+ with mock.patch.object(rm_web, "translate_ledger_path", self._translate), \
+ mock.patch.object(rm_web, "source_is_online", lambda loc: loc == "115"), \
+ mock.patch.object(rm_web.os, "scandir", side_effect=PermissionError("offline")):
+ preview = rm_web.w_resource_sync_scan(self.contract)
+
+ self.assertEqual(preview["missing"], 0)
+ source = next(row for row in preview["sources"] if row["location"] == "115")
+ self.assertEqual(source["checked"], 0)
+ self.assertEqual(source["unreadable"], 4)
+
+ def test_background_sync_polls_then_rechecks_only_missing_candidates(self):
+ with mock.patch.object(rm_web, "translate_ledger_path", self._translate), \
+ mock.patch.object(rm_web, "source_is_online", lambda loc: loc == "115"):
+ started = rm_web.w_resource_sync_scan(
+ self.contract, {"background": True, "restart": True})
+ self.assertEqual(started["status"], "running")
+ deadline = time.time() + 2
+ while True:
+ status = rm_web.w_resource_sync_scan(
+ self.contract, {"background": True})
+ if status["status"] != "running":
+ break
+ self.assertLess(time.time(), deadline)
+ time.sleep(0.01)
+ self.assertEqual(status["status"], "complete")
+ self.assertEqual(status["missing"], 2)
+ result = rm_web.w_resource_sync_apply(self.contract, {
+ "confirm": True, "clean_cache": False, "scan_id": status["scan_id"],
+ })
+
+ self.assertEqual(result["moved_to_trash"], 2)
+ 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()
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 6d03237b8..0e1b8821a 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -1615,8 +1615,12 @@ class WebUiSourceTests(unittest.TestCase):
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/scan',{method:'POST'")
self.assertPageContains("api('/api/resource-sync/apply',{method:'POST'")
+ self.assertPageContains("source.unreadable")
+ self.assertPageContains("background:true,restart:true")
+ self.assertPageContains("payload.status==='running'")
+ self.assertPageContains("location.pathname!=='/resource-sync'")
self.assertPageContains("来源离线时整库跳过")
self.assertPageContains("同步到回收站并清理缓存")
self.assertPageContains("候选 CSV、来源证据、女优头像和厂牌 Logo 不属于缓存")
diff --git a/web/app.js b/web/app.js
index 13f0f21b9..8816b67f7 100644
--- a/web/app.js
+++ b/web/app.js
@@ -15,7 +15,7 @@ const pageTitle=path=>{
const fixed={stats:'统计',taste:'品味',review:'人工复核',duplicates:'重复文件','quality-goals':'高清版',
follow:'关注','follow-manage':'关注管理',playlists:'播放列表',performers:'女优',studios:'厂牌',
creators:'创作者',series:'系列',tags:'标签',unseen:'没看过','watch-later':'稍后看',flagged:'已标记',
- immerse:'沉浸模式',mix:'Mix',item:'作品'};
+ immerse:'沉浸模式',mix:'Mix',item:'作品','resource-sync':'资源同步'};
const label=parts.length>1&&['performers','studios','creators','series'].includes(parts[0])
? parts.slice(1).join('/') : fixed[parts[0]];
return label?`${label} · Peach`:'Peach · 蜜桃';
@@ -1057,7 +1057,7 @@ async function openResourceSync(push=true){
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>
+ <small>${source.online?`已核对 ${source.checked.toLocaleString()} 项${source.unreadable?` · ${source.unreadable.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>`:
@@ -1067,14 +1067,26 @@ async function openResourceSync(push=true){
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})});
+ const applied=await api('/api/resource-sync/apply',{method:'POST',body:JSON.stringify({confirm:true,clean_cache:true,scan_id:payload.scan_id||''})});
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:'{}'}))}
+ scan.disabled=true;scan.innerHTML=`${icon('refresh-cw')}正在扫描…`;result.innerHTML='<p class="resourcescanning">正在后台核对网盘元数据,不会读取视频内容。</p>';
+ try{
+ let payload=await api('/api/resource-sync/scan',{method:'POST',body:JSON.stringify({background:true,restart:true})});
+ while(payload.status==='running'){
+ const done=payload.sources||[];
+ result.innerHTML=`<p class="resourcescanning">后台扫描中:已完成 ${payload.completed_sources||0} / ${payload.total_sources||3} 个来源${done.length?`(${done.map(source=>esc(LOC[source.location]||source.location)).join('、')})`:''}。离开本页不会中断。</p>`;
+ await new Promise(resolve=>setTimeout(resolve,2000));
+ if(location.pathname!=='/resource-sync')return;
+ payload=await api('/api/resource-sync/scan',{method:'POST',body:JSON.stringify({background:true})});
+ }
+ if(payload.status==='failed')throw new Error(payload.error||'后台扫描失败');
+ if(location.pathname!=='/resource-sync')return;
+ render(payload);
+ }
catch(error){result.innerHTML=`<p class="resourceerror">扫描失败:${esc(error.message)}</p>`}
finally{scan.disabled=false;scan.innerHTML=`${icon('refresh-cw')}重新扫描`}
};