Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(cleanup): consolidate physical data cleanup

longmeidaobce8a7d21fe5
diff --git a/README.md b/README.md
index 5506edde5..df37ffd77 100644
--- a/README.md
+++ b/README.md
@@ -128,6 +128,7 @@ npm run check:vendor
| `/follow` | 关注观看 |
| `/follow-manage` | 关注管理与凭据状态 |
| `/review` | 人工复核 |
+| `/data-cleanup` | 数据清理总览:垃圾文件、重复文件与空文件夹 |
| `/junk-files` | 垃圾文件分类与判断 |
| `/trash` | 回收站 |
| `/stats` | 统计、网盘资源同步与孤立缓存清理 |
@@ -137,7 +138,7 @@ npm run check:vendor
在网盘或本地资源目录手动删除文件后,进入「管理 → 统计 → 资源同步」先扫描差异。扫描在后台运行并逐来源显示进度,离开页面不会中断;Peach 只核对已挂载来源,暂时不可读的目录会跳过而不是判成删除。缺失条目先进入回收站,可恢复的账本元数据不会立即丢失。确认同步时会再次核对候选项,并清理不再被正常馆藏使用的截图、海报、图片缩略图、封面和播放缓存;候选 CSV、来源证据、女优头像和厂牌 Logo 不作缓存删除。
-媒体包里夹带的推广视频、广告图片、网址快捷方式和其它文件进入「管理 → 垃圾文件」(`/junk-files`)。页面按视频、图片、压缩包、音频、网址和其它文件分类;每项都可移入回收站,也可标记为「不是垃圾」并在「已排除」中撤销。顶栏多选支持批量执行当前视图可用的判断或回收操作。Peach 按文件名、推广目录及各类型可用的时长/体积证据列候选,不自动永久删除。
+媒体包里夹带的推广视频、广告图片、网址快捷方式和其它文件进入「管理 → 数据清理」(`/data-cleanup`)。垃圾文件页按视频、图片、压缩包、音频、网址和其它文件分类;每项都可打开网盘所在位置、移入回收站,也可标记为「不是垃圾」并在「已排除」中撤销。重复文件与垃圾文件共用这个管理入口,空文件夹也从其中的独立 Fieldset 显式清理。顶栏多选支持批量执行当前视图可用的判断或回收操作。Peach 按文件名、推广目录及各类型可用的时长/体积证据列候选,不自动永久删除;从回收站永久删除物理文件后,只会继续删除同一来源根以内随之变空的父目录,来源根本身不会删除。
## 关注与候选
diff --git a/docs/REUSE.md b/docs/REUSE.md
index e9f44f4fe..55043fb18 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -19,7 +19,7 @@
- profile 行为、稍后看、播放列表、口味和推荐排序;
- 本地、115、PikPak、Stash、在线来源的绑定和回退策略;
- 计费来源授权、隐私分类和候选复核导入;
-- 物理资源垃圾候选的跨类型证据、人工复核和回收站语义;
+- 物理资源垃圾候选的跨类型证据、人工复核和回收站语义;空目录清理复用 Python 标准库自底向上的 `os.walk` 与只删空目录的 `Path.rmdir`,Peach 只负责在线来源、根目录保护和 CloudDrive 并发消失边界;
- 私有获取来源、出处引用和发现关键词;
- 创作者级视觉采样语义;
- 推理 Provider 与 Agent Provider 的能力契约;
diff --git a/src/peach/api.py b/src/peach/api.py
index b663bd791..e645b21a4 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -855,6 +855,7 @@ def create_app(
@app.api_route("/trash", methods=["GET", "HEAD"])
@app.api_route("/review", methods=["GET", "HEAD"])
@app.api_route("/taste", methods=["GET", "HEAD"])
+ @app.api_route("/data-cleanup", methods=["GET", "HEAD"])
@app.api_route("/duplicates", methods=["GET", "HEAD"])
@app.api_route("/quality-goals", methods=["GET", "HEAD"])
@app.api_route("/resource-sync", methods=["GET", "HEAD"])
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 7722928d7..b4027ce56 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -5,9 +5,10 @@ feedback functions; schema changes belong to the migration runner.
"""
from __future__ import annotations
-import os
+import errno
import hashlib
import json
+import os
import random
import re
import shutil
@@ -40,6 +41,7 @@ from .platform import (
root_online,
system_volume,
translate_ledger_path,
+ within_root,
)
from .repository import LedgerDatabase
from .taste_history import (
@@ -1799,6 +1801,102 @@ def _restore_staged_media(staged):
os.replace(quarantine, original)
+def _online_source_roots() -> dict[str, Path]:
+ """Return only declared physical roots that can be enumerated now."""
+ roots: dict[str, Path] = {}
+ for location, declaration in LOCATION_ROOT_DECLARATIONS.items():
+ root = translate_ledger_path(declaration)
+ if is_unmapped(root) or not root.is_dir() or not root_online(root):
+ continue
+ roots[location] = root
+ return roots
+
+
+def _remove_empty_ancestors(parent: Path, source_roots: Sequence[Path]) -> list[Path]:
+ """Remove empty parents up to, but never including, a declared source root."""
+ source_root = next(
+ (root for root in sorted(source_roots, key=lambda item: len(item.parts), reverse=True)
+ if within_root(parent, root)),
+ None,
+ )
+ if source_root is None:
+ return []
+ removed: list[Path] = []
+ current = parent
+ while current != source_root and within_root(current, source_root):
+ if current.is_symlink():
+ break
+ next_parent = current.parent
+ try:
+ current.rmdir()
+ except FileNotFoundError:
+ # CloudDrive may collapse an empty layer as soon as its last file vanishes.
+ current = next_parent
+ continue
+ except OSError:
+ # Non-empty, offline, or protected directories are a normal stop boundary.
+ break
+ removed.append(current)
+ current = next_parent
+ return removed
+
+
+def cleanup_empty_source_directories() -> dict[str, object]:
+ """Delete empty directories below each online physical source.
+
+ The declared source roots themselves are permanent boundaries and are never removed.
+ ``os.walk(..., topdown=False)`` ensures children are considered before their parents;
+ directory links are not followed or removed.
+ """
+ results: list[dict[str, object]] = []
+ total_scanned = total_removed = total_errors = 0
+ for location, declaration in LOCATION_ROOT_DECLARATIONS.items():
+ root = translate_ledger_path(declaration)
+ mapped = not is_unmapped(root)
+ online = bool(mapped and root.is_dir() and root_online(root))
+ row: dict[str, object] = {
+ "location": location,
+ "mapped": mapped,
+ "online": online,
+ "scanned": 0,
+ "removed": 0,
+ "errors": 0,
+ }
+ if not online:
+ results.append(row)
+ continue
+
+ walk_errors: list[OSError] = []
+ for directory, _subdirectories, _files in os.walk(
+ root, topdown=False, onerror=walk_errors.append, followlinks=False):
+ candidate = Path(directory)
+ if candidate == root or candidate.is_symlink():
+ continue
+ row["scanned"] = int(row["scanned"]) + 1
+ try:
+ candidate.rmdir()
+ except FileNotFoundError:
+ # CloudDrive can remove the same empty directory concurrently.
+ continue
+ except OSError as error:
+ if error.errno not in {errno.ENOTEMPTY, errno.EEXIST}:
+ row["errors"] = int(row["errors"]) + 1
+ else:
+ row["removed"] = int(row["removed"]) + 1
+ row["errors"] = int(row["errors"]) + len(walk_errors)
+ total_scanned += int(row["scanned"])
+ total_removed += int(row["removed"])
+ total_errors += int(row["errors"])
+ results.append(row)
+ return {
+ "ok": total_errors == 0,
+ "scanned": total_scanned,
+ "removed": total_removed,
+ "errors": total_errors,
+ "sources": results,
+ }
+
+
def _finish_purge(outcome):
"""Delete committed quarantine files; report any residue for explicit cleanup."""
cleanup_pending = []
@@ -1814,7 +1912,12 @@ def _finish_purge(outcome):
snapshot.unlink(missing_ok=True)
except OSError:
pass
+ source_roots = tuple(_online_source_roots().values())
+ removed_directories: set[Path] = set()
+ for parent in outcome.pop("_parents"):
+ removed_directories.update(_remove_empty_ancestors(parent, source_roots))
outcome["cleanup_pending"] = cleanup_pending
+ outcome["empty_dirs_removed"] = len(removed_directories)
return outcome
@@ -1825,7 +1928,7 @@ def purge_assets(connection, rows):
caller restores the quarantined names if commit fails, then permanently removes
them only after the SQLite transaction has committed.
"""
- purged, blocked, staged, snapshots = [], [], [], []
+ purged, blocked, staged, snapshots, parents = [], [], [], [], []
for row in rows:
media = row["path"]
if media:
@@ -1846,6 +1949,8 @@ def purge_assets(connection, rows):
snapshot = row["snapshot_path"]
if snapshot:
snapshots.append(Path(snapshot))
+ if media:
+ parents.append(Path(media).parent)
purged.append(row["id"])
try:
if purged:
@@ -1866,7 +1971,7 @@ def purge_assets(connection, rows):
raise
return {
"purged": len(purged), "blocked": blocked,
- "_staged": staged, "_snapshots": snapshots,
+ "_staged": staged, "_snapshots": snapshots, "_parents": parents,
}
@@ -1889,6 +1994,11 @@ def w_empty_trash(contract: WebContract):
return result
+def w_cleanup_empty_directories(_contract: WebContract, _body):
+ """Remove empty folders from online physical sources without touching the ledger."""
+ return cleanup_empty_source_directories()
+
+
def w_batch(contract: WebContract, body):
@@ -2200,6 +2310,7 @@ POST_HANDLERS = {
"/api/taste/refresh": w_taste_refresh,
"/api/taste/source": w_taste_source,
"/api/trash/empty": _post_empty_trash,
+ "/api/data-cleanup/empty-folders": w_cleanup_empty_directories,
"/api/purge-missing": w_purge_missing,
"/api/links/check": w_links_check,
"/api/links/prune": w_links_prune,
@@ -2217,7 +2328,7 @@ POST_HANDLERS = {
READ_ONLY_POST_ROUTES = frozenset({
"/api/follow/resolve", "/api/follow/credential",
"/api/taste/refresh", "/api/taste/source", "/api/resource-sync/scan",
- "/api/links/check",
+ "/api/links/check", "/api/data-cleanup/empty-folders",
})
diff --git a/src/peach/web_settings.py b/src/peach/web_settings.py
index 7f76f84ff..f0f2c7042 100644
--- a/src/peach/web_settings.py
+++ b/src/peach/web_settings.py
@@ -26,9 +26,10 @@ DEFAULT_SIDEBAR_ORDER = (
)
#: 可以加进侧栏、但默认不在的入口。
OPTIONAL_SIDEBAR_KEYS = (
- "stats", "review", "ads", "dupes", "trash", "follow-manage", "quality",
+ "stats", "review", "data-cleanup", "trash", "follow-manage", "quality",
)
ALL_SIDEBAR_KEYS = frozenset(DEFAULT_SIDEBAR_ORDER) | frozenset(OPTIONAL_SIDEBAR_KEYS)
+SIDEBAR_KEY_ALIASES = {"ads": "data-cleanup", "dupes": "data-cleanup"}
#: 只有这些键跟着账本走。白名单而不是黑名单:将来往设置里加字段的人必须显式表态
#: 它该不该跨机同步,而不是默认就同步过去。
@@ -52,8 +53,11 @@ def normalise_sidebar_order(raw) -> list[str]:
if not isinstance(raw, list):
return list(DEFAULT_SIDEBAR_ORDER)
seen: list[str] = []
- for key in raw:
- if not isinstance(key, str) or key not in ALL_SIDEBAR_KEYS or key in seen:
+ for raw_key in raw:
+ if not isinstance(raw_key, str):
+ continue
+ key = SIDEBAR_KEY_ALIASES.get(raw_key, raw_key)
+ if key not in ALL_SIDEBAR_KEYS or key in seen:
continue
seen.append(key)
return seen or list(DEFAULT_SIDEBAR_ORDER)
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 518c7a540..d25953f17 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -791,7 +791,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
# 前端路由写好了不等于能直接打开:SPA 路径是逐条登记的,
# 漏登记时源码断言照样全绿,只有真的请求一次才会露出 404。
"/unseen", "/watch-later", "/flagged", "/junk-files",
- "/duplicates", "/quality-goals", "/mix/1/2", "/parts/1/2", "/playlists",
+ "/data-cleanup", "/duplicates", "/quality-goals", "/mix/1/2", "/parts/1/2", "/playlists",
"/resource-sync",
"/playlists/1/1", "/follow", "/follow-manage",
"/follow/item/190"):
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 604921a43..45e3de341 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -623,7 +623,8 @@ class WebDataTests(unittest.TestCase):
"/api/activity", "/api/play", "/api/feedback", "/api/watch-later",
"/api/playlist",
"/api/preference", "/api/quality-goal", "/api/item-tag", "/api/batch",
- "/api/search-history", "/api/trash/empty", "/api/review/decision",
+ "/api/search-history", "/api/trash/empty", "/api/data-cleanup/empty-folders",
+ "/api/review/decision",
"/api/purge-missing", "/api/review/auto-apply",
"/api/links/check", "/api/links/prune",
"/api/resource-sync/scan", "/api/resource-sync/apply",
@@ -854,6 +855,55 @@ class WebDataTests(unittest.TestCase):
).fetchone()[0])
con.close()
+ def test_permanent_delete_removes_newly_empty_parents_but_keeps_the_source_root(self):
+ source_root = Path(self.tmp.name) / "source"
+ media = source_root / "creator" / "release" / "junk.url"
+ media.parent.mkdir(parents=True)
+ media.write_text("junk", encoding="utf-8")
+ con = sqlite3.connect(self.db_path)
+ con.execute("UPDATE asset SET path=?,snapshot_path=NULL WHERE id=1", (str(media),))
+ con.commit(); con.close()
+ rm_web.w_feedback(self.contract, {"id": 1, "kind": "dispose"})
+
+ with mock.patch.object(
+ rm_web, "LOCATION_ROOT_DECLARATIONS", {"local": str(source_root)}):
+ result = rm_web.w_batch(self.contract, {"ids": [1], "operation": "delete"})
+
+ self.assertEqual(result["empty_dirs_removed"], 2)
+ self.assertTrue(source_root.is_dir(), "声明的来源根绝不能随空目录一起删除")
+ self.assertFalse((source_root / "creator").exists())
+
+ def test_empty_folder_cleanup_walks_bottom_up_and_skips_offline_sources(self):
+ source_root = Path(self.tmp.name) / "source"
+ (source_root / "empty" / "nested").mkdir(parents=True)
+ kept = source_root / "kept"
+ kept.mkdir()
+ (kept / "media.mp4").write_bytes(b"keep")
+ offline = Path(self.tmp.name) / "offline"
+
+ with mock.patch.object(rm_web, "LOCATION_ROOT_DECLARATIONS", {
+ "local": str(source_root), "115": str(offline),
+ }):
+ result = rm_web.cleanup_empty_source_directories()
+
+ self.assertEqual(result["removed"], 2)
+ self.assertEqual(result["errors"], 0)
+ self.assertTrue(source_root.is_dir())
+ self.assertTrue((kept / "media.mp4").is_file())
+ self.assertFalse((source_root / "empty").exists())
+ self.assertFalse(result["sources"][1]["online"])
+ self.assertNotIn("root", result["sources"][0], "API 不能泄露物理来源路径")
+
+ def test_empty_folder_cleanup_post_is_registered_as_a_non_ledger_write(self):
+ self.assertIs(
+ rm_web.POST_HANDLERS["/api/data-cleanup/empty-folders"],
+ rm_web.w_cleanup_empty_directories,
+ )
+ self.assertIn(
+ "/api/data-cleanup/empty-folders", rm_web.READ_ONLY_POST_ROUTES,
+ "清理服务端物理目录不写 ledger,不该被 reader 的账本闸门误拦",
+ )
+
def test_failed_database_commit_restores_quarantined_media(self):
path = self.stage_media(1, "commit-failure.mp4")
rm_web.w_feedback(self.contract, {"id": 1, "kind": "dispose"})
diff --git a/tests/test_web_settings.py b/tests/test_web_settings.py
index 8c9ca6abe..8d7641953 100644
--- a/tests/test_web_settings.py
+++ b/tests/test_web_settings.py
@@ -61,6 +61,12 @@ class SidebarOrderNormalisationTests(unittest.TestCase):
["", "trash", "quality"],
)
+ def test_old_cleanup_entries_collapse_into_the_combined_destination(self):
+ self.assertEqual(
+ normalise_sidebar_order(["", "ads", "dupes", "trash"]),
+ ["", "data-cleanup", "trash"],
+ )
+
class SettingsRoundTripTests(unittest.TestCase):
def setUp(self):
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 1ce22eabf..74fdb1f67 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -919,7 +919,7 @@ class WebUiSourceTests(unittest.TestCase):
"""
self.assertPageContains("['manage','管理','database']")
self.assertPageContains("const MANAGE_SECTIONS=[")
- for section in ("'stats','统计'", "'ads','垃圾文件'", "'dupes','重复文件'",
+ for section in ("'stats','统计'", "'cleanup','数据清理'",
"'quality','高清版'", "'trash','回收站'", "'review','人工复核'",
"'taste','口味'"):
self.assertPageContains(section)
@@ -947,7 +947,7 @@ class WebUiSourceTests(unittest.TestCase):
sections = self.page.split("const MANAGE_SECTIONS=[", 1)[1].split("];", 1)[0]
order = [line.split("'")[1] for line in sections.splitlines() if line.strip().startswith("['")]
self.assertEqual(
- order, ["stats", "taste", "review", "ads", "dupes", "trash", "follow", "quality"],
+ order, ["stats", "taste", "review", "cleanup", "trash", "follow", "quality"],
"管理导航的顺序是语义契约:现状 → 复核 → 清理 → 回收站 → 往外拿",
)
@@ -1309,6 +1309,15 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("actionFailure('操作',error)")
self.assertPageContains("kind==='dispose'&&r.disposal==='trash'&&state.state==='ads'")
+ def test_junk_empty_state_only_appears_after_the_loading_request_finishes(self):
+ """待判断为空是请求终态;加载期间只能显示 Loading Dots,不能先闪空态。"""
+ branch = self.app_js.split("if(state.state==='ads'){", 1)[1].split("adsBatch=null;", 1)[0]
+ self.assertLess(branch.index("loadingDotsHtml('正在读取垃圾文件…')"),
+ branch.index("const nextAds=await api('/api/ads?'+junkQuery)"))
+ self.assertLess(branch.index("const nextAds=await api('/api/ads?'+junkQuery)"),
+ branch.index("emptyState('check'"))
+ self.assertPageContains("$('#loadSentinel').hidden=true")
+
def test_junk_review_and_trash_render_every_physical_resource_type(self):
"""图片、网址快捷方式等不能复用视频播放器,但必须可预览、回收和还原。"""
self.assertPageContains("const RESOURCE_MEDIUM_LABEL={image:'图片',audio:'音频',archive:'压缩包',other:'其它文件'}")
@@ -1326,6 +1335,9 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("function junkCardHtml(it)")
self.assertPageContains('data-junk-operation="${decision[0]}" title="${esc(decision[1])}" aria-label="${esc(decision[1])}"')
self.assertPageContains('data-junk-operation="dispose" title="移入回收站" aria-label="移入回收站"')
+ self.assertPageContains('data-junk-reveal title="在资源管理器中显示"')
+ self.assertPageContains("revealSource(id,status,{button:reveal})")
+ self.assertPageContains('<span>打开所在位置</span>')
self.assertPageContains("['dismiss-junk','不是垃圾','check']")
self.assertPageContains("<span>移入回收站</span>")
self.assertPageContains('body[data-density="dense"] .junkcard .junkactions button span{display:none}')
@@ -1411,7 +1423,7 @@ class WebUiSourceTests(unittest.TestCase):
def test_ads_icon_matches_the_lucide_stroke_style(self):
"""图标库里没有表示广告的图形,自绘的感叹号必须和其余图标同风格。"""
self.assertPageContains('<symbol id="i-alert" viewBox="0 0 24 24">')
- self.assertPageContains("['ads','垃圾文件','alert']")
+ self.assertPageContains("['cleanup','数据清理','hard-drive']")
def test_pending_delete_is_visible_without_deleting_media(self):
self.assertPageContains("it.disposal==='trash'?'pending-delete':''")
@@ -2131,7 +2143,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("data-sidebar-hide")
self.assertPageContains("data-sidebar-add-option")
self.assertPageLacks("data-sidebar-add-select")
- self.assertPageContains("const OPTIONAL_SIDEBAR_KEYS=['stats','review','ads','dupes','trash','follow-manage','quality']")
+ self.assertPageContains("const OPTIONAL_SIDEBAR_KEYS=['stats','review','data-cleanup','trash','follow-manage','quality']")
self.assertPageContains("if(DIRECT_MANAGE_NAV[k]){openManage(DIRECT_MANAGE_NAV[k]);return}")
self.assertPageContains(".settingscard{display:flex;flex-direction:column;width:min(520px,100%);max-height:min(720px,90vh);max-height:min(720px,90dvh);overflow:hidden")
self.assertPageContains(".settingsscroll{flex:1;min-height:0;overflow-y:auto")
@@ -2197,12 +2209,27 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains('id="i-calendar"')
self.assertPageLacks("发行 ${esc(it.release_date)}")
- def test_duplicates_page_is_a_management_section(self):
- self.assertPageContains("['dupes','重复文件','hard-drive']")
- self.assertPageContains("if(path==='/duplicates')return 'dupes'")
+ def test_duplicates_page_is_part_of_the_combined_cleanup_section(self):
+ self.assertPageContains("path==='/data-cleanup'||path==='/duplicates'||path==='/junk-files'")
+ self.assertPageContains("if(section==='cleanup'){openDataCleanup();return}")
self.assertPageContains("if(section==='dupes'){openDuplicates();return}")
self.assertPageContains("async function openDuplicates(push=true)")
+ def test_data_cleanup_groups_junk_duplicates_and_empty_folders_in_fieldsets(self):
+ self.assertPageContains("async function openDataCleanup(push=true)")
+ self.assertPageContains("route('/data-cleanup')")
+ self.assertPageContains("api('/api/ads?limit=1'),api('/api/duplicates?limit=1'),api('/api/sources')")
+ for legend in ("<legend>垃圾文件</legend>", "<legend>重复文件</legend>",
+ "<legend>空文件夹</legend>"):
+ self.assertPageContains(legend)
+ self.assertPageContains('class="cleanupfieldset" data-geist-fieldset')
+ self.assertPageContains('class="cleanupfieldset cleanupemptyfolders" data-geist-fieldset')
+ self.assertPageContains("api('/api/data-cleanup/empty-folders',{method:'POST',body:'{}'})")
+ self.assertPageContains("来源根目录不会删除")
+ self.assertPageContains(".cleanupfieldset>.geist-fieldset-content{flex:1;min-height:0;padding:20px}")
+ self.assertPageContains("min-height:56px;margin:0;padding:12px 12px 12px 20px")
+ self.assertPageContains("if(path==='/data-cleanup'){await openDataCleanup(false);return}")
+
def test_duplicate_batch_keeps_one_per_cluster_not_one_per_code(self):
# 每组各自选 keeper:合集与分卷已经在数据层拆成不同簇,界面不能再按番号合并。
self.assertPageContains("function duplicateVictims(groups,keep)")
diff --git a/web/app.css b/web/app.css
index 9ef043cb1..eaae12a0c 100644
--- a/web/app.css
+++ b/web/app.css
@@ -246,6 +246,22 @@ button[aria-busy="true"],[role="button"][aria-busy="true"]{
.reviewstate:empty{display:none}
.reviewalias{margin:2px 0 0;font-size:var(--fs-xs);color:var(--muted)}
.reviewactions button{box-sizing:border-box;height:32px;border:1px solid var(--border-15);border-radius:8px;background:transparent;color:var(--ink-2);padding:0 12px;font-size:var(--fs-sm);cursor:pointer}.reviewactions button:hover{border-color:var(--tungsten);color:var(--ink)}.reviewactions .approve{background:var(--tungsten);border-color:var(--tungsten);color:#fff;font-weight:600}.reviewactions .approve:hover{background:color-mix(in srgb,var(--tungsten) 82%,#000);color:#fff}.reviewactions .skip{color:var(--meter)}.reviewactions .skip:hover{background:var(--meter);border-color:var(--meter);color:#fff}.reviewactions .reject{color:var(--drop)}.reviewactions .reject:hover{background:var(--drop);border-color:var(--drop);color:#fff}
+.cleanuploading,.junkloading{grid-column:1/-1;min-height:280px;display:grid;place-items:center}
+.cleanupgrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;padding:0 0 42px}
+.cleanupfieldset{display:flex;flex-direction:column;min-width:0;min-height:250px;margin:0;padding:0;overflow:hidden;
+ border:1px solid var(--line-soft);border-radius:12px;background:var(--surface)}
+.cleanupfieldset legend{margin-left:14px;padding:0 6px;color:var(--ink);font-size:var(--fs-lg);font-weight:600}
+.cleanupfieldset>.geist-fieldset-content{flex:1;min-height:0;padding:20px}.cleanupfieldset strong{display:block;margin-bottom:10px;font-size:var(--fs-xl)}
+.cleanupfieldset p{margin:0;color:var(--muted);font-size:var(--fs-sm);line-height:1.6}
+.cleanupfieldset>.geist-fieldset-footer{box-sizing:border-box;min-height:56px;margin:0;padding:12px 12px 12px 20px;
+ display:flex;align-items:center;gap:8px;border-top:1px solid var(--border-10);background:var(--overlay-5)}
+.cleanupfieldset button{box-sizing:border-box;min-height:32px;padding:0 12px;border:1px solid var(--border-15);border-radius:var(--control-radius);
+ background:transparent;color:var(--ink-2);display:inline-flex;align-items:center;justify-content:center;gap:7px;cursor:pointer}
+.cleanupfieldset button:hover{border-color:var(--tungsten);color:var(--ink);background:var(--hover)}
+.cleanupfieldset button.danger{color:var(--drop)}.cleanupfieldset button svg{width:16px;height:16px;stroke:currentColor;fill:none}
+.cleanupsources{display:flex;flex-wrap:wrap;gap:6px;margin-top:14px}.cleanupsource{padding:4px 8px;border:1px solid var(--border-15);
+ border-radius:var(--badge-radius);color:var(--keep);font-size:var(--fs-xs)}.cleanupsource[data-online="false"]{color:var(--muted)}
+.cleanupfieldset .cleanupstate{min-height:20px;margin-top:12px;color:var(--ink-2)}
.stats h2{margin:0 0 4px;font-size:var(--fs-2xl)}
.stats .sub{color:var(--muted);margin:0}
@@ -883,7 +899,7 @@ body.select-mode .selectionMark,.card.selected .selectionMark{display:grid}
border:0;padding:0;background:transparent;color:var(--ink);font:inherit;font-weight:600;line-height:1.4;text-align:left}
button.junkcardtitle{cursor:pointer}button.junkcardtitle:hover{color:var(--tungsten);text-decoration:none}
button.junkcardtitle:focus-visible{outline:2px solid var(--tungsten);outline-offset:3px;border-radius:2px}
-.junkactions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:auto;padding:10px 12px;
+.junkactions{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-top:auto;padding:10px 12px;
border-top:1px solid var(--line-soft);background:var(--overlay-5)}
.junkactions button{box-sizing:border-box;min-width:0;min-height:36px;padding:0 10px;display:inline-flex;align-items:center;justify-content:center;gap:7px;
border:1px solid var(--border-15);border-radius:var(--control-radius);background:var(--surface);color:var(--ink-2);
@@ -892,6 +908,7 @@ button.junkcardtitle:focus-visible{outline:2px solid var(--tungsten);outline-off
.junkactions button:focus-visible{outline:2px solid var(--tungsten);outline-offset:2px}
.junkactions button:disabled{cursor:wait;opacity:.64}.junkactions button svg{width:15px;height:15px;flex:none;stroke:currentColor;fill:none;stroke-width:2}
.junkactions .junktrash{color:var(--drop)}.junkactions .junktrash:hover:not(:disabled){border-color:color-mix(in srgb,var(--drop) 46%,transparent);color:var(--drop);background:color-mix(in srgb,var(--drop) 8%,transparent)}
+.junkstate{grid-column:1/-1;color:var(--drop);font-size:var(--fs-xs)}.junkstate:empty{display:none}
body[data-density="dense"] .junkcard .junkactions button span{display:none}
.badge{position:absolute;top:6px;left:6px;display:flex;gap:4px;z-index:2;align-items:center;
transition:opacity .15s ease}
@@ -1692,6 +1709,8 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
.managebar.is-open .managebar-menu{display:grid}
.runtimegate a{grid-column:2/-1}
.managebar-menu button{width:100%;min-height:42px;justify-content:flex-start;padding:9px 11px}
+ .cleanupgrid{grid-template-columns:minmax(0,1fr)}
+ .cleanupfieldset{min-height:230px}
.grid{gap:16px 8px}
.count{align-items:center;flex-direction:row;gap:10px;padding-block:8px;
overflow-x:auto;overflow-y:hidden;scrollbar-width:none;overscroll-behavior-inline:contain}
diff --git a/web/app.js b/web/app.js
index e96cb6564..d1f64d256 100644
--- a/web/app.js
+++ b/web/app.js
@@ -25,7 +25,13 @@ function renderCatalogLoading(label='正在读取作品'){
Spinner、再切成目标页 Loading Dots。 */
function renderInitialSurfaceLoading(){
const path=decodeURIComponent(location.pathname);
- const management=new Set(['/stats','/taste','/review','/duplicates','/quality-goals',
+ if(path==='/junk-files'){
+ const count=$('#count');count.setAttribute('aria-busy','true');count.textContent='';
+ $('#grid').innerHTML=`<div class="junkloading">${loadingDotsHtml('正在读取垃圾文件…')}</div>`;
+ $('#loadSentinel').hidden=true;
+ return;
+ }
+ const management=new Set(['/stats','/taste','/review','/data-cleanup','/duplicates','/quality-goals',
'/playlists','/resource-sync','/follow','/follow-manage']);
if(management.has(path)||path.startsWith('/follow/item/')){
const stats=$('#stats');stats.hidden=false;$('#grid').innerHTML='';
@@ -141,7 +147,7 @@ function dropOfflineFromDefaultLoc(){
const DURATION_TAGS=new Set(['短片-2分内','中片-10分内','长片-30分内','超长片-30分上']);
const SETTINGS_KEY='peach.settings.v1';
const DEFAULT_SIDEBAR_ORDER=['','performers','tags','jav','flagged','playlists','follow','immerse','manage'];
-const OPTIONAL_SIDEBAR_KEYS=['stats','review','ads','dupes','trash','follow-manage','quality'];
+const OPTIONAL_SIDEBAR_KEYS=['stats','review','data-cleanup','trash','follow-manage','quality'];
const ALL_SIDEBAR_KEYS=[...DEFAULT_SIDEBAR_ORDER,...OPTIONAL_SIDEBAR_KEYS];
const SORTS=[['seed','随机'],['rating','评分'],['o','高潮计数'],['plays','观看次数'],['long','时长'],
['big','体积'],['new','最近入库'],['played','最近看的']];
@@ -167,7 +173,8 @@ appSettings.ambientMode=appSettings.ambientMode!==false;
appSettings.theaterMode=appSettings.theaterMode===true;
appSettings.searchHistoryLimit=allowedSetting(+appSettings.searchHistoryLimit,[5,10,20],10);
appSettings.relatedLimit=allowedSetting(+appSettings.relatedLimit,[12,20,30],20);
-appSettings.sidebarOrder=[...new Set(Array.isArray(appSettings.sidebarOrder)?appSettings.sidebarOrder:DEFAULT_SIDEBAR_ORDER)].filter(key=>ALL_SIDEBAR_KEYS.includes(key));
+const sidebarKeyAlias=key=>key==='ads'||key==='dupes'?'data-cleanup':key;
+appSettings.sidebarOrder=[...new Set((Array.isArray(appSettings.sidebarOrder)?appSettings.sidebarOrder:DEFAULT_SIDEBAR_ORDER).map(sidebarKeyAlias))].filter(key=>ALL_SIDEBAR_KEYS.includes(key));
if(!appSettings.sidebarOrder.length)appSettings.sidebarOrder=[...DEFAULT_SIDEBAR_ORDER];
document.documentElement.style.setProperty('--hover-delay',`${appSettings.hoverDelaySeconds}s`);
const saveSettings=()=>localStorage.setItem(SETTINGS_KEY,JSON.stringify(appSettings));
@@ -1186,8 +1193,10 @@ function junkCardHtml(it){
:`<span class="t junkcardtitle" data-middle-truncate title="${esc(it.name||'')}">${esc(it.name||'未命名资源')}</span>`}
<div class="s mono"><span class="who">${esc(meta[0])}</span>${it.why?`<span class="why">${esc(it.why)}</span>`:''}<span class="size">${Number(it.size)>0?fmtSize(Number(it.size)):'大小未知'}</span></div>
</div><footer class="junkactions">
+ <button type="button" data-junk-reveal title="在资源管理器中显示" aria-label="在资源管理器中显示">${icon('folder-open')}<span>打开所在位置</span></button>
<button type="button" data-junk-operation="${decision[0]}" title="${esc(decision[1])}" aria-label="${esc(decision[1])}">${icon(decision[2])}<span>${decision[1]}</span></button>
<button type="button" class="junktrash" data-junk-operation="dispose" title="移入回收站" aria-label="移入回收站">${icon('trash')}<span>移入回收站</span></button>
+ <span class="junkstate" aria-live="polite"></span>
</footer></div></article>`;
}
async function runJunkOperation(id,operation){
@@ -1198,7 +1207,7 @@ function wireJunkCards(root){
root.querySelectorAll('.junkcard').forEach(card=>{
const id=+card.dataset.id,item=CACHE[id];
card.onclick=event=>{
- if(event.target.closest('[data-junk-operation]'))return;
+ if(event.target.closest('[data-junk-operation],[data-junk-reveal]'))return;
if(selectMode||event.shiftKey||event.ctrlKey||event.metaKey){
event.preventDefault();event.stopPropagation();toggleSelection(id,event.shiftKey);
}
@@ -1211,6 +1220,10 @@ function wireJunkCards(root){
if(item?.junk_kind==='image')window.open('/photo?id='+id,'_blank','noopener');
else openItem(id,true,null,card);
});
+ const reveal=card.querySelector('[data-junk-reveal]'),status=card.querySelector('.junkstate');
+ if(reveal)reveal.onclick=event=>{
+ event.preventDefault();event.stopPropagation();revealSource(id,status,{button:reveal});
+ };
card.querySelectorAll('[data-junk-operation]').forEach(button=>button.onclick=async event=>{
event.preventDefault();event.stopPropagation();
const operation=button.dataset.junkOperation;
@@ -2300,6 +2313,54 @@ let reviewData=null,reviewRuntime=null,reviewCategory='metadata_fields';
/* 主体是实体而不是单条作品的复核分类。值就是实体 kind。 */
const ENTITY_REVIEW_CATEGORIES={creator_tags:'creator',western_identity:'creator'};
const REVIEW_LABELS={metadata_fields:'元数据字段',creator_tags:'创作者标签',studio_logos:'厂牌 Logo',performer_avatars:'女优头像',western_identity:'西方身份回配',code_creators:'番号目录存疑',fc2_markings:'FC2 评论标记',fc2_similarity:'FC2 跨号相似',video_endcards:'片尾/出处证据',media_failure:'媒体失败'};
+
+async function openDataCleanup(push=true){
+ releaseHoverPreviews();disposeStage(false);enterManagementSurface();
+ if(push)route('/data-cleanup');
+ const surface=claimSurface('/data-cleanup');
+ showManagementBody({placeholder:`<div class="cleanuploading">${loadingDotsHtml('正在读取数据清理状态…')}</div>`});
+ const [junk,duplicates,sources]=await Promise.all([
+ api('/api/ads?limit=1'),api('/api/duplicates?limit=1'),api('/api/sources'),
+ ]);
+ if(!surfaceCurrent(surface))return;
+ paintManageLede('垃圾文件、重复文件和空文件夹集中处理');
+ const sourceState=(sources.sources||[]).filter(source=>['local','115','pikpak'].includes(source.location)).map(source=>
+ `<span class="cleanupsource" data-online="${source.online?'true':'false'}">${esc(LOC[source.location]||source.location)} · ${source.online?'在线':'离线'}</span>`).join('');
+ $('#stats').innerHTML=`<div class="cleanupgrid">
+ <fieldset class="cleanupfieldset" data-geist-fieldset><legend>垃圾文件</legend>
+ <div class="geist-fieldset-content"><strong>${Number(junk.pending_total||0).toLocaleString()} 个待判断</strong>
+ <p>查看推广文件、网址快捷方式和其它物理资源候选;确认后先进入回收站。</p></div>
+ <footer class="geist-fieldset-footer" data-geist-fieldset-footer><button type="button" data-cleanup-open="junk">查看垃圾文件</button></footer>
+ </fieldset>
+ <fieldset class="cleanupfieldset" data-geist-fieldset><legend>重复文件</legend>
+ <div class="geist-fieldset-content"><strong>${Number(duplicates.total||0).toLocaleString()} 组 · ${Number(duplicates.files||0).toLocaleString()} 个文件</strong>
+ <p>按番号、分卷与时长证据分组;批量操作仍只把文件移入回收站。</p></div>
+ <footer class="geist-fieldset-footer" data-geist-fieldset-footer><button type="button" data-cleanup-open="duplicates">查看重复文件</button></footer>
+ </fieldset>
+ <fieldset class="cleanupfieldset cleanupemptyfolders" data-geist-fieldset><legend>空文件夹</legend>
+ <div class="geist-fieldset-content"><p>从已挂载的资源根开始自底向上删除空目录;来源根本身不会删除。</p>
+ <div class="cleanupsources">${sourceState}</div><p class="cleanupstate" aria-live="polite"></p></div>
+ <footer class="geist-fieldset-footer" data-geist-fieldset-footer><button type="button" class="danger" data-cleanup-empty>${icon('trash')}<span>删除空文件夹</span></button></footer>
+ </fieldset>
+ </div>`;
+ $('#stats').querySelector('[data-cleanup-open="junk"]').onclick=()=>openManage('ads');
+ $('#stats').querySelector('[data-cleanup-open="duplicates"]').onclick=()=>openDuplicates();
+ const emptyButton=$('#stats').querySelector('[data-cleanup-empty]');
+ emptyButton.onclick=async()=>{
+ if(!confirm('删除所有已挂载资源来源中的空文件夹?来源根目录不会删除。'))return;
+ const status=$('#stats').querySelector('.cleanupstate'),original=emptyButton.innerHTML;
+ setActionBusy(emptyButton);emptyButton.innerHTML=`${spinnerHtml('正在删除空文件夹')}<span>正在清理</span>`;
+ status.textContent='正在自底向上检查已挂载来源…';
+ try{
+ const result=await api('/api/data-cleanup/empty-folders',{method:'POST',body:'{}'});
+ status.textContent=`已检查 ${Number(result.scanned||0).toLocaleString()} 个目录,删除 ${Number(result.removed||0).toLocaleString()} 个${result.errors?`,${Number(result.errors).toLocaleString()} 个读取或删除失败`:''}。`;
+ if(result.errors)actionFailure('空文件夹清理',new Error(`${result.errors} 个目录处理失败`));
+ else actionReceipt(`已删除 ${Number(result.removed||0).toLocaleString()} 个空文件夹`);
+ }catch(error){status.textContent=error.message||'空文件夹清理失败';actionFailure('空文件夹清理',error)}
+ finally{setActionBusy(emptyButton,false);emptyButton.innerHTML=original}
+ };
+}
+
let dupData=null;
/* 重复文件。判据是「同番号 + 时长相近 + 分卷标记一致」,不是同番号即重复——
合集、分卷和混入的广告都会共用一个 code,只按番号做「保留最大」会删掉内容。
@@ -4777,7 +4838,7 @@ const EDGE_ICONS=[
['immerse','沉浸模式','play'],
['manage','管理','database'],
];
-/* 统计、垃圾文件、回收站、人工复核默认都收在「管理」下,不主动占用顶层空间;
+/* 统计、数据清理、回收站、人工复核默认都收在「管理」下,不主动占用顶层空间;
用户仍可在设置里把某个具体页面加到顶层。每个页面都有可直接打开的 URL。
顺序按做事顺序分成两段:先是库里已有的东西——看现状、复核新进来的候选、
清广告与重复、落到回收站;再是要往外拿的——关注和高清版都是「还想要什么」,
@@ -4786,16 +4847,16 @@ const MANAGE_SECTIONS=[
['stats','统计','chart'],
['taste','口味','heart'],
['review','人工复核','square-check-big'],
- ['ads','垃圾文件','alert'],
- ['dupes','重复文件','hard-drive'],
+ ['cleanup','数据清理','hard-drive'],
['trash','回收站','trash'],
['follow','关注','rss'],
['quality','高清版','sparkles'],
];
const OPTIONAL_EDGE_ICONS=MANAGE_SECTIONS.map(([key,label,ic])=>
- key==='follow'?['follow-manage','关注管理',ic]:[key,label,ic]);
+ key==='follow'?['follow-manage','关注管理',ic]
+ :key==='cleanup'?['data-cleanup',label,ic]:[key,label,ic]);
const NAV_CATALOG=[...EDGE_ICONS,...OPTIONAL_EDGE_ICONS];
-const DIRECT_MANAGE_NAV={stats:'stats',review:'review',ads:'ads',dupes:'dupes',trash:'trash','follow-manage':'follow',quality:'quality'};
+const DIRECT_MANAGE_NAV={stats:'stats',review:'review','data-cleanup':'cleanup',trash:'trash','follow-manage':'follow',quality:'quality'};
function orderedEdgeIcons(){
const byKey=new Map(NAV_CATALOG.map(item=>[item[0],item]));
return appSettings.sidebarOrder.map(key=>byKey.get(key)).filter(Boolean);
@@ -4948,10 +5009,10 @@ function manageSection(){
if(path==='/taste')return 'taste';
if(path==='/review')return 'review';
if(path==='/trash')return 'trash';
- if(path==='/duplicates')return 'dupes';
+ if(path==='/data-cleanup'||path==='/duplicates'||path==='/junk-files'||state.state==='ads')return 'cleanup';
if(path==='/quality-goals')return 'quality';
if(path==='/follow-manage')return 'follow';
- return path==='/junk-files'||state.state==='ads'?'ads':'';
+ return '';
}
function buildManageBar(){
const current=manageSection(),bar=$('#managebar');
@@ -5001,6 +5062,8 @@ function openManage(section='stats'){
if(section==='stats'){openStats();return}
if(section==='taste'){openTaste();return}
if(section==='review'){openReview();return}
+ if(section==='cleanup'){openDataCleanup();return}
+ // 旧直达 URL 继续保留;它们共享同一个「数据清理」导航身份。
if(section==='dupes'){openDuplicates();return}
if(section==='quality'){openQualityGoals();return}
if(section==='follow'){openFollowManage();return}
@@ -5193,6 +5256,10 @@ async function load(reset){
countRow.classList.toggle('junkcount',staticManageCount);
if(staticManageCount)countRow.classList.remove('is-stuck');
if(state.state==='ads'){
+ if(reset){
+ $('#grid').innerHTML=`<div class="junkloading">${loadingDotsHtml('正在读取垃圾文件…')}</div>`;
+ $('#loadSentinel').hidden=true;
+ }
if(reset||!adsBatch){const junkQuery=new URLSearchParams({limit:'200',status:junkView});if(junkKind)junkQuery.set('kind',junkKind);
const nextAds=await api('/api/ads?'+junkQuery);if(requestSeq!==loadRequestSeq||!surfaceCurrent(surface))return;
adsBatch=nextAds;cache(adsBatch.items)}
@@ -6353,6 +6420,7 @@ async function restoreRoute(){
if(path==='/stats'){await openStats(false);return}
if(path==='/taste'){await openTaste(false);return}
if(path==='/review'){await openReview(false);return}
+ if(path==='/data-cleanup'){await openDataCleanup(false);return}
if(path==='/duplicates'){await openDuplicates(false);return}
if(path==='/resource-sync'){await openResourceSync(false);return}
if(path==='/quality-goals'){await openQualityGoals(false);return}
diff --git a/web/js/core.js b/web/js/core.js
index 8ba6b339e..80d9c76c1 100644
--- a/web/js/core.js
+++ b/web/js/core.js
@@ -18,7 +18,7 @@ const api=async(p,o)=>{
};
const pageTitle=path=>{
const url=new URL(path,location.origin),parts=decodeURIComponent(url.pathname).split('/').filter(Boolean);
- const fixed={stats:'统计',taste:'口味',review:'人工复核',duplicates:'重复文件','quality-goals':'高清版',
+ const fixed={stats:'统计',taste:'口味',review:'人工复核','data-cleanup':'数据清理',duplicates:'重复文件','quality-goals':'高清版',
follow:'关注','follow-manage':'关注管理',playlists:'播放列表',performers:'女优',studios:'厂牌',
creators:'创作者',series:'系列',tags:'标签',unseen:'没看过','watch-later':'稍后看',flagged:'已标记',
immerse:'沉浸模式',mix:'Mix',item:'作品','resource-sync':'统计','junk-files':'垃圾文件'};