Peach: Local-first video metadata scraper and media manager.
feat(library): 按模板整理文件名与目录,可预览可回滚
longmeidaoac4f8e46236a
diff --git a/README.en.md b/README.en.mdindex 92a84f515..3d11acf9e 100644--- a/README.en.md+++ b/README.en.md@@ -79,7 +79,7 @@ FFmpeg and ffprobe are installed separately: without them you can still browse a## Data boundaries-Media stays in its original folders, while the catalog, identities, viewing history and human decisions stay in a local SQLite ledger. External metadata and AI output enter as candidates with provenance and confidence; credentials stay outside Git, logs and API responses. Peach is for single-user self-hosting and does not provide a public-site or team permission model.+Media stays in its original folders by default; organizing is an explicit action you start yourself, with a preview first and a rollback afterwards. The catalog, identities, viewing history and human decisions stay in a local SQLite ledger. External metadata and AI output enter as candidates with provenance and confidence; credentials stay outside Git, logs and API responses. Peach is for single-user self-hosting and does not provide a public-site or team permission model.## Documentationdiff --git a/README.md b/README.mdindex 24468743f..1c440e03b 100644--- a/README.md+++ b/README.md@@ -79,7 +79,7 @@ FFmpeg 与 ffprobe 需自行安装:缺少时仍可浏览和播放浏览器兼## 数据边界-媒体保留在原目录,馆藏、身份、观看记录和人工决定保存在本机 SQLite ledger;外部元数据与 AI 结果先作为带来源和置信度的候选,凭据不进入 Git、日志或 API 返回。Peach 面向单人自托管,不提供公开站点或团队权限模型。+媒体默认保留在原目录,整理是用户显式发起、可预览可回滚的操作;馆藏、身份、观看记录和人工决定保存在本机 SQLite ledger;外部元数据与 AI 结果先作为带来源和置信度的候选,凭据不进入 Git、日志或 API 返回。Peach 面向单人自托管,不提供公开站点或团队权限模型。## 文档diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.mdindex 527ff1550..0f10f9da9 100644--- a/docs/PRODUCT_BACKLOG.md+++ b/docs/PRODUCT_BACKLOG.md@@ -52,7 +52,7 @@ shuffle_key 改变随机浏览的序列语义,先测关系筛选收益再决- 公开分发:待项目相对稳定,安装、升级、数据迁移及跨平台回归稳定后,同批推进 PyPI 包发布和 WinGet 登记;现阶段仅记录计划,不上传或登记。发布前确认发行名,调整禁止上传标记,完善自动构建、版本发布与两端安装验收。- 发行名与 WinGet 应用 ID 未定案也未注册,发布前确认并复核可用性;产品显示名继续使用 Peach。8. 女优高清头像的写入侧:`scripts/audit_performer_portraits.py` 出候选与实测证据,资料页上人可以逐个换掉任何一张(图库同名候选、用过的图、本机文件、https 地址),`scripts/fill_portrait_gaps.py` 把图库里只命中一张的批量装上、其余产对照表。仍缺换源那一轮(在位的封面裁片挡住更好的源),以及实体合并后孤立头像的 relink(如 `8022 <- 8168`:只有旧 ID 的 provenance 名唯一命中当前实体、当前目标又不存在时才算候选,不覆盖、不删除旧文件)。-9. 文件名与网盘目录整理的落地:`scripts/clean_names.py` 与目录计划只出 dry-run CSV。真正改名要独立维护窗口——停同类任务、确认本机是 writer、SQLite backup、逐条同目录 rename 并同步账本 path/name、失败时文件名回滚,最后跑完整性、外键与路径存在性检查;不跨盘移动,也不按文件夹名猜创作者。+9. 文件名与网盘目录整理:按模板的那一路已落地(ADR-0039)——数据管理页的「整理」与 `scripts/organize_media.py` 共用 `peach.organize`,预览出计划 CSV、执行前 SQLite backup、逐条 rename 并同步账本 path/name、失败回滚、事后完整性与外键检查,只动视频、只在同卷内、目标已存在整行跳过,批次可整批退回。仍缺三件:`scripts/clean_names.py`(域名噪声)与 `scripts/flatten_release_dirs.py`(冗余目录层)两条专门形态仍只出 dry-run CSV;旁挂封面与字幕不跟着主文件改名;真实库上还没执行过任何一批(2026-09-22 只读预览:115 会改 1484、跳过 8627,PikPak 会改 167、跳过 10436,`local` 因外置盘未挂载整批跳过)。10. 来源与默认值通用化(ADR-0023 第 5 阶段候选):`peach init` 的问答已按本机路径只声明 `local`,非交互路径写出的 `DEFAULT_LOCATION_ROOTS`(`R:\media`、`B:/`、`A:/`)仍是维护者的示例盘符。剩两件事:来源用「本地 / 远端挂载」类型字段代替代码里按 `local`/`115`/`pikpak` 名字点名(`web_resource_sync.py` 的 SQL、`media.py` 的 HLS 规则);复制链路支持 win↔win、mac↔mac 与任意一台当写者,目前只验证过 Windows 写者 + macOS 读者。11. 非 editable 安装的跨平台验收:wheel 资源与 Windows 基础依赖、仓库外 CLI 冒烟已就绪,仍需取得 macOS、Python 3.12 消费任务结果。12. 健康检查生产验收:`db` 区分 missing、empty、available、unavailable,`?ready=1` 检查 schema 校验和;待部署后用项目 CA 验证 HTTPS 与损坏/未初始化状态。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 33cfa17eb..2f43d851c 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -8,7 +8,7 @@- 女优头像 545 张,脸宽中位数 320px,37 张带水印待复核;被顶掉的整套留在 `avatars-superseded/`(判据见 `SOURCING.md`)。- 小图、资料骨架、官网图标、社媒品牌色与自动播放开关已实现,请求共用 Chrome UA;厂牌标识 198 张随仓库分发(ADR-0026)。-- Eightman 与 SO MODEL AGENT 已合为 8662,成员与关联作品保留,旧名仍可解析。+- 数据管理页的「整理」按模板预览、执行、回滚上一批,只动视频、同卷内(ADR-0039),真实库未执行过。- 产地是独立维度,JAV 是它的投影:`region` 为空时按厂牌、创作者、番号逐层推断,不落库;韩国 MIB 已不算 JAV。- Windows 是 ledger writer,入口是源码托盘(`pythonw -m peach.tray`,子服务用 venv 的 `peach.exe`),重启 `restart_windows_tray.py --source`;代码与数据在内置盘,外置盘只供 `R:\media`。@@ -20,7 +20,7 @@- 可选密码已上线:首启可跳过,配置页可改可关,登录可记住设备;旧安装保留口令。- macOS 是 reader,代码与 `peach-data` 在内置盘;`peach.local` 经 8900/8443 和 pf 提供 80/443,GET 正常、写入返回 409。- 两端各用本机 CA,私钥与凭据不跨机同步;代码走 Git、账本走单写者复制、图片走 Syncthing,三条链路互不兜底。本机坐标在 `<数据根>/config.toml`;ADR-0023 第 1~3 阶段已在 Windows 生效。-- Windows 真实 ledger `peach-data/database/ledger.db`,2026-09-13 已应用到 `0031`;`asset_subtitle` 195 行(孤立 19),175 部带字幕轨。09-12 修掉 `local` 路径大小写重复,`asset` 80,761 行。+- Windows 真实 ledger `peach-data/database/ledger.db`,2026-09-13 已应用到 `0031`;`asset_subtitle` 195 行(孤立 19),175 部带字幕轨,`asset` 80,761 行。- Mac ledger 已授权从共享副本显式拉取并恢复 `in-sync`;`sources` 已迁内置盘,`archive`、`tools` 仍可指向外置盘。- 前端按 ADR-0031 逐页迁往 `frontend/` 的 React + Tailwind + BoardUI 源码,只有 React 一档;产物进 Git,经 `/dist/{name}` 提供;改前端需 Node 24+(`docs/FRONTEND.md`)。- 本机运行 Python 3.14;`requires-python` 下限 3.12,GitHub Actions 同时测 3.12 与 3.14;Windows FFmpeg/ffprobe 位于 `peach-data/tools/ffmpeg`,macOS 走 PATH。diff --git a/scripts/organize_media.py b/scripts/organize_media.pynew file mode 100644index 000000000..606cad322--- /dev/null+++ b/scripts/organize_media.py@@ -0,0 +1,109 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""按模板整理文件名与目录(ADR-0039)。++和数据管理页上那一块是同一份实现(`peach.organize`):模板解析、计划生成、执行与回滚+只有一处,命令行和界面看到的结果因此必然一致。++默认只出计划 CSV。`--apply` 走 `peach.scripting` 的标准门槛:必须同时给 `--backup`,+备份用 SQLite 备份 API 落盘,写完跑 `integrity_check` 与 `foreign_key_check`。++用法:+ python scripts/organize_media.py --location 115 --file-template '{number}[ {title}]'+ python scripts/organize_media.py --location 115 --file-template '…' --apply --backup <落点>+ python scripts/organize_media.py --rollback-last --apply --backup <落点>+"""+from __future__ import annotations++import argparse+import sys+from pathlib import Path++PROJECT_ROOT = Path(__file__).resolve().parent.parent+SRC_DIR = PROJECT_ROOT / "src"+if str(SRC_DIR) not in sys.path:+ sys.path.insert(0, str(SRC_DIR))++from peach import organize+from peach.config import DATABASE_PATH, GENERATED_DIR+from peach.organize_templates import PLACEHOLDERS, TemplateError+from peach.scripting import add_ledger_write_args, open_for_write, verify_after_write+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="按模板整理文件名与目录;默认只出计划",+ epilog="占位符:" + "、".join(f"{{{key}}}={label}" for key, label in PLACEHOLDERS.items()))+ add_ledger_write_args(parser, db_default=DATABASE_PATH)+ parser.add_argument("--location", choices=("local", "115", "pikpak"), default="local")+ parser.add_argument("--file-template", default="", help="文件名模板,不含扩展名")+ parser.add_argument("--dir-template", default="",+ help="目录模板,相对来源根;留空表示原地改名")+ parser.add_argument("--generated-root", type=Path, default=GENERATED_DIR,+ help="计划 CSV 与批次日志的落点")+ parser.add_argument("--rollback-last", action="store_true",+ help="把最近一批整理原样退回去")+ return parser+++def _report_plan(plan: dict) -> None:+ counts = plan["counts"]+ print(f"扫描 {counts['total']} 条:会改 {counts['change']},"+ f"已经就是目标名字 {counts['unchanged']},跳过 {counts['skip']}")+ for reason, count in sorted(plan["reasons"].items(), key=lambda item: -item[1]):+ print(f" {reason}:{count} 条")+++def run(args: argparse.Namespace) -> int:+ connection = open_for_write(args)+ try:+ if args.rollback_last:+ latest = organize.latest_batch(args.generated_root)+ if latest is None:+ print("没有可以回滚的批次")+ return 0+ print(f"上一批:{latest}")+ if not args.apply:+ print("未加 --apply,什么都没退回。")+ return 0+ result = organize.rollback_batch(connection, latest)+ print(f"退回 {result['restored']} 条,失败 {result['failed']}")+ for failure in result["failures"]:+ print(f" {failure['path']}:{failure['reason']}")+ else:+ plan = organize.build_plan(+ connection, location=args.location,+ file_template=args.file_template, dir_template=args.dir_template)+ path = organize.plan_path(args.generated_root, args.location)+ organize.write_plan(path, plan["rows"])+ _report_plan(plan)+ print(f"→ {path}")+ if not args.apply:+ print("未加 --apply,只出计划未动文件。")+ return 0+ result = organize.apply_plan(connection, plan["rows"],+ generated_root=args.generated_root)+ print(f"整理 {result['moved']} 条,失败 {result['failed']}")+ for failure in result["failures"]:+ print(f" {failure['path']}:{failure['reason']}")+ print(f"批次日志:{result['log_path']}")+ integrity, violations = verify_after_write(connection)+ if integrity != "ok" or violations:+ print(f"写入后 ledger 校验失败:integrity={integrity} foreign_keys={violations}")+ return 2+ return 0+ finally:+ connection.close()+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ return run(args)+ except (TemplateError, organize.OrganizeError) as error:+ print(f"[stop] {error}")+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 41e4f128d..2c56790d4 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -97,7 +97,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_job_status.py", "test_jobs.py", "test_task_runs.py","test_task_center_integration.py", "test_reference_updates.py","test_repo_hygiene.py",- "test_review_csv.py", "test_jav_code_domain.py",+ "test_review_csv.py", "test_jav_code_domain.py", "test_organize.py","test_subprocess_encoding.py", "test_module_layering.py","test_copy_final_state.py", "test_demo_dataset.py","test_cloudflared_packaging.py", "test_tunnel.py"),diff --git a/src/peach/organize.py b/src/peach/organize.pynew file mode 100644index 000000000..c1a7937a5--- /dev/null+++ b/src/peach/organize.py@@ -0,0 +1,368 @@+"""按模板整理文件名与目录:生成计划、执行、回滚(ADR-0039)。++三件事在一个模块里,因为它们共用同一份判据:什么算「会变的一行」、目标路径怎么算出来、+哪些行必须跳过。散开写的下场是预览说会改、执行时又按另一套规则跳过,而用户手上那份+CSV 于是变成一份不准的清单。++顺序是固定的,和 `scripts/flatten_release_dirs.py` 一致:先备份 SQLite,再动文件,最后+改账本;账本写失败就把文件名改回去。反过来先改账本会留下一批指向不存在路径的行。++路径一律按账本口径(Windows 形态)计算,真正动盘时才由 `platform.translate_ledger_path`+翻译成本机路径。macOS 上因此也能生成和 Windows 完全一样的计划。+"""+from __future__ import annotations++import json+import ntpath+import os+import sqlite3+import time+from collections.abc import Callable, Sequence+from pathlib import Path++from .catalog_rules import is_jav_code, is_uncensored_release, normalise_code_key, part_marker+from .jobs import ACTIVE_ASSET_SQL+from .organize_templates import MAX_PATH, TemplateError, render, validate_template+from .platform import location_roots, resolve_root, root_online, translate_ledger_path+from .review_csv import write_rows++#: 计划 CSV 的列。`reason` 只在 `action=skip` 时有值。+PLAN_FIELDS = ["asset_id", "location", "current_path", "target_path", "action", "reason"]++#: 界面上给的几组模板。第一组是最小可用的一套,后两组演示目录分层。+PRESETS: tuple[dict[str, str], ...] = (+ {"label": "番号 标题", "file": "{number}[ {title}]", "dir": ""},+ {"label": "厂牌分目录", "file": "{number}[ {title}]", "dir": "{studio}"},+ {"label": "厂牌 / 番号目录", "file": "{number}[ {title}][ CD{cd}]", "dir": "{studio}/{number}"},+)++#: 跳过原因的固定写法。界面按这几个键分组计数,所以它们是契约的一部分。+SKIP_OFFLINE = "来源未挂载"+SKIP_MISSING_FIELD = "字段缺失"+SKIP_OUTSIDE_ROOT = "不在来源根内"+SKIP_TARGET_EXISTS = "目标已存在"+SKIP_CROSS_VOLUME = "跨盘"+SKIP_TOO_LONG = "路径过长"+++class OrganizeError(RuntimeError):+ """整理本身拒绝执行。消息直接给用户看。"""+++def _definition(width, height) -> str:+ """按高度给一档画质。取不到尺寸就留空,让可选分组整段省略。"""+ try:+ lines = int(height or 0)+ columns = int(width or 0)+ except (TypeError, ValueError):+ return ""+ if columns and lines and columns < lines:+ # 竖屏素材按短边算,不然一条 1080×1920 会被报成 1920p。+ lines = columns+ for floor, label in ((2160, "4K"), (1440, "1440p"), (1080, "1080p"),+ (720, "720p"), (480, "480p")):+ if lines >= floor:+ return label+ return ""+++def placeholder_values(row, performers: Sequence[str] = ()) -> dict[str, str]:+ """一行资产的占位符取值,全部来自 approved 真相字段。++ 候选表一个都不查:整理会改文件系统,而文件系统上没有地方记「这个名字是猜的」。+ """+ code = str(row["code"] or "")+ name = str(row["name"] or "")+ title = str(row["catalog_title"] or "") or str(row["original_title"] or "")+ release_date = str(row["release_date"] or "")+ marker = part_marker(name)+ return {+ "number": normalise_code_key(code) if is_jav_code(code) else code.strip(),+ "title": title.strip(),+ "studio": str(row["studio"] or "").strip(),+ "series": str(row["series"] or "").strip(),+ "year": release_date[:4] if len(release_date) >= 4 else "",+ # 四个以上就不再往文件名里塞:名字会长到在资源管理器里看不见番号。+ "actors": "、".join(list(performers)[:4]),+ "cd": marker.upper() if marker else "",+ # 有码不是本机可核验的事实,所以只在有无码证据时给值;`[{mosaic}]` 于是+ # 在普通片上整段消失,而不是写上一个猜出来的「有码」。+ "mosaic": "无码" if is_uncensored_release(name, code) else "",+ "definition": _definition(row["width"], row["height"]),+ }+++def _performers(connection: sqlite3.Connection, location: str) -> dict[int, list[str]]:+ """资产 → 出演者规范名。`entity` 是规范身份,扁平字段只是兼容投影(ADR-0005)。"""+ found: dict[int, list[str]] = {}+ for asset_id, name in connection.execute(+ "SELECT ae.asset_id,e.canonical_name FROM asset_entity ae "+ "JOIN entity e ON e.id=ae.entity_id JOIN asset a ON a.id=ae.asset_id "+ "WHERE e.kind='performer' AND a.location=? ORDER BY e.canonical_name",+ (location,),+ ):+ found.setdefault(int(asset_id), []).append(str(name))+ return found+++def _rows(connection: sqlite3.Connection, location: str) -> list[sqlite3.Row]:+ """这个来源上会被整理的行:只有视频,且不在回收站里。++ 只取视频不是图省事。旁挂的封面、截图、下载页残渣(`.jpg`/`.gif`/`.js`)在账本里+ 继承着同一个番号,按同一份模板算出来的目标名只差扩展名——2026-09-22 在真实库上+ 试了一次,115 那趟 581 条「目标已存在」几乎全是它们。模板说的是「一部片叫什么」,+ 它回答不了一张封面该叫什么。+ """+ connection.row_factory = sqlite3.Row+ return connection.execute(+ "SELECT id,location,path,name,code,catalog_title,original_title,studio,series,"+ f"release_date,width,height FROM asset WHERE location=? AND {ACTIVE_ASSET_SQL} "+ "AND medium='video' AND path IS NOT NULL AND trim(path)<>'' ORDER BY id",+ (location,),+ ).fetchall()+++def _extension(name: str) -> str:+ stem, dot, ext = str(name).rpartition(".")+ return f".{ext}" if dot and stem else ""+++def build_plan(connection: sqlite3.Connection, *, location: str,+ file_template: str = "", dir_template: str = "",+ roots=None, online: bool | None = None) -> dict:+ """按模板给一个来源生成逐文件计划。++ 返回 `{"rows": [...], "counts": {...}}`:`rows` 只含会变的行与被跳过的行,+ 已经就是目标名字的行只进 `counts["unchanged"]`——几万行原样列出来,用户要找的+ 那几百行反而看不见了。++ 存在性只用挂载判定(`root_online`),不逐行 `stat`:115 与 PikPak 的挂载上那是+ 一次网络往返。撞名在执行那一步 `rename` 之前当场判(ADR-0039)。+ """+ file_template = validate_template(file_template)+ dir_template = validate_template(dir_template, directory=True)+ if not file_template and not dir_template:+ raise OrganizeError("至少要给一个模板")++ declared = dict(location_roots() if roots is None else roots)+ rows = _rows(connection, location)+ counts: dict[str, int] = {"total": len(rows), "unchanged": 0, "change": 0, "skip": 0}+ reasons: dict[str, int] = {}+ plan: list[dict] = []++ def skip(row, reason: str, target: str = "") -> None:+ counts["skip"] += 1+ reasons[reason] = reasons.get(reason, 0) + 1+ plan.append({"asset_id": row["id"], "location": location,+ "current_path": str(row["path"]), "target_path": target,+ "action": "skip", "reason": reason})++ if online is None:+ mounts = [translate_ledger_path(root) for root in declared.get(location, ())]+ online = any(root_online(mount) for mount in mounts)+ if not online:+ for row in rows:+ skip(row, SKIP_OFFLINE)+ return {"rows": plan, "counts": counts, "reasons": reasons}++ performers = _performers(connection, location)+ # 目标撞名先按账本已知的路径判一遍:同一批里两行算出同一个名字,或者目标位置上+ # 已经躺着另一条记录,都在预览里就说清楚,而不是等执行到一半才报一行失败。+ claimed = {str(row["path"]).casefold(): int(row["id"]) for row in rows}++ for row in rows:+ path = str(row["path"])+ matched, index, _tail = resolve_root(path, declared)+ if matched != location or index < 0:+ skip(row, SKIP_OUTSIDE_ROOT)+ continue+ root = declared[location][index]+ values = placeholder_values(row, performers.get(int(row["id"]), []))+ current_dir = ntpath.dirname(path)+ target_dir = current_dir+ missing: set[str] = set()+ if dir_template:+ rendered, absent = render(dir_template, values, directory=True)+ missing |= absent+ if not rendered:+ skip(row, SKIP_MISSING_FIELD)+ continue+ target_dir = ntpath.join(root, *rendered.split("/"))+ name = str(row["name"] or ntpath.basename(path))+ target_name = name+ if file_template:+ rendered, absent = render(file_template, values)+ missing |= absent+ if not rendered:+ skip(row, SKIP_MISSING_FIELD)+ continue+ target_name = rendered + _extension(name)+ if missing:+ skip(row, SKIP_MISSING_FIELD)+ continue+ target = ntpath.join(target_dir, target_name)+ if target == path:+ counts["unchanged"] += 1+ continue+ if ntpath.splitdrive(target)[0].casefold() != ntpath.splitdrive(path)[0].casefold():+ skip(row, SKIP_CROSS_VOLUME, target)+ continue+ if len(target) > MAX_PATH:+ skip(row, SKIP_TOO_LONG, target)+ continue+ occupant = claimed.get(target.casefold())+ if occupant is not None and occupant != int(row["id"]):+ skip(row, SKIP_TARGET_EXISTS, target)+ continue+ claimed.pop(path.casefold(), None)+ claimed[target.casefold()] = int(row["id"])+ counts["change"] += 1+ plan.append({+ "asset_id": row["id"], "location": location, "current_path": path,+ "target_path": target,+ "action": "rename" if target_dir == current_dir else "move", "reason": "",+ })+ return {"rows": plan, "counts": counts, "reasons": reasons}+++def write_plan(path: Path | str, rows: Sequence[dict]) -> Path:+ write_rows(path, PLAN_FIELDS, rows, atomic=True)+ return Path(path)+++def plan_path(root: Path | str, location: str) -> Path:+ return Path(root) / f"organize-plan-{location}.csv"+++def batch_log_dir(root: Path | str) -> Path:+ return Path(root) / "organize-batches"+++def latest_batch(root: Path | str) -> Path | None:+ """最近一个批次日志;一次都没执行过返回 None。"""+ logs = sorted(batch_log_dir(root).glob("organize-*.json"))+ return logs[-1] if logs else None+++def _rename(source: str, target: str) -> None:+ """按账本路径改名,真正动盘时翻译成本机路径。"""+ local_source = translate_ledger_path(source)+ local_target = translate_ledger_path(target)+ local_target.parent.mkdir(parents=True, exist_ok=True)+ os.rename(local_source, local_target)+++def _update_row(connection: sqlite3.Connection, asset_id: int,+ old_path: str, new_path: str) -> int:+ return connection.execute(+ "UPDATE asset SET path=?,name=? WHERE id=? AND path=?",+ (new_path, ntpath.basename(new_path), int(asset_id), old_path),+ ).rowcount+++def _move_one(connection: sqlite3.Connection, asset_id: int,+ old_path: str, new_path: str) -> str:+ """动一个文件并同步账本;返回 `ok` 或跳过/失败原因。++ 账本写失败就把文件改回去:反过来留下的是一条指向不存在路径的行,而它看起来+ 和正常的行没有任何区别。+ """+ if ntpath.splitdrive(old_path)[0].casefold() != ntpath.splitdrive(new_path)[0].casefold():+ # 计划那一步已经拦过一次。这里再拦是因为执行接受的是一份计划数据,而计划可以+ # 来自命令行、来自一份被人编辑过的 CSV;跨盘「改名」在这台机器上会退化成+ # 拷贝加删除,中断就是半个文件。+ return SKIP_CROSS_VOLUME+ local_source = translate_ledger_path(old_path)+ local_target = translate_ledger_path(new_path)+ if not local_source.exists():+ return "源文件不存在"+ if local_target.exists():+ return SKIP_TARGET_EXISTS+ try:+ _rename(old_path, new_path)+ except OSError as error:+ return f"改名失败:{error.strerror or error}"+ try:+ if not _update_row(connection, asset_id, old_path, new_path):+ raise OrganizeError("账本里这一行已经变了")+ connection.commit()+ except Exception as error:+ connection.rollback()+ try:+ _rename(new_path, old_path)+ return f"账本写入失败,已改回原名:{error}"+ except OSError:+ return f"账本写入失败且改不回原名,需要人工处理:{error}"+ return "ok"+++def apply_plan(connection: sqlite3.Connection, rows: Sequence[dict], *,+ generated_root: Path | str, progress: Callable[..., None] | None = None,+ stamp: str | None = None) -> dict:+ """执行计划,逐条动文件并同步账本;失败的行单独报,不影响其余行。++ 调用方必须在拿到可写连接之前完成 SQLite 备份(`scripting.open_for_write` 与+ `web_organize` 都是这么做的)。这里只负责动盘、写账本和留下批次日志。+ """+ movable = [row for row in rows if row.get("action") in {"rename", "move"}]+ entries: list[dict] = []+ failures: list[dict] = []+ log_path = batch_log_dir(generated_root) / (+ f"organize-{stamp or time.strftime('%Y%m%d-%H%M%S')}.json")+ log_path.parent.mkdir(parents=True, exist_ok=True)+ try:+ for index, row in enumerate(movable, 1):+ old_path, new_path = str(row["current_path"]), str(row["target_path"])+ outcome = _move_one(connection, int(row["asset_id"]), old_path, new_path)+ if outcome == "ok":+ entries.append({"asset_id": int(row["asset_id"]),+ "old_path": old_path, "new_path": new_path})+ else:+ failures.append({"asset_id": int(row["asset_id"]),+ "path": old_path, "reason": outcome})+ if progress:+ progress(checked=index, total=len(movable))+ finally:+ log_path.write_text(json.dumps(+ {"stamp": stamp or time.strftime("%Y%m%d-%H%M%S"),+ "entries": entries, "failures": failures},+ ensure_ascii=False, indent=1), encoding="utf-8")+ return {"moved": len(entries), "failed": len(failures), "failures": failures[:50],+ "batch": log_path.name, "log_path": str(log_path)}+++def rollback_batch(connection: sqlite3.Connection, log_path: Path | str, *,+ progress: Callable[..., None] | None = None) -> dict:+ """把一个批次逆序改回去。已经被人手工改过的行改不回来,单独报出来。"""+ path = Path(log_path)+ payload = json.loads(path.read_text(encoding="utf-8"))+ entries = list(payload.get("entries") or [])+ restored: list[dict] = []+ failures: list[dict] = []+ for index, entry in enumerate(reversed(entries), 1):+ outcome = _move_one(connection, int(entry["asset_id"]),+ str(entry["new_path"]), str(entry["old_path"]))+ if outcome == "ok":+ restored.append(entry)+ else:+ failures.append({"asset_id": int(entry["asset_id"]),+ "path": str(entry["new_path"]), "reason": outcome})+ if progress:+ progress(checked=index, total=len(entries))+ remaining = [entry for entry in entries+ if entry not in restored]+ if remaining:+ payload["entries"] = remaining+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")+ else:+ # 整批都退回去了,这个批次就不该再出现在「回滚上一批」里。+ path.unlink(missing_ok=True)+ return {"restored": len(restored), "failed": len(failures), "failures": failures[:50],+ "batch": path.name}+++__all__ = [+ "MAX_PATH", "PLAN_FIELDS", "PRESETS", "OrganizeError", "TemplateError",+ "apply_plan", "batch_log_dir", "build_plan", "latest_batch", "placeholder_values",+ "plan_path", "rollback_batch", "write_plan",+]diff --git a/src/peach/organize_templates.py b/src/peach/organize_templates.pynew file mode 100644index 000000000..2188606e8--- /dev/null+++ b/src/peach/organize_templates.py@@ -0,0 +1,233 @@+"""整理用的路径模板:占位符取值、可选分组、文件名清洗与逃逸防护(ADR-0039)。++模板只有三种记号:字面量、`{占位符}`、`[可选分组]`。分组里的占位符只要有一个取不到值,+整段就不出现——`{number}[ {title}][ CD{cd}]` 在没有标题时给 `ABC-123`,而不是+`ABC-123 CD2` 这种带着两个空格的名字。++占位符一律从 approved 真相字段取值(见 `organize.placeholder_values`)。候选不参与:+按未复核的猜测改文件名等于把猜测写进文件系统,而那一层没有 `source` 和 `confidence`。++清洗与逃逸防护分两层,缺一层都会出事:++* **取值这一层**只可能带来非法字符(标题里的 `:` 与 `?`、演员名之间的 `/`),所以按+ Windows 的保留字符逐个替换,并挡住 `CON`、`PRN` 这类保留名与结尾的点和空格。+* **模板本身这一层**才可能带来路径逃逸:`..\\..\\Windows`、`C:\\`、`/etc`。取值那层的+ 清洗挡不住它——那些字符是用户自己写在模板里的字面量。所以模板在保存和使用前都要过+ `validate_template`,而不是等渲染完再看结果像不像话。+"""+from __future__ import annotations++import ntpath+import re+from dataclasses import dataclass++#: 模板认识的占位符,以及它在界面上的说明。顺序就是界面上列出来的顺序。+PLACEHOLDERS: dict[str, str] = {+ "number": "番号",+ "title": "标题",+ "studio": "厂牌",+ "series": "系列",+ "year": "发行年",+ "actors": "出演者",+ "cd": "分片号",+ "mosaic": "有码无码",+ "definition": "画质",+}++#: 单个路径组件的长度上限。Windows 的组件上限是 255 个字符,但长名字在资源管理器、+#: 压缩包和网盘客户端里到处挨截断,所以留一大截余量;超出的从中间截断而不是末尾——+#: 末尾往往是分片号和画质这些用来区分的部分。+MAX_COMPONENT = 120+#: 整条目标路径的长度上限。Windows 的 `MAX_PATH` 是 260;长路径要注册表开关配合,+#: 而 115 与 PikPak 的挂载层不保证支持,所以按最保守的那一档拦。+MAX_PATH = 240++#: Windows 不收的字符。POSIX 只禁 `/` 和 NUL,但账本路径一律是 Windows 形态+#: (ADR-0017),所以按 Windows 这一套清洗,两个平台上结果一致。+_ILLEGAL = re.compile(r'[<>:"/\\|?*\x00-\x1f]')+#: 保留设备名。带扩展名也算:`CON.mp4` 在 Windows 上同样建不出来。+_RESERVED = frozenset({"CON", "PRN", "AUX", "NUL",+ *(f"COM{n}" for n in range(1, 10)),+ *(f"LPT{n}" for n in range(1, 10))})+++class TemplateError(ValueError):+ """模板本身不合法。消息直接给用户看,所以写成一句中文。"""+++@dataclass(frozen=True)+class _Token:+ kind: str # "text" | "field" | "group"+ text: str = ""+ parts: tuple = ()+++def sanitise_component(value: str) -> str:+ """把一个取值收敛成能当路径组件的样子。++ 替换成 `_` 而不是删掉:`ABC-123:完整版` 删掉冒号会变成 `ABC-123完整版`,看不出+ 该处有过分隔;`_` 一眼能看出这个位置上有个不能进文件名的符号。+ """+ text = _ILLEGAL.sub("_", str(value or "")).strip()+ # 结尾的点和空格在 Windows 上会被静默吃掉,于是「建出来的名字」和「要求的名字」+ # 不一致,下一轮整理又会认为这一行还没做完。+ text = text.rstrip(". ")+ if not text:+ return ""+ stem = text.split(".", 1)[0].upper()+ if stem in _RESERVED:+ text = "_" + text+ if len(text) > MAX_COMPONENT:+ head = MAX_COMPONENT - 21+ text = text[:head] + "…" + text[-20:]+ return text+++def _parse(template: str) -> tuple[_Token, ...]:+ """把模板切成记号。`{{`、`}}`、`[[`、`]]` 是对应符号的字面量写法。"""+ tokens: list[_Token] = []+ buffer: list[str] = []+ stack: list[list[_Token]] = []+ target = tokens++ def flush() -> None:+ if buffer:+ target.append(_Token("text", "".join(buffer)))+ buffer.clear()++ index = 0+ while index < len(template):+ char = template[index]+ pair = template[index:index + 2]+ if pair in {"{{", "}}", "[[", "]]"}:+ buffer.append(char)+ index += 2+ continue+ if char == "{":+ end = template.find("}", index)+ if end < 0:+ raise TemplateError("占位符的 `{` 没有配对的 `}`")+ name = template[index + 1:end].strip()+ if name not in PLACEHOLDERS:+ raise TemplateError(+ f"不认识的占位符 `{{{name}}}`;可用的是 "+ + "、".join(f"{{{key}}}" for key in PLACEHOLDERS))+ flush()+ target.append(_Token("field", name))+ index = end + 1+ continue+ if char == "[":+ flush()+ stack.append(target)+ target = []+ index += 1+ continue+ if char == "]":+ if not stack:+ raise TemplateError("可选分组的 `]` 没有配对的 `[`")+ flush()+ group = _Token("group", parts=tuple(target))+ target = stack.pop()+ target.append(group)+ index += 1+ continue+ buffer.append(char)+ index += 1+ if stack:+ raise TemplateError("可选分组的 `[` 没有配对的 `]`")+ flush()+ return tuple(tokens)+++def _render_tokens(tokens: tuple[_Token, ...], values: dict[str, str]) -> tuple[str, bool]:+ """返回渲染结果,以及这一段里的占位符是不是都有值。"""+ out: list[str] = []+ filled = True+ for token in tokens:+ if token.kind == "text":+ out.append(token.text)+ elif token.kind == "field":+ value = sanitise_component(values.get(token.text, ""))+ if not value:+ filled = False+ out.append(value)+ else:+ text, group_filled = _render_tokens(token.parts, values)+ # 分组里有占位符没取到值就整段省略。方括号本身永远不出现在结果里;+ # 要一对字面的方括号写 `[[` 和 `]]`。一个占位符都没有的分组等于一段+ # 普通字面量,照常输出,而不是一段永远不出现的字。+ if group_filled or not _fields_in(token.parts):+ out.append(text)+ return "".join(out), filled+++def _fields_in(tokens: tuple[_Token, ...]) -> bool:+ return any(token.kind == "field" or (token.kind == "group" and _fields_in(token.parts))+ for token in tokens)+++def template_fields(template: str) -> frozenset[str]:+ """模板用到的占位符名字。界面据此说明「缺哪个字段这一行就整理不了」。"""+ def walk(tokens: tuple[_Token, ...]) -> set[str]:+ found: set[str] = set()+ for token in tokens:+ if token.kind == "field":+ found.add(token.text)+ elif token.kind == "group":+ found |= walk(token.parts)+ return found+ return frozenset(walk(_parse(template)))+++def required_fields(template: str) -> frozenset[str]:+ """不在可选分组里的占位符:取不到值这一行就没法整理,只能跳过。"""+ def walk(tokens: tuple[_Token, ...]) -> set[str]:+ return {token.text for token in tokens if token.kind == "field"}+ return frozenset(walk(_parse(template)))+++def validate_template(template: str, *, directory: bool = False) -> str:+ """校验并返回规范化的模板;不合法抛 `TemplateError`。++ 目录模板可以带 `/` 或 `\\` 分层,文件名模板不行——文件名里的分隔符意味着模板在+ 悄悄多建一层目录,而用户以为自己只是在给文件取名。+ """+ text = str(template or "").strip()+ if not text:+ return ""+ if len(text) > 300:+ raise TemplateError("模板太长")+ _parse(text) # 记号配对与占位符名字先过一遍+ if ntpath.splitdrive(text)[0]:+ raise TemplateError("模板不能带盘符;它只描述来源根下面的相对位置")+ normalised = text.replace("\\", "/")+ if normalised.startswith("/"):+ raise TemplateError("模板不能以分隔符开头;它只描述来源根下面的相对位置")+ if not directory and "/" in normalised:+ raise TemplateError("文件名模板不能带目录分隔符;分层写在目录模板里")+ for component in normalised.split("/"):+ stripped = component.strip()+ if stripped in {".", ".."}:+ raise TemplateError("模板不能包含 `.` 或 `..`")+ if directory and not stripped and normalised.strip("/") != "":+ raise TemplateError("目录模板里有空的一层")+ return normalised.strip("/") if directory else normalised+++def render(template: str, values: dict[str, str], *,+ directory: bool = False) -> tuple[str, frozenset[str]]:+ """渲染模板,返回 `(结果, 缺失的必填占位符)`。++ 缺失的占位符一起返回而不是抛异常:调用方要把「这一行为什么没整理」写进计划 CSV,+ 一次说清楚缺哪几个字段,比让用户改一次模板试一次强。+ """+ normalised = validate_template(template, directory=directory)+ if not normalised:+ return "", frozenset()+ missing = {name for name in required_fields(normalised)+ if not sanitise_component(values.get(name, ""))}+ text, _filled = _render_tokens(_parse(normalised), values)+ components = [sanitise_component(part) for part in text.split("/")] if directory \+ else [sanitise_component(text)]+ components = [part for part in components if part]+ return "/".join(components), frozenset(missing)diff --git a/src/peach/task_runs.py b/src/peach/task_runs.pyindex 5c9ff16ec..81adb72e2 100644--- a/src/peach/task_runs.py+++ b/src/peach/task_runs.py@@ -68,6 +68,7 @@ TASK_LABELS = {"empty-folders": "空文件夹与失效条目清理","scraping-cover": "封面采集","media-repair": "播放兼容修复",+ "organize": "按模板整理","batch": "批量操作","scrape-codes": "番号资料刮削","jav-covers": "封面批量抓取",diff --git a/src/peach/web_organize.py b/src/peach/web_organize.pynew file mode 100644index 000000000..af3cf78c5--- /dev/null+++ b/src/peach/web_organize.py@@ -0,0 +1,142 @@+"""整理端点:预览、执行、回滚上一批(ADR-0039)。++预览只读,执行与回滚是真实 ledger 写入,所以它们不进 `READ_ONLY_POST_ROUTES`——+只读端那份账本是复制来的,改了路径就是一处合不回去的分叉。++执行走后台任务:几千行改名在 115 挂载上是分钟级的事,HTTP 等不住。互斥、进度和+「这一批什么时候跑的、动了多少」都落在任务中心那张表里。+"""+from __future__ import annotations++import sqlite3+import time+from pathlib import Path++from . import organize+from .migrations import sqlite_backup+from .organize_templates import PLACEHOLDERS, TemplateError, validate_template+from .platform import location_roots+from .scripting import verify_after_write+from .web_settings import organize_templates++#: 界面上能整理的来源。`online` 是追更抓来的东西,不在任何一个媒体根下面。+ORGANIZE_LOCATIONS = ("local", "115", "pikpak")+++def _templates(contract, body) -> tuple[str, str, str]:+ """取出这一次要用的来源与两份模板;模板缺省时用账本里存着的那一份。"""+ location = str(body.get("location") or "").strip()+ if location not in ORGANIZE_LOCATIONS:+ raise ValueError(f"不认识的来源:{location or '(空)'}")+ stored = organize_templates(contract).get(location, {})+ file_template = body.get("file_template")+ dir_template = body.get("dir_template")+ file_template = stored.get("file", "") if file_template is None else str(file_template)+ dir_template = stored.get("dir", "") if dir_template is None else str(dir_template)+ return (location, validate_template(file_template),+ validate_template(dir_template, directory=True))+++def q_organize(contract, _args=None) -> dict:+ """整理这一块的当前状态:任务快照、可选来源、占位符说明与上一批。"""+ # 任务快照摊在顶层:进度组件(`followJobProgress`)认的就是这个形状,+ # 多包一层 `job` 就要在前端再写一遍拆包。+ state = contract.organize_job.snapshot() or {"status": "idle"}+ latest = organize.latest_batch(contract.candidate_root)+ declared = location_roots()+ return {+ **state,+ "status": state.get("status", "idle"),+ "locations": [{"location": location, "roots": list(declared.get(location, ()))}+ for location in ORGANIZE_LOCATIONS if declared.get(location)],+ "templates": organize_templates(contract),+ "presets": [dict(preset) for preset in organize.PRESETS],+ "placeholders": [{"key": key, "label": label} for key, label in PLACEHOLDERS.items()],+ "last_batch": latest.name if latest else "",+ }+++def w_organize_preview(contract, body) -> dict:+ """出计划:写一份 CSV,回给界面会变的行(上限 200)与跳过统计。"""+ location, file_template, dir_template = _templates(contract, body)+ with contract.read_connection() as connection:+ plan = organize.build_plan(connection, location=location,+ file_template=file_template, dir_template=dir_template)+ path = organize.plan_path(contract.candidate_root, location)+ organize.write_plan(path, plan["rows"])+ changes = [row for row in plan["rows"] if row["action"] != "skip"]+ return {"ok": True, "location": location, "counts": plan["counts"],+ "reasons": plan["reasons"], "rows": changes[:200],+ "truncated": len(changes) > 200, "plan_csv": str(path)}+++def _run_write(contract, job_id: str, work) -> dict:+ """备份、开一条自己的连接干活、事后自检。++ 连接不走 `contract.write_transaction()`:那把写锁在整批期间会一直被握着,而任务+ 中心的进度也要拿同一把锁,同一个线程里就是死锁。逐条提交让每个事务都很短,+ 并发的普通写入照常进行。+ """+ backup = Path(contract.candidate_root) / "organize-backups" / (+ f"ledger.pre-organize-{time.strftime('%Y%m%d-%H%M%S')}.db")+ backup.parent.mkdir(parents=True, exist_ok=True)+ sqlite_backup(Path(contract.db_path), backup)+ connection = sqlite3.connect(str(contract.db_path), timeout=30)+ connection.row_factory = sqlite3.Row+ try:+ result = work(connection)+ integrity, violations = verify_after_write(connection)+ finally:+ connection.close()+ contract.cache_bust()+ if integrity != "ok" or violations:+ raise RuntimeError(+ f"写入后 ledger 校验失败:integrity={integrity} foreign_keys={violations}")+ return {**result, "backup": str(backup)}+++def w_organize_apply(contract, body) -> dict:+ """按确认过的模板执行整理。重跑一次计划,不信任界面手上那份。"""+ if body.get("confirm") is not True:+ raise ValueError("整理需要确认")+ location, file_template, dir_template = _templates(contract, body)+ if not file_template and not dir_template:+ raise ValueError("至少要给一个模板")+ job = contract.organize_job++ def work(job_id: str) -> None:+ with contract.read_connection() as connection:+ plan = organize.build_plan(connection, location=location,+ file_template=file_template,+ dir_template=dir_template)+ job.update(job_id, total=plan["counts"]["change"], stage="正在整理")+ result = _run_write(contract, job_id, lambda connection: organize.apply_plan(+ connection, plan["rows"], generated_root=contract.candidate_root,+ progress=lambda **fields: job.update(job_id, **fields)))+ job.update(job_id, **result, counts=plan["counts"], status="complete",+ completed_at=time.time())++ return job.start(work, restart=True,+ initial={"stage": "正在核对计划", "location": location})+++def w_organize_rollback(contract, body) -> dict:+ """把上一批整理原样退回去。"""+ if body.get("confirm") is not True:+ raise ValueError("回滚需要确认")+ latest = organize.latest_batch(contract.candidate_root)+ if latest is None:+ raise ValueError("没有可以回滚的批次")+ job = contract.organize_job++ def work(job_id: str) -> None:+ result = _run_write(contract, job_id, lambda connection: organize.rollback_batch(+ connection, latest, progress=lambda **fields: job.update(job_id, **fields)))+ job.update(job_id, **result, status="complete", completed_at=time.time())++ return job.start(work, restart=True,+ initial={"stage": "正在回滚上一批", "batch": latest.name})+++__all__ = ["ORGANIZE_LOCATIONS", "TemplateError", "q_organize", "w_organize_apply",+ "w_organize_preview", "w_organize_rollback"]diff --git a/src/peach/web_router.py b/src/peach/web_router.pyindex 906be8605..1b5c7fe4d 100644--- a/src/peach/web_router.py+++ b/src/peach/web_router.py@@ -66,6 +66,9 @@ from .web_follow import (from .web_links import w_links, w_links_check, w_links_prunefrom .web_library_processing import q_library_processing, q_library_processing_issues, w_library_processingfrom .web_media_repair import q_media_repair, w_media_repair+from .web_organize import (+ q_organize, w_organize_apply, w_organize_preview, w_organize_rollback,+)from .web_playlists import q_playlist, q_playlists, w_playlistfrom .web_resource_sync import w_purge_missing, w_resource_sync_apply, w_resource_sync_scanfrom .web_review import q_review, w_review_decision, w_review_genre@@ -292,6 +295,7 @@ GET_HANDLERS = {"/api/links/prune": lambda contract, args: contract.link_prune_job.snapshot() or {"status": "idle"},"/api/resource-sync/apply": lambda contract, args: contract.resource_apply_job.snapshot() or {"status": "idle"},"/api/media-repair": q_media_repair,+ "/api/organize": q_organize,"/api/items": q_items,"/api/item": _get_item,"/api/parts": q_parts,@@ -349,6 +353,9 @@ POST_HANDLERS = {"/api/taste/source": w_taste_source,"/api/trash/empty": _post_empty_trash,"/api/data-cleanup/empty-folders": w_cleanup_empty_directories,+ "/api/organize/preview": w_organize_preview,+ "/api/organize/apply": w_organize_apply,+ "/api/organize/rollback": w_organize_rollback,"/api/purge-missing": w_purge_missing,"/api/links/check": w_links_check,"/api/links/prune": w_links_prune,@@ -373,6 +380,8 @@ READ_ONLY_POST_ROUTES = frozenset({"/api/links/check",# 修复只写 `transcode_root` 里的边车,那是本机缓存,不是账本。"/api/media-repair",+ # 整理的预览只出一份计划 CSV,不动文件也不改账本;执行与回滚不在这里。+ "/api/organize/preview",})# `/api/data-cleanup/empty-folders` 不在上面:它连文件已消失的账本行一起删,走的是# `purge_assets`。检查那一步(`dry_run`)确实不写,但闸门按路径判,宁可连检查一起拦,diff --git a/src/peach/web_settings.py b/src/peach/web_settings.pyindex d08c1c389..98d87e16c 100644--- a/src/peach/web_settings.py+++ b/src/peach/web_settings.py@@ -45,8 +45,10 @@ DEFAULT_FOLLOW_INITIAL_DAYS = 30#: 它该不该跨机同步,而不是默认就同步过去。#: `postSetupTutorialDone` 说的是「这套馆藏已经装完了」,不是「这台设备看过教程」——#: 装完就是装完,换台设备打开不该再被教一遍,所以它也跟着账本走。+#: 整理模板(ADR-0039)同理:它是「我要我的库长什么样」,不是这台设备上的顺手。SYNCED_SETTING_KEYS = frozenset({"sidebarOrder", "metadataRefreshDays", "followInitialDays", "postSetupTutorialDone",+ "organizeTemplates",})@@ -109,6 +111,33 @@ def follow_initial_days(contract: SettingsContract) -> int:return normalise_follow_initial_days(_stored(contract).get("followInitialDays"))+def normalise_organize_templates(raw) -> dict:+ """收敛整理模板:`{来源: {"file": 模板, "dir": 模板}}`。++ 模板在这里就要过一遍 `validate_template`:它决定文件会被改成什么名字、放到哪一层,+ 一个带 `..` 的模板存进去、等到执行那一刻才拒绝,用户已经点过确认了。+ """+ from .organize_templates import validate_template+ if not isinstance(raw, dict):+ return {}+ clean: dict[str, dict[str, str]] = {}+ for location, entry in raw.items():+ if location not in {"local", "115", "pikpak"} or not isinstance(entry, dict):+ continue+ # 模板不合法时 `TemplateError` 原样抛给调用方:它是 `ValueError`,API 翻成 400+ # 并把那句中文交给用户,而不是把这一份悄悄丢掉。+ file_template = validate_template(str(entry.get("file") or ""))+ dir_template = validate_template(str(entry.get("dir") or ""), directory=True)+ if file_template or dir_template:+ clean[location] = {"file": file_template, "dir": dir_template}+ return clean+++def organize_templates(contract: SettingsContract) -> dict:+ """服务端读到的整理模板。没配过就是空字典,整理端点据此拒绝执行。"""+ return normalise_organize_templates(_stored(contract).get("organizeTemplates"))++def _stored(contract: SettingsContract) -> dict:with contract.read_connection() as connection:row = connection.execute(@@ -133,6 +162,7 @@ def q_settings(contract: SettingsContract, _args=None) -> dict:payload.get("metadataRefreshDays")),"followInitialDays": normalise_follow_initial_days(payload.get("followInitialDays")),"postSetupTutorialDone": payload.get("postSetupTutorialDone") is True,+ "organizeTemplates": normalise_organize_templates(payload.get("organizeTemplates")),}@@ -160,6 +190,8 @@ def w_settings(contract: SettingsContract, body) -> dict:merged["followInitialDays"] = normalise_follow_initial_days(body["followInitialDays"])if "postSetupTutorialDone" in body:merged["postSetupTutorialDone"] = body["postSetupTutorialDone"] is True+ if "organizeTemplates" in body:+ merged["organizeTemplates"] = normalise_organize_templates(body["organizeTemplates"])stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())with contract.write_transaction() as connection:updated = connection.execute(diff --git a/src/peach/web_state.py b/src/peach/web_state.pyindex 8a383d6e3..1ac7d45cd 100644--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@ -158,6 +158,8 @@ class WebContract:"PeachTimelineThumbnailJob", "timeline-thumbnails")self.resource_apply_job = self._job("PeachResourceApplyJob", "resource-apply")self.media_repair_job = self._job("PeachMediaRepairJob", "media-repair")+ # 整理(ADR-0039):同一时间只跑一批,互斥由这个任务自己的键提供。+ self.organize_job = self._job("PeachOrganizeJob", "organize")self.follow_scheduler = None#: 批量修 MP4 头要的两件东西,由 `api` 在装配时接上:它们属于播放链路,#: 建在 app 那一侧,契约这边只留接口。没接上时修复端点会说清楚。diff --git a/tests/test_organize.py b/tests/test_organize.pynew file mode 100644index 000000000..0f7e3b6d8--- /dev/null+++ b/tests/test_organize.py@@ -0,0 +1,379 @@+"""按模板整理:模板渲染、逃逸防护、计划生成、执行与回滚(ADR-0039)。"""+from __future__ import annotations++import sqlite3+import tempfile+import unittest+from contextlib import closing+from pathlib import Path, PureWindowsPath+from unittest import mock++from peach import organize+from peach.organize_templates import (+ TemplateError, render, sanitise_component, validate_template,+)+from support.ledger import fresh_ledger++ROOT_DECLARATION = "R:\\media"+DECLARED = {"local": (ROOT_DECLARATION,)}++VALUES = {+ "number": "ABC-123", "title": "标题", "studio": "厂牌", "series": "系列",+ "year": "2024", "actors": "甲、乙", "cd": "2", "mosaic": "无码",+ "definition": "1080p",+}+++class TemplateRenderTests(unittest.TestCase):+ CASES = [+ # (模板, 取值覆盖, 期望)+ ("{number}", {}, "ABC-123"),+ ("{number} {title}", {}, "ABC-123 标题"),+ ("{number}[ {title}]", {"title": ""}, "ABC-123"),+ ("{number}[ {title}]", {}, "ABC-123 标题"),+ ("{number}[ CD{cd}]", {"cd": ""}, "ABC-123"),+ ("{number}[ CD{cd}]", {}, "ABC-123 CD2"),+ ("[{mosaic} ]{number}", {"mosaic": ""}, "ABC-123"),+ ("[{studio} ][{series} ]{number}", {"series": ""}, "厂牌 ABC-123"),+ ("{number} [{definition}]", {}, "ABC-123 1080p"),+ # 方括号是分组记号,不进结果;一个占位符都没有的分组就是一段普通字面量。+ ("{number} [完整版]", {}, "ABC-123 完整版"),+ # 转义写法给出字面的括号。+ ("{number} {{x}}", {}, "ABC-123 {x}"),+ ("{number} [[x]]", {}, "ABC-123 [x]"),+ # 出演者与年份是最常见的两组可选信息。+ ("{number}[ ({year})][ {actors}]", {"year": ""}, "ABC-123 甲、乙"),+ ]++ def test_render_table(self):+ for template, overrides, expected in self.CASES:+ with self.subTest(template=template, overrides=overrides):+ values = {**VALUES, **overrides}+ text, _missing = render(template, values)+ self.assertEqual(text, expected)++ def test_missing_required_field_is_reported(self):+ text, missing = render("{number} {title}", {**VALUES, "title": ""})+ self.assertEqual(missing, frozenset({"title"}))+ self.assertEqual(text, "ABC-123")++ def test_optional_field_is_not_required(self):+ _text, missing = render("{number}[ {title}]", {**VALUES, "title": ""})+ self.assertEqual(missing, frozenset())++ def test_directory_template_keeps_layers(self):+ text, _missing = render("{studio}/{number}", VALUES, directory=True)+ self.assertEqual(text, "厂牌/ABC-123")+++class SanitiseTests(unittest.TestCase):+ def test_illegal_characters_become_underscore(self):+ self.assertEqual(sanitise_component('a<b>c:d"e/f\\g|h?i*j'),+ "a_b_c_d_e_f_g_h_i_j")++ def test_trailing_dot_and_space_are_dropped(self):+ self.assertEqual(sanitise_component("名字. "), "名字")++ def test_reserved_device_name_is_prefixed(self):+ self.assertEqual(sanitise_component("CON"), "_CON")+ self.assertEqual(sanitise_component("nul.mp4"), "_nul.mp4")++ def test_long_value_is_truncated_from_the_middle(self):+ value = sanitise_component("甲" * 400)+ self.assertLessEqual(len(value), 120)+ self.assertIn("…", value)+++class TemplateEscapeTests(unittest.TestCase):+ REJECTED = [+ "..\\{number}",+ "../{number}",+ "C:\\{number}",+ "/{number}",+ "{number}/{title}", # 文件名模板不带分隔符+ "{unknown}",+ "{number",+ "{number}]",+ "[{number}",+ ]++ def test_escaping_templates_are_rejected(self):+ for template in self.REJECTED:+ with self.subTest(template=template):+ with self.assertRaises(TemplateError):+ validate_template(template)++ def test_directory_template_may_layer_but_not_escape(self):+ self.assertEqual(validate_template("{studio}\\{number}", directory=True),+ "{studio}/{number}")+ with self.assertRaises(TemplateError):+ validate_template("{studio}/../{number}", directory=True)++ def test_value_cannot_introduce_a_layer(self):+ text, _missing = render("{title}", {"title": "a/../b"})+ self.assertEqual(text, "a_.._b")+++def _seed(db_path: Path, rows: list[dict]) -> None:+ with closing(sqlite3.connect(db_path)) as connection:+ for row in rows:+ connection.execute(+ "INSERT INTO asset(id,location,path,name,medium,code,catalog_title,"+ "studio,series,release_date,width,height) "+ "VALUES(:id,'local',:path,:name,'video',:code,:title,:studio,NULL,"+ ":release_date,:width,:height)",+ {"series": None, "code": None, "title": None, "studio": None,+ "release_date": None, "width": None, "height": None, **row})+ connection.commit()+++def _plan(db_path: Path, **kwargs) -> dict:+ with closing(sqlite3.connect(db_path)) as connection:+ return organize.build_plan(connection, location="local", roots=DECLARED,+ online=True, **kwargs)+++class PlanTests(unittest.TestCase):+ def setUp(self):+ self.holder = Path(tempfile.mkdtemp(prefix="peach-organize-")).resolve()+ self.addCleanup(lambda: __import__("shutil").rmtree(self.holder, ignore_errors=True))+ self.db_path = fresh_ledger(self.holder)++ def test_rename_in_place_and_move_into_template_directory(self):+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\旧\\[site.com]abc123.mp4",+ "name": "[site.com]abc123.mp4", "code": "ABC-123", "title": "标题",+ "studio": "厂牌"},+ ])+ plan = _plan(self.db_path, file_template="{number}[ {title}]")+ self.assertEqual(plan["counts"]["change"], 1)+ self.assertEqual(plan["rows"][0]["action"], "rename")+ self.assertEqual(plan["rows"][0]["target_path"],+ "R:\\media\\旧\\ABC-123 标题.mp4")++ plan = _plan(self.db_path, file_template="{number}", dir_template="{studio}")+ self.assertEqual(plan["rows"][0]["action"], "move")+ self.assertEqual(plan["rows"][0]["target_path"], "R:\\media\\厂牌\\ABC-123.mp4")++ def test_row_already_named_as_asked_is_not_listed(self):+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\ABC-123.mp4", "name": "ABC-123.mp4",+ "code": "ABC-123"},+ ])+ plan = _plan(self.db_path, file_template="{number}")+ self.assertEqual(plan["counts"]["unchanged"], 1)+ self.assertEqual(plan["rows"], [])++ def test_missing_field_skips_the_row(self):+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\x.mp4", "name": "x.mp4", "code": None},+ ])+ plan = _plan(self.db_path, file_template="{number}")+ self.assertEqual(plan["rows"][0]["action"], "skip")+ self.assertEqual(plan["rows"][0]["reason"], organize.SKIP_MISSING_FIELD)++ def test_two_rows_landing_on_one_name_keep_the_first(self):+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\a.mp4", "name": "a.mp4", "code": "ABC-123"},+ {"id": 2, "path": "R:\\media\\b.mp4", "name": "b.mp4", "code": "ABC-123"},+ ])+ plan = _plan(self.db_path, file_template="{number}")+ self.assertEqual(plan["counts"]["change"], 1)+ skipped = [row for row in plan["rows"] if row["action"] == "skip"]+ self.assertEqual(skipped[0]["reason"], organize.SKIP_TARGET_EXISTS)++ def test_offline_source_skips_every_row(self):+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\a.mp4", "name": "a.mp4", "code": "ABC-123"},+ ])+ with closing(sqlite3.connect(self.db_path)) as connection:+ plan = organize.build_plan(connection, location="local", roots=DECLARED,+ online=False, file_template="{number}")+ self.assertEqual(plan["counts"]["skip"], 1)+ self.assertEqual(plan["reasons"], {organize.SKIP_OFFLINE: 1})++ def test_path_outside_the_declared_root_is_skipped(self):+ _seed(self.db_path, [+ {"id": 1, "path": "B:\\其它\\a.mp4", "name": "a.mp4", "code": "ABC-123"},+ ])+ plan = _plan(self.db_path, file_template="{number}")+ self.assertEqual(plan["rows"][0]["reason"], organize.SKIP_OUTSIDE_ROOT)++ def test_plan_csv_carries_every_column(self):+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\a.mp4", "name": "a.mp4", "code": "ABC-123"},+ ])+ plan = _plan(self.db_path, file_template="{number}")+ path = organize.write_plan(self.holder / "plan.csv", plan["rows"])+ header = path.read_text(encoding="utf-8-sig").splitlines()[0]+ self.assertEqual(header.split(","), organize.PLAN_FIELDS)+++class ApplyTests(unittest.TestCase):+ """执行与回滚都真的动文件:`translate_ledger_path` 指到临时目录,两个平台一致。"""++ def setUp(self):+ self.holder = Path(tempfile.mkdtemp(prefix="peach-organize-apply-")).resolve()+ self.addCleanup(lambda: __import__("shutil").rmtree(self.holder, ignore_errors=True))+ self.media = self.holder / "media"+ self.media.mkdir()+ self.db_path = fresh_ledger(self.holder)+ patcher = mock.patch.object(organize, "translate_ledger_path", self._translate)+ patcher.start()+ self.addCleanup(patcher.stop)++ def _translate(self, raw) -> Path:+ return self.media.joinpath(*PureWindowsPath(str(raw)).parts[2:])++ def _file(self, relative: str) -> Path:+ path = self.media / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("x", encoding="utf-8")+ return path++ def _apply(self, plan):+ with closing(sqlite3.connect(self.db_path)) as connection:+ return organize.apply_plan(connection, plan["rows"],+ generated_root=self.holder)++ def test_apply_moves_the_file_and_updates_the_ledger(self):+ self._file("旧/abc123.mp4")+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\旧\\abc123.mp4", "name": "abc123.mp4",+ "code": "ABC-123", "studio": "厂牌"},+ ])+ plan = _plan(self.db_path, file_template="{number}", dir_template="{studio}")+ result = self._apply(plan)+ self.assertEqual((result["moved"], result["failed"]), (1, 0))+ self.assertTrue((self.media / "厂牌" / "ABC-123.mp4").is_file())+ self.assertFalse((self.media / "旧" / "abc123.mp4").exists())+ with closing(sqlite3.connect(self.db_path)) as connection:+ row = connection.execute("SELECT path,name FROM asset WHERE id=1").fetchone()+ self.assertEqual(row, ("R:\\media\\厂牌\\ABC-123.mp4", "ABC-123.mp4"))++ def test_rollback_puts_everything_back(self):+ self._file("旧/abc123.mp4")+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\旧\\abc123.mp4", "name": "abc123.mp4",+ "code": "ABC-123", "studio": "厂牌"},+ ])+ self._apply(_plan(self.db_path, file_template="{number}", dir_template="{studio}"))+ batch = organize.latest_batch(self.holder)+ self.assertIsNotNone(batch)+ with closing(sqlite3.connect(self.db_path)) as connection:+ result = organize.rollback_batch(connection, batch)+ self.assertEqual((result["restored"], result["failed"]), (1, 0))+ self.assertTrue((self.media / "旧" / "abc123.mp4").is_file())+ with closing(sqlite3.connect(self.db_path)) as connection:+ path = connection.execute("SELECT path FROM asset WHERE id=1").fetchone()[0]+ self.assertEqual(path, "R:\\media\\旧\\abc123.mp4")+ # 整批退回去之后它不该再出现在「回滚上一批」里。+ self.assertIsNone(organize.latest_batch(self.holder))++ def test_target_taken_on_disk_fails_only_that_row(self):+ self._file("旧/abc123.mp4")+ self._file("ABC-123.mp4")+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\旧\\abc123.mp4", "name": "abc123.mp4",+ "code": "ABC-123"},+ ])+ plan = {"rows": [{"asset_id": 1, "action": "move",+ "current_path": "R:\\media\\旧\\abc123.mp4",+ "target_path": "R:\\media\\ABC-123.mp4"}]}+ result = self._apply(plan)+ self.assertEqual((result["moved"], result["failed"]), (0, 1))+ self.assertEqual(result["failures"][0]["reason"], organize.SKIP_TARGET_EXISTS)+ self.assertTrue((self.media / "旧" / "abc123.mp4").is_file())++ def test_cross_volume_row_is_refused(self):+ self._file("旧/abc123.mp4")+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\旧\\abc123.mp4", "name": "abc123.mp4",+ "code": "ABC-123"},+ ])+ plan = {"rows": [{"asset_id": 1, "action": "move",+ "current_path": "R:\\media\\旧\\abc123.mp4",+ "target_path": "B:\\media\\ABC-123.mp4"}]}+ result = self._apply(plan)+ self.assertEqual(result["failures"][0]["reason"], organize.SKIP_CROSS_VOLUME)+ self.assertTrue((self.media / "旧" / "abc123.mp4").is_file())++ def test_missing_source_is_reported_not_raised(self):+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\旧\\abc123.mp4", "name": "abc123.mp4",+ "code": "ABC-123"},+ ])+ plan = _plan(self.db_path, file_template="{number}")+ result = self._apply(plan)+ self.assertEqual((result["moved"], result["failed"]), (0, 1))+ self.assertEqual(result["failures"][0]["reason"], "源文件不存在")+++class EndpointTests(unittest.TestCase):+ """整理端点:预览只读、执行要确认、模板跟着账本走。"""++ def setUp(self):+ from peach.web_state import WebContract++ self.holder = Path(tempfile.mkdtemp(prefix="peach-organize-web-")).resolve()+ self.addCleanup(lambda: __import__("shutil").rmtree(self.holder, ignore_errors=True))+ self.db_path = fresh_ledger(self.holder)+ _seed(self.db_path, [+ {"id": 1, "path": "R:\\media\\旧\\abc123.mp4", "name": "abc123.mp4",+ "code": "ABC-123", "title": "标题"},+ ])+ self.contract = WebContract(self.db_path, candidate_root=self.holder)+ for target, value in (("location_roots", lambda: DECLARED),+ ("root_online", lambda _root: True)):+ patcher = mock.patch.object(organize, target, value)+ patcher.start()+ self.addCleanup(patcher.stop)++ def test_preview_writes_a_plan_and_counts_changes(self):+ from peach.web_organize import w_organize_preview++ result = w_organize_preview(self.contract, {+ "location": "local", "file_template": "{number}[ {title}]"})+ self.assertEqual(result["counts"]["change"], 1)+ self.assertEqual(result["rows"][0]["target_path"], "R:\\media\\旧\\ABC-123 标题.mp4")+ self.assertTrue(Path(result["plan_csv"]).is_file())++ def test_apply_without_confirmation_is_refused(self):+ from peach.web_organize import w_organize_apply++ with self.assertRaises(ValueError):+ w_organize_apply(self.contract, {"location": "local",+ "file_template": "{number}"})++ def test_rollback_without_a_batch_is_refused(self):+ from peach.web_organize import w_organize_rollback++ with self.assertRaises(ValueError):+ w_organize_rollback(self.contract, {"confirm": True})++ def test_templates_round_trip_through_the_ledger(self):+ from peach.web_settings import organize_templates, w_settings++ w_settings(self.contract, {"organizeTemplates": {+ "115": {"file": "{number}[ {title}]", "dir": "{studio}"}}})+ self.assertEqual(organize_templates(self.contract),+ {"115": {"file": "{number}[ {title}]", "dir": "{studio}"}})++ def test_escaping_template_is_refused_on_save(self):+ from peach.web_settings import w_settings++ with self.assertRaises(TemplateError):+ w_settings(self.contract, {"organizeTemplates": {+ "115": {"file": "{number}", "dir": "../{studio}"}}})++ def test_status_lists_placeholders_and_presets(self):+ from peach.web_organize import q_organize++ payload = q_organize(self.contract)+ self.assertEqual(payload["status"], "idle")+ self.assertTrue(payload["presets"])+ self.assertIn("number", [item["key"] for item in payload["placeholders"]])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 441cfc33e..fba7b135f 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -902,7 +902,7 @@ class WebDataTests(unittest.TestCase):"/api/taste/refresh","/api/links/prune", "/api/resource-sync/apply","/api/follow/tags", "/api/follow/authors",- "/api/taste", "/api/settings", "/api/links",+ "/api/taste", "/api/settings", "/api/links", "/api/organize",})self.assertEqual(set(rm_web.POST_HANDLERS), {"/api/library-processing", "/api/thumbnail-jobs", "/api/media-repair",@@ -922,6 +922,7 @@ class WebDataTests(unittest.TestCase):"/api/follow/author-alias", "/api/follow/schedule","/api/taste/refresh", "/api/taste/source", "/api/settings","/api/entity-name", "/api/entity-alias",+ "/api/organize/preview", "/api/organize/apply", "/api/organize/rollback",})with self.assertRaises(rm_web.ContractRouteNotFound):rm_web.dispatch_api_get(self.contract, "/api/typo", {})diff --git a/tests/test_web_settings.py b/tests/test_web_settings.pyindex f6e8ff8a1..02cae61f7 100644--- a/tests/test_web_settings.py+++ b/tests/test_web_settings.py@@ -94,7 +94,8 @@ class SettingsRoundTripTests(unittest.TestCase):self.assertEqual(q_settings(self.contract),{"sidebarOrder": list(DEFAULT_SIDEBAR_ORDER),"metadataRefreshDays": web_settings.DEFAULT_METADATA_REFRESH_DAYS,- "followInitialDays": 30, "postSetupTutorialDone": False})+ "followInitialDays": 30, "postSetupTutorialDone": False,+ "organizeTemplates": {}})def test_the_metadata_refresh_period_round_trips_and_rejects_odd_values(self):"""这个数直接决定服务端要不要出网重取头像,坏载荷不能把它变成 1 秒或 1 天。"""@@ -118,7 +119,8 @@ class SettingsRoundTripTests(unittest.TestCase):self.assertEqual(w_settings(self.contract, {"sidebarOrder": order}),{"ok": True, "sidebarOrder": order,"metadataRefreshDays": web_settings.DEFAULT_METADATA_REFRESH_DAYS,- "followInitialDays": 30, "postSetupTutorialDone": False})+ "followInitialDays": 30, "postSetupTutorialDone": False,+ "organizeTemplates": {}})self.assertEqual(q_settings(self.contract)["sidebarOrder"], order)self.assertEqual(self._stored_json()["sidebarOrder"], order)diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 29bbcf61d..0f97f9b0a 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -9161,12 +9161,15 @@ class WebUiSourceTests(unittest.TestCase):# 死链表里的地址:`/official/talent/X` 与 `/talent/X` 的差别就在尾部,# 尾部省略会把这张表要回答的东西切掉。省略挂在里面那个 span 上,# 外链标才留得住:中缩靠改写 textContent 实现,同一节点里的图标会被抹掉。- '<span data-middle-truncate>${esc(item.url)}</span>'):+ '<span data-middle-truncate>${esc(item.url)}</span>',+ # 整理预览的两列都是文件名,差别常常只在番号或结尾的 CD 标记上。+ '<span data-middle-truncate title="${esc(row.current_path)}">',+ '<span data-middle-truncate title="${esc(row.target_path)}">'):self.assertPageContains(consumer)# 高清版目标页、统计页与复核页归 React 子树,由 frontend 的用例覆盖。- # 十处里有一处是重复文件名上的 `data-middle-truncate-within`:它后面紧跟着「最大」+ # 十二处里有一处是重复文件名上的 `data-middle-truncate-within`:它后面紧跟着「最大」# 「最长」标记,自己按内容收缩,可用宽度要按父级量。- self.assertEqual(self.app_js.count("data-middle-truncate"), 10)+ self.assertEqual(self.app_js.count("data-middle-truncate"), 12)self.assertPageContains('class="dupname" data-middle-truncate data-middle-truncate-within')self.assertPageContains("if(element.dataset.middleTruncateWithin===undefined)return element.clientWidth;")self.assertEqual(self.app_js.count('class="mixitemtext"'), 3)@@ -10286,7 +10289,8 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains('<span class="board-plain-stat-head"><span class="board-stat-tile">${icon(glyph)}</span>${esc(title)}</span>${body}</button>`;')self.assertPageContains('<div class="cleanuppage"><div class="cleanupstats">')self.assertPageLacks('cleanup-workspace-switch')- self.assertPageContains('</div><div class="cleanupgrid">${cleanupCards.scraping}${cleanupCards.empty}</div>')+ self.assertPageContains('</div><div class="cleanupgrid">${cleanupCards.scraping}${cleanupCards.empty}'+ '${organizeCardMarkup(organizeState)}</div>')# 样式也一起走:没有使用者的选择器留在 board.css 里,下一个人会当它是现役版式去改。self.assertNotIn("cleanup-workspace-switch",(Path(__file__).resolve().parents[1] / "web/board.css").read_text(encoding="utf-8"))diff --git a/web/app.js b/web/app.jsindex 490c7fa39..f32a51bc3 100644--- a/web/app.js+++ b/web/app.js@@ -5044,14 +5044,167 @@ const DATA_MANAGEMENT_ENTRIES=[各占一整行放在读数下面。 */const DATA_MANAGEMENT_STATS=['review','quality','duplicates','junk','trash'];+/* 整理(ADR-0039):媒体默认留在原目录,这一块是唯一会动文件名和目录的入口。+ 两份模板、一次预览、一次执行,外加把上一批原样退回去。 */+function organizeCardMarkup(payload){+ const locations=payload.locations||[];+ const presets=payload.presets||[];+ const hint=(payload.placeholders||[]).map(item=>`{${item.key}} ${item.label}`).join(' · ');+ return `<section class="cleanupfieldset cleanuporganize" id="organize" data-geist-fieldset data-cleanup-task aria-labelledby="cleanupOrganizeTitle">+ <div class="geist-fieldset-content">${fieldsetTitle('cleanupOrganizeTitle','整理')}+ <p>按模板给文件改名并归入目录。先预览,确认后执行;执行过的一批可以整批退回。</p>+ <div class="organizefields">+ <div class="organizesource" data-organize-source></div>+ <label class="organizefield"><span>文件名模板</span>+ <input type="text" class="geist-input" data-organize-file spellcheck="false"+ autocapitalize="off" placeholder="{number}[ {title}]"></label>+ <label class="organizefield"><span>目录模板</span>+ <input type="text" class="geist-input" data-organize-dir spellcheck="false"+ autocapitalize="off" placeholder="留空表示原地改名"></label>+ <div class="organizepresets">${presets.map((preset,index)=>+ `<button type="button" class="geist-button" data-organize-preset="${index}">${esc(preset.label)}</button>`).join('')}</div>+ <p class="cleanupmeta">${esc(hint)};方括号里的内容在字段为空时整段省略。</p>+ </div>+ <div class="organizestate" aria-live="polite"></div></div>+ <footer class="geist-fieldset-footer" data-geist-fieldset-footer>+ <button type="button" class="geist-button primary" data-organize-preview ${locations.length?'':'disabled'}>预览</button>+ <button type="button" class="geist-button primary" data-organize-apply hidden>执行整理</button>+ <button type="button" class="geist-button" data-organize-rollback ${payload.last_batch?'':'hidden'}>回滚上一批</button>+ </footer></section>`;+}++/* 预览结果只列会变的行:库里几万行里改不到的那部分是背景,不是结果。 */+function organizePlanHtml(result){+ const counts=result.counts||{},reasons=result.reasons||{};+ const rows=(result.rows||[]).slice(0,8).map(row=>+ `<li><span data-middle-truncate title="${esc(row.current_path)}">${esc(baseName(row.current_path))}</span><span aria-hidden="true">→</span><span data-middle-truncate title="${esc(row.target_path)}">${esc(baseName(row.target_path))}</span></li>`).join('');+ const skipped=Object.entries(reasons).sort((a,b)=>b[1]-a[1])+ .map(([reason,count])=>`${esc(reason)} ${Number(count).toLocaleString()}`).join(' · ');+ if(!Number(counts.change||0))+ return noteHtml(`没有要改的文件。${skipped?`跳过:${skipped}。`:''}`,{label:'预览结果'});+ return `${noteHtml(`${Number(counts.change).toLocaleString()} 个文件会改名或移动,${Number(counts.unchanged||0).toLocaleString()} 个已经就是目标名字${skipped?`;跳过 ${skipped}`:''}。`,{label:'预览结果'})}+ <ol class="organizeplan">${rows}</ol>${result.truncated?'<p class="cleanupmeta">只列出前 8 行,完整计划在计划 CSV 里。</p>':''}`;+}++function baseName(path){+ const text=String(path||'');+ return text.slice(Math.max(text.lastIndexOf('\\'),text.lastIndexOf('/'))+1);+}++async function wireOrganize(surface,payload){+ const host=$('#organize');+ if(!host)return;+ const status=host.querySelector('.organizestate');+ const fileInput=host.querySelector('[data-organize-file]');+ const dirInput=host.querySelector('[data-organize-dir]');+ const previewButton=host.querySelector('[data-organize-preview]');+ const applyButton=host.querySelector('[data-organize-apply]');+ const rollbackButton=host.querySelector('[data-organize-rollback]');+ const locations=payload.locations||[];+ const templates=payload.templates||{};+ const mount=host.querySelector('[data-organize-source]');+ let location=locations[0]?.location||'';+ const loadTemplates=()=>{+ const stored=templates[location]||{};+ fileInput.value=stored.file||'';+ dirInput.value=stored.dir||'';+ };+ if(locations.length){+ mount.innerHTML=selectFieldHtml(locations.map(item=>+ [item.location,LOC[item.location]||item.location,MEDIA_SOURCE_ICONS[item.location]||'database']),+ location,{label:'整理哪个来源'});+ const field=wireSelectField(mount.firstElementChild);+ field.addEventListener('change',()=>{location=field.value;loadTemplates();applyButton.hidden=true;status.innerHTML=''});+ }+ loadTemplates();+ host.querySelectorAll('[data-organize-preset]').forEach(button=>button.onclick=()=>{+ const preset=(payload.presets||[])[Number(button.dataset.organizePreset)];+ if(!preset)return;+ fileInput.value=preset.file;dirInput.value=preset.dir;+ fileInput.removeAttribute('aria-invalid');dirInput.removeAttribute('aria-invalid');+ });+ const body=()=>JSON.stringify({location,file_template:fileInput.value.trim(),+ dir_template:dirInput.value.trim()});+ /* 模板跟着账本走,所以预览成功的那一刻顺手存下来:用户下次进这一页看到的是+ 自己上次用的那两行,而不是又一次空框。只读端存不进去,那不该挡住预览。 */+ const remember=async()=>{+ try{await api('/api/settings',{method:'POST',body:JSON.stringify({organizeTemplates:{+ ...templates,[location]:{file:fileInput.value.trim(),dir:dirInput.value.trim()}}})})}+ catch(_error){}+ };+ previewButton.onclick=async()=>{+ fileInput.removeAttribute('aria-invalid');dirInput.removeAttribute('aria-invalid');+ setActionBusy(previewButton);applyButton.hidden=true;+ status.innerHTML=loadingDotsHtml('正在按模板算计划…');+ try{+ const result=await api('/api/organize/preview',{method:'POST',body:body()});+ if(!surfaceCurrent(surface))return;+ status.innerHTML=organizePlanHtml(result);+ applyButton.hidden=!Number(result.counts?.change||0);+ templates[location]={file:fileInput.value.trim(),dir:dirInput.value.trim()};+ void remember();+ }catch(error){+ /* 模板不合法时错误就出在这两个框里的一个,所以除了说原因还要指出是哪一格。 */+ const target=/目录模板|分隔符|盘符|`\.`/.test(error.message)?dirInput:fileInput;+ target.setAttribute('aria-invalid','true');target.focus();+ status.innerHTML=noteHtml(error.message,{variant:'error',label:'模板不可用'});+ }finally{setActionBusy(previewButton,false)}+ };+ applyButton.onclick=async()=>{+ const name=LOC[location]||location;+ return confirmModal({title:'按模板整理文件',+ body:`将按这两份模板改动「${name}」上的文件名与目录,目标已存在的行会整行跳过。这一批可以从「回滚上一批」整批退回。`,+ confirmLabel:'整理文件',danger:false,onConfirm:async()=>{+ const started=await api('/api/organize/apply',{method:'POST',+ body:JSON.stringify({location,file_template:fileInput.value.trim(),+ dir_template:dirInput.value.trim(),confirm:true})});+ sessionStorage.setItem('peach-organize-job',started.job_id);+ if(surfaceCurrent(surface))void wireOrganizeProgress();+ }});+ };+ rollbackButton.onclick=async()=>{+ return confirmModal({title:'回滚上一批整理',+ body:`将把上一批整理动过的文件退回整理前的名字与位置,账本路径跟着退回。退回后这一批不再出现在这里。`,+ confirmLabel:'回滚整理',danger:false,onConfirm:async()=>{+ const started=await api('/api/organize/rollback',{method:'POST',+ body:JSON.stringify({confirm:true})});+ sessionStorage.setItem('peach-organize-job',started.job_id);+ if(surfaceCurrent(surface))void wireOrganizeProgress();+ }});+ };+ void wireOrganizeProgress();+}++function wireOrganizeProgress(){+ return wireOperationProgress({host:$('#organize'),path:'/api/organize',+ key:'peach-organize-job',title:'正在整理文件…',+ busy:running=>{const button=$('#organize')?.querySelector('[data-organize-apply]');+ if(button)setActionBusy(button,running)},+ complete:out=>{+ const status=$('#organize')?.querySelector('.organizestate');+ if(!status)return;+ const restored=out.restored;+ const failed=Number(out.failed||0);+ const done=Number(restored===undefined?out.moved||0:restored);+ const text=restored===undefined+ ?`已整理 ${done.toLocaleString()} 个文件${failed?`,${failed.toLocaleString()} 行未能处理`:''}。`+ :`已退回 ${done.toLocaleString()} 个文件${failed?`,${failed.toLocaleString()} 行未能退回`:''}。`;+ status.innerHTML=noteHtml(text,{label:failed?'部分完成':'整理结果',variant:failed?'warning':'success'});+ if(failed)actionFailure('按模板整理',new Error(`${failed} 行未能处理`));+ else actionReceipt(text.replace(/。$/,''));+ const rollback=$('#organize')?.querySelector('[data-organize-rollback]');+ if(rollback)rollback.hidden=restored!==undefined&&!failed;+ }});+}+async function openDataCleanup(push=true){releaseHoverPreviews();disposeStage(false);enterManagementSurface();if(push)route('/data-cleanup');const surface=claimSurface('/data-cleanup');showManagementBody({placeholder:managementPlaceholder('/data-cleanup')});- const [junk,duplicates,sources]=await Promise.all([+ const [junk,duplicates,sources,organizeState]=await Promise.all([surfaceApi(surface,'/api/ads?limit=1'),surfaceApi(surface,'/api/duplicates?limit=1'),- surfaceApi(surface,'/api/sources'),+ surfaceApi(surface,'/api/sources'),surfaceApi(surface,'/api/organize'),]);if(!surfaceCurrent(surface))return;paintManageLede();@@ -5102,7 +5255,7 @@ async function openDataCleanup(push=true){};$('#stats').innerHTML=`<div class="cleanuppage"><div class="cleanupstats">${DATA_MANAGEMENT_STATS.map(section=>cleanupCards[section]).join('')}- </div><div class="cleanupgrid">${cleanupCards.scraping}${cleanupCards.empty}</div>+ </div><div class="cleanupgrid">${cleanupCards.scraping}${cleanupCards.empty}${organizeCardMarkup(organizeState)}</div>${linkManagerMarkup()}${(sources.sources||[]).some(source=>['local','115','pikpak'].includes(source.location)&&source.roots?.length)?resourceSyncMarkup():''}</div>`;$('#stats').querySelector('[data-cleanup-open="junk"]').onclick=()=>openManage('ads');@@ -5141,6 +5294,7 @@ async function openDataCleanup(push=true){}finally{setActionBusy(emptyButton,false);emptyButton.innerHTML=original;emptyButton.hidden=true}}});};+ await wireOrganize(surface,organizeState);await wireLinkManager();await wireResourceSync();}diff --git a/web/css/04-manage.css b/web/css/04-manage.cssindex 3d4b60c99..570d263f2 100644--- a/web/css/04-manage.css+++ b/web/css/04-manage.css@@ -72,6 +72,19 @@.cleanupfieldset button:where(:not(.gselectfield)) svg{width:16px;height:16px;stroke:currentColor;fill:none}.cleanupfieldset .cleanupstate{margin-top:8px;font-size:var(--fs-sm);color:var(--ink-2)}.cleanupfieldset .cleanupstate:empty{display:none}+/* 整理那张卡:两份模板、一排预设、一段结果。字段标签是块级、排在控件上方(Geist 的+ Label 就是这个形状);来源下拉靠框内前缀图标自报用途,同一行不再挂文字标签。 */+.organizefields{display:grid;gap:12px;margin-top:12px}+.organizefield{display:grid;gap:6px;min-width:0}+.organizefield>span{color:var(--ink-2);font-size:var(--fs-sm)}+.organizepresets{display:flex;flex-wrap:wrap;gap:8px}+.organizeplan{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:4px;min-width:0}+.organizeplan li{display:flex;align-items:center;gap:8px;min-width:0;+ color:var(--ink-2);font-size:var(--fs-sm)}+.organizeplan li span{min-width:0;overflow:hidden;white-space:nowrap}+.organizeplan li span:last-child{color:var(--ink)}+.cleanupfieldset .organizestate{margin-top:12px;display:grid;gap:8px}+.cleanupfieldset .organizestate:empty{display:none}.stats h2{margin:0 0 4px;font-size:var(--fs-2xl)}.stats .sub{color:var(--muted);margin:0}/* 来源和凭证页的正文归 React 子树(ADR-0031)。这两条只服务遗留骨架:那一句静态说明