Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(media): 媒体库与存储根目录各有持久身份

longmeidao8126fb43030d
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 74aacd322..f4600b460 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -198,9 +198,21 @@ Windows 测试包默认使用 `%LOCALAPPDATA%\Peach\peach-data`。首次设置
`/api/sources` 返回周期快照和检测时间;正在检测或探测未返回时,`online` 为 `null`,页面保留来源可用状态。故障面板的「刷新状态」读取最新快照,后台按上述间隔重新探测。实际播放和扫描仍即时检查目录。`/healthz` 的 `media_mounts` 摘要与托盘显示来源名和故障原因;挂载故障不触发正常服务重启。探测线程最多四个,同一目录有未返回的探测时不重复启动。
+### 媒体库与存储根目录
+
+媒体库保存名称和图标,可以包含多个存储根目录。配置页与首次设置中的「目录所属媒体库」明确指定归属;名称相同的媒体库保持独立。修改同一库的名称或图标会同步到其全部目录,调整目录顺序不会改变身份。
+
+`media.library_catalog.<library_id>` 和 `media.storage_roots.<root_id>` 持久保存身份。路径、挂载、来源及读取策略归根目录,名称与图标归媒体库。`media.locations` 等路径表是兼容投影,手动配置以身份表为准,字段与升级依据见 [ADR-0115](adr/0115-library-and-storage-root-identity.md)。
+
+路径配置首次保存时按原同名分组写入稳定身份。也可用 `scripts/upgrade_media_identity.py --data-root <数据根>` 预演,核对后加 `--apply` 显式升级;脚本备份配置并原子写入,不打开 ledger。重复执行保留身份。真实配置升级按部署授权执行,先在隔离配置验证。
+
+已有目录更换位置时,选择「重定位此目录,保留文件记录」;它保留账本前缀并更新本机挂载位置。选择「添加另一目录」创建独立根目录。移除目录声明保留文件及个人记录,文件删除仍使用各自的确认入口。目录重定位应指向同一批文件,不能用已有 ID 接管另一批内容。
+
+每个根目录的离线状态按 `root_id` 返回。多目录媒体库中的一项目录离线,只影响该目录中的作品;来源筛选仅在所有根目录离线时禁用该来源。资源清理继续保留现有在线保护条件。
+
### 在 macOS 上对应 Windows 路径:`[media.mounts]`
-在首次设置或配置页中添加媒体目录,填写这台设备能读取的目录,例如 macOS 的 `/Volumes/Media`、Linux 的 `/mnt/media` 或 Docker 容器内的 `/media`。Peach 自动保存数据库所需的路径配置。已有目录改位置时,修改这一行的媒体目录;内部路径的对应关系由 Peach 保留。
+在首次设置或配置页中添加媒体目录,填写这台设备能读取的目录,例如 macOS 的 `/Volumes/Media`、Linux 的 `/mnt/media` 或 Docker 容器内的 `/media`。Peach 自动保存数据库所需的路径配置。已有目录改位置时,修改这一行的媒体目录并选择重定位;内部路径的对应关系由 Peach 保留。
以下字段说明供手动编辑配置或在多台 Peach 之间对应已有媒体目录时参考。
@@ -211,7 +223,7 @@ Peach 数据库中每部影片的 `path` 字段都使用 Windows 格式,例如
- `[media.mounts] local = '/Volumes/<卷名>/media'` 表示本机实际读取的目录。数据库中的 `R:\media\x` 会转换成 `/Volumes/<卷名>/media/x`。
- 一个来源有多个目录时,两项都写数组,目录数量和顺序必须相同。
-Windows 直接使用 `[media.locations]` 中的路径,`[media.mounts]` 可以留空。macOS 和 Linux 仍然使用两项配置;缺少对应实际目录时,该来源显示离线,媒体记录保留,但无法读取文件。把 `[media.locations]` 的值改成 POSIX 路径不会同步修改已有影片记录,也无法替代这一步转换。媒体来源键写错或写成盘符时,配置会被拒绝。
+Windows 的 `[media.mounts]` 可以留空,此时直接使用账本前缀;重定位目录时同样执行挂载映射。macOS 和 Linux 仍然使用两项配置;缺少对应实际目录时,该根目录显示离线,媒体记录保留,但无法读取文件。把 `[media.locations]` 的值改成 POSIX 路径不会同步修改已有影片记录,也无法替代这一步转换。媒体来源键写错或写成盘符时,配置会被拒绝。
临时诊断时可以用环境变量覆盖,例如 `PEACH_MEDIA_MOUNTS=local=/mnt/res,115=/mnt/115`。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index e561c39bb..bfde1d3e4 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -860,3 +860,9 @@ Python 源文件纳入 `src/peach/library_sharing.py` 与 `src/peach/library_pro
任务中心复用 `CodeBlock` 展示可复制的 JSON 技术详情。`task_results.result_counts` 将链接检查、资源扫描、追更、订阅、来源查找及浏览记录分析的明细折算为领域数量,供后台结算与读取投影共用;读取投影只补同一轮已结束的恢复检查点,不写 ledger。想要资料任务按作品保存未完整取得的结果,续跑时逐项更新数量。页面保留失败、访问失败、未能清理等结果,有问题的完成任务显示“发现问题”并独立展示;原始任务执行状态仍由任务服务维护。未新增依赖。
普通 Toast 与扫描任务卡共用 Agent Progress 外框,16px 半径由通知栈内的既有 token 解析,细边框与接触阴影分别复用 `border-button-default`、`elevation-xs`,不改变内容排版。浏览器回归核对桌面、手机和明暗主题下的外框一致性,并以同一任务、同一内容回放外框基线生成对比图。
+
+## 媒体库与根目录身份
+
+身份生成复用 Python 3.14 标准库 [`uuid`](https://docs.python.org/3.14/library/uuid.html) 的 UUIDv4、UUIDv5(PSF 许可,随运行时维护,Windows/macOS/Linux,无新增安装体积);路径归属复用 `platform.resolve_root`、`PureWindowsPath`,配置写入复用 `fsutil.atomic_write_text`,扫描沿用 SQLite upsert 与现有断点。当前树与 Git 中的媒体库分组、目录索引、来源探测和下载渠道共同消费这些身份。
+
+媒体库与根目录的归属是 Peach 的领域模型,不引入 Jellyfin/Emby 等独立媒体服务器或数据库 ORM:这些方案不能直接维护现有账本、个人记录和 Windows 账本路径契约。只读旧配置使用确定性升级,显式保存持久化身份;新增实体的随机 UUID 与显示名称无关。隔离用例覆盖配置往返、同名库、重排、重定位、根目录离线及扫描个人记录保护;实现与验收边界见 [ADR-0115](adr/0115-library-and-storage-root-identity.md)。未新增依赖,不自动写真实 ledger。
diff --git a/docs/ROUTES.md b/docs/ROUTES.md
index f8aa640b0..89909e7ed 100644
--- a/docs/ROUTES.md
+++ b/docs/ROUTES.md
@@ -28,6 +28,12 @@
## 浏览入口
+馆藏查询的 `library` 参数使用持久 `library_id`。`GET /api/libraries` 返回 `id`、`name`、`icon`、`folders`、`metered` 与根目录身份列表;名称只用于展示。未知 ID 筛选为空集。`GET /api/items` 和 `/api/item` 的可归属资产附带 `root_id`、`library_id`,版本和分卷仍使用各自资产 ID。
+
+`GET /api/sources` 在来源行的 `roots` 中提供 `root_id`、`library_id`、根目录状态和检测时间;`offline_roots` 列出确认离线的根目录 ID,`offline` 保留全部根目录离线的来源摘要。媒体访问失败的 `offline` 响应同时包含对应 `root_id`。
+
+配置和首次设置的媒体行接受 `root_id`、`library_id`;新增媒体库使用独立 ID,同名不合并。既有根目录更改实际位置必须附 `change_mode: "relocate"`,保留 `root` 账本前缀;添加另一目录省略根目录身份。名称与图标在同一 `library_id` 的行间必须一致。非法路径、归属或身份通过原字段错误契约返回,不写配置。详见 [媒体库与存储根目录](OPERATIONS.md#媒体库与存储根目录)。
+
| 地址 | 用途 |
| --- | --- |
| `/` | 全部馆藏,含本地硬盘与已挂载网盘;新作行使用作品详情地址 |
diff --git a/docs/adr/0115-library-and-storage-root-identity.md b/docs/adr/0115-library-and-storage-root-identity.md
new file mode 100644
index 000000000..36926bf17
--- /dev/null
+++ b/docs/adr/0115-library-and-storage-root-identity.md
@@ -0,0 +1,31 @@
+# ADR-0115:媒体库与存储根目录身份
+
+状态:已采纳
+
+## 背景
+
+媒体库组织作品,存储根目录声明文件的来源、账本路径及本机挂载映射。名称可以重复或修改,目录顺序也不构成身份。多目录媒体库需要按根目录判断可达性。
+
+## 决策
+
+配置持久化两类独立 UUID:`media.library_catalog.<library_id>` 保存名称和图标,`media.storage_roots.<root_id>` 保存 `library_id`、`location`、`root`、`mount` 与 `cost`。一个根目录属于一个媒体库,同名媒体库保持独立。`root_id` 表示一项目录声明,不代表硬盘。
+
+`media.locations`、`media.mounts`、路径键名称、图标及成本表是兼容投影。存在身份表时以身份表为准。扫描与路径授权继续使用平台路径解析,不维护第二套文件路径。目录重复和父子重叠在所有媒体库之间统一拒绝。
+
+已有路径配置按原有同名分组升级。根目录 UUIDv5 的输入是规范化的账本前缀;媒体库 UUIDv5 的输入是排序后的成员前缀集合。升级结果与配置行顺序无关。配置读取不写文件;首次保存或显式升级将这些身份写入配置。持久化后修改名称、顺序与挂载映射均沿用 ID。新增媒体库使用独立 UUID,不根据名称寻找归属。
+
+文件的稳定身份仍是 `asset.id`。根目录归属由稳定账本前缀经 `platform.resolve_root` 投影,不新增 ledger 列,也不改写既有 `asset.path`。列表使用原有资产查询与 OR 范围筛选,不关联展开多份卡片。扫描保留已有路径写法,大小写等价的路径登记到原记录;既有多行冲突停止自动处理,不盲目合并副本或个人记录。
+
+重定位必须显式选择,保留根目录来源和账本前缀,仅更新实际挂载映射。Windows 同样执行挂载转换。添加另一目录取得新根目录身份。来源变更不能借已有根目录 ID 覆盖原归属。移除配置仅移除目录声明,文件删除和个人记录清理由各自入口负责。
+
+来源健康摘要仅在所有根目录均离线时判整个来源离线。接口同时提供每个根目录的身份与可达性;作品播放门槛按 `root_id` 判断。扫描恢复记录绑定实际挂载位置,重定位后重新遍历并按原文件键登记。
+
+## 升级与验证
+
+`scripts/upgrade_media_identity.py` 默认只预演,`--apply` 排他备份原配置再原子写入。重复读取与升级保留已写入身份。它不打开 ledger;生产配置升级须由用户明确授权,账本迁移遵循独立门槛。
+
+隔离验证覆盖旧配置分组、持久化往返、改名及重排、同名独立库、跨库重叠、目录重定位、个人记录与大小写路径登记、多根离线状态。界面使用真实小样本验收。
+
+## 代价
+
+路径表兼容消费者需要保持投影一致。手动修改配置应编辑身份表并重启;只修改投影不会改变目录归属。尚未持久化的旧配置应先升级再进行人工拆分,避免把名称变化解释为分组变化。
diff --git a/frontend/e2e/configuration-layout.test.ts b/frontend/e2e/configuration-layout.test.ts
index 81af5f29a..36789ad1d 100644
--- a/frontend/e2e/configuration-layout.test.ts
+++ b/frontend/e2e/configuration-layout.test.ts
@@ -97,16 +97,17 @@ describe('配置表单与行间距', () => {
const form = page.getByRole('form', { name: '媒体目录', exact: true });
const protectedFolder = form.locator('[data-media-read-policy="0"] [aria-haspopup="listbox"]');
await protectedFolder.waitFor();
+ // 带品牌图的四行,来源、所属媒体库与图标各显示一枚站标。
await page.waitForFunction(() => {
const marks = [...document.querySelectorAll<HTMLImageElement>('[data-folder-row] img')];
- return marks.length === 8 && marks.every(image => image.complete && image.naturalWidth > 0);
+ return marks.length === 12 &&marks.every(image => image.complete && image.naturalWidth > 0);
});
const marks = await form.locator('[data-folder-row] img').evaluateAll(images => images.map(image => {
const box = image.getBoundingClientRect();
return { inline: image.getAttribute('src')?.startsWith('data:image/png;base64,'),
width: box.width, height: box.height };
}));
- assert.deepEqual(marks, Array.from({ length: 8 }, () => ({ inline: true, width: 16, height: 16 })));
+ assert.deepEqual(marks, Array.from({ length: 12 }, () => ({ inline: true, width: 16, height: 16 })));
assert.ok(!(await form.innerText()).includes('(只读)'));
assert.ok((await protectedFolder.textContent())?.includes('代理保护'));
assert.ok((await form.locator('[data-media-read-policy="1"]').textContent())?.includes('正常读取'));
@@ -115,11 +116,19 @@ describe('配置表单与行间距', () => {
const row = form.locator('[data-folder-row]').nth(index);
const source = await row.locator('[aria-haspopup="listbox"]').first().boundingBox();
const policy = await row.locator('[data-media-read-policy] [aria-haspopup="listbox"]').boundingBox();
+ const library = await row.getByRole('button', { name: new RegExp(`目录所属媒体库 ${index + 1}`) }).boundingBox();
const name = await row.getByRole('textbox', { name: `媒体库名称 ${index + 1}`, exact: true }).boundingBox();
const icon = await row.getByRole('button', { name: `媒体库图标 ${index + 1}`, exact: true }).boundingBox();
- assert.ok(source && policy && name && icon);
- const centers = [source, policy, name, icon].map(box => box.y + box.height / 2);
- assert.ok(Math.max(...centers) - Math.min(...centers) <= 3, JSON.stringify({ index, source, policy, name, icon }));
+ assert.ok(source && policy && library && name && icon);
+ // 两排:来源与读取策略一排,所属媒体库、名称、图标一排;同排控件中线对齐,所属媒体库与来源同列。
+ const spread = (boxes: { y: number; height: number }[]) => {
+ const centers = boxes.map(box => box.y + box.height / 2);
+ return Math.max(...centers) - Math.min(...centers);
+ };
+ assert.ok(spread([source, policy]) <= 3, JSON.stringify({ index, source, policy }));
+ assert.ok(spread([library, name, icon]) <= 3, JSON.stringify({ index, library, name, icon }));
+ assert.ok(library.y >= source.y + source.height, JSON.stringify({ index, source, library }));
+ assert.ok(Math.abs(library.x - source.x) <= 1 && Math.abs(library.width - source.width) <= 1);
assert.ok(policy.width <= 132);
const bounds = await row.boundingBox();
assert.ok(bounds && bounds.x + bounds.width - (icon.x + icon.width) <= 14);
diff --git a/frontend/src/application/chrome.js b/frontend/src/application/chrome.js
index 8d3a81a0d..26070d92e 100644
--- a/frontend/src/application/chrome.js
+++ b/frontend/src/application/chrome.js
@@ -75,14 +75,21 @@ api('/api/libraries',{signal:effects.signal}).then(data=>{
if(!effects.isActive)return;
const choices=[['','全部媒体库','database'],...data.libraries.map(row=>[row.id,row.name,row.icon||'database'])];
const selected=sessionStorage.getItem('peach.library')||'';
- if(!choices.some(row=>row[0]===selected)){sessionStorage.removeItem('peach.library');location.reload();return}
+ if(!choices.some(row=>row[0]===selected)){
+ const matching=data.libraries.filter(row=>row.name===selected);
+ if(matching.length===1)sessionStorage.setItem('peach.library',matching[0].id);
+ else sessionStorage.removeItem('peach.library');
+ sessionStorage.removeItem('peach.library-label');location.reload();return;
+ }
const current=sessionStorage.getItem('peach.library')||'';
- boardBrand.querySelector('h1').textContent=current||'全部媒体库';
+ const currentName=choices.find(row=>row[0]===current)?.[1]||'全部媒体库';
+ sessionStorage.setItem('peach.library-label',currentName);
+ boardBrand.querySelector('h1').textContent=currentName;
const libraryMark=glyph=>MEDIA_SOURCE_ICONS[glyph]?.startsWith('data:')?`<img src="${MEDIA_SOURCE_ICONS[glyph]}" alt="">`:icon(MEDIA_SOURCE_ICONS[glyph]||glyph);
const mark=document.createElement('span');mark.className='mark';mark.setAttribute('aria-hidden','true');
mark.innerHTML=libraryMark(choices.find(row=>row[0]===current)?.[2]||'database');boardBrand.querySelector('.mark').replaceWith(mark);
libraryPicker.innerHTML=`<p>媒体库</p><div class="board-library-rows">${choices.map(([id,name,glyph])=>`<button type="button" data-library="${esc(id)}" aria-pressed="${id===current}"><span class="board-library-avatar">${libraryMark(glyph)}</span><span>${esc(name)}</span></button>`).join('')}</div><footer><button type="button" class="geist-button primary" data-library-manage>管理媒体库</button></footer>`;
- libraryPicker.querySelectorAll('[data-library]').forEach(button=>effects.handler(button, 'onclick', ()=>{sessionStorage.setItem('peach.library',button.dataset.library);location.assign('/')}));
+ libraryPicker.querySelectorAll('[data-library]').forEach(button=>effects.handler(button, 'onclick', ()=>{sessionStorage.setItem('peach.library',button.dataset.library);sessionStorage.setItem('peach.library-label',choices.find(row=>row[0]===button.dataset.library)?.[1]||'全部媒体库');location.assign('/')}));
effects.handler(libraryPicker.querySelector('[data-library-manage]'), 'onclick', ()=>{libraryFloating.setOpen(false);openDrawer(false);openConfigurationSection('媒体库与入库')});
/* 委托在这一列上,不挂在每个按钮身上:菜单每次取回媒体库都整块重画。
`pointerover`/`pointerout` 而不是 enter/leave,后两个不冒泡,委托接不到。 */
diff --git a/frontend/src/application/preferences.js b/frontend/src/application/preferences.js
index 4361f0584..a9698ffd8 100644
--- a/frontend/src/application/preferences.js
+++ b/frontend/src/application/preferences.js
@@ -31,8 +31,9 @@ export async function loadSourceStatus(){
try{
const d=await loadMediaSources(effects.signal);
if(!effects.isActive)return preferencesState.sourceOnline;
- preferencesState.sourceOnline=Object.fromEntries((d.sources||[]).map(s=>[s.location,s.online]));
- preferencesState.sourceProblems=Object.fromEntries((d.sources||[]).map(s=>[s.location,s.message||'']));
+ const roots=(d.sources||[]).flatMap(s=>s.roots||[]).filter(r=>r.root_id);
+ preferencesState.sourceOnline=Object.fromEntries([...(d.sources||[]).map(s=>[s.location,s.online]),...roots.map(r=>[r.root_id,r.online])]);
+ preferencesState.sourceProblems=Object.fromEntries([...(d.sources||[]).map(s=>[s.location,s.message||'']),...roots.map(r=>[r.root_id,r.message||''])]);
}catch{if(!effects.isActive)return preferencesState.sourceOnline;preferencesState.sourceOnline={};preferencesState.sourceProblems={}}
document.body.classList.toggle('offline-source',Object.values(preferencesState.sourceOnline).includes(false));
dropOfflineFromDefaultLoc();
diff --git a/frontend/src/player/detail-player.ts b/frontend/src/player/detail-player.ts
index e37239290..388e8b073 100644
--- a/frontend/src/player/detail-player.ts
+++ b/frontend/src/player/detail-player.ts
@@ -218,8 +218,8 @@ export async function mountDetailPlayer(
// 播到一半掉盘时 video 元素只报通用错误;来源状态才分得清脱盘和文件损坏。
if (options.checkSourceStatus === false) return;
void host.loadSourceStatus().then((status) => {
- if (status[String(item.location)] !== false || player.isDisposed()) return;
- player.error({ code: 2, message: `媒体目录无法访问 · ${host.offlineReason(String(item.location))}` });
+ if (status[String(item.root_id || item.location)] !== false || player.isDisposed()) return;
+ player.error({ code: 2, message: `媒体目录无法访问 · ${host.offlineReason(String(item.root_id || item.location))}` });
});
});
player.ready(() => {
diff --git a/frontend/src/player/types.ts b/frontend/src/player/types.ts
index 54e0ba79f..e737da6b8 100644
--- a/frontend/src/player/types.ts
+++ b/frontend/src/player/types.ts
@@ -56,6 +56,8 @@ export type VideojsFactory = (video: HTMLVideoElement, options: Record<string, u
/** 作品与关注条目共有的那几样。作品来自 `/api/item`,关注来自 `/api/follow/item`。 */
export interface PlayerItem {
id: number;
+ root_id?: string;
+ library_id?: string;
name?: string;
title?: string;
location?: string;
diff --git a/frontend/src/query/media-sources.ts b/frontend/src/query/media-sources.ts
index 4ae9994cc..783839fa3 100644
--- a/frontend/src/query/media-sources.ts
+++ b/frontend/src/query/media-sources.ts
@@ -16,7 +16,7 @@ export interface MediaSourceStatus {
online: boolean | null;
state?: string;
message?: string;
- roots?: unknown[];
+ roots?: { root_id?: string; library_id?: string; online: boolean | null; message?: string }[];
}
export interface MediaSourcesData {
diff --git a/frontend/src/react/bundle.d.ts b/frontend/src/react/bundle.d.ts
index 3e00f1c7d..c57bde500 100644
--- a/frontend/src/react/bundle.d.ts
+++ b/frontend/src/react/bundle.d.ts
@@ -235,6 +235,7 @@ export interface UpdateJob {
}
export interface MediaSource {
+ root_id?: string; library_id?: string;
location: string; root: string; path: string; online?: boolean; library?: string; library_icon?: string; cost?: 'free' | 'metered';
}
diff --git a/frontend/src/react/catalog-grid/types.ts b/frontend/src/react/catalog-grid/types.ts
index 7d33b0c45..1d48d8c64 100644
--- a/frontend/src/react/catalog-grid/types.ts
+++ b/frontend/src/react/catalog-grid/types.ts
@@ -8,6 +8,8 @@ export interface MediaEntityRef extends FaceRef { id: number }
/** `/api/items` 的一条。只列卡片读到的字段,其余原样带着,壳的缓存要的是整条。 */
export interface MediaItem {
id: number;
+ root_id?: string;
+ library_id?: string;
name?: string;
code?: string;
is_jav?: boolean;
diff --git a/frontend/src/react/immerse/immerse.ts b/frontend/src/react/immerse/immerse.ts
index 3123884f6..09eac7649 100644
--- a/frontend/src/react/immerse/immerse.ts
+++ b/frontend/src/react/immerse/immerse.ts
@@ -12,6 +12,7 @@ export interface ImmerseItem {
name?: string;
title?: string;
location?: string;
+ root_id?: string;
cost?: string;
duration?: number | null;
width?: number | null;
@@ -43,7 +44,7 @@ export function immerseQuery(filters: Record<string, string | number | null | un
/** 能直接进片单的:不按流量计费、有时长、来源没脱盘。脱盘来源的片子拉不到流,进了片单就是
* 一条黑屏加载中;详情页有门挡着,这里只能在入口筛掉。 */
export const playable = (item: ImmerseItem, offline: (location: string) => boolean): boolean =>
- item.cost !== 'metered' && !!item.duration && !offline(String(item.location ?? ''));
+ item.cost !== 'metered' && !!item.duration && !offline(String(item.root_id || item.location || ''));
export function shuffle<T>(list: T[], random: () => number = Math.random): T[] {
for (let i = list.length - 1; i > 0; i--) {
diff --git a/frontend/src/react/item-detail/item-detail-page.tsx b/frontend/src/react/item-detail/item-detail-page.tsx
index fba7faabf..b7775ae7b 100644
--- a/frontend/src/react/item-detail/item-detail-page.tsx
+++ b/frontend/src/react/item-detail/item-detail-page.tsx
@@ -106,7 +106,7 @@ function Detail(props: ItemDetailProps & { item: DetailItem; queue: DetailQueue
apiSend(PLAYLIST_URL, { action: 'progress', id: queue.playlistId, asset_id: item.id }).catch(() => {});
}, []);
- const gate = mediaGate(item, helpers.sourceOffline(item.location || ''));
+ const gate = mediaGate(item, helpers.sourceOffline(String(item.root_id || item.location || '')));
const next = nextPart(queue, item.id);
const continuePart = () => {
if (next && queue) actions.openQueueItem({ kind: queue.kind, seedId: queue.seedId, autoplay: true }, next.id);
@@ -226,7 +226,7 @@ function OfflineGate({ item, badge, helpers, actions }: {
<div id="offlineGate" role="status" data-item-gate="offline">
<Html html={badge} />
<b>媒体目录无法访问</b>
- <span>{helpers.offlineReason(item.location || '')}</span>
+ <span>{helpers.offlineReason(String(item.root_id || item.location || ''))}</span>
<button className="chip" id="offlineRetry" type="button" disabled={checking} onClick={() => void retry()}>
{still ? '仍无法读取 · 刷新' : '刷新状态'}
</button>
diff --git a/frontend/src/react/pages/setup/setup-api.ts b/frontend/src/react/pages/setup/setup-api.ts
index cd8dd4d0a..c6ac37cbf 100644
--- a/frontend/src/react/pages/setup/setup-api.ts
+++ b/frontend/src/react/pages/setup/setup-api.ts
@@ -54,7 +54,7 @@ export interface SetupDone {
export type SetupErrors = Partial<Record<string, string | string[]>>;
-export interface SetupFolder { path: string; location: string; root: string; cost?: 'free' | 'metered' | '' }
+export interface SetupFolder { path: string; location: string; root: string; library_id?: string; library?: string; cost?: 'free' | 'metered' | '' }
export interface SetupSubmission {
media_dir: SetupFolder[];
diff --git a/frontend/src/react/pages/setup/setup-form.tsx b/frontend/src/react/pages/setup/setup-form.tsx
index b4bc5e19c..d97886749 100644
--- a/frontend/src/react/pages/setup/setup-form.tsx
+++ b/frontend/src/react/pages/setup/setup-form.tsx
@@ -13,13 +13,17 @@ import { Checkbox } from '@/components/base/checkbox/checkbox';
import { Input } from '@/components/base/input/input';
import { Label } from '@/components/base/input/label';
import { Switch } from '@/components/base/switch/switch';
+import { Select, SelectItem } from '@/components/base/select/select';
import { SEGMENT, SEGMENTED_TRACK, SegmentedRadioGroup } from '../../components/segmented';
import { busyProps } from '../../settings/busy-props';
-import { FolderRow, isCloudSource, MediaReadPolicy, MediaReadPolicyHelp, SourceSelect, useFolderRows } from '../../settings/folder-rows';
+import {
+ FolderField, FolderFieldLine, FolderRow, isCloudSource, MediaReadPolicy, MediaReadPolicyHelp, SourceSelect, useFolderRows,
+} from '../../settings/folder-rows';
+import { libraryAutoChoice } from '../../settings/library-icon-picker';
import { PasswordPair } from '../../settings/password-pair';
import { ReportingChoices } from '../../settings/remote-reporting-settings';
-import { Disclosure, ErrorText, ExternalLink, Help } from '../../settings/section';
+import { Disclosure, ErrorText, ExternalLink, Help, SourceMark } from '../../settings/section';
import { CardGroup, GroupTitle } from '../auth-card';
import {
describeFailure, pickFolder, SetupRequestError, submitSetup,
@@ -49,7 +53,7 @@ export function SetupForm({ setup, onDone }: { setup: SetupQuestions; onDone: (d
const media = setup.questions.find((question) => question.input === 'folders');
const others = setup.questions.filter((question) => question.input !== 'folders');
const sources = setup.media_sources.map(({ value, label }) => [value, label] as const);
- const blank = (path = ''): SetupFolder => ({ path, location: setup.media_source_default, root: '', cost: setup.media_source_default === 'local' ? 'free' : '' });
+ const blank = (path = ''): SetupFolder => ({ path, location: setup.media_source_default, root: '', library_id: crypto.randomUUID(), library: '', cost: setup.media_source_default === 'local' ? 'free' : '' });
const folders = useFolderRows<SetupFolder>({
initial: () => [blank(media?.default ?? '')], blank: () => blank(), pickFolder, describe: describeFailure,
focusAfterPick: true,
@@ -175,16 +179,39 @@ export function SetupForm({ setup, onDone }: { setup: SetupQuestions; onDone: (d
inputRef={folders.inputRef(index)} picking={folders.picking === index}
onPick={() => void folders.pick(index)}
onRemove={folders.rows.length > 1 ? () => { folders.remove(index); addButton.current?.focus(); } : undefined}>
- <SourceSelect index={index} value={row.location} options={sources}
- onChange={(location) => folders.edit(index, { location, cost: location === 'local' ? 'free' : '' })} />
- <MediaReadPolicy index={index} cost={row.cost ?? ''}
- error={requireReadPolicy && !row.cost ? '请选择媒体读取策略' : undefined}
- onChange={(cost) => folders.edit(index, { cost })} />
+ <FolderFieldLine>
+ <SourceSelect index={index} value={row.location} options={sources}
+ onChange={(location) => folders.edit(index, { location, cost: location === 'local' ? 'free' : '' })} />
+ <MediaReadPolicy index={index} cost={row.cost ?? ''}
+ error={requireReadPolicy && !row.cost ? '请选择媒体读取策略' : undefined}
+ onChange={(cost) => folders.edit(index, { cost })} />
+ </FolderFieldLine>
+ <FolderFieldLine>
+ <FolderField label="所属媒体库" className="w-full @lg:w-60">
+ <Select className="w-full" aria-label={`目录所属媒体库 ${index + 1}`} selectedKey={row.library_id}
+ renderValue={<span className="flex min-w-0 items-center gap-2"><SourceMark mark={libraryAutoChoice(row.location)[0]} /><span className="truncate">{row.library || '未命名媒体库'}</span></span>}
+ onSelectionChange={key => {
+ const other = folders.rows.find(value => value.library_id === key);
+ folders.edit(index, { library_id: other?.library_id || crypto.randomUUID(), library: other?.library || '' });
+ }}>
+ {[...new Map(folders.rows.map(value => [value.library_id, value])).values()].map(value => (
+ <SelectItem key={value.library_id} id={value.library_id}>{value.library || '未命名媒体库'}</SelectItem>
+ ))}
+ <SelectItem id="new">新建媒体库</SelectItem>
+ </Select>
+ </FolderField>
+ <FolderField label="媒体库名称" className="w-full min-w-32 @lg:w-auto @lg:flex-1">
+ <Input className="w-full" aria-label={`媒体库名称 ${index + 1}`} placeholder="媒体库名称" maxLength={80}
+ value={row.library || ''} onChange={library => folders.rows.forEach((other, i) => {
+ if (other.library_id === row.library_id) folders.edit(i, { library });
+ })} />
+ </FolderField>
+ </FolderFieldLine>
</FolderRow>
))}
</div>
<Button ref={addButton} variant="secondary" leadingIcon={RiAddLine} className="self-start" onClick={folders.add}>
- 添加媒体库
+ 添加文件夹
</Button>
{cloud ? (
<>
diff --git a/frontend/src/react/settings/folder-rows.tsx b/frontend/src/react/settings/folder-rows.tsx
index 7f019faa2..93ca1b3b5 100644
--- a/frontend/src/react/settings/folder-rows.tsx
+++ b/frontend/src/react/settings/folder-rows.tsx
@@ -1,7 +1,7 @@
/* 媒体目录的行:配置页「这台电脑」与首启页共用。
*
- * 一行是一块描边卡:路径框、「选择文件夹」、多行时的移除键,下面一排放这一行的其余字段
- * (媒体来源与读取策略,配置页另有媒体库名称与图标),宽度够时并成一行。行的增删、
+ * 一行是一块描边卡:路径框、「选择文件夹」、多行时的移除键,下面按含义分两排、每格上方一行标签:
+ * 先是这个目录怎么读(来源、读取策略),再是它显示成哪个媒体库(所属、名称,配置页另有图标)。行的增删、
* 按行错误、新行接焦点与选择文件夹的忙态归 `useFolderRows`;弹系统对话框那一请求由调用方注入,这里不认识任何端点,首启页的独立
* 页面包因此不必带上主界面的请求封装。 */
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
@@ -11,7 +11,9 @@ import { MEDIA_SOURCE_ICONS } from '@peach/legacy/ui';
import { IconButton } from '@/components/base/buttons/icon-button';
import { Button } from '@/components/base/buttons/button';
import { Input } from '@/components/base/input/input';
+import { Label } from '@/components/base/input/label';
import { Select, SelectItem } from '@/components/base/select/select';
+import { cx } from '@/utils/cx';
import { ErrorText, Help, SourceMark } from './section';
import { busyProps } from './busy-props';
@@ -35,10 +37,27 @@ export const MEDIA_SOURCES: readonly SourceOption[] = MEDIA_SOURCE_OPTIONS;
export const sourceMark = (location: string) => MEDIA_SOURCE_ICONS[location] || 'database';
export const isCloudSource = (location: string) => CLOUD_LOCATIONS.includes(location);
+/** 行内一格:上方块级标签,下面是控件。标签只写给看的人;控件的无障碍名由各自带序号的
+ * `aria-label` 给,标签文字是它的一段,读屏与语音输入按看到的字也找得到。 */
+export function FolderField({ label, className, children }: { label: string; className?: string; children: ReactNode }) {
+ return (
+ <div className={cx('flex min-w-0 flex-col gap-1', className)}>
+ <Label elementType="span" aria-hidden>{label}</Label>
+ {children}
+ </div>
+ );
+}
+
+/** 一排字段。宽度够时并排,窄了逐格换行;按顶端对齐,标签同高所以控件也齐,某格下面多一句报错只往下长。 */
+export function FolderFieldLine({ children }: { children: ReactNode }) {
+ return <div className="flex w-full flex-wrap items-start gap-2">{children}</div>;
+}
+
export function MediaReadPolicy({ index, cost, error, onChange }: {
index: number; cost: SourceCost | ''; error?: string; onChange(cost: SourceCost): void;
}) {
- return <div data-media-read-policy={index} className="flex w-full flex-col gap-1.5 @lg:w-32">
+ return <div data-media-read-policy={index} className="flex w-full flex-col gap-1 @lg:w-32">
+ <Label elementType="span" aria-hidden>读取策略</Label>
<Select aria-label={`媒体读取策略 ${index + 1}`} placeholder="选择读取策略" isRequired
validationBehavior="aria" isInvalid={Boolean(error)} selectedKey={cost || null}
onSelectionChange={(key) => { if (key === 'free' || key === 'metered') onChange(key); }}>
@@ -50,7 +69,7 @@ export function MediaReadPolicy({ index, cost, error, onChange }: {
}
export function MediaReadPolicyHelp() {
- return <Help>代理保护会限制自动读取视频。</Help>;
+ return <Help>读取策略选「代理保护」时,会限制自动读取视频。</Help>;
}
export interface FolderRowValue { path: string; location: string }
@@ -168,8 +187,8 @@ export function FolderRow({ label, path, onPath, error, inputRef, picking, onPic
);
}
-/** 媒体来源下拉,每项带站标;本地磁盘是雪碧图的 `hard-drive`。选中项的站标就是它的标签,
- * 框上不再挂文字名,无障碍名称由 `aria-label` 给。 */
+/** 媒体来源下拉,每项带站标;本地磁盘是雪碧图的 `hard-drive`。上方标「来源」,
+ * 无障碍名称由带序号的 `aria-label` 给。 */
export function SourceSelect({ index, value, onChange, options = MEDIA_SOURCES }: {
index: number;
value: string;
@@ -177,11 +196,13 @@ export function SourceSelect({ index, value, onChange, options = MEDIA_SOURCES }
options?: readonly SourceOption[];
}) {
return (
- <Select className="w-full @lg:w-60" aria-label={`媒体来源 ${index + 1}`} selectedKey={value}
- onSelectionChange={(key) => { if (key !== null) onChange(String(key)); }}>
- {options.map(([kind, name]) => (
- <SelectItem key={kind} id={kind} textValue={name}><SourceMark mark={sourceMark(kind)} />{name}</SelectItem>
- ))}
- </Select>
+ <FolderField label="来源" className="w-full @lg:w-60">
+ <Select className="w-full" aria-label={`媒体来源 ${index + 1}`} selectedKey={value}
+ onSelectionChange={(key) => { if (key !== null) onChange(String(key)); }}>
+ {options.map(([kind, name]) => (
+ <SelectItem key={kind} id={kind} textValue={name}><SourceMark mark={sourceMark(kind)} />{name}</SelectItem>
+ ))}
+ </Select>
+ </FolderField>
);
}
diff --git a/frontend/src/react/settings/media-settings.tsx b/frontend/src/react/settings/media-settings.tsx
index 0ca5bbb62..6afa0a032 100644
--- a/frontend/src/react/settings/media-settings.tsx
+++ b/frontend/src/react/settings/media-settings.tsx
@@ -10,6 +10,7 @@ import { Button } from '@/components/base/buttons/button';
import { LinkButton } from '@/components/base/buttons/link-button';
import { Checkbox } from '@/components/base/checkbox/checkbox';
import { Input } from '@/components/base/input/input';
+import { Select, SelectItem } from '@/components/base/select/select';
import { ConnectionStatus } from '../components/connection-status';
import { ApiError, apiSend, errorMessage } from '../../api';
@@ -22,12 +23,15 @@ import { CloudDriveGuide } from './clouddrive-guide';
import { CloudProxySettings } from './cloud-proxy-settings';
import { CONFIGURATION_KEY, fetchConfiguration } from './configuration';
import { groupRoot } from './configuration-panel';
-import { FolderRow, isCloudSource, MEDIA_SOURCES, MediaReadPolicy, MediaReadPolicyHelp, SourceSelect, sourceMark, useFolderRows } from './folder-rows';
+import {
+ FolderField, FolderFieldLine, FolderRow, isCloudSource, MEDIA_SOURCES, MediaReadPolicy, MediaReadPolicyHelp, SourceSelect, sourceMark,
+ useFolderRows,
+} from './folder-rows';
import { sourceDefaultCost, type SourceCost } from '../../core/media-sources';
-import { LibraryIconPicker } from './library-icon-picker';
+import { libraryAutoChoice, LibraryIconPicker } from './library-icon-picker';
import { PushDiscoveryForm } from './push-discovery-settings';
import {
- ErrorText, ExternalLink, Fact, FactList, FieldLabel, Footer, Help, Section, SourceMark, Stack,
+ ErrorText, ExternalLink, Fact, FactList, Footer, Help, Section, SourceMark, Stack,
} from './section';
import { busyProps, useAction } from './use-action';
@@ -35,17 +39,18 @@ const sourceName = (location: string) => MEDIA_SOURCES.find(([kind]) => kind ===
const pickFolder = async (initial: string) =>
(await apiSend<{ path: string | null }>(PICK_FOLDER_URL, { initial })).path;
-interface MediaRow { path: string; location: string; root: string; library: string; library_icon: string; cost: SourceCost | '' }
+interface MediaRow { path: string; location: string; root: string; root_id?: string; library_id: string; library: string; library_icon: string; cost: SourceCost | ''; change_mode?: string }
interface FieldErrors { media_dirs?: string[]; port?: string }
interface SaveResult { saved: boolean; url: string; revision: string }
-const blankRow = (path = ''): MediaRow => ({ path, location: 'local', root: '', library: '', library_icon: '', cost: 'free' });
+const blankRow = (path = ''): MediaRow => ({ path, location: 'local', root: '', library_id: crypto.randomUUID(), library: '', library_icon: '', cost: 'free' });
function initialRows(data: ConfigurationData): MediaRow[] {
const known = data.media_sources?.filter((row) => MEDIA_SOURCES.some(([kind]) => kind === row.location));
if (known?.length) {
return known.map((row) => ({
path: row.path, location: row.location, root: row.root, library: row.library || '', library_icon: row.library_icon || '',
+ root_id: row.root_id, library_id: row.library_id || crypto.randomUUID(),
cost: row.cost ?? sourceDefaultCost(row.location),
}));
}
@@ -81,6 +86,15 @@ function MediaForm({ data, receipt }: ConfigurationGroupProps) {
const [saved, setSaved] = useState<SaveResult | null>(null);
const revision = useRef(data.revision);
const action = useAction();
+ const editLibrary = (index: number, patch: Partial<MediaRow>) => {
+ rows.forEach((row, i) => { if (row.library_id === rows[index]!.library_id) edit(i, patch); });
+ };
+ const libraries = [...new Map(rows.map(row => [row.library_id, row])).values()];
+ const chooseLibrary = (index: number, key: string) => {
+ const chosen = rows.find(row => row.library_id === key);
+ edit(index, chosen ? { library_id: chosen.library_id, library: chosen.library, library_icon: chosen.library_icon }
+ : { library_id: crypto.randomUUID(), library: '', library_icon: '' });
+ };
useEffect(() => {
if (!saved) return undefined;
@@ -129,30 +143,56 @@ function MediaForm({ data, receipt }: ConfigurationGroupProps) {
}
// 挂载状态是已保存的那份配置的读数,只标在路径没改过的行上。
- const mountOf = (path: string) => (path ? data.media_sources?.find((source) => source.path === path) : undefined);
+ const mountOf = (row: MediaRow) => data.media_sources?.find(source => source.root_id === row.root_id && source.path === row.path);
const cloud = rows.some((row) => isCloudSource(row.location));
const missing = cloud ? (data.mount_dependencies ?? []).filter((dependency) => !dependency.available) : [];
return (
<Section title="媒体目录" onSubmit={submit}>
<Stack>
<div className="flex flex-col gap-3">
- <FieldLabel>媒体目录</FieldLabel>
<div role="group" aria-label="媒体目录" className="flex flex-col gap-3">
{rows.map((row, index) => (
<FolderRow key={index} label={`媒体目录 ${index + 1}`} path={row.path}
onPath={(path) => edit(index, { path })} error={rowErrors[index]} inputRef={inputRef(index)}
picking={picking === index} onPick={() => void pick(index)}
onRemove={rows.length > 1 ? () => remove(index) : undefined}
- status={mountOf(row.path) ? <MountBadge online={mountOf(row.path)?.online} /> : null}>
- <SourceSelect index={index} value={row.location}
- onChange={(location) => edit(index, { location, cost: location === 'local' ? 'free' : '' })} />
- <MediaReadPolicy index={index} cost={row.cost} onChange={(cost) => edit(index, { cost })}
- error={requireReadPolicy && !row.cost ? '请选择媒体读取策略' : undefined} />
- <Input className="w-full min-w-32 @lg:w-auto @lg:flex-1" aria-label={`媒体库名称 ${index + 1}`} maxLength={80}
- placeholder="媒体库名称"
- value={row.library} onChange={(library) => edit(index, { library })} />
- <LibraryIconPicker label={`媒体库图标 ${index + 1}`} value={row.library_icon} kind={row.location}
- onChange={(library_icon) => edit(index, { library_icon })} />
+ status={mountOf(row) ? <MountBadge online={mountOf(row)?.online} /> : null}>
+ <FolderFieldLine>
+ <SourceSelect index={index} value={row.location}
+ onChange={(location) => edit(index, { location, cost: location === 'local' ? 'free' : '' })} />
+ <MediaReadPolicy index={index} cost={row.cost} onChange={(cost) => edit(index, { cost })}
+ error={requireReadPolicy && !row.cost ? '请选择媒体读取策略' : undefined} />
+ {row.root_id && !mountOf(row) ? <FolderField label="变更方式" className="w-full @lg:w-auto @lg:flex-1">
+ <Select className="w-full" aria-label={`目录变更方式 ${index + 1}`}
+ placeholder="选择目录变更方式" selectedKey={row.change_mode || null}
+ onSelectionChange={key => {
+ if (key === 'add') edit(index, { root_id: undefined, root: '', change_mode: '' });
+ else edit(index, { change_mode: 'relocate' });
+ }}>
+ <SelectItem id="relocate">重定位此目录,保留文件记录</SelectItem>
+ <SelectItem id="add">添加另一目录</SelectItem>
+ </Select>
+ </FolderField> : null}
+ </FolderFieldLine>
+ <FolderFieldLine>
+ <FolderField label="所属媒体库" className="w-full @lg:w-60">
+ <Select className="w-full" aria-label={`目录所属媒体库 ${index + 1}`} selectedKey={row.library_id}
+ renderValue={<span className="flex min-w-0 items-center gap-2"><SourceMark mark={row.library_icon || libraryAutoChoice(row.location)[0]} /><span className="truncate">{row.library || '未命名媒体库'}</span></span>}
+ onSelectionChange={key => { if (key) chooseLibrary(index, String(key)); }}>
+ {libraries.map(library => <SelectItem key={library.library_id} id={library.library_id}>{library.library || '未命名媒体库'}</SelectItem>)}
+ <SelectItem id="new">新建媒体库</SelectItem>
+ </Select>
+ </FolderField>
+ <FolderField label="媒体库名称" className="w-full min-w-32 @lg:w-auto @lg:flex-1">
+ <Input className="w-full" aria-label={`媒体库名称 ${index + 1}`} maxLength={80}
+ placeholder="媒体库名称"
+ value={row.library} onChange={(library) => editLibrary(index, { library })} />
+ </FolderField>
+ <FolderField label="图标">
+ <LibraryIconPicker label={`媒体库图标 ${index + 1}`} value={row.library_icon} kind={row.location}
+ onChange={(library_icon) => editLibrary(index, { library_icon })} />
+ </FolderField>
+ </FolderFieldLine>
</FolderRow>
))}
</div>
diff --git a/frontend/src/react/stage/stage-player.ts b/frontend/src/react/stage/stage-player.ts
index 44bf88d30..0d5a96fa2 100644
--- a/frontend/src/react/stage/stage-player.ts
+++ b/frontend/src/react/stage/stage-player.ts
@@ -169,7 +169,7 @@ export async function mountWallPlayer(summary: PlayerItem, frame: HTMLElement, s
if (item.cost === 'metered') throw new Error('请打开详情确认计费来源');
const sources = await stageHost().player.loadSourceStatus();
signal.throwIfAborted();
- if (sources[String(item.location || '')] === false) throw new Error(stageHost().player.offlineReason(String(item.location || '')));
+ if (sources[String(item.root_id || item.location || '')] === false) throw new Error(stageHost().player.offlineReason(String(item.root_id || item.location || '')));
const metadata: StageMeta = { kind: 'item', item, title: String(item.title || item.name || ''),
sub: String((item.performers as string[] | undefined)?.[0] || item.creator || '未归属') };
setStageMeta(metadata);
@@ -407,7 +407,7 @@ export function miniplayerTakesCard(item: PlayerItem | null | undefined): boolea
if (item.medium && item.medium !== 'video') return false;
if (item.cost === 'metered' && item.location !== 'online') return false;
if (item.location === 'online' && !item.follow_item_id) return false;
- if (stageHost().sourceOffline(String(item.location ?? ''))) return false;
+ if (stageHost().sourceOffline(String(item.root_id || item.location || ''))) return false;
return true;
}
diff --git a/frontend/test/react/data-cleanup.test.tsx b/frontend/test/react/data-cleanup.test.tsx
index df09a5277..4092cfc6b 100644
--- a/frontend/test/react/data-cleanup.test.tsx
+++ b/frontend/test/react/data-cleanup.test.tsx
@@ -83,7 +83,7 @@ function confirmWith(answer: boolean) {
const wrap = (element: ReactElement) => mount(<QueryClientProvider client={queryClient}>{element}</QueryClientProvider>);
const withRoots: MediaSourcesData = {
- sources: [{ location: 'local', online: true, roots: ['R:\\media'] }, { location: '115', online: false, roots: ['B:\\'] },
+ sources: [{ location: 'local', online: true, roots: [{ online: true }] }, { location: '115', online: false, roots: [{ online: false }] },
{ location: 'online', online: true }],
};
const withoutRoots: MediaSourcesData = {
diff --git a/frontend/test/react/duplicates.test.tsx b/frontend/test/react/duplicates.test.tsx
index 80a371834..e56bf65e8 100644
--- a/frontend/test/react/duplicates.test.tsx
+++ b/frontend/test/react/duplicates.test.tsx
@@ -38,7 +38,7 @@ const groups = [
];
const data: DuplicatesData = { total: 2, files: 4, reclaimable: 2 * GB, groups };
const sources: MediaSourcesData = {
- sources: [{ location: 'local', online: true, roots: ['R:\\'] }, { location: '115', online: false, roots: ['B:\\'] },
+ sources: [{ location: 'local', online: true, roots: [{ online: true }] }, { location: '115', online: false, roots: [{ online: false }] },
{ location: 'pikpak', online: true, roots: [] }],
};
diff --git a/frontend/test/react/immerse.test.tsx b/frontend/test/react/immerse.test.tsx
index baea6468b..975298c68 100644
--- a/frontend/test/react/immerse.test.tsx
+++ b/frontend/test/react/immerse.test.tsx
@@ -281,6 +281,9 @@ describe('片单与起播', () => {
expect(playable(row(2, { cost: 'metered' }), offline)).toBe(false);
expect(playable(row(3, { duration: 0 }), offline)).toBe(false);
expect(playable(row(4, { location: 'gone' }), offline)).toBe(false);
+ const rootOffline = (key: string) => key === 'root-offline';
+ expect(playable(row(5, { location: 'local', root_id: 'root-offline' }), rootOffline)).toBe(false);
+ expect(playable(row(6, { location: 'local', root_id: 'root-online' }), rootOffline)).toBe(true);
serve({ draws: [[row(1, { location: 'gone' }), row(2)]] });
await open();
expect(current().item.id).toBe(2);
diff --git a/frontend/test/react/media-settings.test.tsx b/frontend/test/react/media-settings.test.tsx
index aa0a69a14..232026e70 100644
--- a/frontend/test/react/media-settings.test.tsx
+++ b/frontend/test/react/media-settings.test.tsx
@@ -6,7 +6,7 @@ import type { ConfigurationData } from '../../src/react/bundle';
import { CloudDriveGuide } from '../../src/react/settings/clouddrive-guide';
import { MEDIA_SOURCE_ICONS } from '../../src/ui-kit/media-source-icons';
import { MediaSettings } from '../../src/react/settings/media-settings';
-import { buttonNamed, choose, click, fetchMock, mount, section, sentBody, settle, submit } from './render';
+import { buttonNamed, choose, click, fetchMock, mount, section, sentBody, settle, submit, type } from './render';
vi.mock('../../src/react/settings/service-preferences', () => ({ VideoThumbnailRow: () => null }));
vi.mock('../../src/react/settings/cloud-proxy-settings', () => ({ CloudProxySettings: () => null }));
@@ -52,6 +52,35 @@ it('不能编辑时只说原因,不画表单', async () => {
});
describe('媒体目录', () => {
+ it('同一媒体库的名称同步到全部目录,保存保留根目录身份', async () => {
+ const fetcher = fetchMock(200, { saved: true, url: '/', revision: 'rev-2' });
+ vi.stubGlobal('fetch', fetcher);
+ const host = await open({ windows: true, media_sources: [
+ { location: 'local', root: 'D:\\JAV', path: 'D:\\JAV', root_id: 'root-one', library_id: 'library-one', library: 'JAV', cost: 'free' },
+ { location: 'local', root: 'E:\\JAV', path: 'E:\\JAV', root_id: 'root-two', library_id: 'library-one', library: 'JAV', cost: 'free' },
+ ] });
+ await type(host.querySelector<HTMLInputElement>('[aria-label="媒体库名称 1"]'), '私人馆藏');
+ expect(host.querySelector<HTMLInputElement>('[aria-label="媒体库名称 2"]')?.value).toBe('私人馆藏');
+ await submit(host.querySelector('form'));
+ expect(sentBody(fetcher).media_sources).toMatchObject([
+ { root_id: 'root-one', library_id: 'library-one', library: '私人馆藏' },
+ { root_id: 'root-two', library_id: 'library-one', library: '私人馆藏' },
+ ]);
+ });
+
+ it('目录重定位保留账本前缀,添加另一目录交由服务端生成身份', async () => {
+ const fetcher = fetchMock(200, { saved: true, url: '/', revision: 'rev-2' });
+ vi.stubGlobal('fetch', fetcher);
+ const host = await open({ windows: true, media_sources: [
+ { location: 'local', root: 'D:\\JAV', path: 'D:\\JAV', root_id: 'root-one', library_id: 'library-one', library: 'JAV', cost: 'free' },
+ ] });
+ await type(paths(host)[0], 'F:\\JAV');
+ await choose(host.querySelector('[aria-label="目录变更方式 1"]'), '重定位此目录,保留文件记录');
+ await submit(host.querySelector('form'));
+ expect(sentBody(fetcher).media_sources[0]).toMatchObject({
+ root_id: 'root-one', root: 'D:\\JAV', path: 'F:\\JAV', change_mode: 'relocate',
+ });
+ });
it.each([['guangya', '光鸭云盘'], ['onedrive', 'OneDrive'], ['mounted', '其他已挂载网盘']])(
'%s 来源回填名称、挂载帮助和现有图标,保存带上来源', async (location, label) => {
const fetcher = fetchMock(200, { saved: true, url: '/', revision: 'rev-2' });
@@ -66,7 +95,7 @@ describe('媒体目录', () => {
else expect(host.querySelector('img')?.getAttribute('src')).toBe(MEDIA_SOURCE_ICONS[location]);
expect(host.textContent).toContain('CloudDrive2 v1.1.0');
await submit(host.querySelector('form'));
- expect(sentBody(fetcher).media_sources).toEqual([
+ expect(sentBody(fetcher).media_sources).toMatchObject([
{ location, root: 'G:\\Movies', path: 'G:\\Movies', library: '', library_icon: '',
cost: location === 'guangya' ? 'free' : 'metered' },
]);
@@ -108,7 +137,7 @@ describe('媒体目录', () => {
expect(paths(host).map((input) => input.value)).toEqual(['/Volumes/115', '/Volumes/PikPak']);
await submit(host.querySelector('form'));
await settle();
- expect(sentBody(fetcher).media_sources).toEqual([
+ expect(sentBody(fetcher).media_sources).toMatchObject([
{ location: '115', root: 'B:\\', path: '/Volumes/115', library: '收藏', library_icon: 'heart', cost: 'free' },
{ location: 'pikpak', root: 'A:\\', path: '/Volumes/PikPak', library: '', library_icon: '', cost: 'metered' },
]);
@@ -124,7 +153,7 @@ describe('媒体目录', () => {
expect(policy?.textContent).toContain('代理保护');
await choose(policy, '正常读取');
await submit(host.querySelector('form'));
- expect(sentBody(fetcher).media_sources).toEqual([
+ expect(sentBody(fetcher).media_sources).toMatchObject([
{ location: 'onedrive', root: 'O:\\Movies', path: 'O:\\Movies', library: '', library_icon: '', cost: 'free' },
]);
});
diff --git a/frontend/test/react/setup-page.test.tsx b/frontend/test/react/setup-page.test.tsx
index 19503ecea..32d356127 100644
--- a/frontend/test/react/setup-page.test.tsx
+++ b/frontend/test/react/setup-page.test.tsx
@@ -158,14 +158,14 @@ describe('媒体库', () => {
expect(host.textContent).toContain('请选择媒体读取策略');
await choose(policy, '正常读取');
await submitForm(host);
- expect(sent(SETUP_URL).media_dir).toEqual([
+ expect(sent(SETUP_URL).media_dir).toMatchObject([
{ path: 'D:\\Videos', location: 'onedrive', root: '', cost: 'free' },
]);
});
it('加一行、删一行,扫描说明跟着行数走,提交按行带上来源', async () => {
const { host, sent } = await open({}, { [SETUP_URL]: { status: 200, body: done() } });
- await click(buttonNamed('添加媒体库', host));
+ await click(buttonNamed('添加文件夹', host));
expect(rows(host)).toHaveLength(2);
expect(document.activeElement).toBe(paths(host)[1]);
await type(paths(host)[1], 'E:\\More');
@@ -174,7 +174,7 @@ describe('媒体库', () => {
expect(paths(host).map((input) => input.value)).toEqual(['E:\\More']);
expect(rows(host)[0]!.querySelector('button[aria-label="移除这个文件夹"]')).toBeNull();
await submitForm(host);
- expect(sent(SETUP_URL).media_dir).toEqual([{ path: 'E:\\More', location: 'local', root: '', cost: 'free' }]);
+ expect(sent(SETUP_URL).media_dir).toMatchObject([{ path: 'E:\\More', location: 'local', root: '', cost: 'free' }]);
});
it('选择文件夹让这台电脑弹对话框,选中的路径填回这一行', async () => {
@@ -228,7 +228,7 @@ describe('填错时原位标错', () => {
it('整表不成立的那一句写在目录区上方,不挂到某一行', async () => {
const { host } = await open({}, { [SETUP_URL]: { status: 400, body: {
error: '有几项需要修改', errors: { media_dir: ['请添加 1 到 100 个媒体目录'] } } } });
- await click(buttonNamed('添加媒体库', host));
+ await click(buttonNamed('添加文件夹', host));
await submitForm(host);
const [alert, ...more] = alertsWith(host, '请添加 1 到 100 个媒体目录');
expect(alert).toBeDefined();
diff --git a/scripts/upgrade_media_identity.py b/scripts/upgrade_media_identity.py
new file mode 100644
index 000000000..6c7ad78cd
--- /dev/null
+++ b/scripts/upgrade_media_identity.py
@@ -0,0 +1,25 @@
+"""显式升级媒体库与存储根目录的配置身份;默认仅预演,不读取账本。"""
+import argparse
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from peach import media_libraries, settings_file
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--data-root", type=Path, required=True)
+ parser.add_argument("--apply", action="store_true")
+ args = parser.parse_args()
+ config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(args.data_root.resolve())})
+ prepared = settings_file.upgrade_media_identity(config, apply=args.apply)
+ print(json.dumps({"applied": args.apply, "already_upgraded": bool(config.storage_roots),
+ "libraries": [{"id": row["id"], "folders": len(row["roots"])}
+ for row in media_libraries.libraries(prepared)]}, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/peach/api.py b/src/peach/api.py
index a993b2175..5573a42cc 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -139,7 +139,7 @@ _DEFAULT_DETAILS = {
def _offline_response(exc: MediaOffline) -> JSONResponse:
"""脱盘:来源盘整体不在,客户端据此显示「脱盘模式」而不是当成文件丢失。"""
response = JSONResponse(
- {"error": "offline", "source": exc.source, "id": exc.asset_id},
+ {"error": "offline", "source": exc.source, "root_id": exc.root_id, "id": exc.asset_id},
status_code=503,
)
response.headers["X-Peach-Offline"] = "1"
diff --git a/src/peach/downloads_channels.py b/src/peach/downloads_channels.py
index 25c145f21..8e85fc4eb 100644
--- a/src/peach/downloads_channels.py
+++ b/src/peach/downloads_channels.py
@@ -111,7 +111,9 @@ class LibraryChannels:
@staticmethod
def _row(key, source, root, target, names, *, cloud_root="", can_cancel=True):
+ from . import media_identity, settings_file
name = names.get(root_key(root)) or PureWindowsPath(root).name or root
label = name if name == SOURCES[source].name else f"{name} · {SOURCES[source].name}"
return {"key": key, "source": source, "label": label, "configured": True,
- "target": target, "root": root, "cloud_root": cloud_root, "can_cancel": can_cancel}
+ "target": target, "root": root, "cloud_root": cloud_root, "can_cancel": can_cancel,
+ **media_identity.ownership(settings_file.active(), root)}
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index a5563ba3a..f8424d207 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -14,7 +14,7 @@ from contextlib import closing
from contextvars import copy_context
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
from dataclasses import dataclass
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
from urllib.parse import urlparse
from filelock import FileLock, Timeout
@@ -1774,7 +1774,7 @@ def _scan_sources(config, db_path, *, locations, asset_ids, stage, guard, update
continue
result.online_roots.append(translated_root)
if scan:
- key = f'{source}:{root}'
+ key = f'{source}:{PureWindowsPath(root)}'.casefold()
def remember(value, key=key):
scan_checkpoints[key] = value
save_checkpoint()
diff --git a/src/peach/media.py b/src/peach/media.py
index baaf82250..d94bb10bd 100644
--- a/src/peach/media.py
+++ b/src/peach/media.py
@@ -107,6 +107,7 @@ class MediaOffline(MediaUnavailable):
super().__init__(asset_id)
self.asset_id = asset_id
self.source = source
+ self.root_id = ""
class FilesystemBackend:
@@ -142,13 +143,19 @@ class FilesystemBackend:
if not thumbnail and is_windows_path(raw):
translated = translate_ledger_path(raw)
source = PureWindowsPath(raw).drive
+ from . import media_identity, settings_file
+ root_id = media_identity.ownership(settings_file.active(), raw).get("root_id", "")
+ def offline():
+ error = MediaOffline(asset_id, source)
+ error.root_id = root_id
+ return error
if is_unmapped(translated):
- raise MediaOffline(asset_id, source)
+ raise offline()
candidate = normalized_path(raw)
for root in self.allowed_roots:
if within_root(candidate, root):
if not root_online(root):
- raise MediaOffline(asset_id, source)
+ raise offline()
break
raise MediaUnavailable(asset_id)
diff --git a/src/peach/media_configuration.py b/src/peach/media_configuration.py
index c6e27a0e3..5093ba894 100644
--- a/src/peach/media_configuration.py
+++ b/src/peach/media_configuration.py
@@ -7,7 +7,7 @@ import shutil
import sys
from typing import Any
-from . import platform
+from . import platform, media_identity
from .media_sources import SOURCE_OPTIONS, cost_for
@@ -53,29 +53,30 @@ def mount_dependencies(*, system: str | None = None) -> list[dict[str, Any]]:
def rows(config, *, windows: bool, probe: bool = False) -> list[dict[str, Any]]:
result = []
+ libraries, stored = media_identity.catalog(config)
for location, roots in config.locations.items():
mounts = config.mounts.get(location, ())
for index, root in enumerate(roots):
- mount = root if windows else (mounts[index] if index < len(mounts) else "")
+ mount = (mounts[index] if index < len(mounts) and mounts[index] else root if windows else "")
+ identity = next(((key, value) for key, value in stored.items()
+ if media_identity.path_key(value["root"]) == media_identity.path_key(root)), None)
+ root_id, value = identity
+ library = libraries[value["library_id"]]
result.append({"location": location, "root": root, "path": mount,
- "library": config.library_names.get(root) or PureWindowsPath(root).name or root,
- "library_icon": config.library_icons.get(root, ""),
+ "root_id": root_id, "library_id": value["library_id"],
+ "library": library["name"], "library_icon": library.get("icon", ""),
"cost": cost_for(location, root, config),
"online": platform.root_online(Path(mount)) if probe and mount else False})
return result
-def _overlaps(first: PureWindowsPath, second: PureWindowsPath) -> bool:
- return first == second or first.is_relative_to(second) or second.is_relative_to(first)
-
-
def _automatic_root(location: str, path: str, used: list[PureWindowsPath]) -> str:
# 媒体来源和目录决定内部路径;已有路径占用时改用其他盘符,避免不同目录共用前缀。
token = hashlib.sha256(f"{location}\0{PurePosixPath(path)}".encode()).hexdigest()[:32]
drives = dict.fromkeys(["R:", *(f"{chr(code)}:" for code in range(65, 91))])
for drive in drives:
candidate = PureWindowsPath(drive + "\\", "peach", location, token)
- if not any(_overlaps(candidate, other) for other in used):
+ if not any(media_identity.overlaps(candidate, other) for other in used):
return str(candidate)
return ""
@@ -115,7 +116,7 @@ def prepare_sources(raws: object, *, windows: bool, config=None) -> object:
def _validated_paths(row: dict, *, windows: bool) -> tuple[PureWindowsPath, PurePath]:
"""取得数据库路径前缀与本机实际目录,用于检查重复和包含关系。"""
text = str(row.get("path", "")).strip()
- root = text if windows else str(row.get("root", "")).strip()
+ root = str(row.get("root") or text).strip() if windows else str(row.get("root", "")).strip()
if any(ord(char) < 32 for char in text + root):
raise ValueError("路径不能包含控制字符")
if not windows and not root:
@@ -160,12 +161,11 @@ def validate(raws: object, *, windows: bool, config=None) -> tuple[dict, dict, l
raise ValueError("媒体目录与另一行重复或互相包含")
seen.append((declared, path))
locations.setdefault(location, []).append(str(declared))
- if not windows:
- mounts.setdefault(location, []).append(str(path))
+ mounts.setdefault(location, []).append(str(path) if not windows or declared != path else "")
except ValueError as exc:
errors[index] = str(exc)
return ({key: tuple(value) for key, value in locations.items()},
- {key: tuple(value) for key, value in mounts.items()},
+ {key: tuple(value) for key, value in mounts.items() if any(value)},
errors if any(errors) else [])
@@ -173,7 +173,7 @@ def costs(raws: list[dict], config, *, windows: bool) -> dict[str, str]:
"""按数据库路径前缀保存已校验媒体行的读取策略。"""
result = dict(getattr(config, "media_costs", {}))
for row in raws:
- root = str(PureWindowsPath(row["path"] if windows else row["root"]))
+ root = str(PureWindowsPath(row.get("root") or row["path"]))
for previous in tuple(result):
if PureWindowsPath(previous) == PureWindowsPath(root):
del result[previous]
diff --git a/src/peach/media_folders.py b/src/peach/media_folders.py
index 4cf67f055..03a0b8b77 100644
--- a/src/peach/media_folders.py
+++ b/src/peach/media_folders.py
@@ -21,10 +21,11 @@ def within(path: str, directory: str, recursive: bool = True) -> bool:
def path_predicate(location: str, path: str, recursive: bool = True, alias: str = 'a'):
"""按完整目录组件匹配,目录名中的 SQL 通配符保持字面含义。"""
prefix = str(PureWindowsPath(path)).rstrip('\\') + '\\'
- clause = f'({alias}.location=? AND substr({alias}.path,1,?)=? COLLATE NOCASE'
+ normalized = f"replace({alias}.path,'/',char(92))"
+ clause = f'({alias}.location=? AND substr({normalized},1,?)=? COLLATE NOCASE'
params: list = [location, len(prefix), prefix]
if not recursive:
- clause += f" AND instr(substr({alias}.path,?),char(92))=0"
+ clause += f" AND instr(substr({normalized},?),char(92))=0"
params.append(len(prefix) + 1)
return clause + ')', params
@@ -50,6 +51,7 @@ def directory_index(connection, config, *, locations: str = '', library: str = '
for location, root in declared:
node = add(location, root, None, folder_id(location, root))
+ node.update(media_libraries.media_identity.ownership(config, root))
node['name'] = getattr(config, 'library_names', {}).get(root) or node['name']
rows = connection.execute(
"SELECT location,path,medium FROM asset WHERE path IS NOT NULL AND path<>'' "
diff --git a/src/peach/media_identity.py b/src/peach/media_identity.py
new file mode 100644
index 000000000..2ab4c6964
--- /dev/null
+++ b/src/peach/media_identity.py
@@ -0,0 +1,193 @@
+"""媒体库与存储根目录的持久身份;路径表是兼容投影。"""
+from __future__ import annotations
+
+from dataclasses import replace
+from pathlib import PureWindowsPath, PurePosixPath
+from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
+
+
+def path_key(path):
+ return str(PureWindowsPath(path)).casefold()
+
+
+def _legacy_value(mapping, root, default=""):
+ return next((value for key, value in mapping.items() if path_key(key) == path_key(root)), default)
+
+
+def catalog(config):
+ """已有身份直接读取;路径配置按同名分组执行确定性升级。"""
+ if getattr(config, "storage_roots", None):
+ return (dict(getattr(config, "library_catalog", {})),
+ {key: dict(value) for key, value in config.storage_roots.items()})
+ from .media_libraries import LIBRARY_ICONS
+ groups, roots, libraries = {}, {}, {}
+ for location, paths in config.locations.items():
+ mounts = getattr(config, "mounts", {}).get(location, ())
+ for index, path in enumerate(paths):
+ root = str(path)
+ name = _legacy_value(getattr(config, "library_names", {}), root) or PureWindowsPath(root).name or root
+ groups.setdefault(name, []).append(root)
+ root_id = str(uuid5(NAMESPACE_URL, "peach:storage-root:" + path_key(root)))
+ roots[root_id] = dict(root=root, location=location,
+ mount=str(mounts[index]) if index < len(mounts) else "",
+ cost=_legacy_value(getattr(config, "media_costs", {}), root),
+ library_id="")
+ for name, paths in groups.items():
+ library_id = str(uuid5(NAMESPACE_URL, "peach:library:" + "\0".join(sorted(path_key(p) for p in paths))))
+ icon = next((_legacy_value(getattr(config, "library_icons", {}), p) for p in paths
+ if _legacy_value(getattr(config, "library_icons", {}), p)), "")
+ libraries[library_id] = dict(name=name, icon=icon if icon in LIBRARY_ICONS else "")
+ for value in roots.values():
+ if value["root"] in paths:
+ value["library_id"] = library_id
+ return libraries, roots
+
+
+def project(config, libraries=None, roots=None):
+ """按根目录身份生成扫描、挂载、名称及成本兼容投影。"""
+ if libraries is None:
+ libraries, roots = catalog(config)
+ locations, mounts, names, icons, costs = {}, {}, {}, {}, {}
+ for value in roots.values():
+ root, location = value["root"], value["location"]
+ library = libraries[value["library_id"]]
+ locations.setdefault(location, []).append(root)
+ mounts.setdefault(location, []).append(value.get("mount", ""))
+ names[root] = library["name"]
+ if library.get("icon"):
+ icons[root] = library["icon"]
+ if value.get("cost"):
+ costs[root] = value["cost"]
+ return replace(config, library_catalog=libraries, storage_roots=roots,
+ locations={key: tuple(values) for key, values in locations.items()},
+ mounts={key: tuple(values) for key, values in mounts.items() if any(values)},
+ library_names=names, library_icons=icons, media_costs=costs)
+
+
+def overlaps(first, second):
+ """两个目录相同或互为父子。"""
+ return first == second or first.is_relative_to(second) or second.is_relative_to(first)
+
+
+def _validate_library(value):
+ """媒体库名称为 1 到 80 个可见字符,图标为空或取自内置列表。"""
+ from .media_libraries import LIBRARY_ICONS
+ name = value.get("name", "")
+ if not isinstance(name, str) or not name.strip() or len(name) > 80 or any(ord(c) < 32 for c in name):
+ raise ValueError("媒体库名称请使用 1 到 80 个可见字符")
+ if value.get("icon", "") not in ("", *LIBRARY_ICONS):
+ raise ValueError("请选择列表中的媒体库图标")
+
+
+def validate_catalog(libraries, roots):
+ """拒绝损坏身份、悬空归属及跨库重叠。"""
+ from .platform import is_windows_path
+ seen, mounted = [], []
+ for key, value in libraries.items():
+ UUID(key)
+ _validate_library(value)
+ for key, value in roots.items():
+ UUID(key)
+ if value.get("library_id") not in libraries:
+ raise ValueError("存储根目录的媒体库不存在")
+ path = PureWindowsPath(value.get("root", ""))
+ if not is_windows_path(str(path)) or not path.is_absolute() or ".." in path.parts:
+ raise ValueError("存储根目录必须使用完整 Windows 路径")
+ if not value.get("location") or value.get("cost", "") not in ("", "free", "metered"):
+ raise ValueError("存储根目录的来源或读取策略无效")
+ if any(overlaps(path, other) for other in seen):
+ raise ValueError("媒体路径与另一文件夹重复或互相包含")
+ seen.append(path)
+ mount = value.get("mount", "")
+ actual = (PureWindowsPath(mount) if len(mount) > 1 and mount[1] == ":" else PurePosixPath(mount)) if mount else path
+ if not actual.is_absolute() or ".." in actual.parts:
+ raise ValueError("挂载目录必须使用完整路径")
+ if any(overlaps(actual, other) for other in mounted):
+ raise ValueError("媒体目录与另一行重复或互相包含")
+ mounted.append(actual)
+ for index, actual in enumerate(mounted):
+ if isinstance(actual, PureWindowsPath) and any(
+ (index != other_index or actual != other) and overlaps(actual, other)
+ for other_index, other in enumerate(seen)):
+ raise ValueError("挂载目录与账本路径重叠,请使用独立目录")
+
+
+def _match_root(row, root, previous, by_path, *, windows):
+ """表单行认回既有根目录:显式 root_id 优先,否则按同一来源的账本前缀;认回的根核对来源、前缀和重定位意图。"""
+ path = row["path"]
+ supplied = str(row.get("root_id") or "")
+ if supplied and supplied not in previous:
+ raise ValueError("存储根目录已变更,请刷新配置")
+ matched = by_path.get(path_key(root))
+ # 只按路径认回同一来源的根;换了来源的同一前缀是另一个目录声明,取新身份。
+ if matched and previous[matched]["location"] != row["location"]:
+ matched = None
+ old = previous.get(supplied or matched or "")
+ if old:
+ if row["location"] != old["location"] or path_key(root) != path_key(old["root"]):
+ raise ValueError("已有根目录的来源和账本路径不可更换;请添加另一目录")
+ old_path = old.get("mount") or (root if windows else "")
+ equal = path_key(path) == path_key(old_path) if windows else path == old_path
+ # 原来没有实际目录的根第一次填上目录,不算重定位。
+ if old_path and not equal and row.get("change_mode") != "relocate":
+ raise ValueError("请选择重定位此目录,或添加另一目录")
+ return supplied or matched or str(uuid4()), old
+
+
+def configure_sources(config, sources, *, windows):
+ """更新根目录与媒体库;既有根的来源和账本前缀保持稳定。"""
+ from .media_sources import cost_for
+ libraries, previous = catalog(config)
+ libraries = {key: dict(value) for key, value in libraries.items()}
+ by_path = {path_key(value["root"]): key for key, value in previous.items()}
+ roots, declared_libraries = {}, {}
+ for row in sources:
+ path = row["path"]
+ root = str(PureWindowsPath(row.get("root") or path))
+ root_id, old = _match_root(row, root, previous, by_path, windows=windows)
+ if root_id in roots:
+ raise ValueError("同一存储根目录不能登记多次")
+ library_id = str(row.get("library_id") or (old or {}).get("library_id") or uuid4())
+ UUID(library_id)
+ name = str(row.get("library") or libraries.get(library_id, {}).get("name") or PureWindowsPath(root).name or root).strip()
+ icon = str(row.get("library_icon", libraries.get(library_id, {}).get("icon", "")))
+ value = dict(name=name, icon=icon)
+ if library_id in declared_libraries and declared_libraries[library_id] != value:
+ raise ValueError("同一媒体库的名称和图标必须一致")
+ declared_libraries[library_id] = value
+ libraries[library_id] = value
+ roots[root_id] = dict(root=root, location=row["location"], library_id=library_id,
+ mount=path if not windows or path_key(path) != path_key(root) else "",
+ cost=row.get("cost") or cost_for(row["location"], root, config))
+ # 不在表单来源列表里的扩展连接器仍由其专用设置维护。
+ from .media_sources import SOURCE_OPTIONS
+ roots.update({key: value for key, value in previous.items() if value["location"] not in dict(SOURCE_OPTIONS)})
+ libraries = {key: value for key, value in libraries.items() if any(root["library_id"] == key for root in roots.values())}
+ validate_catalog(libraries, roots)
+ return project(config, libraries, roots)
+
+
+def sources_for_paths(config, paths, *, windows, keep_other_sources=False):
+ """路径式设置入口按已保存的实际目录接回根目录身份。"""
+ from . import media_configuration
+ existing = media_configuration.rows(config, windows=windows)
+ sources = [dict(row) for row in existing if row["location"] != "local"] if keep_other_sources else []
+ for path in paths:
+ text = str(path)
+ key = path_key(text) if windows else text
+ match = next((row for row in existing if row["location"] == "local" and
+ (path_key(row["path"]) if windows else row["path"]) == key), None)
+ sources.append(dict(match) if match else {"location": "local", "path": text})
+ return media_configuration.prepare_sources(sources, windows=windows, config=config)
+
+
+def ownership(config, path):
+ """复用平台路径归属,将账本路径投影为稳定根目录和媒体库身份。"""
+ from .platform import resolve_root
+ location, index, _tail = resolve_root(path, config.locations)
+ if location is None:
+ return {}
+ root = config.locations[location][index]
+ _libraries, roots = catalog(config)
+ return next((dict(root_id=key, library_id=value["library_id"]) for key, value in roots.items()
+ if path_key(value["root"]) == path_key(root)), {})
diff --git a/src/peach/media_libraries.py b/src/peach/media_libraries.py
index 3876352b9..73fa16bbe 100644
--- a/src/peach/media_libraries.py
+++ b/src/peach/media_libraries.py
@@ -1,5 +1,5 @@
-"""媒体库按声明路径分组,来源与挂载仍由媒体配置管理。"""
-from pathlib import PureWindowsPath
+"""媒体库按持久身份分组,来源与挂载归存储根目录。"""
+from . import media_identity
LIBRARY_ICONS = frozenset({"hard-drive", "database", "heart", "star", "tags", "115", "pikpak",
"heart-hand", "flame", "cherry", "gem", "crown", "shirt", "footprints",
@@ -10,25 +10,23 @@ LIBRARY_ICONS = frozenset({"hard-drive", "database", "heart", "star", "tags", "1
def libraries(config):
+ catalog, stored = media_identity.catalog(config)
groups = {}
- for location, roots in config.locations.items():
- for root in roots:
- name = config.library_names.get(root) or PureWindowsPath(root).name or root
- groups.setdefault(name, []).append({"location": location, "root": root})
- icons = getattr(config, "library_icons", {})
- return [{"id": name, "name": name, "roots": roots,
- "icon": next((icons[item["root"]] for item in roots
- if icons.get(item["root"]) in LIBRARY_ICONS),
- roots[0]["location"] if len({item["location"] for item in roots}) == 1 else "database")}
- for name, roots in groups.items()]
+ for root_id, root in stored.items():
+ groups.setdefault(root["library_id"], []).append({**root, "root_id": root_id})
+ return [{"id": key, "name": catalog[key]["name"], "roots": roots,
+ "icon": catalog[key].get("icon") if catalog[key].get("icon") in LIBRARY_ICONS else (
+ roots[0]["location"] if len({item["location"] for item in roots}) == 1 else "database")}
+ for key, roots in groups.items()]
def predicate(config, library):
"""路径边界精确匹配;未知库返回空集。"""
+ from .media_folders import path_predicate
roots = next((row["roots"] for row in libraries(config) if row["id"] == library), [])
terms, params = [], []
for item in roots:
- prefix = str(PureWindowsPath(item["root"])).rstrip("\\") + "\\"
- terms.append("(a.location=? AND substr(a.path,1,?)=? COLLATE NOCASE)")
- params.extend((item["location"], len(prefix), prefix))
+ clause, values = path_predicate(item["location"], item["root"])
+ terms.append(clause)
+ params.extend(values)
return "(" + " OR ".join(terms) + ")" if terms else "0", params
diff --git a/src/peach/mount_reachability.py b/src/peach/mount_reachability.py
index 7201d3e92..8dfa16f64 100644
--- a/src/peach/mount_reachability.py
+++ b/src/peach/mount_reachability.py
@@ -31,6 +31,8 @@ class MountRoot:
label: str
declared: str
path: Path | None
+ root_id: str = ""
+ library_id: str = ""
def source_roots() -> list[MountRoot]:
@@ -38,6 +40,7 @@ def source_roots() -> list[MountRoot]:
from .config import LOCATION_ROOT_DECLARATIONS
from .media_configuration import SOURCE_OPTIONS
from .platform import is_unmapped, translate_ledger_path
+ from . import media_identity, settings_file
labels = dict(SOURCE_OPTIONS)
roots = []
@@ -45,7 +48,8 @@ def source_roots() -> list[MountRoot]:
for declared in declared_roots:
resolved = translate_ledger_path(declared)
roots.append(MountRoot(location, labels.get(location, location), declared,
- None if is_unmapped(resolved) else resolved))
+ None if is_unmapped(resolved) else resolved,
+ **media_identity.ownership(settings_file.active(), declared)))
return roots
@@ -149,6 +153,7 @@ class MountReachability:
"location": root.location, "label": root.label, "roots": [],
})
row["roots"].append({
+ "root_id": root.root_id, "library_id": root.library_id,
"declared": root.declared,
"resolved": str(root.path) if root.path is not None else None,
"mapped": root.path is not None, "online": online, "state": state,
@@ -160,7 +165,7 @@ class MountReachability:
unknown = next((root for root in roots if root["online"] is None), None)
status = failed or unknown
row.update(mapped=all(root["mapped"] for root in roots),
- online=False if failed else None if unknown else True,
+ online=True if any(root["online"] is True for root in roots) else None if unknown else False,
state=status["state"] if status else "ok",
message=f"{row['label']}:{status['message']}" if status else "",
checked_at=min((root["checked_at"] for root in roots
@@ -170,6 +175,6 @@ class MountReachability:
def summary(self) -> dict:
rows = [{key: row[key] for key in ("location", "label", "online", "state", "message", "checked_at")}
for row in self.sources()]
- warnings = [row["message"] for row in rows if row["online"] is False]
+ warnings = [row["message"] for row in rows if row["state"] in FAILURES]
return {"state": "degraded" if warnings else "checking" if any(
row["online"] is None for row in rows) else "ok", "sources": rows, "warnings": warnings}
diff --git a/src/peach/onboarding.py b/src/peach/onboarding.py
index 889115afb..c362eaacf 100644
--- a/src/peach/onboarding.py
+++ b/src/peach/onboarding.py
@@ -353,9 +353,19 @@ def configure(config: PeachConfig, answers: Answers, *, windows: bool) -> PeachC
for row in sources:
if row.get("library"):
library_names[str(PureWindowsPath(row["path"] if windows else row["root"]))] = str(row["library"])
- return replace(prepared, locations=locations, library_names=library_names,
+ prepared = replace(prepared, locations=locations, library_names=library_names,
+ library_catalog={}, storage_roots={},
media_costs=(media_configuration.costs(sources, config, windows=windows)
if answers.media_sources is not None else dict(config.media_costs)))
+ from . import media_identity
+ if answers.media_sources is not None:
+ identities = media_identity.configure_sources(config, sources, windows=windows)
+ return media_identity.project(prepared, identities.library_catalog, identities.storage_roots)
+ if config.storage_roots:
+ sources = media_identity.sources_for_paths(config, answers.media_dirs, windows=windows)
+ identities = media_identity.configure_sources(config, sources, windows=windows)
+ return media_identity.project(prepared, identities.library_catalog, identities.storage_roots)
+ return media_identity.project(prepared)
@dataclass(frozen=True)
diff --git a/src/peach/organize.py b/src/peach/organize.py
index b265cdd75..d8a4764f7 100644
--- a/src/peach/organize.py
+++ b/src/peach/organize.py
@@ -246,9 +246,10 @@ def build_plan(connection: sqlite3.Connection, *, location: str,
"current_path": str(row["path"]), "target_path": target,
"action": "skip", "reason": reason})
+ root_states = None
if online is None:
- mounts = [translate_ledger_path(root) for root in declared.get(location, ())]
- online = any(root_online(mount) for mount in mounts)
+ root_states = [root_online(translate_ledger_path(root)) for root in declared.get(location, ())]
+ online = any(root_states)
if not online:
for row in rows:
skip(row, SKIP_OFFLINE)
@@ -267,6 +268,9 @@ def build_plan(connection: sqlite3.Connection, *, location: str,
skip(row, SKIP_OUTSIDE_ROOT)
continue
root = declared[location][index]
+ if root_states is not None and not root_states[index]:
+ skip(row, SKIP_OFFLINE)
+ continue
values = placeholder_values(row, performers.get(int(row["id"]), []))
current_dir = ntpath.dirname(path)
target_dir = current_dir
diff --git a/src/peach/platform.py b/src/peach/platform.py
index 8dc253baa..29915f8ed 100644
--- a/src/peach/platform.py
+++ b/src/peach/platform.py
@@ -58,8 +58,11 @@ def location_mounts() -> dict[str, tuple[Path, ...]]:
merged: dict[str, tuple[str, ...]] = dict(settings_file.active().mounts)
for location, mount in _parse_override(os.environ.get(MOUNTS_ENV, "")):
merged[location] = (mount,) if mount else ()
- return {location: tuple(Path(mount) for mount in mounts)
- for location, mounts in merged.items() if mounts}
+ declared = settings_file.active().locations
+ return {location: tuple(Path(mount) if mount else (
+ Path(declared[location][index]) if os.name == "nt" and index < len(declared.get(location, ()))
+ else UNMAPPED_ROOT / location / str(index))
+ for index, mount in enumerate(mounts)) for location, mounts in merged.items() if mounts}
def location_roots() -> dict[str, tuple[str, ...]]:
@@ -167,13 +170,15 @@ def is_unmapped(path: Path) -> bool:
def translate_ledger_path(raw: str | os.PathLike[str]) -> Path:
"""把账本里的 Windows 路径翻译成本机路径;非 Windows 形态原样返回。"""
text = os.fspath(raw)
- if os.name == "nt" or not is_windows_path(text):
+ if not is_windows_path(text):
return Path(text)
location, index, tail = resolve_root(text)
if location is not None:
mounts = location_mounts().get(location, ())
- if index < len(mounts):
+ if index < len(mounts) and str(mounts[index]) not in ("", "."):
return mounts[index].joinpath(*tail)
+ if os.name == "nt":
+ return Path(text)
# 未配置的路径前缀或未挂载的来源转换到 UNMAPPED_ROOT,供读取端识别并拒绝访问。
# 保留盘符和其余层级,方便日志中定位原路径。
parts = PureWindowsPath(text).parts
diff --git a/src/peach/routes_api.py b/src/peach/routes_api.py
index 66eff6adc..c531885da 100644
--- a/src/peach/routes_api.py
+++ b/src/peach/routes_api.py
@@ -57,6 +57,8 @@ def source_health(request: Request, args: dict[str, str] = Depends(require_auth)
"ok": True,
"sources": rows,
"offline": [row["location"] for row in rows if row["online"] is False],
+ "offline_roots": [root["root_id"] for row in rows for root in row.get("roots", [])
+ if root.get("root_id") and root["online"] is False],
}
@@ -66,6 +68,7 @@ def media_library_list(request: Request, args: dict[str, str] = Depends(require_
from .media_sources import cost_for
config = settings_file.active()
return {"libraries": [{"id": row["id"], "name": row["name"], "icon": row["icon"], "folders": len(row["roots"]),
+ "roots": [{"root_id": root["root_id"], "location": root["location"]} for root in row["roots"]],
"metered": any(cost_for(root['location'], root['root'], config) == 'metered'
for root in row['roots'])}
for row in media_libraries.libraries(config)]}
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index cca9a4132..883f41f5b 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -199,8 +199,7 @@ def snapshot(config) -> dict[str, Any]:
"revision": revision(config),
"media_dirs": list(media),
"media_sources": media_configuration.rows(config, windows=os.name == "nt", probe=True),
- # 媒体库按 `media_libraries.libraries` 数:同名的几个数据库路径前缀是一个库,和侧栏切换器、
- # `/api/libraries` 同一份分组,页面不自己再归并一遍。
+ # 媒体库按持久身份计数,与侧栏切换器和 `/api/libraries` 共用分组。
"library_count": len(media_libraries.libraries(config)),
"mount_dependencies": media_configuration.mount_dependencies(),
"windows": os.name == "nt",
@@ -584,6 +583,7 @@ def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, A
"""逐项校验,错误按字段归位:文件夹按行、端口一句。全对时第一个返回值为空。"""
errors: dict[str, Any] = {}
validated: dict[str, Any] = {}
+ from . import media_identity
raws = body.get("media_dirs")
rows = [str(item) for item in raws] if isinstance(raws, list) else [str(raws or "")]
if "media_sources" in body:
@@ -593,6 +593,13 @@ def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, A
validated.update(locations=locations, mounts=mounts)
if not problems:
validated["media_costs"] = media_configuration.costs(sources, config, windows=os.name == "nt")
+ try:
+ prepared = media_identity.configure_sources(config, sources, windows=os.name == "nt")
+ validated.update(library_catalog=prepared.library_catalog, storage_roots=prepared.storage_roots,
+ locations=prepared.locations, mounts=prepared.mounts,
+ media_costs=prepared.media_costs)
+ except ValueError as exc:
+ problems = [str(exc)] * len(sources)
names, icons = {}, {}
if not problems:
for index, row in enumerate(sources):
@@ -617,6 +624,16 @@ def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, A
else:
paths, problems = onboarding.read_media_dirs(
rows, validate=onboarding.media_dir_validator(windows=os.name == "nt"))
+ if not problems:
+ sources = media_identity.sources_for_paths(config, paths, windows=os.name == "nt", keep_other_sources=True)
+ try:
+ prepared = media_identity.configure_sources(config, sources, windows=os.name == "nt")
+ validated.update(locations=prepared.locations, mounts=prepared.mounts,
+ library_catalog=prepared.library_catalog, storage_roots=prepared.storage_roots,
+ library_names=prepared.library_names, library_icons=prepared.library_icons,
+ media_costs=prepared.media_costs)
+ except ValueError as exc:
+ problems = [str(exc)] * max(1, len(rows))
if problems:
errors["media_dirs"] = problems
else:
@@ -854,10 +871,15 @@ def save_configuration(request: Request, body: dict[str, Any] = Body(default_fac
validated["library_names"] = {**config.library_names, **{
row["root"]: row["library"] for row in sources if row.get("library")}}
prepared = replace(config, locations=locations, mounts=mounts,
+ library_catalog=validated.get("library_catalog", config.library_catalog),
+ storage_roots=validated.get("storage_roots", config.storage_roots),
library_names=validated.get("library_names", config.library_names),
library_icons=validated.get("library_icons", config.library_icons),
media_costs=validated.get("media_costs", config.media_costs),
server=replace(config.server, port=validated["port"]))
+ if prepared.storage_roots:
+ from . import media_identity
+ prepared = media_identity.project(prepared)
temporary = config.path.with_suffix(".pending.toml")
try:
shutil.copy2(config.path, config.path.with_suffix(".previous.toml"))
diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.py
index 6dd751bd4..be38631bc 100644
--- a/src/peach/routes_pages.py
+++ b/src/peach/routes_pages.py
@@ -407,6 +407,19 @@ def _json_text(value: object) -> str:
return "" if value is None else str(value)
+def _submitted_media_rows(rows: object) -> dict[str, list]:
+ """JSON 媒体行拆成与表单相同的逐列列表;身份字段按行原样带给配置校验。"""
+ rows = [row if isinstance(row, dict) else {} for row in rows] if isinstance(rows, list) else []
+ return {
+ "media_dir": [_json_text(row.get("path")) for row in rows],
+ "media_location": [_json_text(row.get("location", "local")) for row in rows],
+ "media_root": [_json_text(row.get("root")) for row in rows],
+ "media_cost": [row.get("cost") for row in rows],
+ "media_identity": [{key: row[key] for key in ("root_id", "library_id", "library", "library_icon", "change_mode")
+ if key in row} for row in rows],
+ }
+
+
@router.post("/api/setup")
async def setup_submit_json(request: Request):
"""首启提交:校验一份答卷,全对就落盘;错误按题目 key 回给页面写回原位。
@@ -431,16 +444,11 @@ async def setup_submit_json(request: Request):
reporting = remote_reporting.parse_choices(body.get("remote_reporting", {}), partial=True)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
- rows = body.get("media_dir")
- rows = [row if isinstance(row, dict) else {} for row in rows] if isinstance(rows, list) else []
submitted: dict[str, object] = {
key: _json_text(body[key])
for key in ("data_root", "host", "port", "mdns_name", "access_password", "access_confirm")
if body.get(key) is not None}
- submitted["media_dir"] = [_json_text(row.get("path")) for row in rows]
- submitted["media_location"] = [_json_text(row.get("location", "local")) for row in rows]
- submitted["media_root"] = [_json_text(row.get("root")) for row in rows]
- submitted["media_cost"] = [row.get("cost") for row in rows]
+ submitted.update(_submitted_media_rows(body.get("media_dir")))
scan_now = body.get("scan_now") is True
history_guide = body.get("history_guide") is True
windows = os.name == "nt"
@@ -562,8 +570,17 @@ def _read_answers(
for index, row in enumerate(sources):
if index < len(costs) and costs[index] is not None:
row["cost"] = costs[index]
+ identities = submitted.get("media_identity", [])
+ if isinstance(identities, list) and index < len(identities) and isinstance(identities[index], dict):
+ row.update(identities[index])
sources = media_configuration.prepare_sources(sources, windows=windows, config=config)
_, _, problems = media_configuration.validate(sources, windows=windows, config=config)
+ if not problems:
+ from . import media_identity
+ try:
+ media_identity.configure_sources(config, sources, windows=windows)
+ except ValueError as exc:
+ problems = [str(exc)] * len(sources)
problems = _setup_media_source_errors(dirs, kinds, problems, question.validate)
if problems:
errors["media_dir"] = problems
diff --git a/src/peach/scan.py b/src/peach/scan.py
index 770ee0891..386142342 100644
--- a/src/peach/scan.py
+++ b/src/peach/scan.py
@@ -42,7 +42,7 @@ from pathlib import Path, PureWindowsPath
from filelock import FileLock
from . import folder_rules, junk, record_rehome, subtitles, wants
-from .platform import is_windows_path, resolve_location, resolve_root
+from .platform import is_windows_path, is_unmapped, resolve_location, resolve_root
from .processing_control import checkpoint
from .fsutil import atomic_write_text
@@ -83,6 +83,30 @@ class ScanTargetError(ValueError):
"""来源与扫描根对不上,或者来源在本机没有落点。消息可以直接给人看。"""
+def _registered_paths(connection, location, root):
+ """保留既有文件路径写法;有歧义时拒绝自动合并个人记录。"""
+ declared = PureWindowsPath(root)
+ result = {}
+ for (path,) in connection.execute("SELECT path FROM asset WHERE location=? AND path IS NOT NULL", (location,)):
+ target = PureWindowsPath(path)
+ if not target.is_relative_to(declared):
+ continue
+ key = str(target).casefold()
+ if key in result and result[key] != path:
+ raise ScanTargetError("同一规范路径有多条文件记录,请先复核重复记录")
+ result[key] = path
+ return result
+
+
+def _upsert_records(connection, batch, registered):
+ rows = []
+ for location, path, *values in batch:
+ key = str(PureWindowsPath(path)).casefold()
+ stored = registered.setdefault(key, path)
+ rows.append((location, stored, *values))
+ connection.executemany(_UPSERT, rows)
+
+
def medium_of(name: str) -> str:
suffix = os.path.splitext(name)[1].lower()
if suffix in VIDEO:
@@ -156,16 +180,18 @@ def ledger_root_for(
"""
windows = os.name == "nt" if windows is None else windows
text = os.fspath(root)
- if windows:
- return text if is_windows_path(text) else str(Path(text).resolve())
declared = declared_roots.get(location, ())
location_mounts = tuple(mounts.get(location, ()))
for declared_root, mount in zip(declared, location_mounts):
+ if not str(mount):
+ continue
try:
tail = Path(text).resolve().relative_to(Path(mount).resolve()).parts
except ValueError:
continue
return str(PureWindowsPath(declared_root, *tail))
+ if windows:
+ return text if is_windows_path(text) else str(Path(text).resolve())
if is_windows_path(text):
return text
if not location_mounts:
@@ -182,11 +208,11 @@ def walk_root_for(
) -> Path:
"""取得数据库路径在本机对应的扫描目录。调用前先过 `check_scan_target`。"""
windows = os.name == "nt" if windows is None else windows
- if windows:
- return Path(root)
_location, index, tail = resolve_root(root, declared_roots)
location_mounts = tuple(mounts.get(location, ()))
- if index >= len(location_mounts):
+ if index >= len(location_mounts) or str(location_mounts[index]) in ("", ".") or is_unmapped(Path(location_mounts[index])):
+ if windows:
+ return Path(root)
raise ScanTargetError(
f"✗ 媒体来源 {location!r} 的第 {index + 1} 个数据库路径前缀没有对应的本机目录;"
f"请先在 [media.mounts] 中按相同顺序配置媒体目录")
@@ -294,13 +320,15 @@ def ingest_path(
connection = sqlite3.connect(db_path, timeout=30)
try:
connection.execute("PRAGMA journal_mode=WAL")
- connection.execute(_UPSERT, (location, str(ledger_path), name, medium,
- stat.st_size, mtime, now, now))
+ registered = _registered_paths(connection, location, str(ledger_dir))
+ _upsert_records(connection, [(location, str(ledger_path), name, medium,
+ stat.st_size, mtime, now, now)], registered)
+ stored_path = registered[str(ledger_path).casefold()]
if pairing is not None:
tracks = subtitles.record(connection, location, pairing, now)[0]
asset_id, first_seen = connection.execute(
"SELECT id,first_seen FROM asset WHERE location=? AND path=?",
- (location, str(ledger_path))).fetchone()
+ (location, stored_path)).fetchone()
new = first_seen == now
reattached = len(record_rehome.reattach(connection, [asset_id] if new else [], now=now))
acquired = len(wants.reconcile(connection, [asset_id] if new else []))
@@ -400,7 +428,9 @@ def scan_location(db_path, location, root, **kwargs) -> ScanResult:
if 'save_checkpoint' in kwargs or 'resume_state' in kwargs:
return _scan_location(db_path, location, root, **kwargs)
from .update_tasks import state_for
- key = hashlib.sha256(f'{location}:{root}'.encode()).hexdigest()
+ mapped = walk_root_for(location, root, declared_roots=kwargs['declared_roots'],
+ mounts=kwargs.get('mounts') or {}, windows=kwargs.get('windows'))
+ key = hashlib.sha256(f'{location}:{PureWindowsPath(root)}:{mapped}'.casefold().encode()).hexdigest()
path = state_for(Path(db_path)).parent / 'scan-checkpoints' / f'{key}.json'
path.parent.mkdir(parents=True, exist_ok=True)
with FileLock(str(path) + '.lock', timeout=0):
@@ -438,6 +468,9 @@ def _scan_location(
walk_root = walk_root_for(
location, root, declared_roots=declared_roots, mounts=mounts or {}, windows=windows)
previous = resume_state or {}
+ mapping = str(walk_root)
+ if previous.get('mapping') != mapping:
+ previous = {}
if previous.get('result'):
return ScanResult(**{**previous['result'], 'new_ids': tuple(previous['result']['new_ids'])})
ledger_root = PureWindowsPath(root)
@@ -457,7 +490,7 @@ def _scan_location(
artwork_parents = {os.path.dirname(value) for value in [*pending, *([directory] if directory else [])]
if os.path.basename(value).casefold() in ARTWORK_DIRS}
video_dirs.intersection_update(artwork_parents)
- save_checkpoint(dict(scan_time=now, pending=list(pending), files=files,
+ save_checkpoint(dict(mapping=mapping, scan_time=now, pending=list(pending), files=files,
total_bytes=total, sidecars=skipped, subtitles=tracks,
orphan_subtitles=orphans, video_dirs=sorted(video_dirs),
current_directory=directory, cursor=cursor, here=dict(here or {})))
@@ -466,6 +499,7 @@ def _scan_location(
connection = sqlite3.connect(db_path, timeout=30)
try:
connection.execute("PRAGMA journal_mode=WAL")
+ registered = _registered_paths(connection, location, root)
for directory, entries in _walk(walk_root, pending):
checkpoint('scan')
relative = Path(directory).relative_to(walk_root).parts
@@ -499,7 +533,7 @@ def _scan_location(
total += stat.st_size
progress(files, total)
if len(batch) >= BATCH_SIZE:
- connection.executemany(_UPSERT, batch)
+ _upsert_records(connection, batch, registered)
connection.commit()
batch.clear()
save_directory(directory, name, here)
@@ -509,7 +543,7 @@ def _scan_location(
ledger_root.joinpath(*relative), here,
[name for name in here if medium_of(name) == "video"])
if batch:
- connection.executemany(_UPSERT, batch)
+ _upsert_records(connection, batch, registered)
batch.clear()
directory_tracks, directory_orphans = subtitles.record(connection, location, sidecars, now)
connection.commit()
@@ -517,25 +551,27 @@ def _scan_location(
orphans += directory_orphans
save_directory()
if batch:
- connection.executemany(_UPSERT, batch)
+ _upsert_records(connection, batch, registered)
connection.commit()
# 只有 INSERT 那一支写 `first_seen`,等于本次时刻的就是这一轮新建的行。
+ from .media_folders import path_predicate
+ scope, parameters = path_predicate(location, root)
new_ids = tuple(row[0] for row in connection.execute(
- "SELECT id FROM asset WHERE location=? AND first_seen=? ORDER BY id", (location, now)))
+ "SELECT a.id FROM asset a WHERE " + scope + " AND a.first_seen=? ORDER BY a.id", (*parameters, now)))
reattached = len(record_rehome.reattach(connection, new_ids, now=now))
acquired = len(wants.reconcile(connection, new_ids))
folder_rules.apply_new(connection, new_ids)
connection.commit()
- gone =connection.execute(
- "SELECT COUNT(*) FROM asset WHERE location=? AND last_seen<?",
- (location, now)).fetchone()[0]
+ gone = connection.execute(
+ "SELECT COUNT(*) FROM asset a WHERE " + scope + " AND a.last_seen<?",
+ (*parameters, now)).fetchone()[0]
finally:
connection.close()
checked = junk.isolate(db_path, roots=[(location, root)])
result = ScanResult(location, root, files, total, time.time() - started, gone,
tracks, orphans, skipped, new_ids, reattached, acquired,
checked['isolated'], checked['review'])
- save_checkpoint({'result': asdict(result)})
+ save_checkpoint({'mapping': mapping, 'result': asdict(result)})
progress(files, total, force=True)
report(result.summary())
return result
diff --git a/src/peach/settings_file.py b/src/peach/settings_file.py
index 7f22ccfeb..bdeeee078 100644
--- a/src/peach/settings_file.py
+++ b/src/peach/settings_file.py
@@ -230,6 +230,8 @@ class PeachConfig:
library_names: dict[str, str] = field(default_factory=dict)
library_icons: dict[str, str] = field(default_factory=dict)
media_costs: dict[str, str] = field(default_factory=dict)
+ library_catalog: dict[str, dict[str, str]] = field(default_factory=dict)
+ storage_roots: dict[str, dict[str, str]] = field(default_factory=dict)
#: `asset.location` -> 数据库中的目录前缀,至少一个。
locations: dict[str, tuple[str, ...]] = field(
default_factory=lambda: dict(DEFAULT_LOCATION_ROOTS))
@@ -324,7 +326,7 @@ def _string_map(table: dict, path: Path, prefix: str) -> dict[str, str]:
return result
-def _root_map(table: dict, path: Path, prefix: str) -> dict[str, tuple[str, ...]]:
+def _root_map(table: dict, path: Path, prefix: str, *, allow_empty: bool = False) -> dict[str, tuple[str, ...]]:
"""`[media.locations]` / `[media.mounts]` 的值:一个字符串,或一个字符串数组。
单个来源常常只有一个目录,写成字符串最好读;第二块硬盘加进来时改成数组即可。
@@ -337,9 +339,10 @@ def _root_map(table: dict, path: Path, prefix: str) -> dict[str, tuple[str, ...]
continue
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
raise _fail(path, f"`{prefix}{key}` 必须是字符串,或者字符串数组")
- if any(not item for item in value):
+ if not allow_empty and any(not item for item in value):
raise _fail(path, f"`{prefix}{key}` 的数组里不能有空串")
- if len(set(value)) != len(value):
+ filled = [item for item in value if item] if allow_empty else value
+ if len(set(filled)) != len(filled):
raise _fail(path, f"`{prefix}{key}` 的数组里有重复的路径")
result[key] = tuple(value)
return result
@@ -356,7 +359,7 @@ def _merge(
raise _fail(path, "`directories` 里有不认识的键:" + "、".join(unknown))
media = _table(document, "media", path)
- stray = sorted(set(media) - {_LOCATIONS_KEY, _MOUNTS_KEY, "libraries", "library_icons", "costs"})
+ stray = sorted(set(media) - {_LOCATIONS_KEY, _MOUNTS_KEY, "libraries", "library_icons", "costs", "library_catalog", "storage_roots"})
if stray:
# 第一阶段的 `[media] R = '/Volumes/Media'`。键空间从盘符换成了 location ID,
# 把它当未知键忽略等于「所有来源都没挂」——整台机器安静地进脱盘模式。
@@ -377,7 +380,7 @@ def _merge(
raise _fail(path, "`[media.locations]` 中这些媒体来源没有配置目录前缀:" + "、".join(empty))
else:
locations = dict(DEFAULT_LOCATION_ROOTS)
- mounts = _root_map(_table(media, _MOUNTS_KEY, path), path, "media.mounts.")
+ mounts = _root_map(_table(media, _MOUNTS_KEY, path), path, "media.mounts.", allow_empty="storage_roots" in media)
unknown_mounts = sorted(set(mounts) - set(locations))
if unknown_mounts:
# 打错一个 ID 却静默忽略,同样是安静地脱盘。
@@ -450,6 +453,17 @@ def _merge(
media_costs=media_costs,
server=server, replication=replication, tunnel=tunnel,
)
+ from . import media_identity
+ if "storage_roots" in media or "library_catalog" in media:
+ try:
+ libraries = {key: _string_map(value, path, "media.library_catalog.")
+ for key, value in _table(media, "library_catalog", path).items()}
+ roots = {key: _string_map(value, path, "media.storage_roots.")
+ for key, value in _table(media, "storage_roots", path).items()}
+ media_identity.validate_catalog(libraries, roots)
+ config = media_identity.project(config, libraries, roots)
+ except (ValueError, TypeError, AttributeError) as exc:
+ raise _fail(path, f"媒体库身份配置无效:{exc}") from exc
return _apply_environment(config, environ)
@@ -585,6 +599,13 @@ def _render_pairs(pairs: dict[str, object]) -> list[str]:
def render(config: PeachConfig) -> str:
"""把设置渲染成带注释的 TOML。注释是给人读的,`load_config` 不依赖它们。"""
+ from . import media_identity
+ libraries, roots = media_identity.catalog(config)
+ # 读取时会拒绝的身份不写出,免得一次保存让下次启动读不回配置。
+ try:
+ media_identity.validate_catalog(libraries, roots)
+ except ValueError as exc:
+ raise SettingsFileError(f"媒体库身份配置无效:{exc}") from exc
lines = [
"# Peach 设置文件。优先级:环境变量 > 本文件 > 程序默认值;手动修改后重启服务生效。",
"# 本文件保存在 Peach 数据目录中;该目录由 PEACH_DATA_ROOT 或项目旁的 peach-data 决定。",
@@ -617,7 +638,7 @@ def render(config: PeachConfig) -> str:
"",
"[media.libraries]",
"# [media.locations] 中的目录前缀 -> 界面显示的媒体库名称;不写时取目录名。",
- "# 多个目录使用相同名称时,在界面中显示为同一个媒体库。",
+ "# 名称与路径表是身份配置的兼容投影;媒体库归属以 library_catalog 和 storage_roots 为准。",
]
lines += [f"{_render_value(root)} = {_render_value(name)}" for root, name in config.library_names.items()]
lines += [
@@ -640,6 +661,10 @@ def render(config: PeachConfig) -> str:
"# Windows 直接读取 [media.locations] 中的目录,无需填写本表。",
]
lines += _render_roots(dict(config.mounts))
+ for key, value in libraries.items():
+ lines += ["", f"[media.library_catalog.{_render_key(key)}]", *_render_pairs(value)]
+ for key, value in roots.items():
+ lines += ["", f"[media.storage_roots.{_render_key(key)}]", *_render_pairs(value)]
lines += [
"",
"[server]",
@@ -701,6 +726,23 @@ def write(config: PeachConfig, *, force: bool = False) -> Path:
return path
+def upgrade_media_identity(config: PeachConfig, *, apply: bool = False) -> PeachConfig:
+ """显式升级配置身份;预演不写文件,不访问账本。"""
+ from . import media_identity
+ from .fsutil import atomic_write_text
+ prepared = media_identity.project(config)
+ media_identity.validate_catalog(prepared.library_catalog, prepared.storage_roots)
+ if apply and not config.storage_roots:
+ if not config.present:
+ raise SettingsFileError("请先完成首次设置")
+ backup = config.path.with_suffix(".pre-media-identity.toml")
+ # 排他备份防止覆盖上一次升级前的配置。
+ with backup.open("xb") as target:
+ target.write(config.path.read_bytes())
+ atomic_write_text(config.path, render(prepared))
+ return prepared
+
+
def capture_existing(
config: PeachConfig, *, replication_enabled: bool = True,
overrides: dict[str, object] | None = None,
@@ -730,8 +772,19 @@ def capture_existing(
replication = replace(replication, shared_root=str(config.shared_root))
if not replication.smb_share:
replication = replace(replication, smb_share=config.smb_share)
- return replace(
+ prepared = replace(
config, server=server, replication=replication,
directories={key: config.directories.get(key, key) for key in DIRECTORY_KEYS},
mounts=dict(mounts) if mounts is not None else dict(config.mounts),
)
+ if config.storage_roots and mounts is not None:
+ from . import media_identity
+ libraries, roots = media_identity.catalog(config)
+ for value in roots.values():
+ location = value["location"]
+ index = config.locations[location].index(value["root"])
+ points = mounts.get(location, ())
+ value["mount"] = str(points[index]) if index < len(points) else ""
+ media_identity.validate_catalog(libraries, roots)
+ return media_identity.project(prepared, libraries, roots)
+ return prepared
diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.py
index b2fb93eb7..f1b1ab633 100644
--- a/src/peach/web_catalog.py
+++ b/src/peach/web_catalog.py
@@ -51,6 +51,8 @@ CARD_PERFORMERS = 6
def attach_artwork_fields(contract: WebContract, item: dict) -> None:
"""列表、详情与推荐共用本地官方封面和版本投影。"""
from .strm import is_pointer
+ from .media_identity import ownership
+ item.update(ownership(settings_file.active(), item.get('path') or ''))
if is_pointer(item.get('path') or item.get('name') or ''):
item['size'] = None
item['is_strm'] = True
diff --git a/src/peach/web_folders.py b/src/peach/web_folders.py
index e4f0a548d..33d2720f7 100644
--- a/src/peach/web_folders.py
+++ b/src/peach/web_folders.py
@@ -4,7 +4,8 @@ from . import folder_rules, media_folders, settings_file
def _index(contract, args):
config = settings_file.active()
- scope = (args.get('loc', ''), args.get('library', ''), repr(config.locations), repr(config.library_names))
+ scope = (args.get('loc', ''), args.get('library', ''), repr(config.locations), repr(config.library_names),
+ repr(getattr(config, 'storage_roots', {})), repr(getattr(config, 'library_catalog', {})))
def read():
with contract.read_connection() as connection:
return media_folders.directory_index(connection, config, locations=scope[0], library=scope[1])
diff --git a/tests/test_media_libraries.py b/tests/test_media_libraries.py
index 25b732cd1..af2b9feab 100644
--- a/tests/test_media_libraries.py
+++ b/tests/test_media_libraries.py
@@ -3,10 +3,12 @@ import sqlite3
import tomllib
import unittest
from dataclasses import replace
+from pathlib import Path
+from uuid import uuid4
from tempfile import TemporaryDirectory
from types import SimpleNamespace
-from peach import media_libraries, settings_file
+from peach import media_configuration, media_identity, media_libraries, settings_file
class MediaLibraryTests(unittest.TestCase):
@@ -33,8 +35,8 @@ class MediaLibraryTests(unittest.TestCase):
db.execute("CREATE TABLE asset (location TEXT, path TEXT)")
db.executemany("INSERT INTO asset VALUES (?,?)", [
("local", "r:\\media\\one.mp4"), ("local", "R:\\MediaExtra\\two.mp4"),
- ("online", "R:\\Media\\three.mp4"), ("local", "S:\\Other\\four.mp4")])
- clause, args = media_libraries.predicate(self.config(), "电影")
+ ("online", "R:\\Media\\three.mp4"), ("local", "s:/Other/four.mp4")])
+ clause, args = media_libraries.predicate(self.config(), media_libraries.libraries(self.config())[0]["id"])
self.assertEqual(db.execute("SELECT count(*) FROM asset a WHERE " + clause, args).fetchone()[0], 2)
clause, args = media_libraries.predicate(self.config(), "不存在")
self.assertEqual(db.execute("SELECT count(*) FROM asset a WHERE " + clause, args).fetchone()[0], 0)
@@ -45,9 +47,128 @@ class MediaLibraryTests(unittest.TestCase):
self.assertEqual(tomllib.loads(line), {root: name})
with TemporaryDirectory() as directory:
config = settings_file.load_config(environ={"PEACH_DATA_ROOT": directory})
- config = replace(config, library_names={root: name}, library_icons={root: "star"})
+ config = replace(config, locations={"local": (root,)}, library_names={root: name}, library_icons={root: "star"})
config.path.parent.mkdir(parents=True, exist_ok=True)
config.path.write_text(settings_file.render(config), encoding="utf-8")
loaded = settings_file.load_config(environ={"PEACH_DATA_ROOT": directory})
self.assertEqual(loaded.library_names, {root: name})
self.assertEqual(loaded.library_icons, {root: "star"})
+
+
+class MediaIdentityTests(unittest.TestCase):
+ def setUp(self):
+ temporary = TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.env = {"PEACH_DATA_ROOT": str(self.root)}
+ self.path = self.root / "config.toml"
+ self.path.write_text("[media.locations]\nlocal = ['D:\\JAV', 'E:\\收藏\\JAV']\n"
+ "[media.libraries]\n'D:\\JAV' = 'JAV'\n'E:\\收藏\\JAV' = 'JAV'\n", encoding="utf-8")
+ self.config = settings_file.load_config(environ=self.env)
+
+ def test_upgrade_preserves_group_and_persists_ids_without_opening_ledger(self):
+ original = self.path.read_bytes()
+ projected = settings_file.upgrade_media_identity(self.config)
+ self.assertEqual(self.path.read_bytes(), original)
+ group = media_libraries.libraries(projected)
+ self.assertEqual((len(group), len(group[0]["roots"])), (1, 2))
+ settings_file.upgrade_media_identity(self.config, apply=True)
+ loaded = settings_file.load_config(environ=self.env)
+ self.assertEqual(loaded.storage_roots, projected.storage_roots)
+ self.assertEqual(self.path.with_suffix(".pre-media-identity.toml").read_bytes(), original)
+ before = self.path.read_bytes()
+ settings_file.upgrade_media_identity(loaded, apply=True)
+ self.assertEqual(self.path.read_bytes(), before)
+ self.assertFalse((self.root / "database").exists())
+
+ def test_legacy_upgrade_is_independent_of_order_and_path_spelling(self):
+ expected = media_identity.catalog(self.config)
+ reordered = replace(self.config, locations={"local": ("e:/收藏/JAV/", "d:/jav/")})
+ actual = media_identity.catalog(reordered)
+ self.assertEqual(set(expected[0]), set(actual[0]))
+ self.assertEqual(set(expected[1]), set(actual[1]))
+
+ def test_rename_reorder_and_reload_preserve_all_ids(self):
+ config = settings_file.upgrade_media_identity(self.config)
+ rows = media_configuration.rows(config, windows=True)
+ for row in rows:
+ row.update(library="私人馆藏", library_icon="star")
+ changed = media_identity.configure_sources(config, list(reversed(rows)), windows=True)
+ settings_file.write(changed, force=True)
+ loaded = settings_file.load_config(environ=self.env)
+ self.assertEqual(set(loaded.storage_roots), set(config.storage_roots))
+ self.assertEqual(set(loaded.library_catalog), set(config.library_catalog))
+ self.assertEqual(media_libraries.libraries(loaded)[0]["name"], "私人馆藏")
+ self.assertEqual(media_libraries.libraries(loaded)[0]["icon"], "star")
+
+ def test_same_names_are_independent_and_assignment_uses_library_id(self):
+ empty = replace(self.config, locations={}, library_names={})
+ first, second = str(uuid4()), str(uuid4())
+ sources = [{"location": "local", "path": "D:\\JAV", "library": "JAV", "library_id": first},
+ {"location": "local", "path": "E:\\JAV", "library": "JAV", "library_id": second}]
+ config = media_identity.configure_sources(empty, sources, windows=True)
+ self.assertEqual(len(media_libraries.libraries(config)), 2)
+ rows = media_configuration.rows(config, windows=True)
+ rows[1]["library_id"] = first
+ joined = media_identity.configure_sources(config, rows, windows=True)
+ self.assertEqual(set(joined.storage_roots), set(config.storage_roots))
+ self.assertEqual(len(media_libraries.libraries(joined)), 1)
+ with sqlite3.connect(":memory:") as db:
+ db.execute("CREATE TABLE asset(location TEXT,path TEXT)")
+ db.executemany("INSERT INTO asset VALUES('local',?)", [("D:\\JAV\\one.mp4",), ("E:\\JAV\\one.mp4",)])
+ clause, values = media_libraries.predicate(joined, first)
+ self.assertEqual(db.execute("SELECT count(*) FROM asset a WHERE " + clause, values).fetchone()[0], 2)
+
+ def test_relocation_requires_intent_and_keeps_ledger_prefix(self):
+ config = settings_file.upgrade_media_identity(self.config)
+ rows = media_configuration.rows(config, windows=True)
+ rows[0]["path"] = "F:\\移动收藏"
+ with self.assertRaisesRegex(ValueError, "重定位"):
+ media_identity.configure_sources(config, rows, windows=True)
+ rows[0]["change_mode"] = "relocate"
+ relocated = media_identity.configure_sources(config, rows, windows=True)
+ self.assertEqual(relocated.locations, config.locations)
+ self.assertEqual(set(relocated.storage_roots), set(config.storage_roots))
+ self.assertEqual(media_configuration.rows(relocated, windows=True)[0]["path"], "F:\\移动收藏")
+ settings_file.write(relocated, force=True)
+ loaded = settings_file.load_config(environ=self.env)
+ self.assertEqual(loaded.storage_roots, relocated.storage_roots)
+ self.assertEqual(loaded.mounts, relocated.mounts)
+ rows[0]["location"] = "115"
+ with self.assertRaisesRegex(ValueError, "来源"):
+ media_identity.configure_sources(config, rows, windows=True)
+
+ def test_overlaps_and_duplicate_root_ids_are_rejected_across_libraries(self):
+ config = settings_file.upgrade_media_identity(self.config)
+ rows = media_configuration.rows(config, windows=True)
+ with self.assertRaisesRegex(ValueError, "不能登记多次"):
+ media_identity.configure_sources(config, [rows[0], rows[0]], windows=True)
+ rows.append({"location": "local", "path": "d:/jav/子目录", "library": "独立"})
+ self.assertTrue(media_configuration.validate(rows, windows=True)[2])
+ with self.assertRaisesRegex(ValueError, "包含"):
+ media_identity.configure_sources(config, rows, windows=True)
+
+ def test_removal_keeps_remaining_root_identity(self):
+ config = settings_file.upgrade_media_identity(self.config)
+ rows = media_configuration.rows(config, windows=True)
+ reduced = media_identity.configure_sources(config, rows[1:], windows=True)
+ self.assertEqual(list(reduced.storage_roots), [rows[1]["root_id"]])
+ self.assertEqual(reduced.library_catalog, config.library_catalog)
+
+ def test_path_form_preserves_independent_same_name_libraries(self):
+ first, second = str(uuid4()), str(uuid4())
+ config = media_identity.configure_sources(replace(self.config, locations={}), [
+ dict(location='local', path='D:\\JAV', library='JAV', library_id=first),
+ dict(location='local', path='E:\\JAV', library='JAV', library_id=second),
+ ], windows=True)
+ sources = media_identity.sources_for_paths(config, ['E:\\JAV', 'D:\\JAV'], windows=True)
+ prepared = media_identity.configure_sources(config, sources, windows=True)
+ self.assertEqual(prepared.library_catalog, config.library_catalog)
+ self.assertEqual(set(prepared.storage_roots), set(config.storage_roots))
+
+ def test_nested_relocation_is_rejected(self):
+ config = settings_file.upgrade_media_identity(self.config)
+ rows = media_configuration.rows(config, windows=True)
+ rows[0].update(path='D:\\JAV\\moved', change_mode='relocate')
+ with self.assertRaisesRegex(ValueError, '重叠'):
+ media_identity.configure_sources(config, rows, windows=True)
diff --git a/tests/test_media_sources.py b/tests/test_media_sources.py
index 60559ee06..a536cdad9 100644
--- a/tests/test_media_sources.py
+++ b/tests/test_media_sources.py
@@ -86,12 +86,19 @@ class MediaSourceCostTests(unittest.TestCase):
(*params, "free")).fetchall()
self.assertEqual(rows, [("O:\\Public\\film.mp4",)])
+ def test_nested_roots_are_refused_before_the_file_is_written(self):
+ with self.assertRaisesRegex(settings_file.SettingsFileError, "互相包含"):
+ settings_file.write(self.config)
+ self.assertFalse(self.config.path.exists())
+
def test_config_roundtrip_preserves_root_overrides_and_effective_form_cost(self):
- settings_file.write(self.config)
+ config = replace(self.config, locations={**self.config.locations, "guangya": ("G:/Movies",)},
+ media_costs={"G:/Movies": "metered", "O:/Public": "free"})
+ settings_file.write(config)
loaded = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.root)})
- self.assertEqual(loaded.media_costs, self.config.media_costs)
+ self.assertEqual(loaded.media_costs, {"G:/Movies": "metered", "O:/Public": "free"})
rows = media_configuration.rows(loaded, windows=True)
- self.assertEqual([row["cost"] for row in rows], ["metered", "free", "free", "metered", "metered"])
+ self.assertEqual([row["cost"] for row in rows], ["metered", "free", "metered", "metered"])
costs = media_configuration.costs([{"location": "guangya", "path": "G:/Movies", "cost": "free"}],
loaded, windows=True)
self.assertEqual(costs["G:\\Movies"], "free")
@@ -100,7 +107,7 @@ class MediaSourceCostTests(unittest.TestCase):
for value in (True, "proxy", [], None):
self.assertTrue(media_configuration.validate([
{"location": "onedrive", "path": "O:/", "cost": value}], windows=True)[2])
- settings_file.write(replace(self.config, media_costs={"G:/": "unknown"}))
+ settings_file.write(replace(self.config, locations={"guangya": ("G:/Movies",)}, media_costs={"G:/": "unknown"}))
with self.assertRaisesRegex(settings_file.SettingsFileError, "free.*metered"):
settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.root)})
with self.assertRaisesRegex(ValueError, "列名"):
diff --git a/tests/test_onboarding.py b/tests/test_onboarding.py
index c144886fa..7cc041c68 100644
--- a/tests/test_onboarding.py
+++ b/tests/test_onboarding.py
@@ -1047,7 +1047,7 @@ class StandaloneConfigurationTests(_Case):
from peach import media_libraries
first, second, third = (str(self.media / name) for name in ("a", "b", "c"))
self.config = replace(self.config, locations={"local": (first, second), "115": (third,)},
- library_names={first: "电影", third: "电影"})
+ library_names={first: "电影", third: "电影"}, library_catalog={}, storage_roots={})
settings_file.write(self.config, force=True)
with self.client() as client:
snapshot = client.get("/api/configuration", headers={"X-Token": "test-token"}).json()
diff --git a/tests/test_organize.py b/tests/test_organize.py
index 991bec6ef..a5a7548eb 100644
--- a/tests/test_organize.py
+++ b/tests/test_organize.py
@@ -168,6 +168,20 @@ class PlanTests(unittest.TestCase):
self.addCleanup(lambda: __import__("shutil").rmtree(self.holder, ignore_errors=True))
self.db_path = fresh_ledger(self.holder)
+ def test_online_root_does_not_hide_another_roots_offline_state(self):
+ _seed(self.db_path, [
+ dict(id=1, path='R:\\media\\a.mp4', name='a.mp4', code='ABC-001'),
+ dict(id=2, path='S:\\media\\b.mp4', name='b.mp4', code='ABC-002'),
+ ])
+ with closing(sqlite3.connect(self.db_path)) as connection, \
+ mock.patch.object(organize, 'translate_ledger_path', side_effect=lambda root: root), \
+ mock.patch.object(organize, 'root_online', side_effect=lambda root: str(root).startswith('R:')):
+ result = organize.build_plan(connection, location='local', roots={'local': ('R:\\media', 'S:\\media')},
+ file_template='{number}')
+ self.assertEqual(result['counts']['change'], 1)
+ self.assertEqual(result['counts']['skip'], 1)
+ self.assertEqual(result['rows'][1]['reason'], organize.SKIP_OFFLINE)
+
def test_rename_in_place_and_move_into_template_directory(self):
_seed(self.db_path, [
{"id": 1, "path": "R:\\media\\旧\\[site.com]abc123.mp4",
diff --git a/tests/test_platform.py b/tests/test_platform.py
index 9a15e24f1..4a322abf8 100644
--- a/tests/test_platform.py
+++ b/tests/test_platform.py
@@ -108,6 +108,19 @@ class LocationResolutionTests(unittest.TestCase):
class MountSourceTests(unittest.TestCase):
+ def test_mixed_mount_mapping_keeps_each_roots_position(self):
+ declared = {'local': ('R:\\one', 'S:\\two')}
+ with tempfile.TemporaryDirectory() as temporary:
+ mounted = Path(temporary).resolve()
+ with with_media({'local': ('', str(mounted))}, declared), patch.dict(os.environ, {MOUNTS_ENV: ''}):
+ self.assertEqual(location_mounts()['local'][1], mounted)
+ first = translate_ledger_path('R:\\one\\a.mp4')
+ if os.name == 'nt':
+ self.assertEqual(first, Path('R:\\one\\a.mp4'))
+ else:
+ self.assertTrue(is_unmapped(first))
+ self.assertEqual(translate_ledger_path('S:\\two\\b.mp4'), mounted / 'b.mp4')
+
"""挂载表按来源 ID 取自设置文件;`PEACH_MEDIA_MOUNTS` 仍然压过它。"""
def test_empty_source_uses_the_settings_parser_shape(self):
@@ -250,6 +263,20 @@ class OfflineModeTests(unittest.TestCase):
class MountReachabilityTests(unittest.TestCase):
+ def test_an_offline_root_does_not_disable_other_roots_of_the_same_source(self):
+ from peach.mount_reachability import MountReachability, MountRoot
+ monitor = MountReachability([
+ MountRoot('local', '本地磁盘', 'D:/JAV', self.root, 'root-one', 'library-one'),
+ MountRoot('local', '本地磁盘', 'E:/JAV', None, 'root-two', 'library-one'),
+ ], probe=lambda _path: 'ok', retry_delay=0)
+ self.addCleanup(monitor.stop)
+ monitor._states[self.root].state = 'ok'
+ row = monitor.sources()[0]
+ self.assertTrue(row['online'])
+ self.assertEqual([(root['root_id'], root['online']) for root in row['roots']],
+ [('root-one', True), ('root-two', False)])
+ self.assertEqual(monitor.summary()['state'], 'degraded')
+
def setUp(self):
from peach.mount_reachability import MountReachability, MountRoot
self.tmp = tempfile.TemporaryDirectory()
diff --git a/tests/test_scan.py b/tests/test_scan.py
index f864ada94..bf5f7f479 100644
--- a/tests/test_scan.py
+++ b/tests/test_scan.py
@@ -21,6 +21,7 @@ from unittest.mock import patch
from peach import scan
from peach.migrations import upgrade
+from support.web import route_client
ROOT = Path(__file__).resolve().parents[1]
MIGRATIONS = ROOT / "migrations"
@@ -91,7 +92,6 @@ class WindowsShapeTests(_ScanCase):
(str(video),)).fetchone(), (None,))
def test_scanned_video_is_visible_without_a_thumbnail_filter(self):
- from support.web import route_client
from peach.api import create_app
from peach.config import PeachSettings
self._scan(str(self.media), declared_roots={"local": (str(self.media),)}, windows=True)
@@ -123,6 +123,44 @@ class WindowsShapeTests(_ScanCase):
class PosixShapeTests(_ScanCase):
"""macOS:账本里写 `R:\\media\\...`,遍历的是挂载点,读取侧按挂载表翻回去。"""
+ def test_windows_mount_mapping_has_the_same_ledger_path_contract(self):
+ options = dict(declared_roots={'local': ('R:\\media',)}, mounts={'local': (self.media,)}, windows=True)
+ self.assertEqual(scan.walk_root_for('local', 'R:\\media\\创作者', **options), self.media / '创作者')
+ self.assertEqual(scan.ledger_root_for('local', self.media / '创作者', **options), 'R:\\media\\创作者')
+
+ def test_root_case_changes_preserve_asset_identity_and_personal_records(self):
+ options = dict(declared_roots={'local': ('R:\\media',)}, mounts={'local': (self.media,)}, windows=False)
+ self._scan('R:\\media', **options)
+ with closing(sqlite3.connect(self.db)) as connection, connection:
+ connection.execute("UPDATE asset SET rating=4,play_count=7")
+ before = list(connection.execute("SELECT id,path,rating,play_count FROM asset ORDER BY id"))
+ self._scan('r:\\MEDIA', **options)
+ with closing(sqlite3.connect(self.db)) as connection, connection:
+ self.assertEqual(list(connection.execute("SELECT id,path,rating,play_count FROM asset ORDER BY id")), before)
+
+ def test_relocated_mount_restarts_traversal_and_preserves_file_id(self):
+ saved = []
+ options = dict(declared_roots={'local': ('R:\\media',)}, mounts={'local': (self.media,)}, windows=False)
+ self._scan('R:\\media', save_checkpoint=lambda value: saved.append(value), **options)
+ with closing(sqlite3.connect(self.db)) as connection, connection:
+ before = list(connection.execute("SELECT id,path FROM asset ORDER BY id"))
+ moved = self.root / 'moved'
+ self.media.rename(moved)
+ (moved / 'new.mp4').write_bytes(b'new')
+ self._scan('R:\\media', resume_state=saved[-1], **{**options, 'mounts': {'local': (moved,)}})
+ with closing(sqlite3.connect(self.db)) as connection, connection:
+ self.assertEqual(list(connection.execute("SELECT id,path FROM asset ORDER BY id LIMIT 3")), before)
+ self.assertEqual(connection.execute('SELECT count(*) FROM asset').fetchone()[0], 4)
+
+ def test_scanning_one_root_does_not_count_other_roots_as_missing(self):
+ options = dict(declared_roots={'local': ('R:\\media', 'S:\\other')},
+ mounts={'local': (self.media, self.root / 'other')}, windows=False)
+ with closing(sqlite3.connect(self.db)) as connection, connection:
+ connection.execute("INSERT INTO asset(location,path,name,medium,last_seen) VALUES('local','S:\\other\\copy.mp4','copy.mp4','video','2000-01-01')")
+ result, _ = self._scan('R:\\media', **options)
+ self.assertEqual(result.gone, 0)
+ self.assertEqual(len(result.new_ids), 3)
+
def test_resume_skips_committed_directories_and_retains_subtitles_and_new_ids(self):
(self.media / '创作者/sub/a.srt').write_text('subtitle', encoding='utf-8')
saved = {}
diff --git a/tests/test_web_media_repair.py b/tests/test_web_media_repair.py
index 25d4c4f7b..a9f3f8364 100644
--- a/tests/test_web_media_repair.py
+++ b/tests/test_web_media_repair.py
@@ -88,6 +88,8 @@ class MediaRepairRunTests(unittest.TestCase):
self.contract.transcode_service = self.transcodes
config = SimpleNamespace(locations={"115": ("B:" + SEP,), "pikpak": ("A:" + SEP,)},
library_names={"B:" + SEP: "网盘", "A:" + SEP: "PikPak"})
+ from peach.media_libraries import libraries
+ self.library_ids = {row['name']: row['id'] for row in libraries(config)}
for patch in (
mock.patch.object(rm_repair, "translate_ledger_path",
lambda raw: self.media / PureWindowsPath(str(raw)).name),
@@ -112,7 +114,7 @@ class MediaRepairRunTests(unittest.TestCase):
def run_once(self, library="网盘", **body) -> dict:
"""跑完一轮再返回状态:后台任务在测试里没有别的事要抢。"""
with mock.patch.object(rm_repair.mp4recover, "recover", self.recover):
- started = rm_repair.w_media_repair(self.contract, {"restart": True, "library": library, **body})
+ started = rm_repair.w_media_repair(self.contract, {"restart": True, "library": self.library_ids.get(library, library), **body})
thread = self.contract.media_repair_job.thread
if thread is not None:
thread.join(timeout=30)
@@ -132,7 +134,7 @@ class MediaRepairRunTests(unittest.TestCase):
self.assertEqual(self.store.repaired, [2, 1])
self.assertEqual([name for name, _ in self.recovered], ["cut.mp4"])
self.assertEqual(state["status"], "complete")
- self.assertEqual(state["library"], "网盘")
+ self.assertEqual(state["library"], self.library_ids["网盘"])
self.assertEqual((state["found"], state["repaired"], state["failed"]), (3, 3, 0))
def test_the_most_played_ones_are_repaired_first(self):
@@ -254,7 +256,7 @@ class MediaRepairRunTests(unittest.TestCase):
self.contract.header_repairs = None
with self.assertRaises(ValueError):
- rm_repair.w_media_repair(self.contract, {"library": "网盘"})
+ rm_repair.w_media_repair(self.contract, {"library": self.library_ids["网盘"]})
def test_an_idle_instance_reports_idle_instead_of_nothing(self):
state = rm_repair.q_media_repair(self.contract)
diff --git a/web/index.html b/web/index.html
index 22828545e..0998942fd 100644
--- a/web/index.html
+++ b/web/index.html
@@ -274,7 +274,7 @@ if(location.pathname==='/wall')document.documentElement.setAttribute('data-wall-
const brand=document.querySelector('#brandHome'),toggle=document.querySelector('#filterBtn');
const narrow=matchMedia('(max-width:760px)').matches;
let expanded=!narrow,library='';
- try{expanded=!narrow&&sessionStorage.getItem('board.sidebar')!=='closed';library=sessionStorage.getItem('peach.library')||''}catch(_e){}
+ try{expanded=!narrow&&sessionStorage.getItem('board.sidebar')!=='closed';library=sessionStorage.getItem('peach.library')?(sessionStorage.getItem('peach.library-label')||'媒体库'):''}catch(_e){}
brand.querySelector('h1').textContent=library||'全部媒体库';head.append(brand);
if(!narrow)head.append(toggle);
drawer.classList.toggle('open',expanded);drawer.inert=narrow;