Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor(web): 资源对账域从 web_contract 拆出

longmeidao172b62222006
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 920ca88db..9f2e3bfa8 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -17,7 +17,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"catalog": ("test_ad_judgement.py", "test_duplicate_identity_merge.py",
"test_entity_merge.py", "test_fastapi_api.py", "test_migrations.py",
"test_review_mirror.py", "test_rm_ledger.py", "test_rm_web.py",
- "test_taste_history.py", "test_web_ui.py"),
+ "test_taste_history.py", "test_web_ui.py", "test_web_resource_sync.py"),
"media": ("test_endcard.py", "test_fastapi_api.py", "test_jobs.py",
"test_media.py", "test_providers.py", "test_segments.py",
"test_streaming.py", "test_transcodes.py"),
diff --git a/src/peach/catalog_rules.py b/src/peach/catalog_rules.py
index b28e45e8a..9ac5fc049 100644
--- a/src/peach/catalog_rules.py
+++ b/src/peach/catalog_rules.py
@@ -212,3 +212,31 @@ def duration_clusters(items: list[dict]) -> list[list[dict]]:
clusters.append([item])
clusters.extend([item] for item in items if not (item.get("duration") or 0) > 0)
return clusters
+
+
+def dir_expr(alias: str = "a.") -> str:
+ """从 `path` 去掉 `name` 和分隔符,剩下的就是所在目录。
+
+ 表别名做成参数,是因为图集查询用 `a.`、按目录对账时直接查 `asset` 不带别名;
+ 早先靠对常量做字符串替换来凑另一种写法,改一次别名就会悄悄失配。
+ """
+ return (f"substr({alias}path,1,"
+ f"length({alias}path)-length({alias}name)-1)")
+
+
+#: 只写「这是图片」的通用目录名。它们做标题没有信息量,改用上一级目录名。
+GENERIC_PHOTO_DIRS = frozenset({
+ "p", "photo", "photos", "pic", "pics", "picture", "pictures",
+ "image", "images", "img", "图片", "写真", "照片",
+})
+
+
+def photo_set_title(directory: str) -> str:
+ """图集标题:叶子目录名;叶子只是 `P`、`图片` 这类通用名时用上一级。"""
+ parts = [part for part in str(directory).replace("/", "\\").split("\\") if part]
+ if not parts:
+ return "未命名图集"
+ leaf = parts[-1]
+ if leaf.casefold() in GENERIC_PHOTO_DIRS and len(parts) > 1:
+ return parts[-2]
+ return leaf
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index c3c58fb68..b29ad8073 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -67,8 +67,10 @@ from .web_activity import (
from .catalog_rules import (
DUPLICATE_FLOOR_SECONDS,
DUPLICATE_TOLERANCE,
+ GENERIC_PHOTO_DIRS,
LENGTH_TAGS,
TECH_TAGS,
+ dir_expr,
duration_clusters,
face_focus,
is_jav_asset,
@@ -76,9 +78,17 @@ from .catalog_rules import (
normalise_code_key,
ordered_multipart_items,
part_marker,
+ photo_set_title,
tag_cat,
)
from .web_playlists import q_playlist, q_playlists, w_playlist
+from .web_resource_sync import (
+ clean_resource_orphans,
+ source_is_online,
+ w_purge_missing,
+ w_resource_sync_apply,
+ w_resource_sync_scan,
+)
COST = {"local": "free", "115": "free", "pikpak": "metered", "online": "metered"}
@@ -1111,25 +1121,9 @@ def q_entity(contract: WebContract, args):
# `<作品目录>\P\001.jpg` 这种约定在 A:/B: 上到处都是。图集的 id 用目录里最小的
# 资产 id,既稳定又不用把真实路径发给前端(`q_item` 同样不发 `path`)。
-def dir_expr(alias: str = "a.") -> str:
- """从 `path` 去掉 `name` 和分隔符,剩下的就是所在目录。
-
- 表别名做成参数,是因为图集查询用 `a.`、按目录对账时直接查 `asset` 不带别名;
- 早先靠对常量做字符串替换来凑另一种写法,改一次别名就会悄悄失配。
- """
- return (f"substr({alias}path,1,"
- f"length({alias}path)-length({alias}name)-1)")
-
-
#: 图集查询一律带 `a.` 别名。
PHOTO_DIR = dir_expr()
-#: 只写「这是图片」的通用目录名。它们做标题没有信息量,改用上一级目录名。
-GENERIC_PHOTO_DIRS = frozenset({
- "p", "photo", "photos", "pic", "pics", "picture", "pictures",
- "image", "images", "img", "图片", "写真", "照片",
-})
-
def _resolve_entity(c, kind, name):
"""先取精确规范名,再取唯一别名;撞名时不任意指向另一位。"""
@@ -1159,17 +1153,6 @@ def _display_entity_aliases(canonical_name: str, aliases: list[str]) -> list[str
if east_asian.search(alias or "") or not re.search(r"[A-Za-z]", alias or "")]
-def photo_set_title(directory: str) -> str:
- """图集标题:叶子目录名;叶子只是 `P`、`图片` 这类通用名时用上一级。"""
- parts = [part for part in str(directory).replace("/", "\\").split("\\") if part]
- if not parts:
- return "未命名图集"
- leaf = parts[-1]
- if leaf.casefold() in GENERIC_PHOTO_DIRS and len(parts) > 1:
- return parts[-2]
- return leaf
-
-
def q_entity_photos(contract: WebContract, args):
"""实体名下的图片瀑布流;目录分组只保留为兼容元数据。"""
kind, name = args.get("kind", ""), args.get("name", "")
@@ -2515,463 +2498,10 @@ def w_empty_trash(contract: WebContract):
_restore_staged_media(outcome["_staged"])
raise
result = {"ok": True, "operation": "empty-trash", **_finish_purge(outcome)}
- result.update(_clean_resource_orphans(contract))
+ result.update(clean_resource_orphans(contract))
return result
-def source_is_online(location: str) -> bool:
- """这个来源整体在不在线。对账前的唯一闸门。"""
- declared = LOCATION_ROOT_DECLARATIONS.get(location)
- if not declared:
- return False
- resolved = translate_ledger_path(declared)
- return not is_unmapped(resolved) and root_online(resolved)
-
-
-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(
- "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 = []
- unreadable = 0
- if online:
- missing, unreadable = _missing_resource_ids(items)
- missing_ids.extend(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}
-
-
-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 _managed_cache_root(contract: WebContract, root: Path | None) -> bool:
- """Only let a ledger clean caches inside its own runtime data directory.
-
- Production stores ``ledger.db`` under ``peach-data/database`` and generated files under
- the sibling ``peach-data/generated`` directory. Isolated tests commonly put the database
- directly in a temporary root. In both shapes the database identifies the only directory
- tree cleanup may enter. This prevents a temporary database paired with a forgotten default
- cache root from treating the real generated files as orphans.
- """
- if root is None:
- return False
- database_parent = Path(contract.db_path).resolve().parent
- data_root = (database_parent.parent if database_parent.name.casefold() == "database"
- else database_parent)
- resolved = Path(root).resolve()
- return resolved != data_root and resolved.is_relative_to(data_root)
-
-
-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 (_managed_cache_root(contract, 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 _managed_cache_root(contract, root) or 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 (_managed_cache_root(contract, contract.stream_root)
- and 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 (_managed_cache_root(contract, contract.avatar_root)
- and 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 (_managed_cache_root(contract, contract.cover_root)
- and 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 _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:
- if body.get("status_only") is True:
- with contract.resource_scan_lock:
- state = contract.resource_scan_state
- if state is None:
- return {
- "ok": True, "status": "idle", "scan_id": "", "sources": [],
- "completed_sources": 0,
- "total_sources": len(LOCATION_ROOT_DECLARATIONS),
- }
- return _resource_scan_public(state)
- 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 {
- "ok": True, "sources": scan["sources"],
- "missing": len(scan["missing_ids"]),
- "cache": {"files": caches["total_files"], "bytes": caches["total_bytes"],
- "by_kind": caches["summary"]},
- }
-
-
-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")
- 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()
- 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 行都会看起来像被删。所以先做来源级在线判定,整源不在线就
- 一行都不碰。CloudDrive 掉线后挂载点目录仍然存在,`root_online` 因此判的是
- 「能否列出一个条目」而不是「目录在不在」。
- """
- asset_id = int(body["id"])
- with contract.read_connection() as connection:
- anchor = connection.execute(
- "SELECT id,location,path,name FROM asset WHERE id=?", (asset_id,),
- ).fetchone()
- if not anchor:
- return {"error": "not found"}
- location, path, name = anchor["location"], anchor["path"], anchor["name"]
- if not path or not name:
- return {"error": "asset has no path"}
- if not source_is_online(location):
- # 不是失败,是拒绝:盘不在时无法区分「文件删了」和「盘没挂上」。
- return {"ok": False, "error": "source offline", "location": location}
- directory = path[: len(path) - len(name) - 1]
- rows = connection.execute(
- f"SELECT id,path,name FROM asset WHERE location=? "
- f"AND {dir_expr('')}=?",
- (location, directory),
- ).fetchall()
-
- missing = [
- {"id": row["id"], "name": row["name"]}
- for row in rows
- if not translate_ledger_path(row["path"]).is_file()
- ]
- if not missing:
- return {"ok": True, "directory": photo_set_title(directory),
- "checked": len(rows), "removed": 0, "items": []}
-
- contract.cache_bust()
- ids = [item["id"] for item in missing]
- 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 ids],
- )
- contract.cache_bust()
- return {
- "ok": True, "directory": photo_set_title(directory),
- "checked": len(rows), "removed": len(missing), "items": missing,
- }
def w_batch(contract: WebContract, body):
@@ -3034,7 +2564,7 @@ def w_batch(contract: WebContract, body):
raise
if purge_outcome is not None:
result = {"ok": True, "operation": operation, **_finish_purge(purge_outcome)}
- result.update(_clean_resource_orphans(contract))
+ result.update(clean_resource_orphans(contract))
return result
return {"ok": True, "operation": operation, "changed": len(valid_ids)}
diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.py
new file mode 100644
index 000000000..df6b78b6e
--- /dev/null
+++ b/src/peach/web_resource_sync.py
@@ -0,0 +1,501 @@
+"""资源对账:把账本里的记录和磁盘上真实存在的文件对齐。
+
+从 `web_contract` 拆出。这一域自己持有扫描线程状态、目录遍历和孤儿缓存清理,
+和浏览、复核没有共享逻辑,留在契约巨石里只是让那个文件更难读。
+
+`source_is_online` 也在这里:判断某个来源的根挂载没挂载,只有对账要问这件事。
+`w_purge_missing` 同理——按目录清缺失文件和整库扫描是同一件事的两种入口。
+"""
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import threading
+import time
+import uuid
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from typing import Callable, Protocol, Sequence
+
+from .catalog_rules import dir_expr, normalise_code_key, photo_set_title
+from .config import LOCATION_ROOT_DECLARATIONS
+from .media import remap_managed_path
+from .platform import is_unmapped, root_online, translate_ledger_path
+
+
+class ResourceSyncContract(Protocol):
+ """对账需要契约提供的能力;比整个 WebContract 小得多。"""
+
+ db_path: Path
+ snapshot_root: Path | None
+ legacy_snapshot_roots: tuple[Path, ...]
+ cover_root: Path
+ poster_root: Path
+ avatar_root: Path
+ photo_root: Path
+ stream_root: Path
+ transcode_root: Path
+ resource_cleanup_enabled: bool
+ resource_scan_lock: threading.Lock
+ resource_scan_state: dict | None
+ resource_scan_thread: threading.Thread | None
+
+ def cache_bust(self) -> None: ...
+ def read_connection(self): ...
+ def write_transaction(self): ...
+
+
+def source_is_online(location: str) -> bool:
+ """这个来源整体在不在线。对账前的唯一闸门。"""
+ declared = LOCATION_ROOT_DECLARATIONS.get(location)
+ if not declared:
+ return False
+ resolved = translate_ledger_path(declared)
+ return not is_unmapped(resolved) and root_online(resolved)
+
+
+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: ResourceSyncContract,
+ progress: Callable[[dict], None] | None = None,
+) -> 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 = []
+ unreadable = 0
+ if online:
+ missing, unreadable = _missing_resource_ids(items)
+ missing_ids.extend(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}
+
+
+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 _managed_cache_root(contract: ResourceSyncContract, root: Path | None) -> bool:
+ """Only let a ledger clean caches inside its own runtime data directory.
+
+ Production stores ``ledger.db`` under ``peach-data/database`` and generated files under
+ the sibling ``peach-data/generated`` directory. Isolated tests commonly put the database
+ directly in a temporary root. In both shapes the database identifies the only directory
+ tree cleanup may enter. This prevents a temporary database paired with a forgotten default
+ cache root from treating the real generated files as orphans.
+ """
+ if root is None:
+ return False
+ database_parent = Path(contract.db_path).resolve().parent
+ data_root = (database_parent.parent if database_parent.name.casefold() == "database"
+ else database_parent)
+ resolved = Path(root).resolve()
+ return resolved != data_root and resolved.is_relative_to(data_root)
+
+
+def _resource_orphan_plan(contract: ResourceSyncContract, 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 (_managed_cache_root(contract, 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 _managed_cache_root(contract, root) or 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 (_managed_cache_root(contract, contract.stream_root)
+ and 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 (_managed_cache_root(contract, contract.avatar_root)
+ and 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 (_managed_cache_root(contract, contract.cover_root)
+ and 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: ResourceSyncContract) -> 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 _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: ResourceSyncContract, 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: ResourceSyncContract, 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: ResourceSyncContract, body=None):
+ body = body or {}
+ if body.get("background") is True:
+ if body.get("status_only") is True:
+ with contract.resource_scan_lock:
+ state = contract.resource_scan_state
+ if state is None:
+ return {
+ "ok": True, "status": "idle", "scan_id": "", "sources": [],
+ "completed_sources": 0,
+ "total_sources": len(LOCATION_ROOT_DECLARATIONS),
+ }
+ return _resource_scan_public(state)
+ 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 {
+ "ok": True, "sources": scan["sources"],
+ "missing": len(scan["missing_ids"]),
+ "cache": {"files": caches["total_files"], "bytes": caches["total_bytes"],
+ "by_kind": caches["summary"]},
+ }
+
+
+def _recheck_resource_scan_ids(contract: ResourceSyncContract, 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: ResourceSyncContract, body):
+ if body.get("confirm") is not True:
+ raise ValueError("resource sync requires confirmation")
+ 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()
+ 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: ResourceSyncContract, body):
+ """按目录对账:文件已经在磁盘上删掉的,账本行移入回收站。
+
+ 这条路径服务的是「我在资源管理器里整理网盘目录」——删掉的就是不要的,所以
+ 不进复核;账本记录仍先进入回收站,源文件恢复后还能还原。
+
+ 真正危险的不是删得太干净,而是把「盘没挂上」误判成「文件没了」:R: 掉线时
+ 整条来源 2,552 行都会看起来像被删。所以先做来源级在线判定,整源不在线就
+ 一行都不碰。CloudDrive 掉线后挂载点目录仍然存在,`root_online` 因此判的是
+ 「能否列出一个条目」而不是「目录在不在」。
+ """
+ asset_id = int(body["id"])
+ with contract.read_connection() as connection:
+ anchor = connection.execute(
+ "SELECT id,location,path,name FROM asset WHERE id=?", (asset_id,),
+ ).fetchone()
+ if not anchor:
+ return {"error": "not found"}
+ location, path, name = anchor["location"], anchor["path"], anchor["name"]
+ if not path or not name:
+ return {"error": "asset has no path"}
+ if not source_is_online(location):
+ # 不是失败,是拒绝:盘不在时无法区分「文件删了」和「盘没挂上」。
+ return {"ok": False, "error": "source offline", "location": location}
+ directory = path[: len(path) - len(name) - 1]
+ rows = connection.execute(
+ f"SELECT id,path,name FROM asset WHERE location=? "
+ f"AND {dir_expr('')}=?",
+ (location, directory),
+ ).fetchall()
+
+ missing = [
+ {"id": row["id"], "name": row["name"]}
+ for row in rows
+ if not translate_ledger_path(row["path"]).is_file()
+ ]
+ if not missing:
+ return {"ok": True, "directory": photo_set_title(directory),
+ "checked": len(rows), "removed": 0, "items": []}
+
+ contract.cache_bust()
+ ids = [item["id"] for item in missing]
+ 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 ids],
+ )
+ contract.cache_bust()
+ return {
+ "ok": True, "directory": photo_set_title(directory),
+ "checked": len(rows), "removed": len(missing), "items": missing,
+ }
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 8690bf9d3..39dfcfb12 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -2219,259 +2219,6 @@ class PhotoSetTests(unittest.TestCase):
{"error": "invalid id"})
-class PurgeMissingTests(unittest.TestCase):
- """按目录对账:磁盘上已删掉的,账本行一并删掉。
-
- 这条路径不可恢复,所以测试重点全在「什么时候**不该**删」。
- """
-
- LEDGER_DIR = r"B:\creator\P"
- OTHER_DIR = r"B:\creator\V"
-
- def setUp(self):
- self.tmp = tempfile.TemporaryDirectory()
- self.root = Path(self.tmp.name)
- self.db_path = str(self.root / "ledger.db")
- con = sqlite3.connect(self.db_path)
- con.executescript(BASE_SCHEMA)
- sep = chr(92)
- rows = [
- (1, "115", self.LEDGER_DIR + sep + "001.jpg", "001.jpg"),
- (2, "115", self.LEDGER_DIR + sep + "002.jpg", "002.jpg"),
- (3, "115", self.LEDGER_DIR + sep + "003.jpg", "003.jpg"),
- # 同来源但另一个目录,任何情况下都不该被这次对账碰到。
- (4, "115", self.OTHER_DIR + sep + "a.mp4", "a.mp4"),
- ]
- con.executemany(
- "INSERT INTO asset(id,location,path,name,medium,size) "
- "VALUES(?,?,?,?,'image',10)", rows)
- con.executemany("INSERT INTO asset_tag(asset_id,tag,source) VALUES(?,?,'t')",
- [(2, "标签"), (4, "标签")])
- con.executemany(
- "INSERT INTO asset_preference(profile_id,asset_id,liked,reason) "
- "VALUES('default',?,1,'')", [(2,), (4,)])
- con.commit()
- con.close()
- self.contract = rm_web.WebContract(Path(self.db_path))
- # 只有 001 和 a.mp4 还在盘上;002、003 当作已被手动删除。
- for name in ("001.jpg", "a.mp4"):
- (self.root / name).write_bytes(b"x")
-
- def tearDown(self):
- self.tmp.cleanup()
-
- def _translate(self, raw):
- """把账本的 Windows 路径映射到临时目录里的同名文件。"""
- return self.root / str(raw).rsplit(chr(92), 1)[-1]
-
- def _run(self, online=True):
- patch_translate = mock.patch.object(
- rm_web, "translate_ledger_path", self._translate)
- patch_online = mock.patch.object(
- rm_web, "source_is_online", lambda _loc: online)
- with patch_translate, patch_online:
- return rm_web.w_purge_missing(self.contract, {"id": 1})
-
- def ids(self):
- con = sqlite3.connect(self.db_path)
- try:
- return [r[0] for r in con.execute("SELECT id FROM asset ORDER BY id")]
- finally:
- con.close()
-
- def test_offline_source_refuses_instead_of_deleting_everything(self):
- """盘没挂上时,整目录都会 stat 失败——那不是「文件被删」。
-
- R: 实测掉线过;若不拦,2,552 条本地资产会一次全部消失。
- """
- result = self._run(online=False)
- self.assertFalse(result["ok"])
- self.assertEqual(result["error"], "source offline")
- self.assertEqual(self.ids(), [1, 2, 3, 4])
-
- 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, 2, 3, 4])
- con = sqlite3.connect(self.db_path)
- try:
- self.assertEqual(
- 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_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_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):
- idle = rm_web.w_resource_sync_scan(
- self.contract, {"background": True, "status_only": True})
- self.assertEqual(idle["status"], "idle")
- 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)
- resumed = rm_web.w_resource_sync_scan(
- self.contract, {"background": True, "status_only": True})
- self.assertEqual(resumed["scan_id"], status["scan_id"])
- 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()
- 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_cache_cleanup_never_crosses_the_database_data_root(self):
- """临时数据库漏配缓存根时,宁可不清理,也不能越界碰真实 generated。"""
- with tempfile.TemporaryDirectory() as outside_tmp:
- outside = Path(outside_tmp)
- cover = outside / "covers" / "orphan-001.jpg"
- segment = outside / "stream-segments" / "999" / "0.ts"
- cover.parent.mkdir()
- segment.parent.mkdir(parents=True)
- cover.write_bytes(b"cover")
- segment.write_bytes(b"segment")
- self.contract.cover_root = cover.parent
- self.contract.stream_root = outside / "stream-segments"
- self.contract.resource_cleanup_enabled = True
-
- result = rm_web._clean_resource_orphans(self.contract)
-
- self.assertEqual(result["cache_removed"], 0)
- self.assertTrue(cover.is_file())
- self.assertTrue(segment.is_file())
-
- def test_intact_directory_reports_no_change(self):
- for name in ("002.jpg", "003.jpg"):
- (self.root / name).write_bytes(b"x")
- result = self._run()
- self.assertEqual(result["removed"], 0)
- self.assertEqual(result["checked"], 3)
- self.assertEqual(self.ids(), [1, 2, 3, 4])
if __name__ == "__main__":
diff --git a/tests/test_web_resource_sync.py b/tests/test_web_resource_sync.py
new file mode 100644
index 000000000..9fa7d7cdb
--- /dev/null
+++ b/tests/test_web_resource_sync.py
@@ -0,0 +1,274 @@
+"""资源对账域的隔离测试。
+
+随 `web_resource_sync` 从 `web_contract` 一同拆出:测试巨石镜像代码巨石没有意义。
+patch 目标必须指向真正执行的模块——这批用例大量 patch `source_is_online` 与
+`translate_ledger_path`,拆分时若仍打在 `web_contract` 上,patch 会静默失效,
+测试照样「通过」到断言才炸。
+"""
+import os
+import sqlite3
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from peach import web_contract as rm_web
+from peach import web_resource_sync as rm_sync
+
+from test_rm_web import BASE_SCHEMA
+
+
+class PurgeMissingTests(unittest.TestCase):
+ """按目录对账:磁盘上已删掉的,账本行一并删掉。
+
+ 这条路径不可恢复,所以测试重点全在「什么时候**不该**删」。
+ """
+
+ LEDGER_DIR = r"B:\creator\P"
+ OTHER_DIR = r"B:\creator\V"
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name)
+ self.db_path = str(self.root / "ledger.db")
+ con = sqlite3.connect(self.db_path)
+ con.executescript(BASE_SCHEMA)
+ sep = chr(92)
+ rows = [
+ (1, "115", self.LEDGER_DIR + sep + "001.jpg", "001.jpg"),
+ (2, "115", self.LEDGER_DIR + sep + "002.jpg", "002.jpg"),
+ (3, "115", self.LEDGER_DIR + sep + "003.jpg", "003.jpg"),
+ # 同来源但另一个目录,任何情况下都不该被这次对账碰到。
+ (4, "115", self.OTHER_DIR + sep + "a.mp4", "a.mp4"),
+ ]
+ con.executemany(
+ "INSERT INTO asset(id,location,path,name,medium,size) "
+ "VALUES(?,?,?,?,'image',10)", rows)
+ con.executemany("INSERT INTO asset_tag(asset_id,tag,source) VALUES(?,?,'t')",
+ [(2, "标签"), (4, "标签")])
+ con.executemany(
+ "INSERT INTO asset_preference(profile_id,asset_id,liked,reason) "
+ "VALUES('default',?,1,'')", [(2,), (4,)])
+ con.commit()
+ con.close()
+ self.contract = rm_web.WebContract(Path(self.db_path))
+ # 只有 001 和 a.mp4 还在盘上;002、003 当作已被手动删除。
+ for name in ("001.jpg", "a.mp4"):
+ (self.root / name).write_bytes(b"x")
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def _translate(self, raw):
+ """把账本的 Windows 路径映射到临时目录里的同名文件。"""
+ return self.root / str(raw).rsplit(chr(92), 1)[-1]
+
+ def _run(self, online=True):
+ patch_translate = mock.patch.object(
+ rm_sync, "translate_ledger_path", self._translate)
+ patch_online = mock.patch.object(
+ rm_sync, "source_is_online", lambda _loc: online)
+ with patch_translate, patch_online:
+ return rm_sync.w_purge_missing(self.contract, {"id": 1})
+
+ def ids(self):
+ con = sqlite3.connect(self.db_path)
+ try:
+ return [r[0] for r in con.execute("SELECT id FROM asset ORDER BY id")]
+ finally:
+ con.close()
+
+ def test_offline_source_refuses_instead_of_deleting_everything(self):
+ """盘没挂上时,整目录都会 stat 失败——那不是「文件被删」。
+
+ R: 实测掉线过;若不拦,2,552 条本地资产会一次全部消失。
+ """
+ result = self._run(online=False)
+ self.assertFalse(result["ok"])
+ self.assertEqual(result["error"], "source offline")
+ self.assertEqual(self.ids(), [1, 2, 3, 4])
+
+ 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, 2, 3, 4])
+ con = sqlite3.connect(self.db_path)
+ try:
+ self.assertEqual(
+ 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_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_sync, "translate_ledger_path", self._translate), \
+ mock.patch.object(rm_sync, "source_is_online", online):
+ preview = rm_sync.w_resource_sync_scan(self.contract)
+ self.assertEqual(preview["missing"], 2)
+ self.assertEqual(preview["cache"]["files"], len(cache_files))
+ result = rm_sync.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_lists_each_directory_once_instead_of_stating_every_file(self):
+ real_scandir = os.scandir
+ with mock.patch.object(rm_sync, "translate_ledger_path", self._translate), \
+ mock.patch.object(rm_sync, "source_is_online", lambda loc: loc == "115"), \
+ mock.patch.object(rm_sync.os, "scandir", wraps=real_scandir) as scandir:
+ preview = rm_sync.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_sync, "translate_ledger_path", self._translate), \
+ mock.patch.object(rm_sync, "source_is_online", lambda loc: loc == "115"), \
+ mock.patch.object(rm_sync.os, "scandir", side_effect=PermissionError("offline")):
+ preview = rm_sync.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):
+ idle = rm_sync.w_resource_sync_scan(
+ self.contract, {"background": True, "status_only": True})
+ self.assertEqual(idle["status"], "idle")
+ with mock.patch.object(rm_sync, "translate_ledger_path", self._translate), \
+ mock.patch.object(rm_sync, "source_is_online", lambda loc: loc == "115"):
+ started = rm_sync.w_resource_sync_scan(
+ self.contract, {"background": True, "restart": True})
+ self.assertEqual(started["status"], "running")
+ deadline = time.time() + 2
+ while True:
+ status = rm_sync.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)
+ resumed = rm_sync.w_resource_sync_scan(
+ self.contract, {"background": True, "status_only": True})
+ self.assertEqual(resumed["scan_id"], status["scan_id"])
+ result = rm_sync.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()
+ 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_sync, "translate_ledger_path", self._translate), \
+ mock.patch.object(rm_sync, "source_is_online", lambda loc: loc == "115"):
+ preview = rm_sync.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_cache_cleanup_never_crosses_the_database_data_root(self):
+ """临时数据库漏配缓存根时,宁可不清理,也不能越界碰真实 generated。"""
+ with tempfile.TemporaryDirectory() as outside_tmp:
+ outside = Path(outside_tmp)
+ cover = outside / "covers" / "orphan-001.jpg"
+ segment = outside / "stream-segments" / "999" / "0.ts"
+ cover.parent.mkdir()
+ segment.parent.mkdir(parents=True)
+ cover.write_bytes(b"cover")
+ segment.write_bytes(b"segment")
+ self.contract.cover_root = cover.parent
+ self.contract.stream_root = outside / "stream-segments"
+ self.contract.resource_cleanup_enabled = True
+
+ result = rm_sync.clean_resource_orphans(self.contract)
+
+ self.assertEqual(result["cache_removed"], 0)
+ self.assertTrue(cover.is_file())
+ self.assertTrue(segment.is_file())
+
+ def test_intact_directory_reports_no_change(self):
+ for name in ("002.jpg", "003.jpg"):
+ (self.root / name).write_bytes(b"x")
+ result = self._run()
+ self.assertEqual(result["removed"], 0)
+ self.assertEqual(result["checked"], 3)
+ self.assertEqual(self.ids(), [1, 2, 3, 4])