Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(web): 资源同步一次检查、一次执行,收进空文件夹并永久删除失效记录

longmeidaodb7397dde450
diff --git a/docs/BOARD_UI.md b/docs/BOARD_UI.md
index 86556d703..51b9e42a5 100644
--- a/docs/BOARD_UI.md
+++ b/docs/BOARD_UI.md
@@ -295,7 +295,7 @@ Radial Chart Card、Bar List Card、Heatmap 与 Sankey 的 Pro 源码**未取得
| 首页厂牌一排 | PillTab gray | 40px 灰 Pill 放大一档:28px 圆标识在左、名字在右、圆角 12。标签那一排是 30px 描边药丸,厂牌靠身量、圆标识和无边框跟它分开 |
| 关注页批量条 | 无对应 | 批量条只有保存、跳过这类按行动作;勾选靠每行行首的「全选/全不选」 |
| 复核队列分页 | Pagination:nav 两端对齐 `gap-2`;Previous/Next 是 32px 次级小键(圆角 8、内边距 6/8、带箭头);页码 `size-8 rounded-lg` Body Medium,当前页 border-button 描边 + primary 底 + xs 阴影并标 `aria-current="page"`,其余次文字色、悬停 secondary-hover;两侧折成「…」各留一个邻页;一页时不渲染;没有过渡 | 尺寸与颜色照抄;分页做在前端,一页 20 张(接口 4.6 MB 本机读 0.1 秒,卡的是一次画 1300 张卡);箭头用雪碧图的 `chevron-left/right`,文案「上一页/下一页」;分组与筛选按整条队列算、卡片只画本页;换分类/分组/筛选回第 1 页 |
-| 数据管理页 | dashboard/finance 模板:顶上一排 plain stat card(132px、圆角 16、secondary 底、p 16;32px 图标格 + 20px 字形;标签 Body Medium 次文字色;读数 title-1-medium 24/34;`grid-cols-2 lg:grid-cols-4 gap-4`),下面是图表卡与数据表 | 五张读数卡一行(1120 内),窄了折两列、再折一列;整张卡是入口按钮,悬停抬主文字色 6% 底(上游卡不可点);读数下一行 Caption 是同一份 payload 的分项;扫描与采集、空文件夹各占一整行,左说明右按钮;链接管理与资源同步不动 |
+| 数据管理页 | dashboard/finance 模板:顶上一排 plain stat card(132px、圆角 16、secondary 底、p 16;32px 图标格 + 20px 字形;标签 Body Medium 次文字色;读数 title-1-medium 24/34;`grid-cols-2 lg:grid-cols-4 gap-4`),下面是图表卡与数据表 | 五张读数卡一行(1120 内),窄了折两列、再折一列;整张卡是入口按钮,悬停抬主文字色 6% 底(上游卡不可点);读数下一行 Caption 是同一份 payload 的分项;扫描与采集、媒体修复各占一整行,左说明右按钮;资源同步的结果读数同一副卡片,来源一行、待永久删除/空文件夹/缓存一行,各自等分 |
### 复核卡的候选、未收录 genre 与骨架(2026-09-11)
@@ -485,7 +485,7 @@ Checkbox Card 的整卡选择与独立操作按钮分离;暂停使用黄色 Ch
DatePicker 的内面板、候选草稿及取消/应用结构,候选不包含网盘品牌图标。
统计圆环直接显示终值,只有高亮那一段的浓淡走过渡;没有入场动画,
理由同排名条与雷达图那一行。
-空文件夹先只读扫描,发现候选后显示删除入口,删除仍通过共享确认框。
+资源同步先只读检查失效记录、空文件夹与缓存,有候选才显示实底红的「清理失效条目」;永久删除走共享确认框的危险档,部分没处理时报警告档 Toast。
筛选栏通过「换一批」切到随机并更新种子;默认随机仍在浏览设置中选择。亮色玻璃用淡蓝灰与暖色光斑形成色差,光斑半径为画布的 32%/38%。媒体库选择弹层复用玻璃材质与现有菜单开合。窄屏设置导航与正文之间保留 16px 间距;这些样式的浏览器视觉验收未取得。
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 45a4e8d1a..abd6405ec 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -137,7 +137,7 @@ CloudDrive 见 `docs/CLOUDDRIVE.md`,部署见 `docs/OPERATIONS.md`。
- `src/peach/__init__.py::__version__` 是版本唯一来源;自动更新只做 `merge --ff-only`,不 stash、不 rebase、不 `--force`,工作区脏或两边分叉就原样报出来交给人,因为并行工作树和主检出共用同一个对象库。
- 本机坐标在 `<数据根>/config.toml`(环境变量 > 它 > 内建默认),`src/peach/` 不写死本机字面量或家庭 IP。`[media.mounts]` 按 `asset.location` 给本机落点,Windows 上整表为空;`replication.enabled` 默认关,关掉即整套复制组件不装配。首启问答与扫描是 `peach.onboarding`/`peach.scan` 的纯逻辑,CLI 与托盘设置页共用。
- `.local` 用本机 CA 而不是 Let's Encrypt,证书与私钥留在本机 `peach-data/secrets` 且按设计不跨机共享;FastAPI 是唯一 Web server,探测本机服务必须绕过系统代理,否则代理会替服务回 503。
-- 网盘目录整理后必须经「管理 → 资源同步」显式对账,不做后台静默删除;源文件缺失的 asset 和垃圾文件候选都先进回收站,清空回收站才永久删除账本行。
+- 网盘目录整理后经「管理 → 资源同步」显式对账,不做后台静默删除;确认后逐条复核,永久删除源文件缺失的 asset(含回收站)与空文件夹。垃圾文件候选先进回收站。
- 长任务只停止自己拥有且命令行匹配的 Python/FFmpeg 进程树,禁止全机终止 FFmpeg;转码只写缓存,永不改写原媒体。
- 验证分开报告:静态/单元/API、桌面浏览器、390×844 手机、生产服务是否已重启。
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 449474112..cb0643d95 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -251,11 +251,16 @@ Peach 按下面的顺序找 FFmpeg 和 ffprobe:
在 CloudDrive2 或文件管理器里整理过网盘目录之后,要在「管理 → 资源同步」里手动对账一次。Peach 不会在后台悄悄删除任何记录。
+- 对账分两步:先「检查文件」,再「清理失效条目」。检查只读盘、不改任何东西,每个来源报出文件已不在盘上的记录、空文件夹和读不了的目录,另外报出不再被引用的缓存。
- 对账会核对已配置的本地和网盘来源。离线的来源整个跳过;某个目录读不了时,保留它的记录并在结果里报告。
- 馆藏很大时扫描要很久,所以它作为后台任务运行,并逐个来源报告进度。
+- **确认清理后,源文件已经不存在的记录直接永久删除,在库的和回收站里的都算,不进回收站,无法恢复。** 删除前逐条重新确认文件确实不在,文件又出现了的记录保留并在结果里列出。
+- 清理只认最近一次检查的结果:之后又检查过一次,或者服务重启过,就要重新检查。
+- 空文件夹自底向上删除,每个来源的根目录保留;CloudDrive 上列不出内容的空目录同样算空。
- 对账只清理没有馆藏再引用的生成文件:快照、海报、照片缩略图、转码缓存、播放分段、按文件生成的头像,以及共享的番号封面。演员等资料的头像和 Logo、采集证据、复核用的 CSV 不在自动清理范围内。
- 只清理当前数据库所在数据目录里的缓存,范围之外的一律跳过。
-- 源文件已经不存在的记录,先移入回收站。
+- 每次清理在任务中心留下一条「资源同步清理」记录。
+- 条目详情里的「同步删除」只核对这一个目录,缺失的记录移入回收站,可以还原。
### 回收站
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 5a4efaa6c..b29592077 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -261,7 +261,7 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP
- 浏览历史增量采集使用 SQLite backup API 与 `browserexport`,也接受 Google Takeout ZIP;原始 URL 与标题只留本机私有目录,聚合候选不写 ledger。
- 首次设置的可选历史引导转到 `/taste?onboarding=1`,继续使用现有读取与导入入口。指南链接按 [Google 导出说明](https://support.google.com/accounts/answer/3024190?hl=zh-Hans) 和 [browserexport](https://github.com/purarue/browserexport) 官方说明核验(2026-09-06);沿用 `browserexport==0.4.4`,未新增依赖或解析器。
- 实体的公开事实随仓库分发(ADR-0073、ADR-0075):`scripts/seed_pack.py export` 只读账本生成 `resources/seed/entities.json`(女优、厂牌、事务所的别名、站上编号、官网社媒链接、资料表、所属事务所、label 的片商;不带图像、本机路径、Stash 编号),同一账本同一版本逐字节一致。导入由扫描结算声明的 `seed-import:<版本>` 后继跑(`seed_followup`),命令行 `import` 默认 dry-run;只给本机已有实体填空、不造实体,旧种子写的归属、片商与资料可被新版换掉,与人写的不一致记 `conflicts`、一条对上两位记 `duplicates`,两者写进 `seed-landing.csv`;归属 `auto:seed@<版本>`,`revert_auto_landing.py --source auto:seed` 六张表一起撤。
-- 数据管理首屏直接复用实际 `cleanupfieldset` 正文和操作条,只有计数等待取数;资源同步与重复文件网盘操作根据 `/api/sources` 已配置来源显示,离线来源保留入口。资源同步的扫描和执行复核均限于已配置 115/PikPak,空文件夹和按目录清理仍支持本地磁盘。
+- 数据管理首屏直接复用实际 `cleanupfieldset` 正文和操作条,只有计数等待取数;资源同步与重复文件网盘操作根据 `/api/sources` 已配置来源显示,离线来源保留入口。资源同步的检查与执行覆盖已配置的 local、115、PikPak,一次检查同时报失效记录、空文件夹与孤儿缓存;按目录清理也支持本地磁盘。
## 必须复用的成熟实现
@@ -385,7 +385,7 @@ Python、npm 与 GitHub Actions 的版本由 `.github/dependabot.yml` 每周检
### 文件检查与确认反馈
-资源核对复用 `web_resource_sync` 的目录枚举、离线跳过、写前复验与 BackgroundJob,涵盖 local、
-115、PikPak。展示复用 `frontend/` 构建链、Fieldset、Note、Toast 与 confirmModal;确认失败留在弹层,
+资源核对复用 `web_resource_sync` 的目录枚举、离线跳过、写前逐条复验与 BackgroundJob,涵盖 local、
+115、PikPak;失效记录的永久删除复用 `web_batch.purge_assets`,文件仍在盘上的行进 `blocked`。展示复用 `frontend/` 构建链、Fieldset、Note、Toast 与 confirmModal;确认失败留在弹层,
危险动作初始聚焦取消,忙态阻止重入与关闭。无新增依赖,不引入另一套对话框库。
真实截图的 487 项/643 个缓存作为无写入渲染样本;配置历史及性能建议依据在 OPERATIONS。
diff --git a/frontend/e2e/design.test.ts b/frontend/e2e/design.test.ts
index 43306c090..c745e8151 100644
--- a/frontend/e2e/design.test.ts
+++ b/frontend/e2e/design.test.ts
@@ -1592,7 +1592,7 @@ describe('设计决定', () => {
const expected = await disabledTokens(page);
const waiting = await waitingActionFaces(page, '[data-skeleton="cleanup"] [data-skeleton-action]');
assert.deepEqual(waiting.map((face) => face.name),
- ['扫描并补全资料', '更多扫描与采集方式', '开始修复', '检查来源', '预览', '检查死链', '检查文件']);
+ ['扫描并补全资料', '更多扫描与采集方式', '开始修复', '预览', '检查死链', '检查文件']);
for (const face of waiting) assertDisabledFace(face, expected);
const ring = await page.locator('[data-skeleton="cleanup"] [data-split-button]')
.evaluate((element) => getComputedStyle(element).boxShadow);
@@ -1657,6 +1657,8 @@ describe('设计决定', () => {
for (const target of targets) {
const node = page.locator(target).first();
await node.waitFor({ state: 'visible', timeout: 5_000 });
+ // 落在首屏以下的目标(数据管理的整理卡)先滚进视口:`elementFromPoint` 只认视口里的点。
+ await node.scrollIntoViewIfNeeded();
const box = (await node.boundingBox())!;
const look = () => node.evaluate((element) => [element, ...element.querySelectorAll('*')].slice(0, 6).map((part) => {
const style = getComputedStyle(part);
diff --git a/frontend/src/management.ts b/frontend/src/management.ts
index e44bab5a2..8cd46fd92 100644
--- a/frontend/src/management.ts
+++ b/frontend/src/management.ts
@@ -53,7 +53,7 @@ export function repairCardSkeletonHtml(): string {
</section>`);
}
-/** 首屏复用读数卡、四张任务卡、链接管理与资源同步的最终容器;静态标题、正文和键立即呈现。 */
+/** 首屏复用读数卡、三张任务卡、链接管理与资源同步的最终容器;静态标题、正文和键立即呈现。 */
export function cleanupSkeletonHtml(): string {
const stats = [['人工复核', 'square-check-big'], ['高清版', 'sparkles'], ['重复文件', 'file-stack'], ['垃圾文件', 'file-archive'], ['回收站', 'trash']];
const presets = `<span class="geist-button organize-preset-skeleton">${bar}</span>`.repeat(3);
@@ -67,11 +67,6 @@ export function cleanupSkeletonHtml(): string {
<div class="cleanupgrid">
<div class="cleanupscraping">${scanCardSkeletonHtml()}</div>
<div class="cleanupmediarepair">${repairCardSkeletonHtml()}</div>
- <section class="cleanupfieldset cleanupemptyfolders" data-geist-fieldset data-cleanup-task aria-labelledby="cleanup-loading-empty">
- <div class="geist-fieldset-content"><h3 class="geist-fieldset-title" id="cleanup-loading-empty">空文件夹与失效条目</h3>
- <strong>${bar}</strong><p class="cleanupmeta">${bar}</p></div>
- <footer class="geist-fieldset-footer" data-geist-fieldset-footer><button class="geist-button primary" ${waiting}>${icon('scan-search')}<span>检查来源</span></button></footer>
- </section>
<section class="cleanupfieldset cleanuporganize" data-geist-fieldset data-cleanup-task aria-labelledby="cleanup-loading-organize">
<div class="geist-fieldset-content"><h3 class="geist-fieldset-title" id="cleanup-loading-organize">整理</h3>
<p>按模板给文件改名并归入目录。先预览,确认后执行;执行过的一批可以整批退回。</p>
@@ -96,7 +91,7 @@ export function cleanupSkeletonHtml(): string {
<h2 id="cleanup-loading-sync">资源同步</h2>
<div class="resourcesyncbox" data-geist-fieldset data-cleanup-task>
<div class="resourcesyncbody geist-fieldset-content"><h3 class="geist-fieldset-title">文件与记录核对</h3>
- <p>按馆藏记录逐条查找本地磁盘与网盘上的文件,列出文件已不存在的记录,以及不再被引用的缓存。</p></div>
+ <p>按馆藏记录逐条查找本地磁盘与网盘上的文件,列出文件已不存在的记录、空文件夹,以及不再被引用的缓存。</p></div>
<div class="resourcesyncfooter geist-fieldset-footer" data-geist-fieldset-footer><button class="resourceaction primary" ${waiting}>${icon('git-compare')}<span>检查文件</span></button></div>
</div></section></div>`;
}
diff --git a/frontend/src/resource-sync.ts b/frontend/src/resource-sync.ts
index 7a615ecbe..f9d9f0122 100644
--- a/frontend/src/resource-sync.ts
+++ b/frontend/src/resource-sync.ts
@@ -1,33 +1,38 @@
import { MEDIA_SOURCE_ICONS, noteHtml, selectOptionIconHtml } from '@peach/legacy/ui';
export interface ResourceSource {
- location: string; online: boolean; checked: number; total: number; missing: number; unreadable?: number;
+ location: string; online: boolean; total: number; missing: number; empty: number; unreadable: number;
}
export interface ResourceScan {
- sources?: ResourceSource[]; missing?: number; cache?: {files: number; bytes: number}; scan_id?: string;
+ sources?: ResourceSource[]; missing?: number; empty?: number; unreadable?: number;
+ cache?: {files: number; bytes: number}; scan_id?: string;
}
const count = (value = 0) => Number(value).toLocaleString();
const labels: Record<string, string> = {local: '本地磁盘', '115': '115', pikpak: 'PikPak'};
/* 来源角标问的是「这是哪个网盘」,答案只有一份:品牌取 MEDIA_SOURCE_ICONS 的官方站标,
与配置页、媒体库切换器同一取图入口;认不出的来源退回 database 字形。 */
const sourceMark = (location: string) => selectOptionIconHtml(MEDIA_SOURCE_ICONS[location] ?? 'database');
-/* 结果照 Board 的 stat cards 排:和数据管理顶上一排读数同一副卡片,五个读数一行。 */
+/* 结果照 Board 的 stat cards 排:和数据管理顶上一排读数同一副卡片。来源一行、要清的三样
+ 一行,两行各自等分,来源几个都不折出半行。 */
const statCard = (head: string, value: string, detail: string) => `<article class="board-plain-stat resourcestat">
<span class="board-plain-stat-head">${head}</span>
<strong>${value}</strong>
<span class="cleanupmeta">${detail}</span></article>`;
+const sourceDetail = (source: ResourceSource) => source.online
+ ? [`找不到文件 · 共 ${count(source.total)} 项`, source.empty ? `空文件夹 ${count(source.empty)} 个` : '',
+ source.unreadable ? `${count(source.unreadable)} 个目录读取失败,已跳过` : ''].filter(Boolean).join(' · ')
+ : `馆藏中有 ${count(source.total)} 项`;
export function resourceScanHtml(scan: ResourceScan, formatSize: (bytes: number) => string): string {
const cache = scan.cache || {files: 0, bytes: 0};
- const changes = Boolean(scan.missing || cache.files);
+ const changes = Boolean(scan.missing || scan.empty || cache.files);
const sources = (scan.sources || []).map(source => statCard(
`<span class="board-stat-tile resourcestat-tile">${sourceMark(source.location)}</span>${labels[source.location] || '媒体来源'}`
+ `<span class="resourcestat-state ${source.online ? 'online' : 'offline'}">${source.online ? '可访问' : '离线,已跳过'}</span>`,
- source.online ? `${count(source.missing)} 项` : '—',
- [source.online ? `找不到文件 · 已检查 ${count(source.checked)} 项` : `馆藏中有 ${count(source.total)} 项`,
- source.unreadable ? `${count(source.unreadable)} 项读取失败,已跳过` : ''].filter(Boolean).join(' · ')));
- return `<div class="cleanupstats resourcestats">${sources.join('')}
- ${statCard('待移入回收站', `${count(scan.missing)} 项`, '')}
+ source.online ? `${count(source.missing)} 项` : '—', sourceDetail(source)));
+ return `<div class="cleanupstats resourcestats">${sources.join('')}</div>
+ <div class="cleanupstats resourcestats">${statCard('待永久删除', `${count(scan.missing)} 项`, '文件已不在盘上,含回收站')}
+ ${statCard('空文件夹', `${count(scan.empty)} 个`, '保留来源根目录')}
${statCard('可清理的缓存', `${count(cache.files)} 个`, cache.files ? formatSize(cache.bytes) : '')}</div>
- ${changes ? noteHtml(`将把找不到文件的 ${count(scan.missing)} 项馆藏记录移入回收站,并清理 ${count(cache.files)} 个闲置缓存。`, {label: '清理内容'}) : ''}
- <div class="resourceapplyrow geist-fieldset-footer" data-geist-fieldset-footer>${changes ? '<button class="geist-button primary" type="button" id="resourceApply">清理失效记录与缓存</button>' : '<p class="resourcesyncok">已检查可访问的来源,没有待清理的记录或缓存。</p>'}</div>`;
+ ${changes ? noteHtml(`将永久删除文件已不在盘上的 ${count(scan.missing)} 条记录和 ${count(scan.empty)} 个空文件夹,并清理 ${count(cache.files)} 个闲置缓存。这一步不可撤销。`, {label: '清理内容'}) : ''}
+ <div class="resourceapplyrow geist-fieldset-footer" data-geist-fieldset-footer>${changes ? '<button class="danger" type="button" id="resourceApply">清理失效条目</button>' : '<p class="resourcesyncok">已检查可访问的来源,没有待清理的记录、空文件夹或缓存。</p>'}</div>`;
}
diff --git a/frontend/test/management.test.ts b/frontend/test/management.test.ts
index 02ddd256a..4ce387cd2 100644
--- a/frontend/test/management.test.ts
+++ b/frontend/test/management.test.ts
@@ -35,10 +35,10 @@ describe('数据管理首屏', () => {
expect(card.querySelector('.cleanupmeta > .skeleton-text')).not.toBeNull();
}
});
- it('任务卡按最终顺序排好:扫描与采集、媒体修复两张岛卡,再是空文件夹与整理', () => {
+ it('任务卡按最终顺序排好:扫描与采集、媒体修复两张岛卡,再是整理', () => {
const grid = skeleton().querySelector('.cleanupgrid')!;
expect([...grid.children].map(card => card.className))
- .toEqual(['cleanupscraping', 'cleanupmediarepair', 'cleanupfieldset cleanupemptyfolders', 'cleanupfieldset cleanuporganize']);
+ .toEqual(['cleanupscraping', 'cleanupmediarepair', 'cleanupfieldset cleanuporganize']);
for (const card of grid.querySelectorAll(':scope > .cleanupscraping, :scope > .cleanupmediarepair')) {
expect(card.firstElementChild?.classList.contains('peach-react')).toBe(true);
}
@@ -60,11 +60,11 @@ describe('数据管理首屏', () => {
expect(repair.classList.contains('bg-button-primary')).toBe(true);
expect(repair.hasAttribute('data-skeleton-action')).toBe(true);
const legacy = root.querySelectorAll('.cleanupfieldset footer > button, .resourcesyncfooter > button');
- expect([...legacy].map(button => button.textContent)).toEqual(['检查来源', '预览', '检查死链', '检查文件']);
+ expect([...legacy].map(button => button.textContent)).toEqual(['预览', '检查死链', '检查文件']);
for (const button of legacy) expect(button.classList.contains('primary')).toBe(true);
const actions = root.querySelectorAll('button:not(.board-plain-stat, [aria-haspopup="listbox"])');
expect([...actions].map(button => button.textContent || button.getAttribute('aria-label')))
- .toEqual(['扫描并补全资料', '更多扫描与采集方式', '开始修复', '检查来源', '预览', '检查死链', '检查文件']);
+ .toEqual(['扫描并补全资料', '更多扫描与采集方式', '开始修复', '预览', '检查死链', '检查文件']);
for (const button of actions) {
expect(button.hasAttribute('disabled')).toBe(true);
expect(button.hasAttribute('data-skeleton-action')).toBe(true);
diff --git a/frontend/test/resource-sync.test.ts b/frontend/test/resource-sync.test.ts
index 80a46be73..7d320f0be 100644
--- a/frontend/test/resource-sync.test.ts
+++ b/frontend/test/resource-sync.test.ts
@@ -1,23 +1,33 @@
import { describe, expect, it } from 'vitest';
import { resourceScanHtml, type ResourceSource } from '../src/resource-sync';
-const source = (location: string, online = true): ResourceSource => ({location, online, checked: 18, total: 20, missing: online ? 2 : 0, unreadable: online ? 2 : 0});
+const source = (location: string, online = true): ResourceSource => ({
+ location, online, total: 20, missing: online ? 2 : 0, empty: online ? 3 : 0, unreadable: online ? 2 : 0});
describe('文件检查结果', () => {
it.each([['local'], ['115', 'pikpak'], ['local', '115', 'pikpak']])('呈现实际来源 %s', (...locations) => {
- document.body.innerHTML = resourceScanHtml({sources: locations.map(location => source(location)), missing: 2}, () => '0 B');
- expect(document.querySelectorAll('.resourcestats .board-plain-stat')).toHaveLength(locations.length + 2);
- expect(document.body.textContent).toContain('找不到文件');
- expect(document.body.textContent).toContain('2 项读取失败,已跳过');
- expect(document.querySelector('#resourceApply')?.textContent).toBe('清理失效记录与缓存');
+ document.body.innerHTML = resourceScanHtml({sources: locations.map(location => source(location)), missing: 2, empty: 3}, () => '0 B');
+ const [sources, totals] = document.querySelectorAll('.resourcestats');
+ expect(sources!.querySelectorAll('.board-plain-stat')).toHaveLength(locations.length);
+ expect([...totals!.querySelectorAll('.board-plain-stat-head')].map(head => head.textContent))
+ .toEqual(['待永久删除', '空文件夹', '可清理的缓存']);
+ expect(document.body.textContent).toContain('找不到文件 · 共 20 项');
+ expect(document.body.textContent).toContain('空文件夹 3 个');
+ expect(document.body.textContent).toContain('2 个目录读取失败,已跳过');
+ expect(document.querySelector('.geist-note')?.textContent).toContain('这一步不可撤销');
+ const apply = document.querySelector('#resourceApply');
+ expect(apply?.textContent).toBe('清理失效条目');
+ expect(apply?.className).toBe('danger');
});
it('离线来源没有删除判断,零差异没有清理按钮', () => {
document.body.innerHTML = resourceScanHtml({sources: [source('local', false)]}, () => '0 B');
expect(document.body.textContent).toContain('离线,已跳过');
- expect(document.body.textContent).not.toContain('已从网盘删除');
+ expect(document.body.textContent).toContain('馆藏中有 20 项');
expect(document.querySelector('strong')?.textContent).toBe('—');
expect(document.querySelector('#resourceApply')).toBeNull();
});
- it('仅缓存待清理也提供清理入口', () => {
+ it('只有空文件夹或只有缓存待清理也提供清理入口', () => {
+ document.body.innerHTML = resourceScanHtml({empty: 4}, () => '0 B');
+ expect(document.querySelector('#resourceApply')).not.toBeNull();
document.body.innerHTML = resourceScanHtml({cache: {files: 643, bytes: 48 * 1024 ** 2}}, () => '48 MiB');
expect(document.body.textContent).toContain('643 个');
expect(document.body.textContent).toContain('48 MiB');
diff --git a/scripts/vendor_web_dependencies.mjs b/scripts/vendor_web_dependencies.mjs
index aa668f77e..ca7bf3320 100644
--- a/scripts/vendor_web_dependencies.mjs
+++ b/scripts/vendor_web_dependencies.mjs
@@ -169,11 +169,6 @@ for (const [symbol, icon] of lucideIcons) {
.replace('<path d="M13 6h3a2 2 0 0 1 2 2v7" />', '<path class="gc-part gc-line-a" pathLength="100" d="M13 6h3a2 2 0 0 1 2 2v7"/>')
.replace('<path d="M11 18H8a2 2 0 0 1-2-2V9" />', '<path class="gc-part gc-line-b" pathLength="100" d="M11 18H8a2 2 0 0 1-2-2V9"/>')
.replace('<circle cx="6" cy="6" r="3" />', '<circle class="gc-part gc-end-b" pathLength="100" cx="6" cy="6" r="3"/>');
- if (symbol === "scan-search") inner = inner
- .replace('<path d="M3 7V5a2 2 0 0 1 2-2h2" />', '<path class="scan-corner scan-corner-a" d="M3 7V5a2 2 0 0 1 2-2h2"/>')
- .replace('<path d="M17 3h2a2 2 0 0 1 2 2v2" />', '<path class="scan-corner scan-corner-b" d="M17 3h2a2 2 0 0 1 2 2v2"/>')
- .replace('<path d="M21 17v2a2 2 0 0 1-2 2h-2" />', '<path class="scan-corner scan-corner-a" d="M21 17v2a2 2 0 0 1-2 2h-2"/>')
- .replace('<path d="M7 21H5a2 2 0 0 1-2-2v-2" />', '<path class="scan-corner scan-corner-b" d="M7 21H5a2 2 0 0 1-2-2v-2"/>');
const pattern = new RegExp(`<symbol id="i-${symbol}" viewBox="0 0 24 24">[\\s\\S]*?<\\/symbol>`);
if (!pattern.test(index)) throw new Error(`缺少 Lucide symbol:${symbol}`);
index = index.replace(pattern, `<symbol id="i-${symbol}" viewBox="0 0 24 24">${inner}</symbol>`);
diff --git a/src/peach/task_runs.py b/src/peach/task_runs.py
index 9dd78eb2d..464674240 100644
--- a/src/peach/task_runs.py
+++ b/src/peach/task_runs.py
@@ -77,9 +77,8 @@ TASK_LABELS = {
"taste-refresh": "口味分析",
"link-check": "链接检查",
"link-prune": "失效链接清理",
- "resource-scan": "资源对账扫描",
- "resource-apply": "资源对账执行",
- "empty-folders": "空文件夹与失效条目清理",
+ "resource-scan": "资源同步检查",
+ "resource-apply": "资源同步清理",
"scraping-cover": "封面采集",
"media-repair": "媒体修复",
"organize": "按模板整理",
diff --git a/src/peach/web_batch.py b/src/peach/web_batch.py
index d4c1250c0..a6b0cafc1 100644
--- a/src/peach/web_batch.py
+++ b/src/peach/web_batch.py
@@ -10,7 +10,6 @@
"""
from __future__ import annotations
-import errno
import os
import re
import time
@@ -27,7 +26,7 @@ from .regions import normalize_region
from .task_runs import TaskRunHandle
from .web_activity import DEFAULT_PROFILE_ID
from .web_catalog import COST, attach_card_performers
-from .web_resource_sync import clean_resource_orphans, vanished_asset_rows
+from .web_resource_sync import clean_resource_orphans
from .web_state import WebContract
#: 批量操作在活动页上的名字。表里存 `operation`,人看的是这一列。
@@ -481,136 +480,22 @@ def _remove_empty_ancestors(parent: Path, source_roots: Sequence[Path]) -> list[
return removed
-def _hollow_directory(path: Path) -> bool:
- """CloudDrive 上的空目录:`scandir` 报找不到,`listdir` 却说目录在、里面是空的。
+def purge_vanished_rows(contract: WebContract, rows) -> dict:
+ """永久删除文件已不在盘上的这些行,连同引用与派生产物;返回 `_finish_purge` 的回执。
- 挂载层给空目录列不出 `.` 与 `..`,`FindFirstFileW` 于是回 `ERROR_FILE_NOT_FOUND`;
- `os.listdir` 把它当成空目录,`os.scandir`(`os.walk` 走的就是它)当成错误。2026-09-27
- 本机 115 与 PikPak 两轮遍历都报同样 71 个「读取失败」,逐个复核全是这种空目录。
- """
- try:
- return path.is_dir() and not path.is_symlink() and not os.listdir(path)
- except OSError:
- return False
-
-
-def cleanup_empty_source_directories(
- contract: WebContract | None = None, *, dry_run: bool = False,
-) -> 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.
-
- 网盘那边删掉的文件在账本里留下的行一起清(`contract` 给了才做)。空目录和这些行是
- 同一件事的两半:用户在网盘客户端里删一个目录,盘上留下空壳,账本里留下一批指向
- 不存在文件的行。只清目录,那些行就继续被长跑批处理一轮轮领走、一轮轮失败。删除
- 走 `purge_assets` 这唯一一条物理删除实现,文件本来就没了,删的是账本行和派生产物。
- """
- results: list[dict[str, object]] = []
- total_scanned = total_removed = total_errors = total_empty = 0
- total_vanished = total_purged = 0
- for location, declarations in LOCATION_ROOT_DECLARATIONS.items():
- roots = [translate_ledger_path(declaration) for declaration in declarations]
- mapped = all(not is_unmapped(root) for root in roots)
- online = mapped and all(root.is_dir() and root_online(root) for root in roots)
- row: dict[str, object] = {
- "location": location,
- "mapped": mapped,
- "online": online,
- "scanned": 0,
- "removed": 0,
- "empty": 0,
- "errors": 0,
- "vanished": 0,
- "purged": 0,
- }
- if not online:
- results.append(row)
- continue
-
- if contract is not None:
- gone = vanished_asset_rows(contract, location)
- row["vanished"] = len(gone)
- if gone and not dry_run:
- row["purged"] = _purge_vanished(contract, gone)
- total_vanished += int(row["vanished"])
- total_purged += int(row["purged"])
-
- walk_errors: list[OSError] = []
- empty_paths: set[Path] = set()
-
- def consider(candidate: Path, *, hollow: bool = False) -> None:
- row["scanned"] = int(row["scanned"]) + 1
- try:
- if dry_run:
- if hollow or all(
- child in empty_paths and not child.is_symlink()
- for child in candidate.iterdir()):
- empty_paths.add(candidate)
- row["empty"] = int(row["empty"]) + 1
- return
- candidate.rmdir()
- except FileNotFoundError:
- # CloudDrive can remove the same empty directory concurrently.
- return
- 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
-
- for root in roots:
- # 自底向上时子目录的 onerror 先于父目录产出,空目录在这里记下,父目录照常判空。
- def on_walk_error(error: OSError, root: Path = root) -> None:
- path = Path(error.filename) if isinstance(error, FileNotFoundError) and error.filename else None
- if path is not None and path != root and _hollow_directory(path):
- consider(path, hollow=True)
- else:
- walk_errors.append(error)
-
- for directory, _subdirectories, _files in os.walk(
- root, topdown=False, onerror=on_walk_error, followlinks=False):
- candidate = Path(directory)
- if candidate == root or candidate.is_symlink():
- continue
- consider(candidate)
- row["errors"] = int(row["errors"]) + len(walk_errors)
- total_scanned += int(row["scanned"])
- total_removed += int(row["removed"])
- total_empty += int(row["empty"])
- total_errors += int(row["errors"])
- results.append(row)
- return {
- "ok": total_errors == 0,
- "scanned": total_scanned,
- "removed": total_removed,
- "empty": total_empty,
- "vanished": total_vanished,
- "purged": total_purged,
- "dry_run": dry_run,
- "errors": total_errors,
- "sources": results,
- }
-
-
-def _purge_vanished(contract: WebContract, rows) -> int:
- """删掉这些行,返回真删了几条。
-
- 文件早就不在盘上,`purge_assets` 的文件删除那一步会整条跳过并记进 `blocked`——
- 那正是它要报的东西:还能删掉文件的行说明文件其实还在,它不属于这一批。
+ `missing_only`:到了删的这一刻文件又在了(复核之后网盘才同步回来),这一行整条
+ 跳过进 `blocked`,媒体文件一个字节都不碰。这一批要删的只是账本行。
"""
contract.cache_bust()
outcome = None
try:
with contract.write_transaction() as connection:
- outcome = purge_assets(connection, rows)
+ outcome = purge_assets(connection, rows, missing_only=True)
except BaseException:
if outcome is not None:
_restore_staged_media(outcome["_staged"])
raise
- return int(_finish_purge(outcome).get("purged") or 0)
+ return _finish_purge(outcome)
def _finish_purge(outcome):
@@ -637,17 +522,28 @@ def _finish_purge(outcome):
return outcome
-def purge_assets(connection, rows):
+def purge_assets(connection, rows, *, missing_only: bool = False):
"""Quarantine media, delete ledger rows, and leave final removal to the caller.
Renaming beside the source is reversible and stays on the same filesystem. The
caller restores the quarantined names if commit fails, then permanently removes
them only after the SQLite transaction has committed.
+
+ ``missing_only`` 删的只是账本行:文件还在(或答不上在不在)的行进 ``blocked``。
"""
purged, blocked, staged, snapshots, parents = [], [], [], [], []
for row in rows:
media = row["path"]
- if media:
+ if media and missing_only:
+ try:
+ present = translate_ledger_path(media).exists()
+ reason = "文件仍在盘上"
+ except OSError as error:
+ present, reason = True, error.strerror or str(error)
+ if present:
+ blocked.append({"id": row["id"], "path": media, "reason": reason})
+ continue
+ elif media:
original = Path(media)
try:
if original.exists() and not original.is_file():
@@ -710,27 +606,6 @@ def w_empty_trash(contract: WebContract):
return result
-def w_cleanup_empty_directories(contract: WebContract, body):
- """清掉在线来源上的空目录,以及文件已在网盘那边删掉的账本行。
-
- 检查这一步只看不删,两个数都报;真删那一步走任务中心留一行记录——它会删账本行,
- 事后要答得出「这批是什么时候、删了多少」,而这张表是唯一留着这个答案的地方。
- """
- if body.get("dry_run") is True:
- return cleanup_empty_source_directories(contract, dry_run=True)
- run = contract.task_runs.start("empty-folders", trigger="manual")
- handle = TaskRunHandle(contract.task_runs, run.id if run else None)
- try:
- result = cleanup_empty_source_directories(contract)
- except BaseException as error:
- handle.finish("failed", error=f"{type(error).__name__}: {error}")
- raise
- handle.finish("succeeded", summary={
- "removed": result["removed"], "purged": result["purged"],
- "errors": result["errors"]})
- return result
-
-
def _batch_region_value(body) -> str | None:
"""批量判定产地要写进真相字段的值;`None` 表示退回未判定。
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 205a00072..a84769e87 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -69,14 +69,12 @@ from .web_batch import (
PROMO_FILLER,
PROMO_PHRASE,
REAL_CODE,
- cleanup_empty_source_directories,
has_sibling_original,
promo_residue,
purge_assets,
q_ads,
q_duplicates,
w_batch,
- w_cleanup_empty_directories,
w_empty_trash,
)
from .web_catalog import (
@@ -150,7 +148,7 @@ __all__ = [
"READ_ONLY_POST_ROUTES", "REAL_CODE",
"TASTE_WINDOWS", "WebContract", "_edition_groups", "attach_card_performers",
"attach_edition_groups", "attach_jav_display_fields", "attach_multipart_groups",
- "cleanup_empty_source_directories", "con_entities", "con_tags",
+ "con_entities", "con_tags",
"dispatch_api_get", "dispatch_api_post", "face_focus", "has_sibling_original",
"is_jav_code",
"jav_display_metadata", "normalise_code_key", "normalize_entity_name",
@@ -160,7 +158,7 @@ __all__ = [
"q_index", "q_item", "q_items", "q_parts", "q_photo_set", "q_playlists",
"q_quality_goals", "q_related", "q_search_history", "q_stats", "q_suggest", "q_taste",
"q_tops", "state_clause", "state_predicate", "tag_is_not_a_performer_name",
- "tag_not_hidden", "w_activity", "w_batch", "w_cleanup_empty_directories",
+ "tag_not_hidden", "w_activity", "w_batch",
"w_empty_trash", "w_feedback", "w_item_tag", "w_playlist", "w_preference",
"w_quality_goal", "w_review_decision", "w_review_genre", "w_search_history", "w_taste_refresh",
"w_taste_source", "w_watch_later",
diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.py
index 90cff3a7f..4336bdbdf 100644
--- a/src/peach/web_resource_sync.py
+++ b/src/peach/web_resource_sync.py
@@ -1,19 +1,25 @@
-"""资源对账:把账本里的记录和磁盘上真实存在的文件对齐。
+"""资源对账:把账本里的记录、来源目录和磁盘上真实存在的文件对齐。
从 `web_contract` 拆出。这一域自己持有扫描线程状态、目录遍历和孤儿缓存清理,
和浏览、复核没有共享逻辑,留在契约巨石里只是让那个文件更难读。
+用户在网盘客户端里删掉一个目录,本机看到的是三样东西:账本里一批指向不存在文件的
+行、盘上留下的空壳目录、这些行生成过的缓存。一次检查把三样一起报出来,一次执行
+一起清掉(ADR-0036)。
+
`source_is_online` 也在这里:判断某个来源的根挂载没挂载,只有对账要问这件事。
-`w_purge_missing` 同理——按目录清缺失文件和整库扫描是同一件事的两种入口。
+`w_purge_missing` 是按目录的那个入口,服务详情页上「这个目录我刚整理过」,
+判缺失与整库扫描共用同一套目录枚举。
"""
from __future__ import annotations
+import errno
import os
import re
import shutil
import time
from concurrent.futures import ThreadPoolExecutor
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
from typing import Callable, Protocol, Sequence
from . import jav_poster_crop
@@ -21,7 +27,7 @@ from .catalog_rules import dir_expr, normalise_code_key, photo_set_title
from .config import LOCATION_ROOT_DECLARATIONS
from .jobs import BackgroundJob
from .media import normalized_path
-from .platform import is_unmapped, root_online, translate_ledger_path
+from .platform import is_unmapped, root_online, translate_ledger_path, within_root
class ResourceSyncContract(Protocol):
@@ -97,13 +103,20 @@ def _scan_resource_directory(
)
-def _missing_resource_ids(rows: Sequence) -> tuple[list[int], int]:
+def _directory_key(path: str | os.PathLike[str]) -> str:
+ """同一个目录只数一次:账本枚举与目录遍历报上来的写法不一定相同。"""
+ return os.path.normcase(os.fspath(path))
+
+
+def _missing_resource_ids(
+ rows: Sequence, unreadable_dirs: set[str] | None = None,
+) -> tuple[list[int], int]:
"""Compare ledger paths one directory listing at a time.
Cloud mounts make one ``stat`` request per path painfully slow. ``scandir`` reuses the
directory enumeration that the filesystem already returns, while retaining the same
case-insensitive Windows path semantics. An unreadable directory is skipped rather than
- being mistaken for a directory that the user deleted.
+ being mistaken for a directory that the user deleted; ``unreadable_dirs`` collects it.
"""
directories: dict[Path, dict[str, list[int]]] = {}
for row in rows:
@@ -125,16 +138,22 @@ def _missing_resource_ids(rows: Sequence) -> tuple[list[int], int]:
results = list(executor.map(_scan_resource_directory, directory_items))
missing = [asset_id for ids, _unreadable in results for asset_id in ids]
unreadable = sum(count for _ids, count in results)
+ if unreadable_dirs is not None:
+ unreadable_dirs.update(_directory_key(parent)
+ for (parent, _expected), (_ids, count) in zip(directory_items, results)
+ if count)
return missing, unreadable
-def vanished_asset_rows(contract: ResourceSyncContract, location: str) -> list:
+def vanished_asset_rows(
+ contract: ResourceSyncContract, location: str, *,
+ unreadable_dirs: set[str] | None = None,
+) -> list:
"""这个来源上文件已经不在的行,回收站里的也算。
- 对账扫描(`_scan_missing_resources`)刻意跳过回收站:那边问的是「库里这条还在不在」,
- 等着用户决定去留的行不该混进去。清理这一侧问的是另一件事——文件已经在网盘那边删掉了,
- 账本这一行指的东西不存在了。本机 647 行回收站里有 469 行属于这种,它们既不在对账的
- 视野里,又会被每一轮长跑批处理重新领一次。
+ 问的是「账本这一行指的东西还在不在」,与这一行是否在回收站无关:文件已经在网盘那边
+ 删掉了,回收站里那一行同样指不到任何东西。2026-09-16 本机 647 行回收站里有 469 行
+ 属于这种,它们会被每一轮长跑批处理重新领一次。
调用方必须先确认这个来源在线(`source_is_online`):盘没挂上时目录读不到,
每一条都会被判成文件没了。
@@ -146,7 +165,7 @@ def vanished_asset_rows(contract: ResourceSyncContract, location: str) -> list:
"SELECT id,path,snapshot_path,disposal FROM asset "
"WHERE path IS NOT NULL AND location=? ORDER BY id", (location,),
).fetchall()
- missing, _unreadable = _missing_resource_ids(rows)
+ missing, _unreadable = _missing_resource_ids(rows, unreadable_dirs)
gone = set(missing)
return _confirm_vanished([row for row in rows if int(row["id"]) in gone])
@@ -181,39 +200,78 @@ def _confirm_vanished(rows: Sequence) -> list:
return [row for row, here in zip(rows, verdicts) if not here]
-def _scan_missing_resources(
+def _source_roots(location: str) -> list[Path]:
+ return [translate_ledger_path(root) for root in LOCATION_ROOT_DECLARATIONS.get(location, ())]
+
+
+def _hollow_directory(path: Path) -> bool:
+ """CloudDrive 上的空目录:`scandir` 报找不到,`listdir` 却说目录在、里面是空的。
+
+ 挂载层给空目录列不出 `.` 与 `..`,`FindFirstFileW` 于是回 `ERROR_FILE_NOT_FOUND`;
+ `os.listdir` 把它当成空目录,`os.scandir`(`os.walk` 走的就是它)当成错误。2026-09-27
+ 本机 115 与 PikPak 两轮遍历都报同样 71 个「读取失败」,逐个复核全是这种空目录。
+ """
+ try:
+ return path.is_dir() and not path.is_symlink() and not os.listdir(path)
+ except OSError:
+ return False
+
+
+def _empty_directories(roots: Sequence[Path], unreadable_dirs: set[str]) -> list[Path]:
+ """自底向上找出来源根下的空目录;删掉子目录后会变空的父目录也算,来源根本身不算。
+
+ 判空只用 `os.walk` 已经列出来的名字,不再逐个目录多列一次:网盘挂载上每列一次
+ 就是一次网络往返。目录链接不跟进,也不算空。读不了的目录记进 `unreadable_dirs`。
+ """
+ empty: set[str] = set()
+ found: list[Path] = []
+ for root in roots:
+ # 自底向上时子目录的 onerror 先于父目录产出,空目录在这里记下,父目录照常判空。
+ def on_walk_error(error: OSError, root: Path = root) -> None:
+ path = Path(error.filename) if isinstance(error, FileNotFoundError) and error.filename else None
+ if path is not None and path != root and _hollow_directory(path):
+ empty.add(_directory_key(path))
+ found.append(path)
+ else:
+ unreadable_dirs.add(_directory_key(error.filename or root))
+
+ for directory, subdirectories, files in os.walk(
+ root, topdown=False, onerror=on_walk_error, followlinks=False):
+ candidate = Path(directory)
+ if files or candidate == root or candidate.is_symlink():
+ continue
+ if all(_directory_key(os.path.join(directory, name)) in empty for name in subdirectories):
+ empty.add(_directory_key(candidate))
+ found.append(candidate)
+ return found
+
+
+def _scan_sources(
contract: ResourceSyncContract,
progress: Callable[[dict], None] | None = None,
) -> dict:
- """只读核对已配置磁盘与网盘中的文件。"""
+ """只读核对每个在线来源:文件已不在盘上的行、空文件夹、读不了的目录。"""
with contract.read_connection() as connection:
- rows = connection.execute(
- "SELECT id,location,path FROM asset "
- "WHERE path IS NOT NULL AND COALESCE(disposal,'')!='trash' "
- "AND location IN ('local','115','pikpak') ORDER BY location,id",
- ).fetchall()
- grouped: dict[str, list] = {}
- for row in rows:
- grouped.setdefault(row["location"], []).append(row)
- missing_ids: list[int] = []
+ totals = {row[0]: int(row[1]) for row in connection.execute(
+ "SELECT location,count(*) FROM asset WHERE path IS NOT NULL GROUP BY location")}
+ vanished_ids: list[int] = []
+ empty_dirs: dict[str, list[str]] = {}
sources = []
for location in configured_resource_locations():
- items = grouped.get(location, [])
online = source_is_online(location)
- missing = []
- unreadable = 0
+ source = {"location": location, "online": online, "total": totals.get(location, 0),
+ "missing": 0, "empty": 0, "unreadable": 0}
if online:
- missing, unreadable = _missing_resource_ids(items)
- missing_ids.extend(missing)
- source = {
- "location": location, "online": online,
- "checked": max(0, len(items) - unreadable) if online else 0,
- "total": len(items), "missing": len(missing), "unreadable": unreadable,
- }
+ unreadable: set[str] = set()
+ gone = vanished_asset_rows(contract, location, unreadable_dirs=unreadable)
+ empties = _empty_directories(_source_roots(location), unreadable)
+ vanished_ids.extend(int(row["id"]) for row in gone)
+ empty_dirs[location] = [os.fspath(path) for path in empties]
+ source.update(missing=len(gone), empty=len(empties), unreadable=len(unreadable))
sources.append(source)
if progress is not None:
progress(source)
- return {"sources": sources, "missing_ids": missing_ids}
+ return {"sources": sources, "vanished_ids": vanished_ids, "empty_dirs": empty_dirs}
def _cache_file(path: Path, kind: str, output: list[tuple[str, Path, int]]) -> None:
@@ -407,22 +465,31 @@ def _run_resource_scan(contract: ResourceSyncContract, scan_id: str) -> None:
if state is not None:
state["sources"].append(dict(source))
- scan = _scan_missing_resources(contract, progress)
- caches = _resource_orphan_plan(contract, scan["missing_ids"])
- result = {
- "ok": True, "sources": scan["sources"],
- "missing": len(scan["missing_ids"]),
+ scan = _scan_sources(contract, progress)
+ # 候选名单和空目录路径只留在任务状态里,不进 `result`:公开投影整个下发 `result`,
+ # 物理路径不出服务端。
+ job.update(scan_id, status="complete", result=_scan_result(contract, scan),
+ vanished_ids=list(scan["vanished_ids"]), empty_dirs=scan["empty_dirs"],
+ completed_at=time.time())
+
+
+def _scan_result(contract: ResourceSyncContract, scan: dict) -> dict:
+ caches = _resource_orphan_plan(contract, scan["vanished_ids"])
+ sources = scan["sources"]
+ return {
+ "ok": True, "sources": sources,
+ "missing": len(scan["vanished_ids"]),
+ "empty": sum(source["empty"] for source in sources),
+ "unreadable": sum(source["unreadable"] for source in sources),
"cache": {"files": caches["total_files"], "bytes": caches["total_bytes"],
"by_kind": caches["summary"]},
}
- job.update(scan_id, status="complete", result=result,
- missing_ids=list(scan["missing_ids"]), completed_at=time.time())
def _background_resource_scan(contract: ResourceSyncContract, restart: bool = False) -> dict:
return _resource_scan_public(contract.resource_scan.start(
lambda scan_id: _run_resource_scan(contract, scan_id),
- initial={"sources": [], "result": None, "missing_ids": []},
+ initial={"sources": [], "result": None, "vanished_ids": [], "empty_dirs": {}},
restart=restart,
))
@@ -444,85 +511,120 @@ def w_resource_sync_scan(contract: ResourceSyncContract, body=None):
return _background_resource_scan(contract, restart=body.get("restart") is True)
if not configured_resource_locations():
raise ValueError("请先在配置页添加媒体文件夹")
- scan = _scan_missing_resources(contract)
- caches = _resource_orphan_plan(contract, scan["missing_ids"])
- return {
- "ok": True, "sources": scan["sources"],
- "missing": len(scan["missing_ids"]),
- "cache": {"files": caches["total_files"], "bytes": caches["total_bytes"],
- "by_kind": caches["summary"]},
- }
+ return _scan_result(contract, _scan_sources(contract))
-def _recheck_resource_scan_ids(contract: ResourceSyncContract, asset_ids: Sequence[int]) -> list[int]:
- if not asset_ids:
- return []
+def _completed_scan(contract: ResourceSyncContract, scan_id: str) -> dict:
+ """执行只认这一轮检查:别的一轮、还没跑完的一轮、顶掉了的一轮都不算。"""
+ state = contract.resource_scan.snapshot()
+ if (not scan_id or state is None or state["scan_id"] != scan_id
+ or state["status"] != "complete"):
+ raise ValueError("resource scan expired; scan again")
+ return state
+
+
+def _rows_by_id(contract: ResourceSyncContract, asset_ids: Sequence[int]) -> list:
rows = []
with contract.read_connection() as connection:
for offset in range(0, len(asset_ids), 400):
batch = list(asset_ids[offset:offset + 400])
marks = ",".join("?" for _item in batch)
rows.extend(connection.execute(
- "SELECT id,location,path FROM asset "
- f"WHERE id IN ({marks}) AND path IS NOT NULL "
- "AND COALESCE(disposal,'')!='trash'",
- batch,
+ "SELECT id,location,path,snapshot_path FROM asset "
+ f"WHERE id IN ({marks}) AND path IS NOT NULL", batch,
).fetchall())
- grouped: dict[str, list] = {}
- for row in rows:
- grouped.setdefault(row["location"], []).append(row)
- missing = []
- for location, items in grouped.items():
- if location not in configured_resource_locations() or not source_is_online(location):
+ return rows
+
+
+def _recheck_vanished(contract: ResourceSyncContract, asset_ids: Sequence[int]) -> list:
+ """检查给的候选逐条重新 `stat`,只留仍在线来源上、这一次仍答不在的行。
+
+ 不重跑目录枚举:枚举在网盘上会静默少给名字(`_confirm_vanished`),而这一步之后
+ 就是永久删除。复核前后各判一次在线:复核途中掉线的来源,那一趟 `stat` 全都答不在。
+ """
+ if not asset_ids:
+ return []
+ locations = configured_resource_locations()
+ online = {location for location in locations if source_is_online(location)}
+ rows = [row for row in _rows_by_id(contract, asset_ids) if row["location"] in online]
+ confirmed = _confirm_vanished(rows)
+ still_online = {location for location in online if source_is_online(location)}
+ return [row for row in confirmed if row["location"] in still_online]
+
+
+def _remove_empty_directories(paths: Sequence[Path], roots: Sequence[Path]) -> tuple[int, int]:
+ """按深度从深到浅删检查报出的空目录;来源根和根外的路径一律不碰。
+
+ `rmdir` 只删得掉空目录:检查之后又放进东西的目录照样留着,不算失败。
+ """
+ removed = errors = 0
+ for path in sorted(paths, key=lambda item: len(item.parts), reverse=True):
+ if (path in roots or path.is_symlink()
+ or not any(within_root(path, root) for root in roots)):
continue
- source_missing, _unreadable = _missing_resource_ids(items)
- missing.extend(source_missing)
- return missing
+ try:
+ path.rmdir()
+ except FileNotFoundError:
+ # CloudDrive 会在最后一个子项消失时自己收掉空的一层;删文件那一步也会顺手清空父目录。
+ continue
+ except OSError as error:
+ if error.errno not in {errno.ENOTEMPTY, errno.EEXIST}:
+ errors += 1
+ continue
+ removed += 1
+ return removed, errors
def w_resource_sync_apply(contract: ResourceSyncContract, body, *, progress=None):
+ """永久删除这一轮检查报出的失效记录与空文件夹,再清孤儿缓存。
+
+ 文件已不在盘上的行不进回收站、直接删(用户原话「网盘同步删除了的都直接删」)。
+ 删之前逐条复核,删不掉的进 `blocked`;这一步不可撤销,所以只认检查给的候选集合。
+ """
if not configured_resource_locations():
raise ValueError("请先在配置页添加媒体文件夹")
if body.get("confirm") is not True:
raise ValueError("resource sync requires confirmation")
+ scan_id = str(body.get("scan_id") or "")
+ _completed_scan(contract, scan_id)
if body.get("background"):
job = contract.resource_apply_job
def work(job_id):
result = w_resource_sync_apply(contract, {**body, "background": False},
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={"message": "正在重新核对来源挂载与缺失文件"})
- scan_id = str(body.get("scan_id") or "")
- if scan_id:
- state = contract.resource_scan.snapshot()
- if (state is None or state["scan_id"] != scan_id
- or state["status"] != "complete"):
- raise ValueError("resource scan expired; scan again")
- candidates = list(state["missing_ids"])
- sources = [dict(source) for source in state["result"]["sources"]]
- # Do not trust the background result at write time. Recheck only its bounded
- # candidate set; online sources and unreadable directories retain the safe skip.
- missing_ids = _recheck_resource_scan_ids(contract, candidates)
- scan = {"sources": sources, "missing_ids": missing_ids}
- else:
- # Compatibility path for non-browser callers: still perform a fresh full scan.
- scan = _scan_missing_resources(contract)
- missing_ids = scan["missing_ids"]
- if missing_ids:
- if progress:
- progress(checked=0, total=None, message=f"正在把 {len(missing_ids)} 个确认缺失的条目移入回收站")
- with contract.write_transaction() as connection:
- stamp = time.time()
- connection.executemany(
- "UPDATE asset SET disposal='trash',feedback_at=? WHERE id=?",
- [(stamp, asset_id) for asset_id in missing_ids],
- )
+ return job.start(work, restart=True, initial={"message": "正在逐条复核失效记录"})
+ state = _completed_scan(contract, scan_id)
+ report = progress or (lambda **_fields: None)
+ report(checked=0, total=None, message="正在逐条复核失效记录")
+ confirmed = _recheck_vanished(contract, state["vanished_ids"])
+ purge = {"purged": 0, "blocked": [], "empty_dirs_removed": 0}
+ if confirmed:
+ report(checked=0, total=None, message=f"正在永久删除 {len(confirmed)} 条失效记录")
+ from .web_batch import purge_vanished_rows # web_batch 在模块顶部 import 本模块
+ purge = purge_vanished_rows(contract, confirmed)
+ report(checked=0, total=None, message="正在删除空文件夹")
+ dirs_removed, dir_errors = 0, 0
+ for location, paths in state["empty_dirs"].items():
+ if location not in configured_resource_locations() or not source_is_online(location):
+ continue
+ removed, errors = _remove_empty_directories([Path(path) for path in paths],
+ _source_roots(location))
+ dirs_removed += removed
+ dir_errors += errors
contract.cache_bust()
cleanup = clean_resource_orphans(contract, progress=progress) if body.get("clean_cache", True) else {
"cache_removed": 0, "bytes_reclaimed": 0, "cache_blocked": [],
}
- return {"ok": True, "moved_to_trash": len(missing_ids),
- "sources": scan["sources"], **cleanup}
+ blocked = [{"id": item["id"], "name": PureWindowsPath(item["path"]).name,
+ "reason": item["reason"]} for item in purge["blocked"]]
+ return {
+ "ok": True, "sources": state["result"]["sources"],
+ "purged": int(purge["purged"]), "blocked": blocked, "blocked_count": len(blocked),
+ "dirs_removed": dirs_removed + int(purge.get("empty_dirs_removed") or 0),
+ "dir_errors": dir_errors, "unreadable": int(state["result"].get("unreadable") or 0),
+ **cleanup,
+ }
def w_purge_missing(contract: ResourceSyncContract, body):
diff --git a/src/peach/web_router.py b/src/peach/web_router.py
index e9f6b47ee..1b29365a3 100644
--- a/src/peach/web_router.py
+++ b/src/peach/web_router.py
@@ -20,7 +20,7 @@ from .web_activity import (
w_quality_goal,
w_watch_later,
)
-from .web_batch import q_ads, q_duplicates, w_batch, w_cleanup_empty_directories, w_empty_trash
+from .web_batch import q_ads, q_duplicates, w_batch, w_empty_trash
from .taste_history import history_source_count
from .web_catalog import (
catalog_filter,
@@ -389,7 +389,6 @@ 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/organize/preview": w_organize_preview,
"/api/organize/apply": w_organize_apply,
"/api/organize/rollback": w_organize_rollback,
@@ -420,9 +419,9 @@ READ_ONLY_POST_ROUTES = frozenset({
# 整理的预览只出一份计划 CSV,不动文件也不改账本;执行与回滚不在这里。
"/api/organize/preview",
})
-# `/api/data-cleanup/empty-folders` 不在上面:它连文件已消失的账本行一起删,走的是
-# `purge_assets`。检查那一步(`dry_run`)确实不写,但闸门按路径判,宁可连检查一起拦,
-# 也不能让只读端那份复制来的账本被真删一批行。
+# `/api/resource-sync/apply` 不在上面:它永久删除文件已不在盘上的账本行,走的是
+# `purge_assets`。检查那一步只读盘,候选留在进程内存里;它在任务中心的那一行
+# 在只读端本来就不写。
def dispatch_api_get(contract: WebContract, path, args):
diff --git a/tests/test_desktop_settings.py b/tests/test_desktop_settings.py
index ac31f50dd..dfa8c5aca 100644
--- a/tests/test_desktop_settings.py
+++ b/tests/test_desktop_settings.py
@@ -41,13 +41,8 @@ class DesktopSettingsTests(unittest.TestCase):
renderer = (root / 'frontend/src/resource-sync.ts').read_text(encoding='utf-8')
self.assertIn('resourceScanHtml(payload,fmtSize)', sync)
self.assertIn("{label: '清理内容'}", renderer)
- self.assertIn('class="geist-button primary" type="button" id="resourceApply"', renderer)
- self.assertIn("danger:false,onConfirm", sync)
- empty = app[app.index('empty:`<section'):app.index("review:entryCard('review')")]
- self.assertNotIn('data-fieldset-type="error"', empty)
- self.assertIn('data-cleanup-empty-scan', empty)
- self.assertIn('class="danger" data-cleanup-empty hidden', empty)
- self.assertIn("{dry_run:true}", app)
+ # 失效条目直接永久删除:确认框走危险档;按键的实底红由 frontend/test/resource-sync.test.ts 验。
+ self.assertIn("confirmLabel:'清理失效条目',danger:true,onConfirm", sync)
def setUp(self):
temporary = tempfile.TemporaryDirectory()
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 936522e3f..c93da1a3f 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -125,16 +125,21 @@ class FollowContractTests(unittest.TestCase):
def test_background_resource_apply_has_a_queryable_receipt(self):
from peach import web_resource_sync
- with mock.patch.object(web_resource_sync, '_scan_missing_resources',
- return_value={'sources': [], 'missing_ids': []}), \
+ with mock.patch.object(web_resource_sync, 'LOCATION_ROOT_DECLARATIONS',
+ {'local': (str(self.root),)}), \
+ mock.patch.object(web_resource_sync, '_scan_sources',
+ return_value={'sources': [], 'vanished_ids': [], 'empty_dirs': {}}), \
mock.patch.object(web_resource_sync, 'clean_resource_orphans',
return_value={'cache_removed': 0, 'bytes_reclaimed': 0}):
- started = self._post('/api/resource-sync/apply', {'background': True, 'confirm': True})
+ scan = self._post('/api/resource-sync/scan', {'background': True, 'restart': True})
+ self.contract.resource_scan.thread.join(5)
+ started = self._post('/api/resource-sync/apply', {
+ 'background': True, 'confirm': True, 'scan_id': scan['scan_id']})
self.contract.resource_apply_job.thread.join(5)
final = dispatch_api_get(self.contract, '/api/resource-sync/apply', {})
self.assertEqual(final['job_id'], started['job_id'])
self.assertEqual(final['status'], 'complete')
- self.assertEqual(final['moved_to_trash'], 0)
+ self.assertEqual(final['purged'], 0)
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index e31019e2b..ceb8d77eb 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -959,7 +959,7 @@ 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/data-cleanup/empty-folders",
+ "/api/search-history", "/api/trash/empty",
"/api/review/decision", "/api/review/genre",
"/api/purge-missing",
"/api/links/check", "/api/links/prune",
@@ -1218,126 +1218,6 @@ class WebDataTests(unittest.TestCase):
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(web_batch, "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_a_clouddrive_empty_folder_that_scandir_cannot_open_still_counts_as_empty(self):
- """CloudDrive 的空目录列不出 `.` 与 `..`:`scandir` 报找不到,`listdir` 给空列表。
-
- 它的上一层只装着它,删掉它以后也该跟着删;里面有东西、同样报找不到的目录才是
- 真的读不了,照旧记成错误。
- """
- source_root = Path(self.tmp.name) / "mount"
- hollow = source_root / "release" / "文宣"
- hollow.mkdir(parents=True)
- unreadable = source_root / "unreadable"
- unreadable.mkdir()
- (unreadable / "media.mp4").write_bytes(b"keep")
- failing = {os.path.normcase(os.fspath(hollow)), os.path.normcase(os.fspath(unreadable))}
- real_scandir = os.scandir
-
- def mount_scandir(path="."):
- if os.path.normcase(os.fspath(path)) in failing:
- raise FileNotFoundError(2, "系统找不到指定的文件。", os.fspath(path))
- return real_scandir(path)
-
- with mock.patch.object(web_batch, "LOCATION_ROOT_DECLARATIONS",
- {"115": (str(source_root),)}), \
- mock.patch.object(os, "scandir", mount_scandir):
- checked = rm_web.cleanup_empty_source_directories(dry_run=True)
- self.assertTrue(hollow.is_dir(), "检查只报数不删")
- cleaned = rm_web.cleanup_empty_source_directories()
-
- self.assertEqual((checked["empty"], checked["errors"]), (2, 1))
- self.assertEqual((cleaned["removed"], cleaned["errors"]), (2, 1))
- self.assertFalse((source_root / "release").exists())
- self.assertTrue((unreadable / "media.mp4").is_file())
-
- def test_empty_folder_cleanup_post_is_gated_as_a_ledger_write(self):
- self.assertIs(
- rm_web.POST_HANDLERS["/api/data-cleanup/empty-folders"],
- rm_web.w_cleanup_empty_directories,
- )
- self.assertNotIn(
- "/api/data-cleanup/empty-folders", rm_web.READ_ONLY_POST_ROUTES,
- "它连文件已消失的账本行一起删,只读端那份复制来的账本不能被它清掉",
- )
-
- def test_cleanup_purges_rows_whose_file_is_gone_and_only_counts_them_when_checking(self):
- """网盘那边删掉的文件在账本里留下的行,和空目录是同一件事的两半。
-
- 用户在网盘客户端删掉一个目录,盘上留下空壳,账本里留下一批指向不存在文件的行。
- 只清目录的话那些行继续被长跑批处理一轮轮领走、一轮轮失败——本机 647 行回收站里
- 有 469 行是这样。
- """
- source_root = Path(self.tmp.name) / "gone-source"
- kept = source_root / "kept"
- kept.mkdir(parents=True)
- (kept / "media.mp4").write_bytes(b"keep")
- con = sqlite3.connect(self.db_path)
- con.execute("UPDATE asset SET location='local',path=?,snapshot_path=NULL WHERE id=1",
- (str(source_root / "vanished" / "gone.mp4"),))
- con.execute("UPDATE asset SET location='local',path=?,snapshot_path=NULL WHERE id=2",
- (str(kept / "media.mp4"),))
- con.execute("UPDATE asset SET location='115' WHERE id=3")
- con.commit(); con.close()
-
- with mock.patch.object(web_batch, "LOCATION_ROOT_DECLARATIONS",
- {"local": (str(source_root),)}):
- checked = web_batch.w_cleanup_empty_directories(self.contract, {"dry_run": True})
- self.assertEqual(checked["vanished"], 1)
- self.assertEqual(checked["purged"], 0)
- self.assertIsNotNone(self.row(1), "检查这一步一条都不删")
-
- result = web_batch.w_cleanup_empty_directories(self.contract, {})
-
- self.assertEqual(result["purged"], 1)
- self.assertIsNone(self.row(1), "文件已经不在,这一行指不到任何东西")
- self.assertIsNotNone(self.row(2), "文件还在的行一条都不能碰")
- self.assertEqual((kept / "media.mp4").read_bytes(), b"keep")
- self.assertEqual(
- self.contract.task_runs.query(task_key="empty-folders")[0].status, "succeeded",
- "删账本行这件事要在任务中心留下记录")
-
- def test_empty_folder_scan_counts_nested_candidates_without_removing_anything(self):
- source_root = Path(self.tmp.name) / "scan-source"
- leaf = source_root / "empty" / "nested"
- leaf.mkdir(parents=True)
- kept = source_root / "kept"
- kept.mkdir()
- (kept / "media.mp4").write_bytes(b"keep")
- # 账本行也得落在这个临时来源里:装具里 `local` 的路径是 `R:\Media\...`,本机
- # 那个目录真实存在,失效条目那一步会去读它。
- (kept / "cover.jpg").write_bytes(b"keep")
- con = sqlite3.connect(self.db_path)
- con.execute("UPDATE asset SET path=? WHERE id=1", (str(kept / "media.mp4"),))
- con.execute("UPDATE asset SET path=? WHERE id=3", (str(kept / "cover.jpg"),))
- con.commit(); con.close()
- with mock.patch.object(web_batch, "LOCATION_ROOT_DECLARATIONS", {"local": (str(source_root),)}):
- result = web_batch.w_cleanup_empty_directories(self.contract, {"dry_run": True})
- self.assertEqual(result["empty"], 2)
- self.assertEqual(result["removed"], 0)
- self.assertTrue(leaf.is_dir())
- self.assertEqual((kept / "media.mp4").read_bytes(), b"keep")
-
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_source_assertion_ratchet.py b/tests/test_source_assertion_ratchet.py
index 0c8bbcc02..6c51c4693 100644
--- a/tests/test_source_assertion_ratchet.py
+++ b/tests/test_source_assertion_ratchet.py
@@ -35,7 +35,7 @@ BASELINE: dict[str, int] = {
"test_buildinfo.py": 3,
"test_cloudflared_packaging.py": 2,
"test_dependency_policy.py": 26,
- "test_desktop_settings.py": 17,
+ "test_desktop_settings.py": 12,
"test_face_detect.py": 3,
"test_fastapi_api.py": 4,
"test_follow_assets.py": 2,
@@ -53,7 +53,7 @@ BASELINE: dict[str, int] = {
"test_web_e2e.py": 2,
"test_web_js.py": 1,
"test_web_settings.py": 8,
- "test_web_ui.py": 4487,
+ "test_web_ui.py": 4464,
"test_windows_update.py": 3,
}
diff --git a/tests/test_web_resource_sync.py b/tests/test_web_resource_sync.py
index 249917fbd..c8c5ada78 100644
--- a/tests/test_web_resource_sync.py
+++ b/tests/test_web_resource_sync.py
@@ -5,6 +5,8 @@ patch 目标必须指向真正执行的模块——这批用例大量 patch `sou
`translate_ledger_path`,拆分时若仍打在 `web_contract` 上,patch 会静默失效,
测试照样「通过」到断言才炸。
"""
+import contextlib
+import json
import os
import sqlite3
import tempfile
@@ -13,16 +15,24 @@ import unittest
from pathlib import Path
from unittest import mock
+from peach import web_batch
from peach import web_contract as rm_web
from peach import web_resource_sync as rm_sync
from support.ledger import fresh_ledger
+def finish_scan(contract) -> dict:
+ """跑完一轮后台检查并交回它的公开结果;执行只认这样一轮的 `scan_id`。"""
+ rm_sync.w_resource_sync_scan(contract, {"background": True, "restart": True})
+ contract.resource_scan.thread.join(10)
+ return rm_sync.w_resource_sync_scan(contract, {"background": True, "status_only": True})
+
+
class PurgeMissingTests(unittest.TestCase):
- """按目录对账:磁盘上已删掉的,账本行一并删掉。
+ """对账:磁盘上已删掉的文件,账本行要么进回收站(按目录),要么直接删(整库)。
- 这条路径不可恢复,所以测试重点全在「什么时候**不该**删」。
+ 整库那条不可恢复,所以测试重点全在「什么时候**不该**删」。
"""
LEDGER_DIR = r"B:\creator\P"
@@ -55,6 +65,15 @@ class PurgeMissingTests(unittest.TestCase):
# 只有 001 和 a.mp4 还在盘上;002、003 当作已被手动删除。
for name in ("001.jpg", "a.mp4"):
(self.root / name).write_bytes(b"x")
+ # 检查会遍历每个在线来源的根找空文件夹:声明根不钉在临时目录里,遍历的就是
+ # 这台机器上真实的 `R:\media` 与网盘挂载。
+ self.mount = self.root / "mount"
+ self.mount.mkdir()
+ for module in (rm_sync, web_batch):
+ declared = mock.patch.object(module, "LOCATION_ROOT_DECLARATIONS",
+ {"115": (str(self.mount),)})
+ declared.start()
+ self.addCleanup(declared.stop)
def tearDown(self):
# 状态到达 complete 后,后台线程还要结算 task_run。先等线程真正退出,避免它在
@@ -67,6 +86,14 @@ class PurgeMissingTests(unittest.TestCase):
"""把账本的 Windows 路径映射到临时目录里的同名文件。"""
return self.root / str(raw).rsplit(chr(92), 1)[-1]
+ def _synced(self, online=lambda location: location == "115"):
+ """账本路径映射到临时目录;删除那一侧(`web_batch`)要跟着映射,否则它去问真实的 B:。"""
+ stack = contextlib.ExitStack()
+ stack.enter_context(mock.patch.object(rm_sync, "translate_ledger_path", self._translate))
+ stack.enter_context(mock.patch.object(rm_sync, "source_is_online", online))
+ stack.enter_context(mock.patch.object(web_batch, "translate_ledger_path", self._translate))
+ return stack
+
def _run(self, online=True):
patch_translate = mock.patch.object(
rm_sync, "translate_ledger_path", self._translate)
@@ -155,27 +182,21 @@ class PurgeMissingTests(unittest.TestCase):
self.contract.cover_root = roots["covers"]
self.contract.resource_cleanup_enabled = True
- def online(location):
- return location == "115"
- with mock.patch.object(rm_sync, "translate_ledger_path", self._translate), \
- mock.patch.object(rm_sync, "source_is_online", online):
+ with self._synced():
preview = rm_sync.w_resource_sync_scan(self.contract)
self.assertEqual(preview["missing"], 2)
self.assertEqual(preview["cache"]["files"], len(cache_files))
+ scan = finish_scan(self.contract)
result = rm_sync.w_resource_sync_apply(
- self.contract, {"confirm": True, "clean_cache": True})
+ self.contract, {"confirm": True, "clean_cache": True, "scan_id": scan["scan_id"]})
- self.assertEqual(result["moved_to_trash"], 2)
- self.assertEqual(result["cache_removed"], len(cache_files))
+ self.assertEqual(result["purged"], 2)
+ # 快照随账本行一起删(`_finish_purge`),剩下的才轮到孤儿缓存那一步。
+ self.assertEqual(result["cache_removed"], len(cache_files) - 1)
self.assertTrue(all(not path.exists() for path in cache_files))
self.assertTrue(kept.is_file(), "账本里还在的片子,它那套时间轴图不算孤儿")
self.assertTrue(evidence.is_file(), "候选证据不属于可删除缓存")
- con = sqlite3.connect(self.db_path)
- try:
- self.assertEqual(
- con.execute("SELECT count(*) FROM asset WHERE disposal='trash'").fetchone()[0], 2)
- finally:
- con.close()
+ self.assertEqual(self.ids(), [1, 4])
def test_full_sync_lists_each_directory_once_instead_of_stating_every_file(self):
real_scandir = os.scandir
@@ -185,27 +206,30 @@ class PurgeMissingTests(unittest.TestCase):
preview = rm_sync.w_resource_sync_scan(self.contract)
self.assertEqual(preview["missing"], 2)
- self.assertEqual(scandir.call_count, 1)
+ # 账本那几行同住一个目录,列一次;来源根为找空文件夹再列一次。
+ self.assertEqual(scandir.call_count, 2)
source = next(row for row in preview["sources"] if row["location"] == "115")
- self.assertEqual(source["checked"], 4)
+ self.assertEqual(source["total"], 4)
self.assertEqual(source["unreadable"], 0)
def test_sync_checks_local_and_cloud_files_in_mixed_library(self):
with self.contract.write_transaction() as connection:
connection.execute("INSERT INTO asset(id,location,path,name,medium,size) "
"VALUES(5,'local','R:\\missing.mp4','missing.mp4','video',10)")
- with mock.patch.object(rm_sync, 'LOCATION_ROOT_DECLARATIONS',
- {'local': ('R:\\',), '115': ('B:\\',)}), \
- mock.patch.object(rm_sync, 'translate_ledger_path', self._translate), \
- mock.patch.object(rm_sync, 'source_is_online', return_value=True):
+ local = self.root / "local"
+ local.mkdir()
+ declared = {'local': (str(local),), '115': (str(self.mount),)}
+ with mock.patch.object(rm_sync, 'LOCATION_ROOT_DECLARATIONS', declared), \
+ mock.patch.object(web_batch, 'LOCATION_ROOT_DECLARATIONS', declared), \
+ self._synced(online=lambda _location: True):
preview = rm_sync.w_resource_sync_scan(self.contract)
self.assertEqual([source['location'] for source in preview['sources']], ['local', '115'])
self.assertEqual(preview['missing'], 3)
- self.assertIn(5, rm_sync._recheck_resource_scan_ids(self.contract, [5]))
- result = rm_sync.w_resource_sync_apply(self.contract, {'confirm': True, 'clean_cache': False})
- self.assertEqual(result['moved_to_trash'], 3)
- with self.contract.read_connection() as connection:
- self.assertEqual(connection.execute('SELECT disposal FROM asset WHERE id=5').fetchone()[0], 'trash')
+ scan = finish_scan(self.contract)
+ result = rm_sync.w_resource_sync_apply(
+ self.contract, {'confirm': True, 'clean_cache': False, 'scan_id': scan['scan_id']})
+ self.assertEqual(result['purged'], 3)
+ self.assertEqual(self.ids(), [1, 4])
def test_local_only_configuration_has_resource_check(self):
with mock.patch.object(rm_sync, 'LOCATION_ROOT_DECLARATIONS', {'local': ('R:\\',)}):
@@ -234,15 +258,15 @@ class PurgeMissingTests(unittest.TestCase):
self.assertEqual(preview["missing"], 0)
source = next(row for row in preview["sources"] if row["location"] == "115")
- self.assertEqual(source["checked"], 0)
- self.assertEqual(source["unreadable"], 4)
+ # 账本那几行所在的目录一个,来源根一个:同一个目录只数一次。
+ self.assertEqual(source["unreadable"], 2)
+ self.assertEqual(preview["empty"], 0)
def test_background_sync_polls_then_rechecks_only_missing_candidates(self):
idle = rm_sync.w_resource_sync_scan(
self.contract, {"background": True, "status_only": True})
self.assertEqual(idle["status"], "idle")
- with mock.patch.object(rm_sync, "translate_ledger_path", self._translate), \
- mock.patch.object(rm_sync, "source_is_online", lambda loc: loc == "115"):
+ with self._synced():
started = rm_sync.w_resource_sync_scan(
self.contract, {"background": True, "restart": True})
self.assertIn(started["status"], {"running", "complete"})
@@ -262,13 +286,8 @@ class PurgeMissingTests(unittest.TestCase):
"confirm": True, "clean_cache": False, "scan_id": status["scan_id"],
})
- self.assertEqual(result["moved_to_trash"], 2)
- con = sqlite3.connect(self.db_path)
- try:
- self.assertEqual(
- con.execute("SELECT count(*) FROM asset WHERE disposal='trash'").fetchone()[0], 2)
- finally:
- con.close()
+ self.assertEqual(result["purged"], 2)
+ self.assertEqual(self.ids(), [1, 4])
def test_full_sync_keeps_a_cover_shared_by_an_active_asset(self):
covers = self.root / "covers"
@@ -362,3 +381,185 @@ class PurgeMissingTests(unittest.TestCase):
with mock.patch.object(rm_sync, "translate_ledger_path", self._translate):
rows = rm_sync.vanished_asset_rows(self.contract, "115")
self.assertEqual([int(row["id"]) for row in rows], [2, 3])
+
+
+class ResourceSyncCleanupTests(unittest.TestCase):
+ """一次检查、一次执行:失效记录、空文件夹与孤儿缓存一起清,失效记录直接永久删除。
+
+ 路径全是临时目录里的真路径,不经 `_translate`:执行那一步真的删行、删目录,
+ 删除那一侧(`web_batch`)看到的路径必须和检查那一侧是同一个。
+ """
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name).resolve()
+ self.db_path = fresh_ledger(self.root)
+ self.mount = self.root / "mount"
+ offline = self.root / "offline" # 不存在:这个来源没挂上
+ self.keep = self.mount / "keep"
+ self.keep.mkdir(parents=True)
+ (self.keep / "a.mp4").write_bytes(b"keep")
+ (self.mount / "empty" / "nested").mkdir(parents=True)
+ self.hollow = self.mount / "release" / "文宣"
+ self.hollow.mkdir(parents=True)
+ self.unreadable = self.mount / "unreadable"
+ self.unreadable.mkdir()
+ (self.unreadable / "e.mp4").write_bytes(b"keep")
+ rows = [
+ (1, "115", self.keep / "a.mp4", None),
+ (2, "115", self.mount / "gone" / "b.mp4", None),
+ (3, "115", self.keep / "c.mp4", "trash"),
+ (4, "pikpak", offline / "d.mp4", None),
+ # 所在目录的枚举会报找不到,逐条问一次它却在:不能按枚举判它没了。
+ (5, "115", self.unreadable / "e.mp4", None),
+ ]
+ con = sqlite3.connect(self.db_path)
+ con.executemany(
+ "INSERT INTO asset(id,location,path,name,medium,size,disposal) "
+ "VALUES(?,?,?,?,'video',10,?)",
+ [(asset_id, location, str(path), path.name, disposal)
+ for asset_id, location, path, disposal in rows])
+ con.commit()
+ con.close()
+ self.contract = rm_web.WebContract(Path(self.db_path))
+ posters = self.root / "posters"
+ posters.mkdir()
+ self.orphan_poster = posters / "2_1.jpg"
+ self.live_poster = posters / "1_1.jpg"
+ for poster in (self.orphan_poster, self.live_poster):
+ poster.write_bytes(b"poster")
+ self.contract.poster_root = posters
+ self.contract.resource_cleanup_enabled = True
+ declared = {"115": (str(self.mount),), "pikpak": (str(offline),)}
+ for module in (rm_sync, web_batch):
+ patcher = mock.patch.object(module, "LOCATION_ROOT_DECLARATIONS", declared)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def tearDown(self):
+ self.contract.resource_scan.stop()
+ self.contract.resource_apply_job.stop()
+ self.tmp.cleanup()
+
+ def ids(self):
+ with self.contract.read_connection() as connection:
+ return [row[0] for row in connection.execute("SELECT id FROM asset ORDER BY id")]
+
+ def clouddrive(self):
+ """CloudDrive 的两种目录:空的那个列不出 `.` 与 `..`;有东西的那个这一轮读不了。
+
+ 两个都让 `scandir` 报找不到;`listdir` 给空列表的才算空文件夹。
+ """
+ failing = {os.path.normcase(os.fspath(path)) for path in (self.hollow, self.unreadable)}
+ real_scandir = os.scandir
+
+ def mount_scandir(path="."):
+ if os.path.normcase(os.fspath(path)) in failing:
+ raise FileNotFoundError(2, "系统找不到指定的文件。", os.fspath(path))
+ return real_scandir(path)
+ return mock.patch.object(os, "scandir", mount_scandir)
+
+ def apply(self, scan, **body):
+ return rm_sync.w_resource_sync_apply(
+ self.contract, {"confirm": True, "scan_id": scan["scan_id"], **body})
+
+ def test_check_reports_each_source_and_changes_nothing(self):
+ with self.clouddrive():
+ scan = finish_scan(self.contract)
+
+ self.assertEqual(scan["status"], "complete")
+ sources = {source["location"]: source for source in scan["sources"]}
+ cloud = sources["115"]
+ # 空文件夹:empty、empty/nested、release/文宣,以及只装着它的 release。
+ self.assertEqual((cloud["missing"], cloud["empty"], cloud["unreadable"]), (2, 4, 1))
+ self.assertEqual((scan["missing"], scan["empty"], scan["unreadable"]), (2, 4, 1))
+ self.assertFalse(sources["pikpak"]["online"])
+ self.assertEqual((sources["pikpak"]["missing"], sources["pikpak"]["total"]), (0, 1))
+ self.assertEqual(scan["cache"]["files"], 1)
+ self.assertEqual(self.ids(), [1, 2, 3, 4, 5], "检查只报数不删")
+ self.assertTrue(self.hollow.is_dir())
+ self.assertTrue((self.mount / "empty" / "nested").is_dir())
+ self.assertTrue(self.orphan_poster.is_file())
+ self.assertNotIn("mount", json.dumps(scan, ensure_ascii=False), "物理路径不出服务端")
+
+ def test_apply_purges_vanished_rows_empty_folders_and_orphan_caches(self):
+ with self.clouddrive():
+ scan = finish_scan(self.contract)
+ rm_sync.w_resource_sync_apply(self.contract, {
+ "confirm": True, "background": True, "scan_id": scan["scan_id"]})
+ self.contract.resource_apply_job.thread.join(10)
+ result = self.contract.resource_apply_job.snapshot()
+
+ self.assertEqual(result["status"], "complete")
+ self.assertEqual((result["purged"], result["blocked"]), (2, []))
+ self.assertEqual((result["dirs_removed"], result["dir_errors"]), (4, 0))
+ self.assertEqual((result["cache_removed"], result["unreadable"]), (1, 1))
+ # 在库的 2 与回收站里的 3 都删;文件还在的 1、5 和离线来源上的 4 一条不碰。
+ self.assertEqual(self.ids(), [1, 4, 5])
+ self.assertEqual((self.keep / "a.mp4").read_bytes(), b"keep")
+ self.assertEqual((self.unreadable / "e.mp4").read_bytes(), b"keep")
+ self.assertFalse((self.mount / "empty").exists())
+ self.assertFalse((self.mount / "release").exists())
+ self.assertTrue(self.mount.is_dir(), "声明的来源根绝不删")
+ self.assertFalse(self.orphan_poster.exists())
+ self.assertTrue(self.live_poster.is_file())
+ run = self.contract.task_runs.query(task_key="resource-apply")[0]
+ self.assertEqual(run.status, "succeeded", "删账本行这件事要在任务中心留下记录")
+ self.assertEqual((run.result_summary["purged"], run.result_summary["dirs_removed"],
+ run.result_summary["cache_removed"]), (2, 4, 1))
+
+ def test_a_file_back_on_disk_since_the_check_keeps_its_row(self):
+ scan = finish_scan(self.contract)
+ (self.mount / "gone").mkdir()
+ (self.mount / "gone" / "b.mp4").write_bytes(b"back")
+
+ result = self.apply(scan)
+
+ self.assertEqual(result["purged"], 1)
+ self.assertEqual(self.ids(), [1, 2, 4, 5])
+ self.assertEqual((self.mount / "gone" / "b.mp4").read_bytes(), b"back")
+
+ def test_purge_never_deletes_a_file_that_answers_present_at_the_last_moment(self):
+ """复核之后、删除之前文件回来了:删除那一步自己再问一次,只进 `blocked`。"""
+ scan = finish_scan(self.contract)
+ (self.mount / "gone").mkdir()
+ (self.mount / "gone" / "b.mp4").write_bytes(b"back")
+
+ with mock.patch.object(rm_sync, "_confirm_vanished", side_effect=list):
+ result = self.apply(scan)
+
+ self.assertEqual(result["purged"], 1)
+ self.assertEqual(result["blocked"], [{"id": 2, "name": "b.mp4", "reason": "文件仍在盘上"}])
+ self.assertEqual((self.mount / "gone" / "b.mp4").read_bytes(), b"back")
+ self.assertIn(2, self.ids())
+
+ def test_a_source_that_went_offline_after_the_check_is_left_alone(self):
+ scan = finish_scan(self.contract)
+ with mock.patch.object(rm_sync, "source_is_online", return_value=False):
+ result = self.apply(scan)
+
+ self.assertEqual((result["purged"], result["dirs_removed"]), (0, 0))
+ self.assertEqual(self.ids(), [1, 2, 3, 4, 5])
+ self.assertTrue((self.mount / "empty" / "nested").is_dir())
+
+ def test_apply_only_accepts_the_latest_completed_check(self):
+ with self.assertRaisesRegex(ValueError, "expired"):
+ rm_sync.w_resource_sync_apply(self.contract, {"confirm": True})
+ old = finish_scan(self.contract)
+ new = finish_scan(self.contract)
+ self.assertNotEqual(old["scan_id"], new["scan_id"])
+ for body in ({"confirm": True}, {"confirm": True, "scan_id": old["scan_id"]},
+ {"confirm": True, "scan_id": old["scan_id"], "background": True}):
+ with self.assertRaisesRegex(ValueError, "expired"):
+ rm_sync.w_resource_sync_apply(self.contract, body)
+ with self.assertRaisesRegex(ValueError, "confirmation"):
+ rm_sync.w_resource_sync_apply(self.contract, {"scan_id": new["scan_id"]})
+ self.assertIsNone(self.contract.resource_apply_job.snapshot(), "过期的检查不开执行任务")
+ self.assertEqual(self.ids(), [1, 2, 3, 4, 5])
+
+ def test_apply_is_gated_as_a_ledger_write_and_check_stays_read_only(self):
+ self.assertIs(rm_web.POST_HANDLERS["/api/resource-sync/apply"], rm_sync.w_resource_sync_apply)
+ self.assertNotIn("/api/resource-sync/apply", rm_web.READ_ONLY_POST_ROUTES,
+ "它永久删除账本行,只读端那份复制来的账本不能被它清掉")
+ self.assertIn("/api/resource-sync/scan", rm_web.READ_ONLY_POST_ROUTES)
+ self.assertNotIn("/api/data-cleanup/empty-folders", rm_web.POST_HANDLERS)
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index db46194d4..f14d970f5 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -3154,12 +3154,11 @@ class WebUiSourceTests(unittest.TestCase):
'.entitycollectionhead[aria-busy="true"] .entitybatch svg{\n'
" --strand-dash:100;--strand-cycle:2.2s}")
- def test_data_page_scan_buttons_animate_their_own_glyphs_while_busy(self):
- """「扫一遍」的两枚键各自适配忙态,不统一转圈。
+ def test_data_page_scan_button_animates_its_own_glyph_while_busy(self):
+ """「检查文件」键适配自己的忙态,不统一转圈。
- 检查文件的 git-compare 照 lucide-animated 的 GitCompare 逐笔描画(右下圆→两条
- 枝→左上圆,画完停住再一起淡出);扫描空文件夹的 scan-search 四角按对角两拍
- 轮流亮,放大镜保持不动。动效只能挂在 symbol 自己的零件上:`<use>` 的影子树
+ git-compare 照 lucide-animated 的 GitCompare 逐笔描画(右下圆→两条枝→左上圆,
+ 画完停住再一起淡出)。动效只能挂在 symbol 自己的零件上:`<use>` 的影子树
里选不到外层的忙态标记,继承的自定义属性进得去,所以忙态把动画名和周期传
下去,空闲时名字是 none。这些标注上游不会带,补丁必须住在 vendor 脚本里,
否则换版本一刷新就被抹掉。
@@ -3170,20 +3169,11 @@ class WebUiSourceTests(unittest.TestCase):
'<path class="gc-part gc-line-a" pathLength="100" d="M13 6h3a2 2 0 0 1 2 2v7"/>')
self.assertPageContains(
'<circle class="gc-part gc-end-b" pathLength="100" cx="6" cy="6" r="3"/>')
- self.assertPageContains(
- '<path class="scan-corner scan-corner-a" d="M3 7V5a2 2 0 0 1 2-2h2"/>')
- self.assertPageContains(
- '<path class="scan-corner scan-corner-b" d="M17 3h2a2 2 0 0 1 2 2v2"/>')
self.assertPageContains(
"@keyframes peach-gc-draw-a{\n"
" 0%{stroke-dashoffset:100;opacity:1}\n"
" 17%,86%{stroke-dashoffset:0;opacity:1}\n"
" 100%{stroke-dashoffset:0;opacity:0}}")
- self.assertPageContains(
- "@keyframes peach-scan-corner-a{\n"
- " 0%,40%{opacity:1}\n"
- " 50%,90%{opacity:.25}\n"
- " 100%{opacity:1}}")
self.assertPageContains(
"#i-git-compare .gc-part{stroke-dasharray:var(--gc-dash,none);\n"
" animation-name:var(--gc-anim,none);animation-duration:var(--gc-cycle,1.8s);\n"
@@ -3193,26 +3183,20 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains(
"#i-git-compare .gc-end-b{animation-name:var(--gc-anim-c,none)}")
self.assertPageContains(
- "#i-scan-search .scan-corner{animation-name:var(--scan-anim,none);\n"
- " animation-duration:var(--scan-cycle,1.2s);animation-timing-function:ease-in-out;animation-iteration-count:infinite}")
- self.assertPageContains(
- '#resourceScan[aria-busy="true"] svg,[data-cleanup-empty-scan][aria-busy="true"] svg{\n'
- " --gc-dash:100;--gc-anim:peach-gc-draw-a;--gc-anim-b:peach-gc-draw-b;--gc-anim-c:peach-gc-draw-c;\n"
- " --scan-anim:peach-scan-corner-a;--scan-anim-b:peach-scan-corner-b}")
+ '#resourceScan[aria-busy="true"] svg{\n'
+ " --gc-dash:100;--gc-anim:peach-gc-draw-a;--gc-anim-b:peach-gc-draw-b;--gc-anim-c:peach-gc-draw-c}")
vendor = (Path(__file__).resolve().parents[1] / "scripts/vendor_web_dependencies.mjs").read_text(encoding="utf-8")
self.assertIn('if (symbol === "git-compare") inner = inner', vendor)
- self.assertIn('if (symbol === "scan-search") inner = inner', vendor)
def test_resource_sync_sources_share_the_official_marks_and_board_stat_cards(self):
"""数据管理页「这是哪个网盘」的答案只有一份,结果照 Board 的 stat cards 排。
115 与 PikPak 取 `MEDIA_SOURCE_ICONS` 的官方站标,不是 globe 字形:来源角标、
媒体库切换器和配置页问的是同一件事,同一个答案不该因为取图入口不同而长成
- 两枚图形(SRCICON 的注释)。结果读数和数据管理顶上一排同一副卡片,三个来源
- 带站标 tile,缓存与回收站两张读数凑成同一行;清理内容 Note 与操作行独立成层。
- 空文件夹卡片的来源行取同一份站标,扫描结果与失败都落在 Note 里。操作键统一
- Board primary,销毁键维持 danger 实底红;顶栏密度键与筛选框的版式开关问同一
- 件事「现在是哪种排法」,字形取同一份 PHOTO_SIZES 映射,按下去换成当前状态的图标。
+ 两枚图形(SRCICON 的注释)。结果读数和数据管理顶上一排同一副卡片,来源带站标
+ tile;清理内容 Note 与操作行独立成层。操作键统一 Board primary,销毁键维持
+ danger 实底红;顶栏密度键与筛选框的版式开关问同一件事「现在是哪种排法」,
+ 字形取同一份 PHOTO_SIZES 映射,按下去换成当前状态的图标。
"""
renderer = (Path(__file__).resolve().parents[1] / "frontend/src/resource-sync.ts").read_text(encoding="utf-8")
board = (Path(__file__).resolve().parents[1] / "web/board.css").read_text(encoding="utf-8")
@@ -3226,17 +3210,6 @@ class WebUiSourceTests(unittest.TestCase):
# 扫描中的环形进度独居在结果槽里,自己带框才和链接检查里住在面板中的进度一个形状。
self.assertPageContains(
"#resourceSyncResult>.board-job-progress{margin:0;padding:14px 16px;border:1px solid var(--line-soft);border-radius:var(--control-radius)}")
- # 空文件夹来源行取同一份站标;扫描结果与失败提示是 Note,不是裸文本。
- self.assertPageContains(
- 'const sourceBadge=source=>`<span class="cleanupsourcemark">'
- "${selectOptionIconHtml(MEDIA_SOURCE_ICONS[source.location]||'database')}"
- '${sourceName(source)}</span>`;')
- self.assertIn(".cleanupsourcemark{display:inline-flex;align-items:center;gap:6px}", board)
- self.assertPageContains("status.innerHTML=noteHtml(`已检查 ${Number(result.scanned||0).toLocaleString()} 个目录,发现 ${Number(result.empty||0).toLocaleString()} 个空文件夹")
- self.assertPageContains("status.innerHTML=noteHtml(error.message,{variant:'error',label:'扫描失败'})")
- # 检查结果 Note 留在说明列里、保留自己的圆角,状态容器也得是能装 Note 的块级元素。
- self.assertPageContains('<div class="cleanupstate" aria-live="polite"></div>')
- self.assertIn(".cleanupgrid>.cleanupemptyfolders .cleanupstate .geist-note{margin:12px 0 0}", board)
# 操作键统一 Board primary;销毁键另有一副实底红,不掺进来。
for needle in (
'id="linkCheck">',
@@ -3244,8 +3217,6 @@ class WebUiSourceTests(unittest.TestCase):
'id="linkRetryAll">',
'id="resourceScan">'):
self.assertIn(f'class="resourceaction primary" type="button" {needle}', self.app_js)
- self.assertIn('class="geist-button primary" data-cleanup-empty-scan', self.app_js)
- self.assertIn('class="danger" data-cleanup-empty hidden', self.app_js)
# 顶栏密度键跟筛选框的版式开关取同一份字形映射。
self.assertPageContains("button.innerHTML=iconSwapHtml(big[2],small[2],")
self.assertPageContains("}else setIconSwap(button,size===small[0]?'b':'a');")
@@ -4928,7 +4899,7 @@ class WebUiSourceTests(unittest.TestCase):
def test_manage_menu_only_offers_pages_that_are_not_inside_data_management(self):
"""人工复核、回收站、高清版都从数据管理进,管理菜单里不再各占一行。
- 它们和垃圾文件、重复文件、空文件夹是同一件事的不同步骤。身份注册表仍然
+ 它们和垃圾文件、重复文件、失效条目是同一件事的不同步骤。身份注册表仍然
保留全部页面:URL 要能直达,用户也仍可把其中任何一个钉到顶层侧栏。
活动页是菜单里的例外:它横跨扫描、追更、批量这几页,从其中任何一页进都会
@@ -5123,7 +5094,7 @@ class WebUiSourceTests(unittest.TestCase):
vercel.com/geist/breadcrumbs 实测语义:nav[aria-label=Breadcrumb] > ol > li,
当前项 aria-current="true" 渲染纯文本,上一级是 /data-cleanup 的链接;
分隔符是每项自带的 chevron,最后一项由 CSS 隐藏。人工复核、回收站、
- 高清版在侧栏保留直达入口,但层级上仍从数据管理进;空文件夹是 hub 上的
+ 高清版在侧栏保留直达入口,但层级上仍从数据管理进;资源同步是 hub 上的
就地操作,没有独立页面,不在此列。
"""
self.assertPageContains(
@@ -8913,7 +8884,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("const target=ROUTES.find(spec=>spec.section===section);")
self.assertPageContains("async function openDuplicates(push=true)")
- def test_data_cleanup_groups_junk_duplicates_and_empty_folders_in_fieldsets(self):
+ def test_data_cleanup_groups_junk_duplicates_and_resource_sync_in_fieldsets(self):
self.assertPageContains("async function openDataCleanup(push=true)")
self.assertPageContains("route('/data-cleanup')")
self.assertPageContains("${(sources.sources||[]).some(source=>['local','115','pikpak'].includes(source.location)&&source.roots?.length)?resourceSyncMarkup():''}")
@@ -8924,15 +8895,10 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains(path)
# 标题是正文区的第一行,不用原生 legend——legend 会在上边框上开个缺口,
# 卡片内容高度不同时那道缺口的位置也跟着不齐。垃圾文件与重复文件是顶上一排的读数卡。
- self.assertPageContains("fieldsetTitle('cleanupEmptyTitle','空文件夹与失效条目')")
self.assertPageContains("junk:statCard('垃圾文件','file-archive',")
self.assertPageContains("duplicates:statCard('重复文件','file-stack',")
self.assertPageLacks("<legend>垃圾文件</legend>")
- self.assertPageContains('class="cleanupfieldset cleanupemptyfolders" data-geist-fieldset data-cleanup-task')
- self.assertPageContains("api('/api/data-cleanup/empty-folders',{method:'POST',body:'{}'})")
- self.assertPageContains("保留来源根目录")
- # 这一屏会删账本行,检查那一步就得把条数写在脸上,确认框里也要说清不可撤销。
- self.assertPageContains("条文件已不在盘上的记录")
+ # 资源同步会永久删账本行,确认框里要说清不可撤销。
self.assertPageContains("这一步不可撤销")
self.assertPageContains(".cleanupfieldset>.geist-fieldset-content{flex:1;min-height:0;padding:20px}")
# Geist 的 Fieldset 全框只有一条线,在底部操作条上方;标题底下不划线。
@@ -9000,12 +8966,6 @@ class WebUiSourceTests(unittest.TestCase):
self.assertIn("`其余 ${rest.toLocaleString()}`", counts)
self.assertIn("`占用 ${fmtSize(data.bytes||0)}`", counts, "回收站要说清空能腾出多少")
self.assertPageContains(".cleanupmeta:empty{display:none}")
- # 三个「· 在线」徽章换成一行来源名:在线与否是资源同步那块的读数,
- # 在空文件夹卡上只有离线时才改变结论。来源行带官方站标,离线的归到同一枚标记后。
- self.assertPageLacks("class=\"cleanupsource\"")
- self.assertPageLacks(".cleanupsources{")
- self.assertIn("offline.length?`${offline.map(sourceBadge).join('')}<span class=\"cleanupsourcemark cleanupsourcelost\">离线</span>`", cleanup)
- self.assertIn("<strong>${online.length.toLocaleString()} 个来源可扫描</strong>", cleanup)
# 单列布局里高度由内容决定,和同页「网盘与账本」一致;三列时的对齐地板
# 到了单列只剩下把每张卡撑出一段空白。
self.assertPageLacks("min-height:176px")
@@ -10222,7 +10182,7 @@ class WebUiSourceTests(unittest.TestCase):
读数卡是 stat-cards.tsx 的 plain 变体做成按钮(132px、圆角 16、secondary 底、内边距 16、
32px 图标格里 20px 字形、读数 24/34),整张卡就是那一页的入口;五张在 1120 内一行摆下,
- 窄了折两列、再折一列。扫描与采集、媒体修复和空文件夹是要做的事,不是读数,各占一整行、左说明右按钮;
+ 窄了折两列、再折一列。扫描与采集、媒体修复和整理是要做的事,不是读数,各占一整行;
下方每张任务卡同样用 secondary 灰底,浅色主题不会退回白卡。
骨架复用同一套结构,页首因此和读数卡直接接上:同样五个入口再排一条链接条,是同一件事
画两遍,而那条链接条连选中态都没有。
@@ -10232,7 +10192,7 @@ 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.mediaRepair}${cleanupCards.empty}'
+ self.assertPageContains('</div><div class="cleanupgrid">${cleanupCards.scraping}${cleanupCards.mediaRepair}'
'${organizeCardMarkup(organizeState)}</div>')
# 样式也一起走:没有使用者的选择器留在 board.css 里,下一个人会当它是现役版式去改。
self.assertNotIn("cleanup-workspace-switch",
@@ -10248,16 +10208,15 @@ class WebUiSourceTests(unittest.TestCase):
self.assertIn(".board-plain-stat>.cleanupmeta{display:block;min-height:16px;margin:0;font:var(--board-caption);color:var(--color-text-tertiary);", board)
self.assertIn("@media(max-width:1119px){.cleanupstats{grid-template-columns:repeat(2,minmax(0,1fr))}}", board)
self.assertIn("@media(max-width:559px){.cleanupstats{grid-template-columns:minmax(0,1fr)}}", board)
- self.assertIn(".cleanupgrid :is(.cleanupemptyfolders,[data-cleanup-processing]){display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}", board)
+ self.assertIn(".cleanupgrid [data-cleanup-processing]{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}", board)
self.assertIn(".cleanupgrid [data-cleanup-task],.resourcesyncbox[data-cleanup-task]{border:1px solid var(--color-separator-border);border-radius:16px;background:var(--color-background-secondary-default);", board)
self.assertIn(".resourcesyncbox[data-cleanup-task]{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}", board)
self.assertIn(".resourcesyncbox[data-cleanup-task]>.resourcesyncfooter{align-self:stretch;justify-content:flex-end;min-height:0;padding:24px;border:0;background:none}", board)
self.assertGreaterEqual(self.app_js.count('class="resourcesyncbox" data-geist-fieldset data-cleanup-task'), 2)
skeleton = (root / "frontend/src/management.ts").read_text(encoding="utf-8")
self.assertIn('<div class="cleanupstats">${stats.map(([title, glyph]) => `', skeleton)
- self.assertIn('<section class="cleanupfieldset cleanupemptyfolders" data-geist-fieldset data-cleanup-task aria-labelledby="cleanup-loading-empty">', skeleton)
- self.assertEqual(skeleton.count("data-cleanup-task"), 6,
- "数据管理骨架要同步画出四张任务卡和两块 BoardUI 操作区")
+ self.assertEqual(skeleton.count("data-cleanup-task"), 5,
+ "数据管理骨架要同步画出三张任务卡和两块 BoardUI 操作区")
def test_the_shorts_band_is_told_apart_by_its_fill_not_a_line(self):
"""竖屏带靠底色和网格区分,不描一圈线。
@@ -12273,7 +12232,7 @@ class WebUiSourceTests(unittest.TestCase):
# 上一轮跑完的结果是那一刻的快照。进页面就铺开会被读成现在的账本状态,
# 而页面上没有任何东西说它是旧的。
self.assertPageContains("if(existing.status==='running')void followScan(existing)")
- self.assertPageContains("清理失效记录与缓存")
+ self.assertPageContains("清理失效条目")
self.assertPageContains('class="resourcesyncfooter geist-fieldset-footer"')
self.assertPageContains('class="resourcepanel"')
self.assertPageContains('class="resourceapplyrow"')
diff --git a/web/app.js b/web/app.js
index 3a425cb83..a8c2678b9 100644
--- a/web/app.js
+++ b/web/app.js
@@ -18,7 +18,7 @@ import { mountIsland, unmountIsland, islandMounted, paginationHtml, pageCount, c
import { catalogSuggestions, catalogEmptyHtml, emptyCatalogLayout, syncSidebarSurface, sidebarTagCounts, sidebarHasCatalogContent, cleanupSkeletonHtml, scanCardSkeletonHtml, repairCardSkeletonHtml, cloudLocations, cloudPreferenceLocations } from './dist/peach-ui.js';
import { javImageKind, normalizeJavImage, normalizeJavLayout, normalizeJavPreferences, panelFrame, syncJavImages, nativeImageFit, faceSourceScale, entitySkeletonHtml } from './dist/peach-ui.js';
import {
- attachOverlayScrollbar, breadcrumbHtml, checkboxHtml, collectionSummaryHtml, closeAnchoredMenu, confirmModal, dialSliderHtml, dismissMenu, emptyStateHtml, fieldsetTitle, selectOptionIconHtml,
+ attachOverlayScrollbar, breadcrumbHtml, checkboxHtml, collectionSummaryHtml, closeAnchoredMenu, confirmModal, dialSliderHtml, dismissMenu, emptyStateHtml, fieldsetTitle,
fillSkeletonTier, fitSkeleton, formModal, iconSwapHtml, iconSwitchHtml, indexSkeletonHtml, loadingDotsHtml,
dissolveValue, popBadges, popCount, revealSkeleton, revealTexts, setIconSwap, swapText,
mediaViewButtonsHtml, boardTabsHtml, mountFilterFrame, filterChipHtml, moveGlidePane, glideEase, sortControlsHtml, collectionHeaderHtml, wireHorizontalScroller, noteHtml, presentMenu, gaugeHtml, scrollerHtml, searchInputHtml, selectFieldHtml,
@@ -5172,7 +5172,7 @@ function resourceSyncMarkup(){
<h2 id="resourceSyncTitle">资源同步</h2>
<div class="resourcesyncbox" data-geist-fieldset data-cleanup-task>
<div class="resourcesyncbody geist-fieldset-content">${fieldsetTitle('resourceBoxTitle','文件与记录核对')}
- <p>按馆藏记录逐条查找本地磁盘与网盘上的文件,列出文件已不存在的记录,以及不再被引用的缓存。</p></div>
+ <p>按馆藏记录逐条查找本地磁盘与网盘上的文件,列出文件已不存在的记录、空文件夹,以及不再被引用的缓存。</p></div>
<div class="resourcesyncfooter geist-fieldset-footer" data-geist-fieldset-footer>
<button class="resourceaction primary" type="button" id="resourceScan">${iconSwapHtml('git-compare','rotate-cw')}<span data-scan-label>检查文件</span></button></div></div>
<div id="resourceSyncResult" aria-live="polite"></div></section>`;
@@ -5192,17 +5192,19 @@ async function wireResourceSync(){
const cache=payload.cache||{files:0,bytes:0};
result.innerHTML=resourceScanHtml(payload,fmtSize);
$('#resourceApply')?.addEventListener('click',async event=>{
- const button=event.currentTarget;
- return confirmModal({title:'清理失效记录与缓存',body:`将把找不到文件的 ${payload.missing||0} 项馆藏记录移入回收站,并清理 ${cache.files||0} 个闲置缓存。记录可从回收站还原。`,confirmLabel:'清理失效记录与缓存',danger:false,onConfirm:async()=>{
+ const button=event.currentTarget,count=value=>Number(value||0).toLocaleString();
+ /* 文件已不在盘上的记录直接删,不进回收站,也就没有撤销:确认框用危险档,正文把
+ 「不可撤销」写明。执行那一步只认这次检查的候选,逐条复核后再删。 */
+ return confirmModal({title:'清理失效条目',body:`将永久删除文件已不在盘上的 ${count(payload.missing)} 条记录(含回收站里的)、${count(payload.empty)} 个空文件夹,并清理 ${count(cache.files)} 个闲置缓存。来源根目录保留。这一步不可撤销。`,confirmLabel:'清理失效条目',danger:true,onConfirm:async()=>{
setActionBusy(button);
- button.innerHTML=`${spinnerHtml('正在清理')}<span>正在检查并清理…</span>`;
+ button.innerHTML=`${spinnerHtml('正在清理')}<span>正在复核并清理…</span>`;
try{
const applied=await api('/api/resource-sync/apply',{method:'POST',body:JSON.stringify({confirm:true,clean_cache:true,scan_id:payload.scan_id||'',background:true})});
sessionStorage.setItem('peach-resource-apply-job',applied.job_id);
if(active())void wireResourceApplyProgress();
}catch(error){
setActionBusy(button,false);
- button.textContent='清理失效记录与缓存';
+ button.textContent='清理失效条目';
if(active())void wireResourceApplyProgress();throw error}
}});
});
@@ -5235,11 +5237,22 @@ async function wireResourceSync(){
void wireResourceApplyProgress();
}
function wireResourceApplyProgress(){
- return wireOperationProgress({host:$('#resource-sync'),path:'/api/resource-sync/apply',key:'peach-resource-apply-job',title:'正在检查文件并清理…',
- busy:running=>{const button=$('#resourceApply');if(button){setActionBusy(button,running);if(!running)button.textContent='清理失效记录与缓存'}},
- complete:out=>{const failed=out.cache_blocked||[];
- $('#resourceSyncResult').innerHTML=noteHtml(`已把 ${out.moved_to_trash} 项记录移入回收站,清理 ${out.cache_removed} 个缓存,释放 ${fmtSize(out.bytes_reclaimed||0)}。${failed.length?`${failed.length} 个缓存未能清理,请重新检查后重试。`:''}`,{label:failed.length?'部分完成':'清理结果',variant:failed.length?'warning':'success'});
- if(!failed.length)actionReceipt('已清理失效记录与缓存')}});
+ return wireOperationProgress({host:$('#resource-sync'),path:'/api/resource-sync/apply',key:'peach-resource-apply-job',title:'正在复核并清理失效条目…',
+ busy:running=>{const button=$('#resourceApply');if(button){setActionBusy(button,running);if(!running)button.textContent='清理失效条目'}},
+ /* 没删的几样是这一轮留下的:文件其实还在、目录这会儿读不了、缓存正被占用。能删的
+ 已经删了,所以报警告档、写完成与没处理的数目,不说清理失败。 */
+ complete:out=>{const count=value=>Number(value||0).toLocaleString();
+ const blocked=out.blocked||[],cacheBlocked=out.cache_blocked||[],dirErrors=Number(out.dir_errors||0);
+ const done=Number(out.purged||0)+Number(out.dirs_removed||0)+Number(out.cache_removed||0);
+ const left=blocked.length+dirErrors+cacheBlocked.length;
+ const names=blocked.slice(0,3).map(item=>`「${item.name}」`).join('、')+(blocked.length>3?' 等':'');
+ const rest=[blocked.length?`${count(blocked.length)} 条记录没有删除(${names})`:'',
+ dirErrors?`${count(dirErrors)} 个文件夹没有删除`:'',
+ cacheBlocked.length?`${count(cacheBlocked.length)} 个缓存没有清理`:''].filter(Boolean).join(',');
+ const summary=`已永久删除 ${count(out.purged)} 条失效记录和 ${count(out.dirs_removed)} 个空文件夹,清理 ${count(out.cache_removed)} 个缓存,释放 ${fmtSize(out.bytes_reclaimed||0)}。`;
+ $('#resourceSyncResult').innerHTML=noteHtml(rest?`${summary}${rest},重新检查后可再试。`:summary,{label:rest?'部分完成':'清理结果',variant:rest?'warning':'success'});
+ if(left)toast({text:`已完成 ${count(done)} 项,${count(left)} 项没有处理`},{sound:'warning'});
+ else actionReceipt('已清理失效条目')}});
}
/* 旧直达 URL 仍然可用,落点跟着面板一起搬到数据管理。 */
async function openResourceSync(push=true){
@@ -5475,7 +5488,7 @@ async function openPlaylists(push=true){
window.scrollTo({top:0,behavior:'smooth'});
}
-/* 数据管理是「库里已经有的东西怎么收拾」的唯一入口:广告、重复、空目录,
+/* 数据管理是「库里已经有的东西怎么收拾」的唯一入口:广告、重复、失效条目,
加上复核队列、回收站和高清版。它们此前散在管理菜单和统计页两处,
统计页因此还挂着两块跟统计无关的面板。 */
const DATA_MANAGEMENT_ENTRIES=[
@@ -5485,7 +5498,7 @@ const DATA_MANAGEMENT_ENTRIES=[
];
/* 这一页照 Board 的 dashboard 模板排:顶上一排是读数卡(stat-cards.tsx 的 plain 变体),五张按一条
内容在库里的经过排——先把它说清楚(人工复核、高清版),再把不该留的挑出去(重复文件、垃圾文件),
- 最后是删掉的东西还在哪儿(回收站)。扫描与采集和空文件夹是两件要在这页上做的事,不是读数,
+ 最后是删掉的东西还在哪儿(回收站)。扫描与采集、媒体修复和整理是要在这页上做的事,不是读数,
各占一整行放在读数下面。 */
const DATA_MANAGEMENT_STATS=['review','quality','duplicates','junk','trash'];
@@ -5653,15 +5666,6 @@ async function openDataCleanup(push=true){
]);
if(!surfaceCurrent(surface))return;
paintManageLede();
- /* 三个「· 在线」徽章换成一行来源名:卡片要说的是这次会扫哪几个来源,
- 来源在线与否是资源同步那一块的读数,在这里只有离线时才改变结论。 */
- const scanSources=(sources.sources||[]).filter(source=>['local','115','pikpak'].includes(source.location));
- const sourceName=source=>esc(LOC[source.location]||source.location);
- const online=scanSources.filter(source=>source.online),offline=scanSources.filter(source=>!source.online);
- /* 来源行的站标和资源同步结果面板同一份(MEDIA_SOURCE_ICONS);离线的归到同一枚标记后。 */
- const sourceBadge=source=>`<span class="cleanupsourcemark">${selectOptionIconHtml(MEDIA_SOURCE_ICONS[source.location]||'database')}${sourceName(source)}</span>`;
- const sourceLine=[online.map(sourceBadge).join(''),
- offline.length?`${offline.map(sourceBadge).join('')}<span class="cleanupsourcemark cleanupsourcelost">离线</span>`:''].filter(Boolean).join('');
const junkCounts=junk.counts||{};
const junkBreakdown=[...JUNK_KIND_OPTIONS.filter(([key])=>key&&Number(junkCounts[key])>0)
.map(([key,label])=>`${esc(label)} ${Number(junkCounts[key]).toLocaleString()}`),
@@ -5686,12 +5690,6 @@ async function openDataCleanup(push=true){
?`${Number(duplicates.total).toLocaleString()} 组 · ${Number(duplicates.files||0).toLocaleString()} 个文件`
:'没有重复内容'}</strong>
<span class="cleanupmeta">${Number(duplicates.total||0)?`可回收 ${fmtSize(duplicates.reclaimable||0)}`:''}</span>`,'data-cleanup-open="duplicates"'),
- empty:`<section class="cleanupfieldset cleanupemptyfolders" data-geist-fieldset data-cleanup-task aria-labelledby="cleanupEmptyTitle">
- <div class="geist-fieldset-content">${fieldsetTitle('cleanupEmptyTitle','空文件夹与失效条目')}
- <strong>${online.length.toLocaleString()} 个来源可扫描</strong>
- <p class="cleanupmeta">${sourceLine}</p><div class="cleanupstate" aria-live="polite"></div></div>
- <footer class="geist-fieldset-footer" data-geist-fieldset-footer><button type="button" class="geist-button primary" data-cleanup-empty-scan ${online.length?'':'disabled'}>${icon('scan-search')}<span>检查来源</span></button><button type="button" class="danger" data-cleanup-empty hidden>${icon('trash')}<span>清理</span></button></footer>
- </section>`,
/* 媒体修复是一轮几十分钟起步的长任务,要确认、要看进度,所以和扫描与采集排在同一列
(ADR-0050)。卡片由 island 画,这里是它取数期间的那一版,与首屏骨架同一张。 */
mediaRepair:`<div class="cleanupmediarepair" id="mediaRepair">${repairCardSkeletonHtml()}</div>`,
@@ -5699,7 +5697,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.mediaRepair}${cleanupCards.empty}${organizeCardMarkup(organizeState)}</div>
+ </div><div class="cleanupgrid">${cleanupCards.scraping}${cleanupCards.mediaRepair}${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');
@@ -5715,33 +5713,6 @@ async function openDataCleanup(push=true){
$('#stats').querySelectorAll('[data-cleanup-go]').forEach(button=>
button.onclick=()=>openManage(button.dataset.cleanupGo));
paintDataManagementCounts();
- const emptyButton=$('#stats').querySelector('[data-cleanup-empty]');
- const emptyScan=$('#stats').querySelector('[data-cleanup-empty-scan]');
- emptyScan.onclick=async()=>{
- const status=$('#stats').querySelector('.cleanupstate');setActionBusy(emptyScan);emptyButton.hidden=true;
- /* 来源检查是挂载点上的慢活,接口只有跑完才回话:状态行用 Loading Dots 说
- 「还在推进」,不假装有百分比。 */
- status.innerHTML=loadingDotsHtml('正在检查来源…');
- try{const result=await api('/api/data-cleanup/empty-folders',{method:'POST',body:JSON.stringify({dry_run:true})});
- if(!surfaceCurrent(surface))return;
- status.innerHTML=noteHtml(`已检查 ${Number(result.scanned||0).toLocaleString()} 个目录,发现 ${Number(result.empty||0).toLocaleString()} 个空文件夹、${Number(result.vanished||0).toLocaleString()} 条文件已不在盘上的记录${result.errors?`,${result.errors} 个目录读取失败`:''}。`,{label:'检查结果'});
- emptyButton.hidden=!(result.empty>0||result.vanished>0);
- }catch(error){status.innerHTML=noteHtml(error.message,{variant:'error',label:'扫描失败'})}finally{setActionBusy(emptyScan,false)}
- };
- emptyButton.onclick=async()=>{
- return confirmModal({title:'清理空文件夹与失效条目',body:'将删除已连接磁盘和网盘中的空文件夹,保留来源根目录;文件已在盘上删掉的记录连同它们的派生产物一起从库里移除,这一步不可撤销。',confirmLabel:'清理',danger:true,onConfirm:async()=>{
- 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.innerHTML=noteHtml(`已检查 ${Number(result.scanned||0).toLocaleString()} 个目录,删除 ${Number(result.removed||0).toLocaleString()} 个空文件夹、${Number(result.purged||0).toLocaleString()} 条失效记录${result.errors?`,${Number(result.errors).toLocaleString()} 个读取或删除失败`:''}。`,{label:'清理结果',variant:result.errors?'warning':'success'});
- /* 读不到的目录只是这一轮没走到,能删的已经删了:报警告档,不说清理失败。 */
- if(result.errors)toast({text:`已删除 ${Number(result.removed||0).toLocaleString()} 个空文件夹、${Number(result.purged||0).toLocaleString()} 条失效记录,${Number(result.errors).toLocaleString()} 个目录读取或删除失败`},{sound:'warning'});
- else actionReceipt(`已删除 ${Number(result.removed||0).toLocaleString()} 个空文件夹、${Number(result.purged||0).toLocaleString()} 条失效记录`);
- }finally{setActionBusy(emptyButton,false);emptyButton.innerHTML=original;emptyButton.hidden=true}
- }});
- };
await wireOrganize(surface,organizeState);
await wireLinkManager();
await wireResourceSync();
@@ -8763,7 +8734,7 @@ const MANAGE_SECTIONS=[
['configuration','配置','folder-cog'],
];
/* 管理菜单只留这几项。人工复核、回收站、高清版都是「收拾库里已有的东西」,
- 和垃圾文件、重复文件、空文件夹是同一件事的不同步骤,统一从数据管理进;
+ 和垃圾文件、重复文件、失效条目是同一件事的不同步骤,统一从数据管理进;
统计页也因此不再挂链接管理和资源同步这两块跟统计无关的面板。
活动页进这张菜单:它横跨所有这些页面(扫描、追更、批量都在它上面出现),
从其中任何一页进都会像是那一页的下一步,而它不是。
@@ -8970,7 +8941,7 @@ function buildManageBar(){
本来就没有标题层;统计/复核/重复各自内嵌 h2 又导致字号不一致。 */
/* 数据管理五张卡对应的子页(vercel.com/geist/breadcrumbs:有上一级页面的
子页才画面包屑)。人工复核、回收站、高清版虽也保留侧栏直达入口,
- 层级上仍从数据管理进;空文件夹是 hub 上的就地操作,没有独立页面。 */
+ 层级上仍从数据管理进;资源同步是 hub 上的就地操作,没有独立页面。 */
//: 上一次页面标题说的是哪一页。空串表示此刻没有管理区标题(首页、目录这些)。
let lastManagePageLabel='';
const MANAGE_CRUMB_PAGES={
diff --git a/web/board.css b/web/board.css
index 8de13c1de..a54e22396 100644
--- a/web/board.css
+++ b/web/board.css
@@ -470,26 +470,24 @@ body :is(#manageTitle,#manageCrumb,#manageLede){max-width:var(--board-content);w
@media(max-width:559px){.cleanupstats{grid-template-columns:minmax(0,1fr)}}
/* 读数下面那两张是要做的事,各占一行,与扫描卡同一个左说明右按钮的形状。 */
.cleanupgrid [data-cleanup-task],.resourcesyncbox[data-cleanup-task]{border:1px solid var(--color-separator-border);border-radius:16px;background:var(--color-background-secondary-default);box-shadow:var(--elevation-card)}
-.cleanupgrid :is(.cleanupemptyfolders,[data-cleanup-processing]){display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}
-.cleanupgrid :is(.cleanupemptyfolders,[data-cleanup-processing])>:is(.geist-fieldset-content,[data-geist-fieldset-content]){min-height:0;padding:24px}
-.cleanupgrid :is(.cleanupemptyfolders,[data-cleanup-processing])>:is(.geist-fieldset-footer,[data-geist-fieldset-footer]){justify-content:flex-end;border:0;padding:24px;background:none;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
+.cleanupgrid [data-cleanup-processing]{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}
+.cleanupgrid [data-cleanup-processing]>:is(.geist-fieldset-content,[data-geist-fieldset-content]){min-height:0;padding:24px}
+.cleanupgrid [data-cleanup-processing]>:is(.geist-fieldset-footer,[data-geist-fieldset-footer]){justify-content:flex-end;border:0;padding:24px;background:none;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.cleanupgrid [data-cleanup-processing]>:is(.geist-fieldset-content,[data-geist-fieldset-content]){display:flex;flex-direction:column;gap:8px}
.cleanupgrid [data-cleanup-processing]>:is(.geist-fieldset-content,[data-geist-fieldset-content])>:is(h3,p){margin:0}
.cleanupgrid [data-cleanup-processing] h3{font:var(--board-heading);letter-spacing:0}
-.cleanupgrid>.cleanupemptyfolders strong{font:var(--board-body);color:var(--color-text-secondary);letter-spacing:0}
.resourcesyncbox[data-cleanup-task]{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}
.resourcesyncbox[data-cleanup-task]>.resourcesyncbody{min-height:0;padding:24px}
.resourcesyncbox[data-cleanup-task]>.resourcesyncfooter{align-self:stretch;justify-content:flex-end;min-height:0;padding:24px;border:0;background:none}
.resourcesyncbox[data-cleanup-task] .geist-fieldset-title{margin:0 0 8px;font:var(--board-heading);letter-spacing:0}
-/* 来源行和资源同步结果面板取同一份站标;离线那枚跟着结果面板的 offline 用色。 */
-.cleanupgrid>.cleanupemptyfolders .cleanupmeta{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px}
-.cleanupsourcemark{display:inline-flex;align-items:center;gap:6px}
-.cleanupsourcemark .gselectmark{width:14px;height:14px}
-.cleanupsourcemark.cleanupsourcelost{color:var(--drop)}
-/* 资源同步的结果照 Board 的 stat cards 排:和数据管理顶上一排读数同一副卡片,
- 三个来源带官方站标,缓存与回收站两张读数跟在后面凑成同一行节奏。卡片不是入口,
+/* 资源同步的结果照 Board 的 stat cards 排:和数据管理顶上一排读数同一副卡片。
+ 来源带官方站标排一行,待永久删除、空文件夹、缓存三张排一行;每行按自己的卡数等分,
+ 来源几个都不折出半行,窄屏再照顶上那排读数折两列、一列。卡片不是入口,
不接悬停抬色;在线状态挂在标题行最右,标题行放不下的说明在窄屏折行。 */
-.resourcestats{margin:0}
+.resourcestats{margin:0;grid-template-columns:none;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr)}
+#resourceSyncResult>.resourcestats+.resourcestats{margin:16px 0 0}
+@media(max-width:1119px){.resourcestats{grid-auto-flow:row;grid-template-columns:repeat(2,minmax(0,1fr))}}
+@media(max-width:559px){.resourcestats{grid-template-columns:minmax(0,1fr)}}
.resourcestat{cursor:default}
.resourcestat:hover{background:var(--color-background-secondary-default)}
.resourcestat-tile svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
@@ -498,9 +496,6 @@ body :is(#manageTitle,#manageCrumb,#manageLede){max-width:var(--board-content);w
.resourcestat-state.online{color:var(--success)}
.resourcestat-state.offline{color:var(--drop)}
.resourcestat .cleanupmeta{white-space:normal}
-/* 检查结果 Note 是说明列里一块完整的圆角 Note,与加工卡的失败提示同一副形状。按钮
- 单占右列,说明列到不了卡片右边框,Note 若出血顶边只会左边贴框、右边悬空。 */
-.cleanupgrid>.cleanupemptyfolders .cleanupstate .geist-note{margin:12px 0 0}
#resourceSyncResult>.cleanupstats{margin:0}
/* 结果槽里三层各管各的间距:读数卡、说明 Note、操作行都不再共享一只面板框。 */
#resourceSyncResult>.geist-note{margin:16px 0 0}
@@ -1332,7 +1327,7 @@ body .board-chip.success{background:color-mix(in srgb,#84cc16 16%,var(--color-ba
.followmanage .fsource:has([data-follow-select]):not(tr){border:1px solid var(--color-border-button-default);border-radius:10px;padding:12px 20px 12px 16px;margin:8px 0;cursor:pointer;transition:background-color 150ms ease,border-color 150ms ease;box-shadow:var(--elevation-sm)}
.followmanage .fsource:has([data-follow-select]):hover{background:var(--color-background-primary-hover)}
.followmanage .fsec:has(.board-follow-selection){padding:0;border-radius:18px;background:var(--ground);overflow:visible}.followmanage .fsec>.board-follow-selection{padding:4px 24px 12px}
-@media(max-width:1000px){.cleanupgrid :is(.cleanupemptyfolders,[data-cleanup-processing]),.resourcesyncbox[data-cleanup-task]{grid-template-columns:1fr}.cleanupgrid :is(.cleanupemptyfolders,[data-cleanup-processing])>:is(.geist-fieldset-footer,[data-geist-fieldset-footer]),.resourcesyncbox[data-cleanup-task]>.resourcesyncfooter{justify-content:flex-start;padding-top:0}}
+@media(max-width:1000px){.cleanupgrid [data-cleanup-processing],.resourcesyncbox[data-cleanup-task]{grid-template-columns:1fr}.cleanupgrid [data-cleanup-processing]>:is(.geist-fieldset-footer,[data-geist-fieldset-footer]),.resourcesyncbox[data-cleanup-task]>.resourcesyncfooter{justify-content:flex-start;padding-top:0}}
.metricstrip>button[aria-selected=true]{background:var(--color-background-primary-default);box-shadow:none}.metricstrip>button[aria-selected=true]::after{box-sizing:border-box}.metricstrip>button[aria-selected=true] .board-stat-footer{background:var(--board-card-foot)}
body .gselectmenu [role=option][aria-selected=true],body .popmenu [aria-checked=true]{background:color-mix(in srgb,var(--color-text-primary) 10%,var(--color-background-primary-default));color:var(--color-text-primary)}
.insightswitch{display:inline-flex;align-items:center;gap:2px;padding:3px;border:1px solid var(--line);border-radius:10px;background:var(--color-background-primary-default);box-shadow:var(--elevation-xs)}.insightswitch label>span{display:flex;align-items:center;min-height:28px;padding:4px 10px;border-radius:7px;color:var(--color-text-secondary);font:var(--board-body-medium)}.insightswitch label:has(input:checked)>span{background:var(--color-background-primary-hover);color:var(--color-text-primary);box-shadow:0 1px 2px light-dark(#0000001a,#0000008c)}
@@ -1377,7 +1372,6 @@ body [data-skeleton-action][data-skeleton-action]:disabled{background:var(--surf
body [data-skeleton-action][data-skeleton-action]:disabled::before{display:none}
body [data-split-button]>[data-skeleton-action][data-skeleton-action]:disabled{box-shadow:none}
[data-split-button]:has(>[data-skeleton-action]:disabled){--split-seam:var(--border-15);box-shadow:0 0 0 1px var(--border-15)}
-body [data-cleanup-empty][hidden]{display:none}
body .junkactions button:not(.danger){height:36px;border:1px solid var(--color-border-button-default);border-radius:10px;padding:8px 12px;background:var(--color-background-primary-default);color:var(--ink);box-shadow:var(--elevation-xs);font:var(--board-body-medium)}
body [data-follow-bulk],body [data-follow-status=seen],body [data-follow-status=ignored]{background:color-mix(in srgb,var(--color-accent-400) 16%,var(--color-background-primary-default));color:var(--color-accent-600);border-color:transparent}
.reviewcontrols{border:0;border-radius:20px}.batchbar,.tagselection{background:var(--glass-drift-a),var(--glass-drift-b),linear-gradient(125deg,var(--glass-sheen),transparent 42%,var(--glass-low)),var(--glass-fill);background-size:200% 200%,200% 200%,auto;background-repeat:no-repeat,no-repeat,repeat;background-position:50% 20%,80% 70%,0 0;animation:glassdriftx calc(41s * var(--glow-drift-scale)) linear infinite,glassdrifty calc(67s * var(--glow-drift-scale)) linear infinite;animation-play-state:var(--glow-drift-play);backdrop-filter:var(--glass-optic,blur(22px)) saturate(145%);border:0;box-shadow:inset 0 1px 0 var(--glass-rim),var(--glass-shadow);border-radius:20px}
diff --git a/web/css/04-manage.css b/web/css/04-manage.css
index 570d263f2..084df1ec9 100644
--- a/web/css/04-manage.css
+++ b/web/css/04-manage.css
@@ -70,8 +70,6 @@
transition:color .15s ease-in-out,background-color .15s ease-in-out}
.cleanupfieldset button:where(:not(.gselectfield)):hover{background:color-mix(in srgb,var(--ink) 8%,var(--ground));color:var(--ink)}
.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}
diff --git a/web/css/12-cards.css b/web/css/12-cards.css
index c67160b99..bee0fcc3a 100644
--- a/web/css/12-cards.css
+++ b/web/css/12-cards.css
@@ -72,9 +72,8 @@ main{position:relative;z-index:1;padding:14px 16px 90px}
body.refreshing #batchAction svg,
.entitycollectionhead[aria-busy="true"] .entitybatch svg{
--strand-dash:100;--strand-cycle:2.2s}
-/* 数据管理里两枚「扫一遍」的键各自适配忙态,不统一转圈:检查文件的 git-compare 照
- lucide-animated 的 GitCompare 逐笔描画(右下圆→两条枝→左上圆,画完停住再一起淡出),
- 扫描空文件夹的 scan-search 四角按左上右下/右上左下两拍轮流亮,放大镜保持不动。
+/* 资源同步的「检查文件」键适配自己的忙态,不统一转圈:git-compare 照 lucide-animated 的
+ GitCompare 逐笔描画(右下圆→两条枝→左上圆,画完停住再一起淡出)。
机制同换批键:动效写在 symbol 自己的零件上,忙态把动画名和周期传下去;空闲时名字是
none,什么都不动。全局的 prefers-reduced-motion 规则会关掉它们。 */
@keyframes peach-gc-draw-a{
@@ -89,25 +88,13 @@ body.refreshing #batchAction svg,
0%,50%{stroke-dashoffset:100;opacity:1}
67%,86%{stroke-dashoffset:0;opacity:1}
100%{stroke-dashoffset:0;opacity:0}}
-@keyframes peach-scan-corner-a{
- 0%,40%{opacity:1}
- 50%,90%{opacity:.25}
- 100%{opacity:1}}
-@keyframes peach-scan-corner-b{
- 0%,40%{opacity:.25}
- 50%,90%{opacity:1}
- 100%{opacity:.25}}
#i-git-compare .gc-part{stroke-dasharray:var(--gc-dash,none);
animation-name:var(--gc-anim,none);animation-duration:var(--gc-cycle,1.8s);
animation-timing-function:linear;animation-iteration-count:infinite}
#i-git-compare .gc-line-a,#i-git-compare .gc-line-b{animation-name:var(--gc-anim-b,none)}
#i-git-compare .gc-end-b{animation-name:var(--gc-anim-c,none)}
-#i-scan-search .scan-corner{animation-name:var(--scan-anim,none);
- animation-duration:var(--scan-cycle,1.2s);animation-timing-function:ease-in-out;animation-iteration-count:infinite}
-#i-scan-search .scan-corner-b{animation-name:var(--scan-anim-b,none)}
-#resourceScan[aria-busy="true"] svg,[data-cleanup-empty-scan][aria-busy="true"] svg{
- --gc-dash:100;--gc-anim:peach-gc-draw-a;--gc-anim-b:peach-gc-draw-b;--gc-anim-c:peach-gc-draw-c;
- --scan-anim:peach-scan-corner-a;--scan-anim-b:peach-scan-corner-b}
+#resourceScan[aria-busy="true"] svg{
+ --gc-dash:100;--gc-anim:peach-gc-draw-a;--gc-anim-b:peach-gc-draw-b;--gc-anim-c:peach-gc-draw-c}
.count .sorts,.entitycollectionhead .sorts{display:flex;gap:5px;margin-left:auto;flex-wrap:nowrap;
overflow-x:auto;scrollbar-width:none;min-width:0}
.count .sorts::-webkit-scrollbar,.entitycollectionhead .sorts::-webkit-scrollbar{display:none}
diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.js
index 7d35e3a20..527d5db90 100644
--- a/web/dist/peach-ui.js
+++ b/web/dist/peach-ui.js
@@ -742,11 +742,6 @@ function tt() {
<div class="cleanupgrid">
<div class="cleanupscraping">${K()}</div>
<div class="cleanupmediarepair">${q()}</div>
- <section class="cleanupfieldset cleanupemptyfolders" data-geist-fieldset data-cleanup-task aria-labelledby="cleanup-loading-empty">
- <div class="geist-fieldset-content"><h3 class="geist-fieldset-title" id="cleanup-loading-empty">空文件夹与失效条目</h3>
- <strong>${V}</strong><p class="cleanupmeta">${V}</p></div>
- <footer class="geist-fieldset-footer" data-geist-fieldset-footer><button class="geist-button primary" ${H}>${l("scan-search")}<span>检查来源</span></button></footer>
- </section>
<section class="cleanupfieldset cleanuporganize" data-geist-fieldset data-cleanup-task aria-labelledby="cleanup-loading-organize">
<div class="geist-fieldset-content"><h3 class="geist-fieldset-title" id="cleanup-loading-organize">整理</h3>
<p>按模板给文件改名并归入目录。先预览,确认后执行;执行过的一批可以整批退回。</p>
@@ -775,7 +770,7 @@ function tt() {
<h2 id="cleanup-loading-sync">资源同步</h2>
<div class="resourcesyncbox" data-geist-fieldset data-cleanup-task>
<div class="resourcesyncbody geist-fieldset-content"><h3 class="geist-fieldset-title">文件与记录核对</h3>
- <p>按馆藏记录逐条查找本地磁盘与网盘上的文件,列出文件已不存在的记录,以及不再被引用的缓存。</p></div>
+ <p>按馆藏记录逐条查找本地磁盘与网盘上的文件,列出文件已不存在的记录、空文件夹,以及不再被引用的缓存。</p></div>
<div class="resourcesyncfooter geist-fieldset-footer" data-geist-fieldset-footer><button class="resourceaction primary" ${H}>${l("git-compare")}<span>检查文件</span></button></div>
</div></section></div>`;
}
@@ -788,17 +783,22 @@ var J = (e = 0) => Number(e).toLocaleString(), nt = {
}, rt = (t) => o(e[t] ?? "database"), Y = (e, t, n) => `<article class="board-plain-stat resourcestat">
<span class="board-plain-stat-head">${e}</span>
<strong>${t}</strong>
- <span class="cleanupmeta">${n}</span></article>`;
-function it(e, t) {
+ <span class="cleanupmeta">${n}</span></article>`, it = (e) => e.online ? [
+ `找不到文件 · 共 ${J(e.total)} 项`,
+ e.empty ? `空文件夹 ${J(e.empty)} 个` : "",
+ e.unreadable ? `${J(e.unreadable)} 个目录读取失败,已跳过` : ""
+].filter(Boolean).join(" · ") : `馆藏中有 ${J(e.total)} 项`;
+function at(e, t) {
let n = e.cache || {
files: 0,
bytes: 0
- }, r = !!(e.missing || n.files);
- return `<div class="cleanupstats resourcestats">${(e.sources || []).map((e) => Y(`<span class="board-stat-tile resourcestat-tile">${rt(e.location)}</span>${nt[e.location] || "媒体来源"}<span class="resourcestat-state ${e.online ? "online" : "offline"}">${e.online ? "可访问" : "离线,已跳过"}</span>`, e.online ? `${J(e.missing)} 项` : "—", [e.online ? `找不到文件 · 已检查 ${J(e.checked)} 项` : `馆藏中有 ${J(e.total)} 项`, e.unreadable ? `${J(e.unreadable)} 项读取失败,已跳过` : ""].filter(Boolean).join(" · "))).join("")}
- ${Y("待移入回收站", `${J(e.missing)} 项`, "")}
+ }, r = !!(e.missing || e.empty || n.files);
+ return `<div class="cleanupstats resourcestats">${(e.sources || []).map((e) => Y(`<span class="board-stat-tile resourcestat-tile">${rt(e.location)}</span>${nt[e.location] || "媒体来源"}<span class="resourcestat-state ${e.online ? "online" : "offline"}">${e.online ? "可访问" : "离线,已跳过"}</span>`, e.online ? `${J(e.missing)} 项` : "—", it(e))).join("")}</div>
+ <div class="cleanupstats resourcestats">${Y("待永久删除", `${J(e.missing)} 项`, "文件已不在盘上,含回收站")}
+ ${Y("空文件夹", `${J(e.empty)} 个`, "保留来源根目录")}
${Y("可清理的缓存", `${J(n.files)} 个`, n.files ? t(n.bytes) : "")}</div>
- ${r ? i(`将把找不到文件的 ${J(e.missing)} 项馆藏记录移入回收站,并清理 ${J(n.files)} 个闲置缓存。`, { label: "清理内容" }) : ""}
- <div class="resourceapplyrow geist-fieldset-footer" data-geist-fieldset-footer>${r ? "<button class=\"geist-button primary\" type=\"button\" id=\"resourceApply\">清理失效记录与缓存</button>" : "<p class=\"resourcesyncok\">已检查可访问的来源,没有待清理的记录或缓存。</p>"}</div>`;
+ ${r ? i(`将永久删除文件已不在盘上的 ${J(e.missing)} 条记录和 ${J(e.empty)} 个空文件夹,并清理 ${J(n.files)} 个闲置缓存。这一步不可撤销。`, { label: "清理内容" }) : ""}
+ <div class="resourceapplyrow geist-fieldset-footer" data-geist-fieldset-footer>${r ? "<button class=\"danger\" type=\"button\" id=\"resourceApply\">清理失效条目</button>" : "<p class=\"resourcesyncok\">已检查可访问的来源,没有待清理的记录、空文件夹或缓存。</p>"}</div>`;
}
//#endregion
//#region src/jav-artwork.ts
@@ -809,7 +809,7 @@ function X(e) {
"preview"
].includes(String(e)) ? "small" : "big";
}
-function at(e) {
+function ot(e) {
return {
javLayout: X(e.javLayout),
javImage: Z(e.javLayout === "preview" ? "thumbnail" : e.javImage)
@@ -818,10 +818,10 @@ function at(e) {
function Z(e) {
return e === "thumbnail" ? "thumbnail" : "cover";
}
-function ot(e, t) {
+function st(e, t) {
return e.is_jav && e.code && e.has_cover && (Z(t) === "cover" || !e.has_thumb) ? "cover" : e.has_thumb ? "thumbnail" : "";
}
-function st(e, t) {
+function ct(e, t) {
let n = Number(e?.px?.[0]), r = Number(e?.px?.[1]), i = Number(e?.x0);
if (!(n > 0 && r > 0 && t > 0) || !Number.isFinite(i)) return null;
let a = (e, t, n) => Math.min(n, Math.max(0, Number.isFinite(Number(e)) ? Number(e) : t)), o = a(i, 0, n), s = Math.max(o, a(e?.x1, n, n)), c = a(e?.y0, 0, r), l = Math.max(c, a(e?.y1, r, r)), u = s - o, d = l - c;
@@ -841,7 +841,7 @@ function st(e, t) {
height: m(r / d)
};
}
-function ct(e, t) {
+function lt(e, t) {
e.querySelectorAll("img[data-jav-image]").forEach((e) => {
let n = e.dataset.javCover || "", r = e.dataset.javThumb || "", i = !!(n && (Z(t) === "cover" || !r)), a = i ? n : r;
e.classList.toggle("cover", i), e.classList.toggle("whole", i && e.dataset.javImageLayout !== "big"), e.classList.toggle("front", i && e.dataset.javImageLayout === "big"), e.classList.remove("panel"), e.removeAttribute("style"), e.closest(".pic")?.style.removeProperty("--cover-blur"), a && e.getAttribute("src") !== a && (e.src = a);
@@ -863,11 +863,11 @@ var Q = {
activity: { react: "activity" },
stats: { react: "stats" },
taste: { react: "taste" }
-}, lt = () => Object.keys(Q), $ = /* @__PURE__ */ new Map();
-async function ut(e, t, n, r = {}) {
+}, ut = () => Object.keys(Q), $ = /* @__PURE__ */ new Map();
+async function dt(e, t, n, r = {}) {
let i = Q[e];
if (!i) throw Error(`未注册的 island:${String(e)}`);
- pt(t);
+ mt(t);
let a = { controller: new AbortController() };
$.set(t, a);
let o = (await import("/dist/peach-react.js")).pages[i.react];
@@ -876,7 +876,7 @@ async function ut(e, t, n, r = {}) {
} catch {
if (a.controller.signal.aborted) return;
}
- if (!dt(t, a, r)) return;
+ if (!ft(t, a, r)) return;
let s = t.ownerDocument.createElement("div");
s.className = "peach-react", t.append(s);
let c = o.mount(s, n);
@@ -884,20 +884,20 @@ async function ut(e, t, n, r = {}) {
c.unmount(), s.remove();
};
}
-function dt(e, t, n) {
+function ft(e, t, n) {
return $.get(e) === t ? n.isCurrent && !n.isCurrent() ? ($.delete(e), !1) : (e.textContent = "", !0) : !1;
}
-var ft = (e) => !!e && $.has(e);
-function pt(e) {
- for (let t of [...$.keys()]) (t === e || e.contains(t)) && mt(t);
-}
+var pt = (e) => !!e && $.has(e);
function mt(e) {
+ for (let t of [...$.keys()]) (t === e || e.contains(t)) && ht(t);
+}
+function ht(e) {
let t = $.get(e);
t && (t.controller.abort(), $.delete(e), t.dispose?.());
}
-var ht = null;
-function gt(e, t, n, r) {
- ht ??= import("/dist/peach-react.js").then((n) => (n.mountToaster(e, t), n)), ht.then((e) => e.showToast(n, r));
+var gt = null;
+function _t(e, t, n, r) {
+ gt ??= import("/dist/peach-react.js").then((n) => (n.mountToaster(e, t), n)), gt.then((e) => e.showToast(n, r));
}
//#endregion
-export { He as boardPageSkeleton, f as boundedPreference, Ke as catalogEmptyHtml, Ge as catalogSuggestions, ue as clampPage, tt as cleanupSkeletonHtml, Xe as cloudLocations, Ze as cloudPreferenceLocations, Ve as detailSkeletonHtml, We as emptyCatalogLayout, me as entitySkeletonHtml, fe as faceSourceScale, re as followJobProgress, g as initBoardControls, ft as islandMounted, lt as islandNames, ot as javImageKind, w as jobActivityHtml, ut as mountIsland, m as mountNumberSetting, pe as nativeImageFit, Z as normalizeJavImage, X as normalizeJavLayout, at as normalizeJavPreferences, le as pageCount, de as paginationHtml, st as panelFrame, u as preferredDirection, q as repairCardSkeletonHtml, it as resourceScanHtml, K as scanCardSkeletonHtml, oe as selectGroup, ie as selectRange, ae as selectionSummary, gt as showToast, qe as sidebarHasCatalogContent, S as sidebarSectionHtml, Ye as sidebarTagCounts, h as syncBoardRange, ct as syncJavImages, p as syncNumberSetting, se as syncSelectionToolbar, Je as syncSidebarSurface, te as transitionTheme, pt as unmountIsland, T as watchJob, ee as wireSidebarGroups };
+export { He as boardPageSkeleton, f as boundedPreference, Ke as catalogEmptyHtml, Ge as catalogSuggestions, ue as clampPage, tt as cleanupSkeletonHtml, Xe as cloudLocations, Ze as cloudPreferenceLocations, Ve as detailSkeletonHtml, We as emptyCatalogLayout, me as entitySkeletonHtml, fe as faceSourceScale, re as followJobProgress, g as initBoardControls, pt as islandMounted, ut as islandNames, st as javImageKind, w as jobActivityHtml, dt as mountIsland, m as mountNumberSetting, pe as nativeImageFit, Z as normalizeJavImage, X as normalizeJavLayout, ot as normalizeJavPreferences, le as pageCount, de as paginationHtml, ct as panelFrame, u as preferredDirection, q as repairCardSkeletonHtml, at as resourceScanHtml, K as scanCardSkeletonHtml, oe as selectGroup, ie as selectRange, ae as selectionSummary, _t as showToast, qe as sidebarHasCatalogContent, S as sidebarSectionHtml, Ye as sidebarTagCounts, h as syncBoardRange, lt as syncJavImages, p as syncNumberSetting, se as syncSelectionToolbar, Je as syncSidebarSurface, te as transitionTheme, mt as unmountIsland, T as watchJob, ee as wireSidebarGroups };
diff --git a/web/index.html b/web/index.html
index 7bb840ffa..e9914c90c 100644
--- a/web/index.html
+++ b/web/index.html
@@ -76,7 +76,7 @@
<symbol id="i-bed-double" viewBox="0 0 24 24"><path d="M2 20v-8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v8" /><path d="M4 10V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4" /><path d="M12 4v6" /><path d="M2 18h20" /></symbol>
<symbol id="i-camera" viewBox="0 0 24 24"><path d="M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z" /><circle cx="12" cy="13" r="3" /></symbol>
<symbol id="i-video" viewBox="0 0 24 24"><path d="m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5" /><rect x="2" y="6" width="14" height="12" rx="2" /></symbol>
-<symbol id="i-scan-search" viewBox="0 0 24 24"><path class="scan-corner scan-corner-a" d="M3 7V5a2 2 0 0 1 2-2h2"/><path class="scan-corner scan-corner-b" d="M17 3h2a2 2 0 0 1 2 2v2"/><path class="scan-corner scan-corner-a" d="M21 17v2a2 2 0 0 1-2 2h-2"/><path class="scan-corner scan-corner-b" d="M7 21H5a2 2 0 0 1-2-2v-2"/><circle cx="12" cy="12" r="3" /><path d="m16 16-1.9-1.9" /></symbol>
+<symbol id="i-scan-search" viewBox="0 0 24 24"><path d="M3 7V5a2 2 0 0 1 2-2h2" /><path d="M17 3h2a2 2 0 0 1 2 2v2" /><path d="M21 17v2a2 2 0 0 1-2 2h-2" /><path d="M7 21H5a2 2 0 0 1-2-2v-2" /><circle cx="12" cy="12" r="3" /><path d="m16 16-1.9-1.9" /></symbol>
<symbol id="i-home" viewBox="0 0 24 24"><path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8" /><path d="M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /></symbol>
<symbol id="i-panel-left" viewBox="0 0 24 24"><rect width="18" height="18" x="3" y="3" rx="2" /><path d="M9 3v18" /></symbol>
<symbol id="i-search" viewBox="0 0 24 24"><path d="m21 21-4.34-4.34" /><circle cx="11" cy="11" r="8" /></symbol>