Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(organize): 清理文件名符号并支持指定目录整理

longmeidao05e632523b35
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 8f07cf54f..fb3c17c68 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -354,6 +354,14 @@ untrunc 按相同顺序查找,对应目录为 `tools/untrunc`。独立程序
- 同时最多进行 2 个转码或探测,单次最长 1 小时,关掉播放页会取消对应的任务。
- 115 和 PikPak 的视频通过 CloudDrive2 挂载的 `B:`、`A:` 播放。能不能播,以在 Peach 里实际打开一个已知视频为准。
+## 文件整理
+
+在「数据管理 → 整理」选择来源。右侧路径框可直接输入目录,旁边的文件夹按钮在运行 Peach 的电脑上打开目录选择窗口;远程访问或系统选择窗口不可用时,直接输入路径。路径留空表示整个来源,指定目录时包含其子目录。路径须属于所选来源;切换来源会清空路径。
+
+整理会清除文件名中的装饰符号、emoji、替代字符 `�`、私用区字符和不可见噪声,保留正常文字、常用标点、单位、序号和扩展名。不能形成有效名称的条目保留原名;整段乱码文字不猜测还原。两份模板都留空时只清理名称,填写模板时同时按模板改名或归入目录。目录模板以指定路径为起点,路径留空时以来源根为起点。
+
+先点「预览」核对范围和逐文件变化,再确认执行。修改路径、来源或模板后须重新预览。目标已存在的条目跳过,已执行批次可用「回滚上一批」恢复名称、位置和账本路径。PikPak 界面仅提供预览,改名仍需官方核验通道。
+
## 资源同步与删除
哪些操作会删除文件、哪些不会,请在动手前看清楚。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 36a38af1c..5aadaa256 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -18,6 +18,14 @@ Peach 负责独立数据目录、首启、构建身份和资源清单。arm64
Peach 只保留设备选择、一次性合成帧探测、命令尝试顺序与失败回退;探测结果由两个服务共享。复用检索覆盖当前 NVENC 链、媒体工具解析器与 Git 历史,没有独立 VAAPI 路径。FFmpeg 已覆盖编解码与滤镜,ffmpeg-python 一类包装层不提供设备驱动或硬件可用性判定,因此沿用项目 subprocess 入口,不新增 Python 依赖。回归用合成输入与进程替身验证 Linux 节点选择、权限和超时、10-bit 转 NV12、整片及分片回退。2026-10-19 的 Windows NVENC 实测使用 640×360 合成帧完成探测,合成 10-bit HEVC 经整片 MP4 与 HLS 两条 CUDA / NVENC 路径输出 H.264 `yuv420p`;128×128 不满足该编码器的最低尺寸,因此探测统一用 640×360。目标 AMD GPU 的驱动初始化、解码与播放验收未取得。无生产入口或真实 ledger 写入。
+## 文件名噪声清理
+
+整理模板与 `scripts/clean_names.py` 共用 `organize_templates.clean_name_symbols` 和 `clean_filename`。字符分类复用 Python 标准库 `unicodedata`,按 Unicode 类别清除装饰图形、emoji、替代字符、控制字符和私用区噪声;Peach 保留常用标点、文字组合音标、单位、算术符号、扩展名与空名称保护。不新增依赖。
+
+外部候选核对了 [pathvalidate 的文件名清洗](https://pathvalidate.readthedocs.io/en/latest/pages/examples/sanitize.html)与 [ftfy 的编码修复](https://ftfy.readthedocs.io/en/latest/)。前者主要处理文件系统非法字符,其通用符号替换还会删掉番号连接号和扩展名句点;后者通过启发式还原编码,超出本次删除噪声的范围,因此不引入。隔离用例覆盖装饰符号、复合 emoji、不可见字符、乱码替代字形、正常中日文与重音字母、空名称、重复执行和改名回滚;馆藏只读盘点与逐条预览保存在数据目录的复核产物中。
+
+目录范围复用 `platform.resolve_root`、`location_mounts` 与标准库路径组件比较。界面复用 BoardUI Input、IconButton、已有 `FolderSearchIcon` 和 `/api/pick-folder`;预览、执行及后台任务恢复共用 `path` 参数,目录模板以所选目录为起点。空路径表示整个来源,目录边界按组件匹配,不按文本前缀匹配。
+
## 独立页面的请求反馈
请求错误文案复用 `core/request-error.ts`,实体登记复用 `core/entity-links.ts`。API 直接引用这两个模块,首启与登录页不加载主界面的路由和字素分段初始化;主界面仍通过 `core/index.ts` 导出同一份错误文案。冷启动导入回归核对 API 不构造界面分段器,既有反馈测试覆盖状态码、超时与服务端中文原因。无新增依赖。
diff --git a/frontend/e2e/organize-scope.test.ts b/frontend/e2e/organize-scope.test.ts
new file mode 100644
index 000000000..7c642c57e
--- /dev/null
+++ b/frontend/e2e/organize-scope.test.ts
@@ -0,0 +1,54 @@
+/* 整理范围:目录选择、长路径输入和桌面/手机布局。 */
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { Browser } from 'playwright-core';
+import { layout, visit } from './harness.ts';
+import { DESKTOP, MOBILE, installDesignBrowser } from './design-fixture.ts';
+
+describe('整理目录范围', () => {
+ let browser: Browser;
+ installDesignBrowser((next) => { browser = next; });
+
+ it('路径在桌面来源右侧,手机换行且长路径不撑宽页面', { timeout: 60_000 }, async () => {
+ for (const viewport of [DESKTOP, MOBILE]) {
+ const opened = await visit(browser, '/data-cleanup', viewport);
+ try {
+ const page = opened.page;
+ await page.route('**/api/organize', (route) => route.fulfill({ json: {
+ status: 'idle', locations: [{ location: 'local', roots: ['R:\\media'] }],
+ templates: {}, presets: [], placeholders: [], last_batch: '',
+ } }));
+ await page.route('**/api/pick-folder', (route) => route.fulfill({ json: { path: 'R:\\media\\合集' } }));
+ await page.reload({ waitUntil: 'load' });
+ const scope = page.locator('[data-organize-scope]');
+ const input = page.getByRole('textbox', { name: '整理路径', exact: true });
+ await input.waitFor();
+ await page.getByRole('button', { name: '选择整理路径', exact: true }).click();
+ await page.waitForFunction(() => document.querySelector<HTMLInputElement>('input[name="organize-path"]')?.value === 'R:\\media\\合集');
+ await input.fill('R:\\media\\' + '长目录名称'.repeat(40));
+ for (const dark of [false, true]) {
+ await page.evaluate((isDark) => document.documentElement.classList.toggle('dark', isDark), dark);
+ const geometry = await scope.evaluate((element) => {
+ const source = element.querySelector('button')!.getBoundingClientRect();
+ const input = element.querySelector('input')!;
+ const rect = input.getBoundingClientRect();
+ return { source: { right: source.right, bottom: source.bottom, top: source.top },
+ path: { left: rect.left, top: rect.top, bottom: rect.bottom, width: rect.width },
+ font: Number.parseFloat(getComputedStyle(input).fontSize) };
+ });
+ assert.ok(geometry.path.width > 100);
+ if (viewport.mobile) {
+ assert.ok(geometry.path.top >= geometry.source.bottom - 1, JSON.stringify(geometry));
+ assert.ok(geometry.font >= 16);
+ } else {
+ assert.ok(geometry.path.left >= geometry.source.right, JSON.stringify(geometry));
+ assert.ok(Math.abs((geometry.path.top + geometry.path.bottom) / 2
+ - (geometry.source.top + geometry.source.bottom) / 2) <= 2, JSON.stringify(geometry));
+ }
+ const measured = await layout(page);
+ assert.ok(measured.scrollWidth <= measured.viewportWidth + 1, JSON.stringify(measured));
+ }
+ } finally { await opened.close(); }
+ }
+ });
+});
diff --git a/frontend/src/react/data-cleanup/organize-card.tsx b/frontend/src/react/data-cleanup/organize-card.tsx
index aac75a6ec..53e0ec172 100644
--- a/frontend/src/react/data-cleanup/organize-card.tsx
+++ b/frontend/src/react/data-cleanup/organize-card.tsx
@@ -9,6 +9,7 @@ import { confirmModal, MEDIA_SOURCE_ICONS } from '@peach/legacy/ui';
import { LOC } from '@peach/legacy/core';
import { Button } from '@/components/base/buttons/button';
+import { IconButton } from '@/components/base/buttons/icon-button';
import { Input } from '@/components/base/input/input';
import { Select, SelectItem } from '@/components/base/select/select';
@@ -19,14 +20,15 @@ import { Note } from '../components/note';
import { TaskProgress } from '../components/task-progress';
import { queryClient } from '../query';
import { SourceMark } from '../settings/section';
+import { FolderSearchIcon } from '../settings/folder-rows';
import { busyProps } from '../settings/use-action';
import {
baseName, DIRECTORY_TEMPLATE_ERROR, fetchOrganize, ORGANIZE_KEY, organizeOutcome, planSummary,
- previewOrganize, rememberTemplates, startOrganize, withOrganizeJob,
+ pickOrganizeFolder, previewOrganize, rememberTemplates, startOrganize, withOrganizeJob,
type OrganizeCommand, type OrganizeData, type OrganizeJob, type OrganizePlan,
} from './organize';
-const APPLY_BODY = (name: string) => `将按这两份模板改动「${name}」上的文件名与目录,目标已存在的行会整行跳过。`
+const APPLY_BODY = (name: string, path: string) => `将整理「${name}」${path ? `的「${path}」及其子目录` : '上的文件名与目录'},清理特殊符号与乱码,并按已填模板改名或移动。目标已存在的行会整行跳过。`
+ '这一批可以从「回滚上一批」整批退回。';
const ROLLBACK_BODY = '将把上一批整理动过的文件退回整理前的名字与位置,数据库路径跟着退回。'
+ '退回后这一批不再出现在这里。';
@@ -46,7 +48,7 @@ function PlanRows({ plan }: { plan: OrganizePlan }) {
</li>
))}
</ol>
- {plan.truncated
+ {plan.truncated || plan.rows.length > PLAN_ROWS
? <p className="text-caption-1-regular text-text-secondary">只列出前 8 行,完整计划在计划 CSV 里。</p>
: null}
</>
@@ -65,19 +67,34 @@ export function OrganizeCard(
/* 两个框在人动过之前跟着存下的模板走:换来源就换成那个来源上次用的那两行。 */
const [draft, setDraft] = useState<{ location: string; file: string; dir: string } | null>(null);
const fields = draft?.location === location ? draft : { location, file: stored?.file ?? '', dir: stored?.dir ?? '' };
- const edit = (patch: Partial<{ file: string; dir: string }>) => setDraft({ ...fields, ...patch });
- const [invalid, setInvalid] = useState<'file' | 'dir' | null>(null);
+ const edit = (patch: Partial<{ file: string; dir: string }>) => { setDraft({ ...fields, ...patch }); preview.reset() };
+ const [scope, setScope] = useState({ location: '', path: '' });
+ const path = scope.location === location ? scope.path : '';
+ const scopeRef = useRef({ location, path });
+ scopeRef.current = { location, path };
+ const [invalid, setInvalid] = useState<'file' | 'dir' | 'path' | null>(null);
const fileInput = useRef<HTMLInputElement>(null);
const dirInput = useRef<HTMLInputElement>(null);
+ const pathInput = useRef<HTMLInputElement>(null);
- const request = () => ({ location, file_template: fields.file.trim(), dir_template: fields.dir.trim() });
+ const request = () => ({ location, path: path.trim(), file_template: fields.file.trim(), dir_template: fields.dir.trim() });
const preview = useMutation({
mutationFn: previewOrganize,
/* 模板不合法时错误就出在两个框里的一个,所以除了说原因还要指出是哪一格。 */
onError: (cause) => {
- const target = DIRECTORY_TEMPLATE_ERROR.test(errorMessage(cause)) ? 'dir' : 'file';
+ const target = /整理路径/.test(errorMessage(cause)) ? 'path'
+ : DIRECTORY_TEMPLATE_ERROR.test(errorMessage(cause)) ? 'dir' : 'file';
setInvalid(target);
- (target === 'dir' ? dirInput : fileInput).current?.focus();
+ (target === 'path' ? pathInput : target === 'dir' ? dirInput : fileInput).current?.focus();
+ },
+ });
+ const picker = useMutation({
+ mutationFn: ({ initial }: { initial: string; location: string; path: string }) => pickOrganizeFolder(initial),
+ onSuccess: (picked, sent) => {
+ if (!picked.path || sent.location !== scopeRef.current.location || sent.path !== scopeRef.current.path) return;
+ setScope({ location: sent.location, path: picked.path });
+ setInvalid(null); preview.reset();
+ pathInput.current?.focus();
},
});
const job = useBackgroundJob<OrganizeJob, OrganizeCommand, OrganizeData>({
@@ -92,33 +109,38 @@ export function OrganizeCard(
void queryClient.invalidateQueries({ queryKey: ORGANIZE_KEY, exact: true });
if (finished.status !== 'complete') return;
const { text, failed } = organizeOutcome(finished);
- if (failed) failure('按模板整理', new Error(`${failed} 行未能处理`));
+ if (failed) failure('整理文件', new Error(`${failed} 行未能处理`));
else toast(text.replace(/。$/, ''));
},
});
const running = job.running || job.start.isPending;
- const plan = preview.data;
+ const previewMatches = JSON.stringify(preview.variables) === JSON.stringify(request());
+ const plan = previewMatches ? preview.data : undefined;
const changes = Number(plan?.counts?.change || 0);
const name = LOC[location] || location;
const hint = (data?.placeholders ?? []).map((item) => `{${item.key}} ${item.label}`).join(' · ');
const runPreview = () => {
- if (preview.isPending || !location) return;
+ if (preview.isPending || running || !location) return;
+ job.dismiss(); job.start.reset();
setInvalid(null);
preview.mutate(request());
};
- const runApply = () => void confirmModal({
- title: '按模板整理文件', body: APPLY_BODY(name), confirmLabel: '整理文件',
- /* 预览只是试一试,不落盘;确认执行的那两行才记成这个来源的模板。 */
- onConfirm: async () => {
- const sent = request();
- await job.start.mutateAsync({ kind: 'apply', request: sent });
- void rememberTemplates({
- ...(data?.templates ?? {}), [sent.location]: { file: sent.file_template, dir: sent.dir_template },
- });
- },
- });
+ const runApply = () => {
+ const sent = preview.variables;
+ if (!sent || !plan || !changes) return;
+ void confirmModal({
+ title: '整理文件', body: APPLY_BODY(name, sent.path), confirmLabel: '整理文件',
+ /* 确认执行时保存该来源的模板。 */
+ onConfirm: async () => {
+ await job.start.mutateAsync({ kind: 'apply', request: sent });
+ void rememberTemplates({
+ ...(data?.templates ?? {}), [sent.location]: { file: sent.file_template, dir: sent.dir_template },
+ });
+ },
+ });
+ };
const runRollback = () => void confirmModal({
title: '回滚上一批整理', body: ROLLBACK_BODY, confirmLabel: '回滚整理',
onConfirm: () => job.start.mutateAsync({ kind: 'rollback' }),
@@ -139,9 +161,9 @@ export function OrganizeCard(
} else if (job.start.isError) {
state = <Note tone="error" title="整理失败">{errorMessage(job.start.error)}</Note>;
} else if (preview.isPending) {
- state = <TaskProgress embedded label="正在按模板算计划…" />;
- } else if (preview.isError) {
- state = <Note tone="error" title="模板不可用">{errorMessage(preview.error)}</Note>;
+ state = <TaskProgress embedded label="正在核对整理计划…" />;
+ } else if (preview.isError && previewMatches) {
+ state = <Note tone="error" title="整理预览失败">{errorMessage(preview.error)}</Note>;
} else if (plan) {
state = <><Note tone="neutral" title="预览结果">{planSummary(plan)}</Note>{changes ? <PlanRows plan={plan} /> : null}</>;
}
@@ -151,7 +173,7 @@ export function OrganizeCard(
attributes={{ 'data-cleanup-organize': '' }}
footer={
<>
- <Button disabled={!locations.length} {...busyProps(preview.isPending)} onClick={runPreview}>预览</Button>
+ <Button disabled={!locations.length || running} {...busyProps(preview.isPending)} onClick={runPreview}>预览</Button>
{changes && !running && !job.outcome
? <Button onClick={runApply}>执行整理</Button>
: null}
@@ -162,17 +184,19 @@ export function OrganizeCard(
}>
<FieldsetTitle id="cleanup-organize-title" gap="medium">整理</FieldsetTitle>
<p className="text-body-regular text-text-secondary">
- 按模板给文件改名并归入目录。先预览,确认后执行;执行过的一批可以整批退回。
+ 清理文件名中的特殊符号与乱码,也可按模板改名并归入目录。先预览,确认后执行;执行过的一批可以整批退回。
</p>
{organize.isError
? <div className="mt-3"><Note tone="error" title="整理配置读取失败">{errorMessage(organize.error)}</Note></div>
: null}
<div className="mt-3 flex flex-col gap-3">
+ <div data-organize-scope className="flex min-w-0 flex-wrap items-start gap-2">
{locations.length
? <Select aria-label="整理哪个来源" className="w-fit min-w-25" selectedKey={location || null}
onSelectionChange={(key) => {
if (key === null) return;
- setChosen(String(key)); setInvalid(null); preview.reset();
+ setChosen(String(key)); setScope({ location: String(key), path: '' });
+ setInvalid(null); preview.reset(); picker.reset();
}}>
{locations.map((row) => (
<SelectItem key={row.location} id={row.location} textValue={LOC[row.location] || row.location}>
@@ -181,6 +205,17 @@ export function OrganizeCard(
))}
</Select>
: null}
+ <div className="flex min-w-0 basis-64 flex-1 items-start gap-2">
+ <Input aria-label="整理路径" className="min-w-0 flex-1" placeholder="留空整理整个来源"
+ name="organize-path" autoComplete="off" spellCheck="false" value={path} ref={pathInput}
+ isInvalid={invalid === 'path'}
+ onChange={(value) => { setScope({ location, path: value }); setInvalid(null); preview.reset(); picker.reset() }} />
+ <IconButton icon={FolderSearchIcon} aria-label="选择整理路径" {...busyProps(picker.isPending)}
+ onClick={() => picker.mutate({ initial: path || locations.find((row) => row.location === location)?.roots[0] || '', location, path })} />
+ </div>
+ </div>
+ <p className="text-caption-1-regular text-text-secondary">指定路径时包含子目录,目录模板以该路径为起点。模板均留空时只清理文件名。</p>
+ {picker.isError ? <Note tone="error" title="目录选择失败">{errorMessage(picker.error)};也可直接输入路径。</Note> : null}
<Input label="文件名模板" placeholder="{number}[ {title}]" value={fields.file} ref={fileInput}
spellCheck="false" isInvalid={invalid === 'file'}
onChange={(value) => { edit({ file: value }); setInvalid(null) }} />
diff --git a/frontend/src/react/data-cleanup/organize.ts b/frontend/src/react/data-cleanup/organize.ts
index 4de55b148..1ac165993 100644
--- a/frontend/src/react/data-cleanup/organize.ts
+++ b/frontend/src/react/data-cleanup/organize.ts
@@ -6,6 +6,7 @@
* 来源与模板原样留着。执行与回滚是真实 ledger 写入,调用方必须先过确认弹层。 */
import { apiGet, apiSend } from '../../api';
import { queryClient } from '../query';
+import { PICK_FOLDER_URL } from '../../configuration-endpoints';
/* 模板跟着数据库走(`SYNCED_SETTING_KEYS` 里的 `organizeTemplates`),写的是设置面板同一个端点。 */
import { SETTINGS_URL } from '../settings-panel/settings-data';
@@ -43,6 +44,7 @@ export interface OrganizeData extends OrganizeJob {
export interface OrganizePlanRow { current_path: string; target_path: string; action: string }
export interface OrganizePlan {
+ path?: string;
counts: { change?: number; unchanged?: number; [key: string]: number | undefined };
reasons: Record<string, number>;
rows: OrganizePlanRow[];
@@ -51,7 +53,7 @@ export interface OrganizePlan {
}
/** 这一次要整理什么:来源与两份模板。 */
-export interface OrganizeRequest { location: string; file_template: string; dir_template: string }
+export interface OrganizeRequest { location: string; file_template: string; dir_template: string; path: string }
/** 执行还是回滚。两条都起同一个后台任务,结果落在同一格里。 */
export type OrganizeCommand = { kind: 'apply'; request: OrganizeRequest } | { kind: 'rollback' };
@@ -65,6 +67,8 @@ export async function prefetchOrganize(signal: AbortSignal): Promise<void> {
export const previewOrganize = (request: OrganizeRequest) =>
apiSend<OrganizePlan>(ORGANIZE_PREVIEW_URL, request);
+export const pickOrganizeFolder = (initial: string) => apiSend<{ path: string | null }>(PICK_FOLDER_URL, { initial });
+
export const startOrganize = (command: OrganizeCommand) => command.kind === 'apply'
? apiSend<OrganizeJob>(ORGANIZE_APPLY_URL, { ...command.request, confirm: true })
: apiSend<OrganizeJob>(ORGANIZE_ROLLBACK_URL, { confirm: true });
diff --git a/frontend/test/react/data-cleanup.test.tsx b/frontend/test/react/data-cleanup.test.tsx
index b6c08a375..98bbdae1b 100644
--- a/frontend/test/react/data-cleanup.test.tsx
+++ b/frontend/test/react/data-cleanup.test.tsx
@@ -22,7 +22,7 @@ import { hasResourceRoots, RESOURCE_SCAN_KEY, type ResourceScanState } from '../
import { IDLE_REPAIR } from '../../src/react/media-repair/media-repair';
import type { MediaSourcesData } from '../../src/react/media-sources';
import { queryClient } from '../../src/react/query';
-import { buttonNamed, click, mount, settle, type } from './render';
+import { buttonNamed, choose, click, mount, settle, type } from './render';
afterEach(() => {
queryClient.clear();
@@ -555,7 +555,7 @@ describe('整理', () => {
await click(buttonNamed('预览', host));
await settle();
expect(server.posts('/api/organize/preview')).toEqual([
- { location: 'local', file_template: '{number} {title}', dir_template: '' },
+ { location: 'local', path: '', file_template: '{number} {title}', dir_template: '' },
]);
expect(server.posts('/api/settings')).toEqual([]);
expect(host.textContent).toContain('2 个文件会改名或移动,5 个已经就是目标名字;跳过 缺番号 1。');
@@ -572,16 +572,62 @@ describe('整理', () => {
await settle();
await click(buttonNamed('执行整理', host));
await settle();
- expect(seen.map((options) => options.title)).toEqual(['按模板整理文件']);
+ expect(seen.map((options) => options.title)).toEqual(['整理文件']);
expect(seen[0]!.body).toContain('「本地」上的文件名与目录');
expect(server.posts('/api/organize/apply')).toEqual([
- { location: 'local', file_template: '{number}', dir_template: '', confirm: true },
+ { location: 'local', path: '', file_template: '{number}', dir_template: '', confirm: true },
]);
expect(server.posts('/api/settings')).toEqual([
{ organizeTemplates: { local: { file: '{number}', dir: '' } } },
]);
});
+ it('路径选择与输入共用预览范围;编辑路径后须重新预览', async () => {
+ const seen = confirmWith(true);
+ const server = serve({
+ '/api/organize': { ...organizeIdle, status: 'running' },
+ '/api/organize/preview': plan,
+ '/api/organize/apply': { status: 'running', job_id: 'scoped-1' },
+ '/api/pick-folder': { path: 'R:\\media\\合集' },
+ '/api/settings': { ok: true },
+ });
+ queryClient.setQueryData(['organize'], organizeIdle);
+ const host = await wrap(<OrganizeCard toast={vi.fn()} failure={vi.fn()} />);
+ const path = host.querySelector<HTMLInputElement>('input[name="organize-path"]');
+ await click(host.querySelector('[aria-label="选择整理路径"]'));
+ await settle();
+ expect(server.posts('/api/pick-folder')).toEqual([{ initial: 'R:\\media' }]);
+ expect(path?.value).toBe('R:\\media\\合集');
+ await click(buttonNamed('预览', host));
+ await settle();
+ expect(server.posts('/api/organize/preview')[0]).toMatchObject({ path: 'R:\\media\\合集' });
+ await type(path, 'R:\\media\\其他');
+ expect(buttonNamed('执行整理', host)).toBeNull();
+ await click(buttonNamed('预览', host));
+ await settle();
+ await click(buttonNamed('执行整理', host));
+ await settle();
+ expect(seen[0]?.body).toContain('R:\\media\\其他');
+ expect(server.posts('/api/organize/apply')[0]).toMatchObject({ path: 'R:\\media\\其他', confirm: true });
+ });
+
+ it('取消目录选择保留输入;切换来源清空路径和预览', async () => {
+ const data = { ...organizeIdle, locations: [...organizeIdle.locations, { location: '115', roots: ['B:\\'] }] };
+ serve({ '/api/organize': data, '/api/organize/preview': plan, '/api/pick-folder': { path: null } });
+ queryClient.setQueryData(['organize'], data);
+ const host = await wrap(<OrganizeCard toast={vi.fn()} failure={vi.fn()} />);
+ const path = host.querySelector<HTMLInputElement>('input[name="organize-path"]');
+ await type(path, 'R:\\media\\合集');
+ await click(host.querySelector('[aria-label="选择整理路径"]'));
+ await settle();
+ expect(path?.value).toBe('R:\\media\\合集');
+ await click(buttonNamed('预览', host));
+ await settle();
+ await choose(host.querySelector('[aria-label="整理哪个来源"]'), '115');
+ expect(path?.value).toBe('');
+ expect(buttonNamed('执行整理', host)).toBeNull();
+ });
+
it('有上一批才给回滚;回滚也先确认,取消就不发', async () => {
const seen = confirmWith(false);
const server = organizeServer({ ...organizeIdle, last_batch: 'batch-9' });
diff --git a/scripts/clean_names.py b/scripts/clean_names.py
index c26127ce7..e65eee654 100644
--- a/scripts/clean_names.py
+++ b/scripts/clean_names.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-文件名净化 —— 去掉盗版站塞进文件名的推广域名与残留噪声。
+文件名净化:清除推广域名、装饰符号、乱码字形与残留噪声。
只做可逆、无歧义的改写。番号使用 Peach 的统一规范:大写、标准连字符、片商番号
至少三位数字;FC2 统一为 ``FC2-PPV-<数字>``。
@@ -35,6 +35,7 @@ from peach.review_csv import write_rows
from peach.catalog_rules import is_jav_code, normalise_code_key
from peach.config import DATABASE_PATH, GENERATED_DIR, LOG_DIR
from peach.media_sources import SCANNABLE_LOCATIONS
+from peach.organize_templates import clean_filename
from peach.scripting import (
add_ledger_write_args, open_for_write, open_readonly, verify_after_write,
)
@@ -130,7 +131,7 @@ def propose(name: str, code: str | None = None,
if not dot or not stem: # 没有扩展名、或形如 ".mp4" 的空主干,都不碰
return name
- new = RE_PREFIX.sub("", name, count=1)
+ new = RE_PREFIX.sub("", clean_filename(name), count=1)
new, bracket_domains = RE_BRACKET_DOMAIN.subn("", new)
new = RE_SUFFIX.sub("", new)
new = RE_ADCOPY.sub("", new)
diff --git a/src/peach/organize.py b/src/peach/organize.py
index e4a6260a5..3906eb232 100644
--- a/src/peach/organize.py
+++ b/src/peach/organize.py
@@ -19,11 +19,11 @@ import sqlite3
import time
from collections.abc import Callable, Iterable, Sequence
from contextlib import contextmanager
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
from .catalog_rules import is_jav_code, is_uncensored_release, normalise_code_key, part_marker
from .jobs import ACTIVE_ASSET_SQL
-from .organize_templates import MAX_PATH, TemplateError, render, validate_template
+from .organize_templates import MAX_PATH, TemplateError, clean_filename, render, validate_template
from .platform import (is_windows_path, location_mounts, location_roots, resolve_root, root_online,
translate_ledger_path, within_root)
from .review_csv import write_rows
@@ -181,11 +181,38 @@ def _extension(name: str) -> str:
return f".{ext}" if dot and stem else ""
+def scope_path(location: str, path: str = '', roots=None) -> str:
+ """将指定目录核对并转换为账本路径;空值表示整个来源。"""
+ if not isinstance(path, str):
+ raise OrganizeError('整理路径必须是目录路径')
+ text = path.strip()
+ if not text:
+ return ''
+ if '..' in PureWindowsPath(text).parts or '\x00' in text:
+ raise OrganizeError('整理路径不能包含上级目录跳转或空字符')
+ declared = location_roots() if roots is None else roots
+ if resolve_root(text, declared)[0] != location:
+ local = Path(text)
+ if local.is_absolute():
+ for index, mount in enumerate(location_mounts().get(location, ())):
+ if within_root(local, mount) and index < len(declared.get(location, ())):
+ tail = local.resolve().relative_to(mount.resolve())
+ text = str(PureWindowsPath(declared[location][index], *tail.parts))
+ break
+ candidate = PureWindowsPath(text)
+ if not candidate.is_absolute() or '..' in candidate.parts:
+ raise OrganizeError('整理路径须为所选来源内的绝对目录路径,不能包含上级目录跳转')
+ canonical = ntpath.normpath(text)
+ if resolve_root(canonical, declared)[0] != location:
+ raise OrganizeError('整理路径不在所选来源内')
+ return canonical
+
+
def build_plan(connection: sqlite3.Connection, *, location: str,
file_template: str = "", dir_template: str = "",
roots=None, online: bool | None = None,
- asset_ids: Sequence[int] | None = None) -> dict:
- """按模板给一个来源生成逐文件计划。
+ asset_ids: Sequence[int] | None = None, path: str = '') -> dict:
+ """按目录范围与可选模板生成逐文件整理计划。
返回 `{"rows": [...], "counts": {...}}`:`rows` 只含会变的行与被跳过的行,
已经就是目标名字的行只进 `counts["unchanged"]`——几万行原样列出来,用户要找的
@@ -196,11 +223,12 @@ def build_plan(connection: sqlite3.Connection, *, location: str,
"""
file_template = validate_template(file_template)
dir_template = validate_template(dir_template, directory=True)
- if not file_template and not dir_template:
- raise OrganizeError("至少要给一个模板")
-
declared = dict(location_roots() if roots is None else roots)
+ selected_path = scope_path(location, path, declared)
rows = _rows(connection, location, asset_ids)
+ if selected_path:
+ selected = PureWindowsPath(selected_path)
+ rows = [row for row in rows if PureWindowsPath(row['path']).is_relative_to(selected)]
counts: dict[str, int] = {"total": len(rows), "unchanged": 0, "change": 0, "skip": 0}
reasons: dict[str, int] = {}
plan: list[dict] = []
@@ -223,7 +251,8 @@ def build_plan(connection: sqlite3.Connection, *, location: str,
performers = _performers(connection, location)
# 目标撞名先按账本已知的路径判一遍:同一批里两行算出同一个名字,或者目标位置上
# 已经躺着另一条记录,都在预览里就说清楚,而不是等执行到一半才报一行失败。
- claimed = {str(row["path"]).casefold(): int(row["id"]) for row in rows}
+ claimed = {str(path).casefold(): int(aid) for aid, path in connection.execute(
+ 'SELECT id,path FROM asset WHERE location=? AND path IS NOT NULL', (location,))}
for row in rows:
path = str(row["path"])
@@ -242,9 +271,9 @@ def build_plan(connection: sqlite3.Connection, *, location: str,
if not rendered:
skip(row, SKIP_MISSING_FIELD)
continue
- target_dir = ntpath.join(root, *rendered.split("/"))
+ target_dir = ntpath.join(selected_path or root, *rendered.split("/"))
name = str(row["name"] or ntpath.basename(path))
- target_name = name
+ target_name = clean_filename(name)
if file_template:
rendered, absent = render(file_template, values)
missing |= absent
diff --git a/src/peach/organize_templates.py b/src/peach/organize_templates.py
index 2188606e8..5b222eea9 100644
--- a/src/peach/organize_templates.py
+++ b/src/peach/organize_templates.py
@@ -9,8 +9,8 @@
清洗与逃逸防护分两层,缺一层都会出事:
-* **取值这一层**只可能带来非法字符(标题里的 `:` 与 `?`、演员名之间的 `/`),所以按
- Windows 的保留字符逐个替换,并挡住 `CON`、`PRN` 这类保留名与结尾的点和空格。
+* **取值这一层**清除符号噪声,并将 Windows 保留字符(标题里的 `:` 与 `?`、演员名之间的 `/`)
+ 逐个替换,同时挡住 `CON`、`PRN` 这类保留名与结尾的点和空格。
* **模板本身这一层**才可能带来路径逃逸:`..\\..\\Windows`、`C:\\`、`/etc`。取值那层的
清洗挡不住它——那些字符是用户自己写在模板里的字面量。所以模板在保存和使用前都要过
`validate_template`,而不是等渲染完再看结果像不像话。
@@ -19,6 +19,7 @@ from __future__ import annotations
import ntpath
import re
+import unicodedata
from dataclasses import dataclass
#: 模板认识的占位符,以及它在界面上的说明。顺序就是界面上列出来的顺序。
@@ -62,13 +63,48 @@ class _Token:
parts: tuple = ()
+def clean_name_symbols(value: str) -> str:
+ """清除装饰符号、替代字形与不可见噪声,保留文字、标点、单位及算术符号。"""
+ parts: list[str] = []
+ for char in value:
+ category = unicodedata.category(char)
+ point = ord(char)
+ if category.startswith('C') or char in '\ufe0e\ufe0f\u20e3':
+ continue
+ if (category in {'So', 'Sm'} and point > 127 and char not in '×÷±−+=~°℃℉'
+ and not 0x3300 <= point <= 0x33FF):
+ parts.append(' ')
+ elif category == 'Sk' and 0x1F3FB <= point <= 0x1F3FF:
+ continue
+ elif char in '※⁂⁎⁑⁕†‡\﹨/':
+ parts.append(' ')
+ else:
+ parts.append(char)
+ text = ''.join(parts)
+ return re.sub(r'\s+', ' ', text).strip() if text != value else value
+
+
+def clean_filename(name: str) -> str:
+ """只清理名称主干;扩展名和可辨认的名称保留,空名称不生成改名计划。"""
+ stem, suffix = ntpath.splitext(name)
+ cleaned = clean_name_symbols(stem)
+ if cleaned != stem:
+ cleaned = re.sub(r' +(?=\.[A-Za-z0-9]{2,4}(?:\.|$))', '', cleaned)
+ cleaned = cleaned.rstrip('. ')
+ if not any(char.isalnum() for char in cleaned):
+ return name
+ if cleaned.split('.', 1)[0].upper() in _RESERVED:
+ cleaned = '_' + cleaned
+ return cleaned + suffix
+
+
def sanitise_component(value: str) -> str:
"""把一个取值收敛成能当路径组件的样子。
替换成 `_` 而不是删掉:`ABC-123:完整版` 删掉冒号会变成 `ABC-123完整版`,看不出
该处有过分隔;`_` 一眼能看出这个位置上有个不能进文件名的符号。
"""
- text = _ILLEGAL.sub("_", str(value or "")).strip()
+ text = _ILLEGAL.sub("_", clean_name_symbols(str(value or ""))).strip()
# 结尾的点和空格在 Windows 上会被静默吃掉,于是「建出来的名字」和「要求的名字」
# 不一致,下一轮整理又会认为这一行还没做完。
text = text.rstrip(". ")
diff --git a/src/peach/web_organize.py b/src/peach/web_organize.py
index ae052f76b..48d492051 100644
--- a/src/peach/web_organize.py
+++ b/src/peach/web_organize.py
@@ -60,13 +60,15 @@ def q_organize(contract, _args=None) -> dict:
def w_organize_preview(contract, body) -> dict:
"""出计划:写一份 CSV,回给界面会变的行(上限 200)与跳过统计。"""
location, file_template, dir_template = _templates(contract, body)
+ path_scope = organize.scope_path(location, body.get('path', ''))
with contract.read_connection() as connection:
plan = organize.build_plan(connection, location=location,
- file_template=file_template, dir_template=dir_template)
+ file_template=file_template, dir_template=dir_template,
+ path=path_scope)
path = organize.plan_path(contract.candidate_root, location)
organize.write_plan(path, plan["rows"])
changes = [row for row in plan["rows"] if row["action"] != "skip"]
- return {"ok": True, "location": location, "counts": plan["counts"],
+ return {"ok": True, "location": location, "path": path_scope, "counts": plan["counts"],
"reasons": plan["reasons"], "rows": changes[:200],
"truncated": len(changes) > 200, "plan_csv": str(path)}
@@ -97,12 +99,11 @@ def _run_write(contract, job_id: str, work) -> dict:
def w_organize_apply(contract, body) -> dict:
- """按确认过的模板执行整理。重跑一次计划,不信任界面手上那份。"""
+ """按确认过的范围与可选模板执行整理,计划由服务端核对。"""
if body.get("confirm") is not True:
raise ValueError("整理需要确认")
location, file_template, dir_template = _templates(contract, body)
- if not file_template and not dir_template:
- raise ValueError("至少要给一个模板")
+ path_scope = organize.scope_path(location, body.get('path', ''))
if organize.unverified_location(location):
raise ValueError(f"{location} 挂载上的改名无法核验云端结果,界面只出预览,不执行")
job = contract.organize_job
@@ -114,7 +115,7 @@ def w_organize_apply(contract, body) -> dict:
with contract.read_connection() as connection:
plan = organize.build_plan(connection, location=location,
file_template=file_template,
- dir_template=dir_template)
+ dir_template=dir_template, path=path_scope)
if not job.checkpoint(job_id, plan=plan, batch_stamp=batch_stamp):
raise InterruptedError('整理已停止')
job.update(job_id, total=plan["counts"]["change"], stage="正在整理")
@@ -126,9 +127,9 @@ def w_organize_apply(contract, body) -> dict:
completed_at=time.time())
started = job.start(work, restart=True,
- initial={"stage": "正在核对计划", "location": location},
+ initial={"stage": "正在核对计划", "location": location, 'path': path_scope},
recovery={'confirm': True, 'location': location, 'file_template': file_template,
- 'dir_template': dir_template, 'action': 'apply'})
+ 'dir_template': dir_template, 'path': path_scope, 'action': 'apply'})
return {key: value for key, value in started.items() if key not in ('plan', 'batch_stamp')}
diff --git a/tests/test_organize.py b/tests/test_organize.py
index 04019051e..f17388700 100644
--- a/tests/test_organize.py
+++ b/tests/test_organize.py
@@ -11,7 +11,7 @@ from unittest import mock
from peach import organize
from peach.organize_templates import (
- TemplateError, render, sanitise_component, validate_template,
+ TemplateError, render, sanitise_component, validate_template, clean_filename,
)
from support.ledger import fresh_ledger
@@ -68,6 +68,24 @@ class TemplateRenderTests(unittest.TestCase):
class SanitiseTests(unittest.TestCase):
+ def test_filename_symbols_and_invalid_unicode_are_removed(self):
+ cases = {
+ '01_First Part⧹⧹Second Part⧹⧹Last Scene.mp4':
+ '01_First Part Second Part Last Scene.mp4',
+ '★ 标题💎👑✨ → 片段 �.mp4': '标题 片段.mp4',
+ '标题\\片段﹨补充/附录.mp4': '标题 片段 补充 附录.mp4',
+ '标题\ue519\u200b\ufeff\x00片段.mp4': '标题片段.mp4',
+ '👩🏽\u200d💻标题❤️\ufe0f.mp4': '标题.mp4',
+ '【中日文】 café ガール 168㎝ 1920×1080 (2).mp4':
+ '【中日文】 café ガール 168㎝ 1920×1080 (2).mp4',
+ '★💎.mp4': '★💎.mp4',
+ '★CON.mp4': '_CON.mp4',
+ }
+ for original, expected in cases.items():
+ with self.subTest(original=original):
+ self.assertEqual(clean_filename(original), expected)
+ self.assertEqual(clean_filename(expected), expected)
+
def test_illegal_characters_become_underscore(self):
self.assertEqual(sanitise_component('a<b>c:d"e/f\\g|h?i*j'),
"a_b_c_d_e_f_g_h_i_j")
@@ -156,6 +174,50 @@ class PlanTests(unittest.TestCase):
self.assertEqual(plan["rows"][0]["action"], "move")
self.assertEqual(plan["rows"][0]["target_path"], "R:\\media\\厂牌\\ABC-123.mp4")
+ def test_directory_scope_includes_descendants_and_excludes_prefix_siblings(self):
+ _seed(self.db_path, [
+ {'id': 1, 'path': r'R:\media\合集\a.mp4', 'name': 'a.mp4', 'code': 'ABC-001'},
+ {'id': 2, 'path': r'R:\media\合集\子目录\b.mp4', 'name': 'b.mp4', 'code': 'ABC-002'},
+ {'id': 3, 'path': r'R:\media\合集2\c.mp4', 'name': 'c.mp4', 'code': 'ABC-003'},
+ ])
+ plan = _plan(self.db_path, file_template='{number}', path='r:/MEDIA/合集/')
+ self.assertEqual([row['asset_id'] for row in plan['rows']], [1, 2])
+ self.assertEqual(plan['counts']['total'], 2)
+ self.assertEqual(_plan(self.db_path, file_template='{number}', path='')['counts']['total'], 3)
+
+ def test_scope_rejects_relative_outside_and_parent_paths(self):
+ for path in ('合集', r'S:\media', r'R:\media2', r'R:\media\..\other'):
+ with self.subTest(path=path), self.assertRaisesRegex(organize.OrganizeError, '整理路径'):
+ _plan(self.db_path, file_template='{number}', path=path)
+
+ def test_directory_template_uses_scope_as_base_and_checks_outside_scope_collisions(self):
+ _seed(self.db_path, [
+ {'id': 1, 'path': r'R:\media\合集\旧\a.mp4', 'name': 'a.mp4', 'code': 'ABC-001', 'studio': '厂牌'},
+ {'id': 2, 'path': r'R:\media\合集\厂牌\ABC-001.mp4', 'name': 'ABC-001.mp4', 'code': 'ABC-001'},
+ ])
+ plan = _plan(self.db_path, file_template='{number}', dir_template='{studio}', path=r'R:\media\合集', asset_ids=[1])
+ self.assertEqual(plan['counts']['skip'], 1)
+ self.assertEqual(plan['rows'][0]['reason'], organize.SKIP_TARGET_EXISTS)
+ self.assertEqual(plan['rows'][0]['target_path'], r'R:\media\合集\厂牌\ABC-001.mp4')
+
+ def test_local_mount_scope_is_translated_to_ledger_shape(self):
+ mount = self.holder / 'mounted'
+ mount.mkdir()
+ with mock.patch.object(organize, 'location_mounts', return_value={'local': (mount,)}):
+ self.assertEqual(organize.scope_path('local', str(mount / '合集'), DECLARED), r'R:\media\合集')
+
+ def test_filename_cleanup_needs_no_template_or_metadata(self):
+ _seed(self.db_path, [{'id': 1, 'path': r'R:\media\★标题⧹⧹片段.mp4',
+ 'name': '★标题⧹⧹片段.mp4'}])
+ plan = _plan(self.db_path)
+ self.assertEqual(plan['rows'][0]['target_path'], r'R:\media\标题 片段.mp4')
+
+ def test_template_values_share_filename_symbol_cleanup(self):
+ _seed(self.db_path, [{'id': 1, 'path': r'R:\media\old.mp4', 'name': 'old.mp4',
+ 'code': 'ABC-123', 'title': '★标题💎'}])
+ plan = _plan(self.db_path, file_template='{number} {title}')
+ self.assertEqual(plan['rows'][0]['target_path'], r'R:\media\ABC-123 标题.mp4')
+
def test_row_already_named_as_asked_is_not_listed(self):
_seed(self.db_path, [
{"id": 1, "path": "R:\\media\\ABC-123.mp4", "name": "ABC-123.mp4",
@@ -278,6 +340,24 @@ class ApplyTests(unittest.TestCase):
row = connection.execute("SELECT path,name FROM asset WHERE id=1").fetchone()
self.assertEqual(row, ("R:\\media\\厂牌\\ABC-123.mp4", "ABC-123.mp4"))
+ def test_scoped_symbol_cleanup_and_rollback_preserve_unselected_files(self):
+ self._file('合集/★标题⧹⧹片段.mp4')
+ self._file('合集2/★标题.mp4')
+ _seed(self.db_path, [
+ {'id': 1, 'path': r'R:\media\合集\★标题⧹⧹片段.mp4', 'name': '★标题⧹⧹片段.mp4'},
+ {'id': 2, 'path': r'R:\media\合集2\★标题.mp4', 'name': '★标题.mp4'},
+ ])
+ plan = _plan(self.db_path, path=r'R:\media\合集')
+ result = self._apply(plan)
+ self.assertEqual((result['moved'], result['failed']), (1, 0))
+ self.assertTrue((self.media / '合集/标题 片段.mp4').exists())
+ self.assertTrue((self.media / '合集2/★标题.mp4').exists())
+ with closing(sqlite3.connect(self.db_path)) as connection:
+ self.assertEqual(connection.execute('SELECT name FROM asset WHERE id=1').fetchone()[0], '标题 片段.mp4')
+ result = organize.rollback_batch(connection, organize.latest_batch(self.holder))
+ self.assertEqual((result['restored'], result['failed']), (1, 0))
+ self.assertTrue((self.media / '合集/★标题⧹⧹片段.mp4').exists())
+
def test_rollback_puts_everything_back(self):
self._file("旧/abc123.mp4")
_seed(self.db_path, [
@@ -409,6 +489,23 @@ class EndpointTests(unittest.TestCase):
w_organize_apply(self.contract, {"location": "local",
"file_template": "{number}"})
+ def test_preview_and_apply_share_validated_scope_and_recovery_parameters(self):
+ from peach.web_organize import w_organize_preview, w_organize_apply
+
+ request = {'location': 'local', 'path': r'R:\media\旧', 'file_template': '{number}', 'dir_template': ''}
+ plan = w_organize_preview(self.contract, request)
+ self.assertEqual(plan['path'], request['path'])
+ self.assertEqual(plan['counts']['total'], 1)
+ with mock.patch.object(self.contract.organize_job, 'start', return_value={'status': 'running'}) as start:
+ w_organize_apply(self.contract, {**request, 'confirm': True})
+ self.assertEqual(start.call_args.kwargs['recovery']['path'], request['path'])
+ self.assertEqual(start.call_args.kwargs['initial']['path'], request['path'])
+ for body in ({**request, 'path': r'S:\outside'}, {**request, 'path': ['R:\\media']}):
+ with self.subTest(body=body), self.assertRaisesRegex(organize.OrganizeError, '整理路径'):
+ w_organize_preview(self.contract, body)
+ with self.subTest(body=body), self.assertRaisesRegex(organize.OrganizeError, '整理路径'):
+ w_organize_apply(self.contract, {**body, 'confirm': True})
+
def test_apply_on_a_source_without_verified_rename_is_refused(self):
from peach.web_organize import w_organize_apply
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 80b56f8fb..cdc5de40e 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -2067,8 +2067,21 @@ class OperationalScriptTests(unittest.TestCase):
)
self.assertEqual(
propose("❤成人游戏-导航-【688GM.CC】.png"),
- "❤成人游戏-导航.png",
+ "成人游戏-导航.png",
)
+
+ def test_filename_cleanup_removes_symbols_and_preserves_words_and_extensions(self):
+ propose = self.clean_names.propose
+ for original, expected in (
+ ('01_Title⧹⧹Part.mp4', '01_Title Part.mp4'),
+ ('★片名💎👩🏽\u200d💻.mp4', '片名.mp4'),
+ ('片名\u200b\ue519�.mp4.jpg', '片名.mp4.jpg'),
+ ('café ガール (2) 1920×1080.mp4', 'café ガール (2) 1920×1080.mp4'),
+ ('★💎.mp4', '★💎.mp4'),
+ ):
+ with self.subTest(original=original):
+ self.assertEqual(propose(original), expected)
+ self.assertEqual(propose(expected), expected)
self.assertEqual(
propose("QR CODE--扫一扫.png"),
"QR CODE--扫一扫.png",