Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: 媒体文件夹支持一次声明多个

longmeidaoaedd24a423eb
diff --git a/README.en.md b/README.en.md
index fdc93270e..c924cc8e2 100644
--- a/README.en.md
+++ b/README.en.md
@@ -106,7 +106,7 @@ Run without arguments, `peach init` asks five questions in the terminal; pressin
| Question | Default |
| --- | --- |
| Data directory (the Peach database, caches and the settings file live here) | `peach-data/` next to the repository |
-| Media folder (must already exist, may live on an external drive; used as source `local`) | `~\Videos` (`~/Movies` on macOS); required when that folder is missing |
+| Media folder (must already exist, may live on an external drive; used as source `local`). Afterwards it keeps asking for one more folder until you press Enter on an empty answer; every folder belongs to `local` | `~\Videos` (`~/Movies` on macOS); required when that folder is missing |
| Who can access: 1 = only this computer, 2 = devices on the same LAN | `2` |
| Port | `8900` |
| LAN address (`<name>.local`, published only when LAN access is allowed) | `peach` |
@@ -137,7 +137,7 @@ Five facts:
- Listening on `127.0.0.1` needs no token. Reaching the service from a phone or any other device on the LAN (`--host 0.0.0.0`, and everything the tray starts) does: `peach init` has already written one to `<data root>/secrets/auth-token`, `peach token` prints it, and each device pastes it into the login page once. `peach serve` refuses to start when it binds a non-loopback address without a token, because that puts the whole collection and the write endpoints on the local network.
- Use `-e` for source development. Regular installations and wheels include pages and migrations and support running from any working directory.
- When the data root is not next to the repository, `peach serve` looks for it only via `PEACH_DATA_ROOT` and the `peach-data/` directories a few levels above the repository, so set `PEACH_DATA_ROOT` as well; the default data root needs no such step.
-- Ledger paths are always in the Windows shape. On Windows the media directory goes straight into `[media.locations]`; on macOS the declared root is `R:\media` and the directory goes into `[media.mounts]`, where the local mount point does the translation. CloudDrive is not required — any cloud drive that mounts as a local path works; 115 and PikPak are recommendations, not requirements.
+- Ledger paths are always in the Windows shape. On Windows the media directories (one or several) go straight into `[media.locations]`; on macOS the declared roots are `R:\media`, `R:\media2`, … and the directories go into `[media.mounts]` in the same order, where the local mount points do the translation. CloudDrive is not required — any cloud drive that mounts as a local path works; 115 and PikPak are recommendations, not requirements.
- The interface is currently available in Chinese only.
The service also starts without a settings file: `/healthz` reports `configured=false`, and the home page is the first-run form described above.
diff --git a/README.md b/README.md
index 887e8b452..cf7171730 100644
--- a/README.md
+++ b/README.md
@@ -102,7 +102,7 @@ Windows 调试用户下载 [GitHub Releases](https://github.com/longmeidao/peach
| 问题 | 默认值 |
| --- | --- |
| 数据目录(Peach 数据库、缓存和设置文件都放在这里) | 仓库同级的 `peach-data/` |
-| 媒体文件夹(必须已经存在,可以在外置硬盘上;作为来源 `local`) | `~\Videos`(macOS 为 `~/Movies`),不存在则必填 |
+| 媒体文件夹(必须已经存在,可以在外置硬盘上;作为来源 `local`)。答完接着问「再加一个媒体文件夹」,回车结束,几个文件夹都归 `local` | `~\Videos`(macOS 为 `~/Movies`),不存在则必填 |
| 谁可以访问:1 = 只有这台电脑,2 = 同一局域网的设备 | `2` |
| 端口 | `8900` |
| 局域网访问地址(`<名字>.local`,只在允许局域网访问时发布) | `peach` |
@@ -129,7 +129,7 @@ Windows 调试用户下载 [GitHub Releases](https://github.com/longmeidao/peach
- 只监听 `127.0.0.1` 不需要口令。要让手机或局域网里别的设备访问(`--host 0.0.0.0`、托盘起的服务都算),就必须有访问口令:`peach init` 已经在 `<数据根>/secrets/auth-token` 生成一份,`peach token` 打印出来,设备第一次访问时贴进登录页。绑非回环地址却读不到口令时 `peach serve` 拒绝启动,因为那等于把整个馆藏和写接口摆在同网段上。
- 源码开发使用 `-e`;普通安装与 wheel 自带页面和迁移文件,可从任意工作目录运行。
- 数据根不在仓库同级时,`peach serve` 只按 `PEACH_DATA_ROOT` 和仓库上方几层的 `peach-data/` 找数据根,所以要同时设 `PEACH_DATA_ROOT`;用默认数据根没有这一步。
-- 账本里的路径一律是 Windows 形态。Windows 上媒体目录直接写进 `[media.locations]`;macOS 上声明根写 `R:\media`、目录写进 `[media.mounts]`,由本机挂载点负责翻译。CloudDrive 不是必需,任何能挂成本地路径的网盘都行;115 与 PikPak 是推荐项,不是要求。
+- 账本里的路径一律是 Windows 形态。Windows 上媒体目录(一个或几个)直接写进 `[media.locations]`;macOS 上声明根写 `R:\media`(第二个目录起是 `R:\media2`……)、目录按同样顺序写进 `[media.mounts]`,由本机挂载点负责翻译。CloudDrive 不是必需,任何能挂成本地路径的网盘都行;115 与 PikPak 是推荐项,不是要求。
- 界面目前只有中文。
没有设置文件也能启动:`/healthz` 报 `configured=false`,首页是上面那张首次运行表单。
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index fa7987845..0851e7de6 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -12,13 +12,15 @@
项目根同级(含上溯四层,覆盖主检出、`peach-worktrees/<任务>` 和打包后 EXE 所在的 `dist/Peach`)
的 `peach-data/`、都没有就是「未配置」。优先级是环境变量 > 设置文件 > 内建默认。
- 全新机器只跑 `peach init`。不带参数且 stdin 是终端时进问答(题目、默认值与落盘逻辑在
- `src/peach/onboarding.py`,托盘设置页复用同一组函数):问数据根、一个已存在的本地媒体
- 目录、谁可以访问(只有这台电脑/同一局域网的设备)、端口、局域网访问地址,每题回车取默认,连续三次无效即退出且
+ `src/peach/onboarding.py`,托盘设置页复用同一组函数):问数据根、一个或几个已存在的本地媒体
+ 目录(问完第一个接着问「再加一个」,回车结束;互相重复或嵌套的目录会被退回)、谁可以访问
+ (只有这台电脑/同一局域网的设备)、端口、局域网访问地址,每题回车取默认,连续三次无效即退出且
不写任何文件。然后建齐 `database`/`generated`/`sources`/`state`/`secrets`/`logs`/
`tools`/`review` 八个目录、把账本迁到最新 schema、生成本机 CA 与访问口令、写出设置文件,问一句
「现在扫描 <目录>?」(默认是)调 `peach.scan.scan_location` 登记文件,最后打印下一步与
- 扫描摘要。写出的 `[media.locations]` 只有 `local`:Windows 上直接是那个目录、
- `[media.mounts]` 为空;macOS 上声明根是 `R:\media`、目录写进 `[media.mounts] local`。
+ 扫描摘要。写出的 `[media.locations]` 只有 `local`,几个目录就几个声明根:Windows 上直接是
+ 那些目录、`[media.mounts]` 为空;macOS 上声明根是 `R:\media`(第二个起 `R:\media2`……)、
+ 目录按同样顺序写进 `[media.mounts] local`。页面上的媒体文件夹是可加减的列表,配置页同样。
复制、writer 镜像、SMB 一律不问,保持关闭或留空。建目录、迁库、生成 CA 与口令、写设置文件
这一整段在 `onboarding.apply()`,CLI 与设置页调的是同一个函数,只在打印方式上不同。
- 不进终端的那条路是托盘首启的引导服务。`peach-tray` 启动时新鲜读一次设置文件,判据在
@@ -45,8 +47,8 @@
写出的文件带 `local`/`115`/`pikpak` 三个示例声明根。已有账本不会被重建,它会提示改用
`--from-existing`。
- `peach scan <来源ID> [根目录]` 把一个目录的文件元数据 upsert 进账本,只新增行与刷新
- `size`/`mtime`/`last_seen`,不改真相字段、不删行。根目录省略时取该来源在
- `[media.locations]` 的声明根,本机目录按 `[media.mounts]` 取;给了目录则必须落在声明根
+ `size`/`mtime`/`last_seen`,不改真相字段、不删行。根目录省略时逐个扫该来源在
+ `[media.locations]` 的全部声明根,本机目录按 `[media.mounts]` 取;给了目录则必须落在某个声明根
(macOS 上是挂载点)之内,否则拒绝——写进去的行否则翻译不回本机路径。
`scripts/ledger.py scan` 是同一实现的薄委托。
- 已经在跑的机器用 `peach init --from-existing`:只写设置文件,不建库、不动 `peach-data/`
@@ -62,6 +64,7 @@
- `[media.mounts]` 的键是 `asset.location`(`[media.locations]` 声明过的来源 ID),
值是该来源的**声明根在本机的落点**:声明 `local = 'R:\media'` 而挂载 `local =
'/Volumes/RESOURCES/media'` 时,账本里的 `R:\media\x` 读作 `/Volumes/RESOURCES/media/x`。
+ 声明了几个根就按同样的顺序给几个落点(两边都写数组),数目不齐会被拒绝。
Windows 上整表为空是正常的,盘符本身就是挂载点。没挂的来源整体按脱盘处理,不报错;
打错来源 ID 或写成盘符键都会被设置层直接拒绝,不会静悄悄变成「全部脱盘」。
临时诊断用 `PEACH_MEDIA_MOUNTS=local=/mnt/res,115=/mnt/115` 覆盖(旧的
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index 83b7c6859..b627a8e03 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -22,7 +22,7 @@
5. **厂牌 Logo 补齐与持续校验**:14 个已确认社交 handle 已有内容缓存、provenance、精确/感知哈希、质量与重复门槛及健康报告;仍有 72 个厂牌没有可信 handle,必须继续从官网/公开来源取证,不能猜账号。
6. **口味证据持续刷新**:ledger 已实时记录搜索、播放、高潮、喜欢/理由、不合口味和稍后看;浏览器历史现可用 SQLite 一致性副本增量进入私有源库,并生成不含 URL/标题的 creator/tag candidate 与聚合报告。旧 2026-08-13 原始包已确认不在 Windows 外置盘;仍需在 Mac 开启 iCloud Safari、完成首次导入,并把两端每周刷新装成系统计划任务。AI 结论不得直接改真相字段。
-## 尚未实现(26 项)
+## 尚未实现(25 项)
1. AI Provider 的真实调用、能力协商、Credential Manager 凭据和候选审核 UI。
2. 剩余单一创作者风格板复核、无标签内容补标。
@@ -49,9 +49,8 @@
23. 性能基准:用 SFW 合成数据生成 1k/10k/100k/500k 四档库,nightly 测冷启动到 `/healthz`、目录页与详情页 p95、两字以上搜索 p95、本地 SSD 与网盘挂载的 Range 首字节、空闲 RSS、后台扫描时前台退化倍数、备份期间读请求不失败。门槛用「相对上一次基线下降超过 20%」,不给绝对毫秒数——不同机器不可比。数据集与第 16 条的演示数据集共用。
24. CI 的 Windows job 太慢,一次 push 的墙钟由它决定。同一批 2786 个用例在 `macos-latest`(arm64)上 57 秒,在 `windows-latest` 上 1475 秒,本机 Windows 是 324 秒——runner 比开发机还慢 4.6 倍。按时间戳差算,250 个用例(9%)吃掉 1119 秒,每个稳定在 4.5 秒上下,形状像每建一个临时文件被 Defender 扫一遍。两条路各自独立:一是在 Windows job 里对 runner 的临时目录加 `Add-MpPreference -ExclusionPath`,先量一轮确认是不是 Defender;二是把 `scripts/test_runner.py` 的域拆成矩阵分片并行跑,代价是每个分片重付一次装依赖的 37 秒。不要为了缩短墙钟把 Windows job 从矩阵里去掉:它是生产平台,也是唯一能拦住 Windows 独有回归的地方。
25. 托盘子服务的日志不轮转:`ServiceManager` 以追加模式打开 `logs/tray-<服务>.out.log` 与 `.err.log`,本机一周就长到 28 MB,`tray-scan.out.log` 与 `windows-source-sync.log` 同样只增不减。在起服务前按大小轮转,超过阈值改名保留一代即可;写文件的是子进程的 stdout,不经 `logging`,所以 `RotatingFileHandler` 用不上。
-26. 多个媒体文件夹:首次运行页与配置页都只收一个「媒体文件夹」,写进设置文件 `[media.locations]` 的 `local` 项;外置硬盘和第二块盘上的资料只能靠后来手改 `config.toml`。要做的是把表单改成可加减的目录列表(Geist 的做法是列表加一枚「添加」次级按钮,不放在输入框同一行),`onboarding.apply` 与 `peach init` 同步收多值,扫描与 `asset.location` 按声明根逐个落账。上一条来源通用化(第 11 条)先做,否则每个新目录还得起一个硬编码的来源名。
-合计:**32 项开放需求**,其中 6 项已有骨架,26 项尚未实现。已完成的需求不在这里留痕,去 Git 历史查。
+合计:**31 项开放需求**,其中 6 项已有骨架,25 项尚未实现。已完成的需求不在这里留痕,去 Git 历史查。
## 待执行的操作(32 项)
diff --git a/src/peach/cli.py b/src/peach/cli.py
index 65f7b7c99..366ed2406 100644
--- a/src/peach/cli.py
+++ b/src/peach/cli.py
@@ -263,15 +263,16 @@ def _ledger_sync(args: argparse.Namespace) -> int:
def _parse_mounts(
- raw: list[str] | None, locations: dict[str, str] | None = None,
-) -> dict[str, str]:
- """`--mount local=/Volumes/RESOURCES/media` 形式的挂载点。
+ raw: list[str] | None, locations: dict[str, tuple[str, ...]] | None = None,
+) -> dict[str, tuple[str, ...]]:
+ """`--mount local=/Volumes/RESOURCES/media` 形式的挂载点;同一来源重复给就按顺序
+ 对应它的几个声明根。
键是 `asset.location`(`[media.locations]` 里声明过的来源 ID),不是盘符:
打错一个 ID 如果静默收下,那个来源就会安静地进脱盘模式,所以这里直接拒绝。
"""
known = dict(locations or {})
- mounts: dict[str, str] = {}
+ mounts: dict[str, list[str]] = {}
for chunk in raw or ():
key, separator, value = chunk.partition("=")
key = key.strip()
@@ -282,8 +283,8 @@ def _parse_mounts(
f"--mount 的来源 ID 未在 [media.locations] 声明:{key}"
f"(已知:{'、'.join(sorted(known))})"
)
- mounts[key] = value.strip()
- return mounts
+ mounts.setdefault(key, []).append(value.strip())
+ return {key: tuple(item for item in values if item) for key, values in mounts.items()}
def _resolved_config(
@@ -372,11 +373,11 @@ def _init_interactive(
windows = os.name == "nt" if windows is None else windows
config, _broken = _resolved_config(None)
print("首次运行问答:每一题直接回车就接受方括号里的默认值。")
- asked = onboarding.questions(config, windows=windows, home=home)
collected: dict[str, object] = {}
try:
- for index, question in enumerate(asked):
- collected[question.key] = onboarding.ask_until_valid(question, ask)
+ for index, (key, value) in enumerate(
+ onboarding.collect(config, ask, windows=windows, home=home)):
+ collected[key] = value
if index == 0:
# 数据根定了,设置文件在哪也就定了。这一题之后就判,别让人把剩下四题
# 答完才听到「文件已存在」——那四个答案会被整份丢掉。
@@ -394,48 +395,51 @@ def _init_interactive(
_report_data_tree(applied.tree)
print(f"设置文件:{applied.settings_path}")
if not windows:
- print(onboarding.mounts_explanation(answers.media_dir))
+ print(onboarding.mounts_explanation(answers.media_dirs))
- summary = None
+ summaries: list[str] = []
try:
- scan_now = onboarding.ask_until_valid(onboarding.scan_question(answers.media_dir), ask)
+ scan_now = onboarding.ask_until_valid(onboarding.scan_question(answers.media_dirs), ask)
except onboarding.OnboardingAborted as exc:
print(f"{exc}跳过扫描,之后可以跑 `peach scan local`。")
scan_now = False
if scan_now:
- result = scan.scan_location(
- prepared.directory("database") / "ledger.db", onboarding.LOCAL_LOCATION,
- onboarding.scan_root(prepared), declared_roots=prepared.locations,
- mounts=prepared.mounts, report=print, windows=windows,
- )
- summary = result.summary()
+ for root in onboarding.scan_roots(prepared):
+ result = scan.scan_location(
+ prepared.directory("database") / "ledger.db", onboarding.LOCAL_LOCATION,
+ root, declared_roots=prepared.locations,
+ mounts=prepared.mounts, report=print, windows=windows,
+ )
+ summaries.append(result.summary())
_print_next_steps(prepared, from_existing=False)
- if summary:
+ for summary in summaries:
print(f" 扫描结果:{summary}")
return 0
def _scan(args: argparse.Namespace) -> int:
- """`peach scan <来源ID> [根目录]`:根目录省略时取该来源的声明根(本机目录按挂载表取)。"""
+ """`peach scan <来源ID> [根目录]`:根目录省略时逐个扫该来源的全部声明根(本机目录按挂载表取)。"""
_require_readable_settings()
if not args.db.is_file():
print(f"账本不存在:{args.db}")
print("这台机器还没初始化过,先跑 `peach init`。")
return 4
config = settings_file.active()
- mounts = {location: str(mount) for location, mount in location_mounts().items()}
+ mounts = {location: tuple(str(mount) for mount in points)
+ for location, points in location_mounts().items()}
try:
if args.root is None:
if args.location not in config.locations:
known = "、".join(sorted(config.locations)) or "(设置文件里一个都没有)"
raise scan.ScanTargetError(
f"✗ 未声明的来源 {args.location!r};[media.locations] 里已知:{known}")
- root = config.locations[args.location]
+ roots = tuple(config.locations[args.location])
else:
- root = scan.ledger_root_for(
- args.location, args.root, declared_roots=config.locations, mounts=mounts)
- scan.scan_location(args.db, args.location, root, declared_roots=config.locations,
- mounts=mounts, report=lambda line: print(line, flush=True))
+ roots = (scan.ledger_root_for(
+ args.location, args.root, declared_roots=config.locations, mounts=mounts),)
+ for root in roots:
+ scan.scan_location(args.db, args.location, root, declared_roots=config.locations,
+ mounts=mounts, report=lambda line: print(line, flush=True))
except scan.ScanTargetError as exc:
raise SystemExit(str(exc)) from None
return 0
diff --git a/src/peach/config.py b/src/peach/config.py
index ca9175791..2d86c1a5f 100644
--- a/src/peach/config.py
+++ b/src/peach/config.py
@@ -62,8 +62,10 @@ SHARED_CREDENTIAL_ROOT: Path | None = SHARED_DATA_ROOT if REPLICATION_ENABLED el
# 媒体来源只用账本口径(Windows 盘符)声明一次,本机挂载点由 platform 层翻译。
# 键是 ledger 的 `asset.location`,脱盘模式按来源逐个判定,不是全局开关。
-LOCATION_ROOT_DECLARATIONS: dict[str, str] = dict(_SETTINGS.locations)
-MEDIA_ROOT_DECLARATIONS: tuple[str, ...] = tuple(LOCATION_ROOT_DECLARATIONS.values())
+LOCATION_ROOT_DECLARATIONS: dict[str, tuple[str, ...]] = {
+ location: tuple(roots) for location, roots in _SETTINGS.locations.items()}
+MEDIA_ROOT_DECLARATIONS: tuple[str, ...] = tuple(
+ root for roots in LOCATION_ROOT_DECLARATIONS.values() for root in roots)
# 同时运行的两台机器必须用不同的 mDNS 名,否则互相抢占同一个 `.local`。
MDNS_NAME: str = _SETTINGS.server.mdns_name
diff --git a/src/peach/onboarding.py b/src/peach/onboarding.py
index 251b9f0fd..786188746 100644
--- a/src/peach/onboarding.py
+++ b/src/peach/onboarding.py
@@ -6,22 +6,25 @@
`PeachConfig`,`apply()` 把它变成一台能直接起服务的机器(目录、账本、CA、口令、设置
文件)。前端只负责把字串送进来、把结果和错误显示出去。
-问答刻意只收最小集合:数据根、一个本地媒体目录、监听范围、端口、局域网名字。复制、
+问答刻意只收最小集合:数据根、一个或几个本地媒体目录、监听范围、端口、局域网名字。复制、
115、PikPak、writer 镜像与 SMB 一律保持默认关闭或留空——陌生人第一次跑不该被这些问题
拦住,设置文件里也只写用户声明过的来源,不把维护者的示例盘符写进别人的文件。
媒体目录在两个平台上落成不同的写法,因为账本路径的形状是不变量(AGENTS.md):
-- Windows:盘符本身就是挂载点,`[media.locations] local = <该目录>`,`[media.mounts]` 留空。
-- macOS:声明根仍写账本口径的 `R:\\media`,`[media.mounts] local = <该目录>`,读取侧
- 按「声明根前缀 → 本机挂载点」翻译(`peach.platform`),扫描侧按同一规则反着写(`peach.scan`)。
+- Windows:盘符本身就是挂载点,`[media.locations] local = <这些目录>`,`[media.mounts]` 留空。
+- macOS:声明根仍写账本口径的 `R:\\media`(第二个起是 `R:\\media2`、`R:\\media3`……),
+ `[media.mounts] local = <这些目录>` 按同样顺序给出,读取侧按「声明根前缀 → 本机挂载点」
+ 翻译(`peach.platform`),扫描侧按同一规则反着写(`peach.scan`)。
+
+几个目录都归同一个来源 `local`:它们是同一块馆藏的几个落点,不是几种来源。
"""
from __future__ import annotations
import os
import re
import socket
-from collections.abc import Callable
+from collections.abc import Callable, Iterator, Sequence
from dataclasses import dataclass, replace
from pathlib import Path
@@ -38,10 +41,12 @@ LAN_HOST = "0.0.0.0"
#: 每题最多问几次。三次都不是有效值就放弃,不能让人困在一个死循环里。
MAX_ATTEMPTS = 3
#: 非 Windows 平台上本地来源的账本口径声明根。账本一律 Windows 形态,这个值只是个前缀,
-#: 真正的目录由 `[media.mounts] local` 给出。
+#: 真正的目录由 `[media.mounts] local` 给出。第二个目录起在后面加序号:`R:\media2`。
POSIX_LOCAL_DECLARED_ROOT = r"R:\media"
-#: 本地来源的 ID。v1 只收一个目录,它就是 `asset.location = 'local'`。
+#: 本地来源的 ID。所有本地媒体目录都是 `asset.location = 'local'`。
LOCAL_LOCATION = "local"
+#: 命令行里追加目录的题面:空答案就是「不加了」。
+MORE_MEDIA_PROMPT = "再加一个媒体文件夹(不加就直接回车)"
#: 迁移随代码走,不随数据走。这里不 import `peach.config`:那个模块的常量在进程启动
#: 那一刻就定型了,而首次设置正是要改变它们指向的数据根。
MIGRATIONS_DIR = settings_file.PROJECT_ROOT / "migrations"
@@ -81,7 +86,8 @@ class Question:
@dataclass(frozen=True)
class Answers:
data_root: Path
- media_dir: Path
+ #: 至少一个,都是已经解析过的绝对路径;互不重复,也互不包含。
+ media_dirs: tuple[Path, ...]
host: str
port: int
mdns_name: str
@@ -114,6 +120,68 @@ def media_dir_validator(*, windows: bool) -> Callable[[str], Path]:
return validate
+def check_media_dirs(dirs: Sequence[Path]) -> dict[int, str]:
+ """几个媒体文件夹之间不能重复、不能一个套在另一个里面。
+
+ 返回「下标 → 原因」,两个前端各自决定错误写在哪一行。套着的目录会让同一个文件被
+ 登记两次,所以和重复一样拒绝,而不是悄悄合并。
+ """
+ problems: dict[int, str] = {}
+ for index, path in enumerate(dirs):
+ for other_index, other in enumerate(dirs):
+ if other_index == index or index in problems:
+ continue
+ if path == other:
+ if other_index < index:
+ problems[index] = f"和上面的 {other} 重复了"
+ elif path.is_relative_to(other):
+ problems[index] = f"已经在 {other} 里面,不用再加"
+ return problems
+
+
+def read_media_dirs(
+ raws: Sequence[str], *, validate: Callable[[str], Path], default: str = "",
+) -> tuple[list[Path], list[str]]:
+ """页面表单里的几行媒体文件夹:逐行校验,再查行与行之间的关系。
+
+ 第一行留空取默认值,后面的空行当没填。返回 `(合格的路径, 每行的错误)`;错误列表与
+ 提交的行一一对应,全对时为空列表,页面据此把原因写回出错的那一行底下。
+ """
+ rows = list(raws) or [""]
+ kept = [(index, raw) for index, raw in enumerate(rows) if index == 0 or raw.strip()]
+ paths: list[Path] = []
+ problems = [""] * len(rows)
+ failed = False
+ for index, raw in kept:
+ try:
+ paths.append(validate(raw if raw.strip() else default))
+ except ValueError as exc:
+ problems[index] = str(exc)
+ failed = True
+ if not failed:
+ for offset, why in check_media_dirs(paths).items():
+ problems[kept[offset][0]] = why
+ failed = True
+ return paths, (problems if failed else [])
+
+
+def more_media_dir_validator(
+ *, windows: bool, taken: Sequence[Path],
+) -> Callable[[str], Path | None]:
+ """追加目录:空答案表示不加了,否则和第一个目录同一套校验,再查与已有目录的关系。"""
+ single = media_dir_validator(windows=windows)
+
+ def validate(raw: str) -> Path | None:
+ if not raw.strip():
+ return None
+ path = single(raw)
+ problems = check_media_dirs((*taken, path))
+ if problems:
+ raise ValueError(problems[len(taken)])
+ return path
+ return validate
+
+
def validate_host(raw: str) -> str:
key = raw.strip().lower()
try:
@@ -184,11 +252,23 @@ def questions(
)
-def scan_question(media_dir: Path | str) -> Question:
- return Question("scan_now", SCAN_PROMPT.format(target=media_dir) + "(Y/n)",
+def scan_target_text(media_dirs: Sequence[Path | str]) -> str:
+ """首扫题里的对象:一个目录就写它的路径,几个就写数目。"""
+ if len(media_dirs) == 1:
+ return str(media_dirs[0])
+ return f"这 {len(media_dirs)} 个文件夹"
+
+
+def scan_question(media_dirs: Sequence[Path | str]) -> Question:
+ return Question("scan_now", SCAN_PROMPT.format(target=scan_target_text(media_dirs)) + "(Y/n)",
"Y", validate_yes_no)
+def more_media_dir_question(*, windows: bool, taken: Sequence[Path]) -> Question:
+ return Question("media_dir", MORE_MEDIA_PROMPT, "",
+ more_media_dir_validator(windows=windows, taken=taken))
+
+
def ask_until_valid(
question: Question, ask: Ask, *, report: Callable[[str], None] = print,
max_attempts: int = MAX_ATTEMPTS,
@@ -205,16 +285,38 @@ def ask_until_valid(
raise OnboardingAborted(f"「{question.prompt}」连续 {max_attempts} 次没有拿到有效值。")
+def collect(
+ config: PeachConfig, ask: Ask, *, windows: bool, home: Path | None = None,
+ report: Callable[[str], None] = print, max_attempts: int = MAX_ATTEMPTS,
+) -> Iterator[tuple[str, object]]:
+ """逐题产出 `(Answers 的字段名, 值)`。`ask` 由前端注入,测试用脚本化答案驱动。
+
+ 媒体文件夹问完第一个之后接着问「再加一个」,回车即结束,整组目录作为 `media_dirs`
+ 一次产出;页面上对应的是「添加文件夹」。做成生成器是为了让命令行在数据根那一题
+ 之后就能判「设置文件已存在」并退出,不必等剩下的题答完。
+ """
+ for question in questions(config, windows=windows, home=home):
+ value = ask_until_valid(question, ask, report=report, max_attempts=max_attempts)
+ if question.key != "media_dir":
+ yield question.key, value
+ continue
+ media_dirs: list[Path] = [value] # type: ignore[list-item]
+ while True:
+ more = ask_until_valid(more_media_dir_question(windows=windows, taken=media_dirs),
+ ask, report=report, max_attempts=max_attempts)
+ if more is None:
+ break
+ media_dirs.append(more) # type: ignore[arg-type]
+ yield "media_dirs", tuple(media_dirs)
+
+
def interview(
config: PeachConfig, ask: Ask, *, windows: bool, home: Path | None = None,
report: Callable[[str], None] = print, max_attempts: int = MAX_ATTEMPTS,
) -> Answers:
- """把全部题目走一遍。`ask` 由前端注入,测试用脚本化答案驱动。"""
- answers: dict[str, object] = {}
- for question in questions(config, windows=windows, home=home):
- answers[question.key] = ask_until_valid(
- question, ask, report=report, max_attempts=max_attempts)
- return Answers(**answers) # type: ignore[arg-type]
+ """把全部题目走一遍,落成 `Answers`。"""
+ return Answers(**dict(collect( # type: ignore[arg-type]
+ config, ask, windows=windows, home=home, report=report, max_attempts=max_attempts)))
# --------------------------------------------------------------------------- 落盘
@@ -222,15 +324,16 @@ def interview(
def configure(config: PeachConfig, answers: Answers, *, windows: bool) -> PeachConfig:
"""把答案落成一份可写回的设置。`config` 要按 `answers.data_root` 重新解析过。
- 只写用户声明过的来源:`[media.locations]` 里只有 `local`。复制保持关闭,writer 镜像
- 与 SMB 坐标留空,目录键全部落成显式值——和非交互 `peach init` 同一形状。
+ 只写用户声明过的来源:`[media.locations]` 里只有 `local`,几个目录就几个声明根。
+ 复制保持关闭,writer 镜像与 SMB 坐标留空,目录键全部落成显式值——和非交互
+ `peach init` 同一形状。
"""
if windows:
- locations = {LOCAL_LOCATION: str(answers.media_dir)}
- mounts: dict[str, str] = {}
+ locations = {LOCAL_LOCATION: tuple(str(path) for path in answers.media_dirs)}
+ mounts: dict[str, tuple[str, ...]] = {}
else:
- locations = {LOCAL_LOCATION: POSIX_LOCAL_DECLARED_ROOT}
- mounts = {LOCAL_LOCATION: str(answers.media_dir)}
+ locations = {LOCAL_LOCATION: posix_declared_roots(len(answers.media_dirs))}
+ mounts = {LOCAL_LOCATION: tuple(str(path) for path in answers.media_dirs)}
prepared = settings_file.capture_existing(
config, replication_enabled=False,
overrides={"host": answers.host, "port": answers.port,
@@ -357,15 +460,25 @@ def take_first_scan_request(config: PeachConfig) -> str | None:
return location or None
-def scan_root(config: PeachConfig) -> str:
- """首次扫描的账本口径根:就是 `local` 的声明根。本机目录由 `peach.scan` 按挂载表取。"""
- return config.locations[LOCAL_LOCATION]
+def posix_declared_roots(count: int) -> tuple[str, ...]:
+ """非 Windows 平台上 `count` 个本地目录的账本口径声明根:`R:\\media`、`R:\\media2`……"""
+ return tuple(POSIX_LOCAL_DECLARED_ROOT + ("" if index == 0 else str(index + 1))
+ for index in range(count))
+
+
+def scan_roots(config: PeachConfig) -> tuple[str, ...]:
+ """首次扫描的账本口径根:`local` 的全部声明根。本机目录由 `peach.scan` 按挂载表取。"""
+ return tuple(config.locations[LOCAL_LOCATION])
-def mounts_explanation(media_dir: Path | str) -> str:
+def mounts_explanation(media_dirs: Sequence[Path | str] | Path | str) -> str:
"""非 Windows 平台写出的两行为什么长那样,一句话说清。"""
- return (f"账本用统一的 Windows 形态记路径({POSIX_LOCAL_DECLARED_ROOT}\\...),"
- f"本机挂载点 [media.mounts] local = {media_dir} 负责翻译成真实文件。")
+ if isinstance(media_dirs, (Path, str)):
+ media_dirs = (media_dirs,)
+ shown = "、".join(str(path) for path in media_dirs) or "(还没填)"
+ roots = "、".join(posix_declared_roots(max(len(media_dirs), 1)))
+ return (f"账本用统一的 Windows 形态记路径({roots} 下的 ...),"
+ f"本机挂载点 [media.mounts] local = {shown} 按同样的顺序负责翻译成真实文件。")
def console_ask(prompt: str, default: str) -> str:
diff --git a/src/peach/platform.py b/src/peach/platform.py
index 4d9b01b64..6bf53291e 100644
--- a/src/peach/platform.py
+++ b/src/peach/platform.py
@@ -4,9 +4,10 @@
`A:\\...`(PikPak)、`B:\\...`(115)。这是不变量,不随平台改写。
真正会变的是「同一个来源在这台机器上落在哪」。`asset.location` 本来就是挂载点 ID
-(`local` / `115` / `pikpak`),设置文件用 `[media.locations]` 声明每个 ID 的账本口径根,
-用 `[media.mounts]` 声明它在本机的落点,翻译按「声明根前缀 → 本机挂载点」进行
-(ADR-0023 第 2 阶段勘误)。Windows 上盘符本身就是挂载点,路径原样返回。
+(`local` / `115` / `pikpak`),设置文件用 `[media.locations]` 声明每个 ID 的账本口径根
+(一个来源可以有几个根:两块硬盘都算 `local`),用 `[media.mounts]` 按同样的顺序声明每个
+根在本机的落点,翻译按「声明根前缀 → 本机挂载点」进行(ADR-0023 第 2 阶段勘误)。
+Windows 上盘符本身就是挂载点,路径原样返回。
没有挂载点的来源会被映射到 `UNMAPPED_ROOT` 下,一定通不过 `allowed_media_roots`
授权,于是该来源整体按「脱盘」处理,而不是意外落到当前工作目录下的同名相对路径。
@@ -15,7 +16,7 @@ from __future__ import annotations
import logging
import os
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from functools import lru_cache
from pathlib import Path, PureWindowsPath
@@ -43,32 +44,39 @@ def _parse_override(raw: str) -> tuple[tuple[str, str], ...]:
return tuple(pairs)
-def location_mounts() -> dict[str, Path]:
- """当前生效的「来源 ID → 本机挂载点」;空值表示显式声明「本机没有这个来源」。
+#: 一个来源的声明根或落点:按顺序一一对应的字符串元组。
+Roots = Mapping[str, Sequence[str]]
+
+
+def location_mounts() -> dict[str, tuple[Path, ...]]:
+ """当前生效的「来源 ID → 本机挂载点」,与该来源的声明根按顺序一一对应;
+ 没有条目表示「本机没有这个来源」。
基础映射来自设置文件的 `[media.mounts]`(内建默认为空:一台新机器什么都没挂,
对应资产按脱盘处理)。`MOUNTS_ENV` 每次现读而不是缓存进设置层——测试和临时诊断
- 会在运行期改它,缓存住就看不到变化。
+ 会在运行期改它,缓存住就看不到变化;覆盖值只给一个目录,对应该来源的第一个根。
"""
- merged = dict(settings_file.active().mounts)
- merged.update(dict(_parse_override(os.environ.get(MOUNTS_ENV, ""))))
- return {location: Path(mount) for location, mount in merged.items() if mount}
+ 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}
-def location_roots() -> dict[str, str]:
- """来源 ID → 账本口径的声明根,来自 `[media.locations]`。"""
+def location_roots() -> dict[str, tuple[str, ...]]:
+ """来源 ID → 账本口径的声明根(至少一个),来自 `[media.locations]`。"""
return dict(settings_file.active().locations)
-def declared_root(location: str) -> str | None:
- """某个来源在账本里的声明根;未声明的来源返回 None。"""
- return location_roots().get(location)
+def declared_roots_of(location: str) -> tuple[str, ...]:
+ """某个来源在账本里的全部声明根;未声明的来源是空元组。"""
+ return tuple(location_roots().get(location, ()))
-def resolve_location(
- raw: str | os.PathLike[str], roots: Mapping[str, str] | None = None,
-) -> tuple[str | None, tuple[str, ...]]:
- """账本路径属于哪个来源,以及它在声明根之后的层级。
+def resolve_root(
+ raw: str | os.PathLike[str], roots: Roots | None = None,
+) -> tuple[str | None, int, tuple[str, ...]]:
+ """账本路径属于哪个来源的第几个声明根,以及它在那个根之后的层级。
翻译和写入侧门槛共用这一段判定,所以它只碰 `PureWindowsPath` 和字符串,
在两个平台上行为一致、也都能测。声明根重叠时取最长的那个(`R:\\` 与
@@ -76,27 +84,37 @@ def resolve_location(
`PureWindowsPath` 负责:账本里写 `R:\\Media`、声明根写 `R:\\media` 是同一处。
`roots` 缺省取当前生效的 `[media.locations]`。`peach init` 刚写完设置文件时进程里
- 那份缓存还是旧的,这种调用方把要用的声明根显式传进来。
+ 那份缓存还是旧的,这种调用方把要用的声明根显式传进来。不属于任何来源时返回
+ `(None, -1, ())`。
"""
text = os.fspath(raw)
if not is_windows_path(text):
- return None, ()
+ return None, -1, ()
candidate = PureWindowsPath(text)
- best: tuple[int, str] | None = None
+ best: tuple[int, str, int] | None = None
declared_roots = location_roots() if roots is None else roots
- for location, root in declared_roots.items():
- declared = PureWindowsPath(root)
- if candidate == declared or candidate.is_relative_to(declared):
- depth = len(declared.parts)
- if best is None or depth > best[0]:
- best = (depth, location)
+ for location, location_roots_ in declared_roots.items():
+ for index, root in enumerate(location_roots_):
+ declared = PureWindowsPath(root)
+ if candidate == declared or candidate.is_relative_to(declared):
+ depth = len(declared.parts)
+ if best is None or depth > best[0]:
+ best = (depth, location, index)
if best is None:
- return None, ()
- return best[1], candidate.parts[best[0]:]
+ return None, -1, ()
+ return best[1], best[2], candidate.parts[best[0]:]
+
+
+def resolve_location(
+ raw: str | os.PathLike[str], roots: Roots | None = None,
+) -> tuple[str | None, tuple[str, ...]]:
+ """账本路径属于哪个来源,以及它在声明根之后的层级。判定见 `resolve_root`。"""
+ location, _index, tail = resolve_root(raw, roots)
+ return location, tail
def location_of(
- raw: str | os.PathLike[str], roots: Mapping[str, str] | None = None,
+ raw: str | os.PathLike[str], roots: Roots | None = None,
) -> str | None:
"""账本路径属于哪个来源;不在任何声明根下则返回 None。
@@ -160,11 +178,11 @@ def translate_ledger_path(raw: str | os.PathLike[str]) -> Path:
text = os.fspath(raw)
if os.name == "nt" or not is_windows_path(text):
return Path(text)
- location, tail = resolve_location(text)
+ location, index, tail = resolve_root(text)
if location is not None:
- mount = location_mounts().get(location)
- if mount is not None:
- return mount.joinpath(*tail)
+ mounts = location_mounts().get(location, ())
+ if index < len(mounts):
+ return mounts[index].joinpath(*tail)
# 没声明过的前缀(例如遗留的 `R:\\Resources\\...`)或没挂载的来源:落到不可达根,
# 保留盘符和其余层级,方便日志里认出是哪条路径。
parts = PureWindowsPath(text).parts
diff --git a/src/peach/routes_api.py b/src/peach/routes_api.py
index 326007974..40f4df373 100644
--- a/src/peach/routes_api.py
+++ b/src/peach/routes_api.py
@@ -44,15 +44,23 @@ def _source_status() -> list[dict[str, Any]]:
脱盘是来源级的:本地硬盘拔掉时 115/PikPak 照常可播,反过来也一样。
"""
rows: list[dict[str, Any]] = []
- for location, declared in LOCATION_ROOT_DECLARATIONS.items():
- resolved = translate_ledger_path(declared)
- mapped = not is_unmapped(resolved)
+ for location, declared_roots in LOCATION_ROOT_DECLARATIONS.items():
+ roots: list[dict[str, Any]] = []
+ for declared in declared_roots:
+ resolved = translate_ledger_path(declared)
+ mapped = not is_unmapped(resolved)
+ roots.append({
+ "declared": declared,
+ "resolved": str(resolved) if mapped else None,
+ "mapped": mapped,
+ "online": bool(mapped and root_online(resolved)),
+ })
+ # 一个来源可以有几个根;只要有一个不在,整个来源就按脱盘处理,宁可少播不可误判。
rows.append({
"location": location,
- "declared": declared,
- "resolved": str(resolved) if mapped else None,
- "mapped": mapped,
- "online": bool(mapped and root_online(resolved)),
+ "roots": roots,
+ "mapped": all(root["mapped"] for root in roots),
+ "online": all(root["online"] for root in roots),
})
# 在线资源是 URL,不依赖任何挂载点。
rows.append({
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index 5145eff76..947ec2753 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -14,7 +14,7 @@ from fastapi.responses import HTMLResponse
from . import distribution, onboarding, settings_file
from .routes_auth import require_page_auth
-from .routes_pages import _check_html, _document, _field_html, runtime_facts_html
+from .routes_pages import _check_html, _document, _field_html, _media_dirs_html, runtime_facts_html
router = APIRouter()
_SAVE_LOCK = threading.Lock()
@@ -27,7 +27,7 @@ def revision(config) -> str:
def page(config, *, values=None, errors=None, saved=False) -> str:
values, errors = values or {}, errors or {}
- media = config.mounts.get("local") or config.locations.get("local", "")
+ media = list(config.mounts.get("local") or config.locations.get("local", ()))
body = '<a href="/">返回馆藏</a><h1>配置 Peach</h1>'
if saved:
url = f"http://127.0.0.1:{config.server.port}/"
@@ -40,11 +40,12 @@ def page(config, *, values=None, errors=None, saved=False) -> str:
body += '<form method="post" action="/configuration">'
body += f'<input type="hidden" name="revision" value="{revision(config)}">'
for question in onboarding.questions(config, windows=os.name == "nt"):
- if question.key not in {"media_dir", "port"}:
- continue
- default = media if question.key == "media_dir" else str(config.server.port)
- body += _field_html(question, values.get(question.key, default),
- errors.get(question.key, ""), "")
+ if question.key == "media_dir":
+ body += _media_dirs_html(values.get("media_dir", media),
+ errors.get("media_dir", []), "")
+ elif question.key == "port":
+ body += _field_html(question, values.get("port", str(config.server.port)),
+ errors.get("port", ""), "")
body += (_check_html("scan_now", "保存后扫描媒体文件夹", checked=False)
+ '<button type="submit">保存配置</button></form>')
elif not distribution.standalone():
@@ -78,19 +79,22 @@ async def save_configuration(request: Request, _args=Depends(require_page_auth))
if origin and origin.rstrip("/") != str(request.base_url).rstrip("/"):
raise HTTPException(403, "请从 Peach 配置页提交")
form = parse_qs((await request.body()).decode("utf-8", "replace"), keep_blank_values=True)
- values = {key: value[0] for key, value in form.items()}
+ values: dict[str, object] = {key: value[0] for key, value in form.items()}
+ values["media_dir"] = list(form.get("media_dir", []))
with _SAVE_LOCK:
config = settings_file.load_config()
if values.get("revision") != revision(config):
raise HTTPException(409, "配置已变更,请刷新后再保存")
- errors, validated = {}, {}
- validators = {"media_dir": onboarding.media_dir_validator(windows=os.name == "nt"),
- "port": onboarding.validate_port}
- for key, validator in validators.items():
- try:
- validated[key] = validator(values.get(key, ""))
- except ValueError as exc:
- errors[key] = str(exc)
+ errors: dict[str, object] = {}
+ validated: dict[str, object] = {}
+ paths, problems = onboarding.read_media_dirs(
+ values["media_dir"], validate=onboarding.media_dir_validator(windows=os.name == "nt"))
+ if problems:
+ errors["media_dir"] = problems
+ try:
+ validated["port"] = onboarding.validate_port(str(values.get("port", "")))
+ except ValueError as exc:
+ errors["port"] = str(exc)
if errors:
return HTMLResponse(page(config, values=values, errors=errors), status_code=400)
try:
@@ -99,10 +103,10 @@ async def save_configuration(request: Request, _args=Depends(require_page_auth))
return HTMLResponse(page(config, values=values, errors={"port": str(exc)}), status_code=400)
locations, mounts = dict(config.locations), dict(config.mounts)
if os.name == "nt":
- locations["local"] = str(validated["media_dir"])
+ locations["local"] = tuple(str(path) for path in paths)
else:
- locations["local"] = onboarding.POSIX_LOCAL_DECLARED_ROOT
- mounts["local"] = str(validated["media_dir"])
+ locations["local"] = onboarding.posix_declared_roots(len(paths))
+ mounts["local"] = tuple(str(path) for path in paths)
prepared = replace(config, locations=locations, mounts=mounts,
server=replace(config.server, port=validated["port"]))
temporary = config.path.with_suffix(".pending.toml")
diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.py
index b72860f4b..f0b50856d 100644
--- a/src/peach/routes_pages.py
+++ b/src/peach/routes_pages.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import hashlib
import os
+from collections.abc import Mapping, Sequence
import re
from html import escape
@@ -98,10 +99,20 @@ display:grid;place-items:center;background:var(--ground);color:transparent}
.check:hover .pcheck>span{background:var(--hover)}
.pcheck input:checked+span{border-color:var(--ink-2);color:var(--ink)}
.pcheck input:focus-visible+span{outline:2px solid var(--tungsten);outline-offset:2px}
-button{margin-top:32px;width:100%;height:var(--control-h);border:1px solid var(--ink);
+button[type=submit]{margin-top:32px;width:100%;height:var(--control-h);border:1px solid var(--ink);
border-radius:var(--control-radius);cursor:pointer;background:var(--ink);color:var(--ground);
font:500 var(--fs-md) system-ui,sans-serif}
-button:hover{background:color-mix(in srgb,var(--ink) 88%,var(--ground));color:var(--ground)}
+button[type=submit]:hover{background:color-mix(in srgb,var(--ink) 88%,var(--ground));color:var(--ground)}
+.dir{display:grid;grid-template-columns:1fr auto;gap:8px;margin-top:8px}
+.dir:first-child{margin-top:0}.dir .bad{grid-column:1/-1;margin:0}
+.dir input[type=text]{min-width:0}
+.rm,.add{height:var(--control-h);border:1px solid var(--line);border-radius:var(--control-radius);
+background:var(--ground);color:var(--ink);cursor:pointer;font:500 var(--fs-sm) system-ui,sans-serif}
+.rm{width:var(--control-h);display:grid;place-items:center;color:var(--muted)}
+.rm svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round}
+.add{margin-top:8px;padding:0 12px}
+.rm:hover,.add:hover{background:var(--hover);color:var(--ink)}
+.rm[hidden],.add[hidden]{display:none}
@media(max-width:760px){input[type=text],input[type=number]{font-size:16px}}
@media(max-width:440px){body{padding:24px 20px}h1{font-size:var(--fs-2xl)}}
</style>"""
@@ -115,7 +126,7 @@ _SETUP_HEAD = ('<!doctype html>\n<html lang="zh-CN"><head><meta charset="utf-8">
#: 这里只决定同一道题在浏览器里怎么称呼:命令行那份题面要把可选值写进去,页面用控件表达。
_SETUP_COPY = {
"data_root": ("数据目录", "Peach 数据库、缓存和设置文件都放在这里。"),
- "media_dir": ("媒体文件夹", "Peach 从这个文件夹读取视频和图片,可以是外置硬盘上的文件夹,但必须已经存在。"),
+ "media_dir": ("媒体文件夹", "Peach 从这些文件夹读取视频和图片。可以是外置硬盘上的文件夹,但必须已经存在。"),
"host": ("谁可以访问", ""),
"port": ("端口", "浏览器地址里冒号后面的数字,一般不用改。"),
"mdns_name": ("局域网访问地址", "选了「同一局域网的设备」之后,其他设备在浏览器里输入这个地址就能打开 Peach。"),
@@ -128,31 +139,60 @@ _HOST_ORDER = ("2", "1")
#: 选「只有这台电脑」时局域网地址没有意义,输入框跟着禁用;禁用的字段不随表单提交,
#: 服务端按题目默认值补上。没有脚本时两个字段都可编辑,提交照样成立。
+#: 媒体文件夹列表的「添加文件夹」与每行的移除键也在这里亮出来:只剩一行时移除键隐藏。
_SETUP_SCRIPT = """<script>
(function(){
var radios=document.querySelectorAll('input[name="host"]');
var field=document.getElementById('f-mdns_name');
- if(!radios.length||!field){return;}
- function sync(){
- var lan=false;
- radios.forEach(function(radio){if(radio.checked&&radio.value==="2"){lan=true;}});
- field.disabled=!lan;
+ if(radios.length&&field){
+ var sync=function(){
+ var lan=false;
+ radios.forEach(function(radio){if(radio.checked&&radio.value==="2"){lan=true;}});
+ field.disabled=!lan;
+ };
+ radios.forEach(function(radio){radio.addEventListener('change',sync);});
+ sync();
}
- radios.forEach(function(radio){radio.addEventListener('change',sync);});
- sync();
+ var list=document.getElementById('dirs');
+ var add=document.getElementById('add-dir');
+ var template=document.getElementById('dir-row');
+ if(!list||!add||!template){return;}
+ var rows=function(){return list.querySelectorAll('.dir');};
+ var refresh=function(){
+ var all=rows();
+ all.forEach(function(row){row.querySelector('.rm').hidden=all.length<2;});
+ };
+ list.addEventListener('click',function(event){
+ var remove=event.target.closest('.rm');
+ if(!remove||rows().length<2){return;}
+ remove.closest('.dir').remove();
+ refresh();
+ add.focus();
+ });
+ add.addEventListener('click',function(){
+ var row=template.content.firstElementChild.cloneNode(true);
+ list.appendChild(row);
+ refresh();
+ row.querySelector('input').focus();
+ });
+ add.hidden=false;
+ refresh();
})();
</script>"""
#: 与站内共用勾选框相同的字形(lucide `check`)。这一页不加载站内脚本,所以内联一份。
_CHECK_SVG = ('<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">'
'<path d="M20 6 9 17l-5-5"/></svg>')
+#: 移除一行媒体文件夹的字形(lucide `x`)。
+_X_SVG = '<svg viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg>'
def _document(title: str, body: str) -> str:
base = (PROJECT_ROOT / "web" / "css" / "01-base.css").read_text(encoding="utf-8")
tokens = re.search(r":root\s*\{[^}]+\}", base).group(0)
+ # 页内脚本对两张页面都生效:找不到对应控件时它什么也不做。
return (f"{_SETUP_HEAD}<title>{title}</title><style>{tokens}</style>{_SETUP_STYLE}"
- f"</head><body><main>{body}</main></body></html>\n")
+ f"</head><body><main>{body}</main>{_SETUP_SCRIPT}</body></html>\n")
def _check_html(name: str, text_html: str, *, checked: bool) -> str:
@@ -187,6 +227,47 @@ def _copy_for(key: str, fallback: str) -> tuple[str, str]:
return _SETUP_COPY.get(key, (fallback, ""))
+def _media_dir_row(value: str, error: str, *, first: bool) -> str:
+ attrs = ' id="f-media_dir" required' if first else ' aria-label="媒体文件夹"'
+ return (f'<div class="dir"><input name="media_dir" type="text"{attrs} autocomplete="off" '
+ f'spellcheck="false" aria-invalid="{"true" if error else "false"}" '
+ f'value="{escape(value, quote=True)}">'
+ f'<button type="button" class="rm" aria-label="移除这个文件夹" hidden>{_X_SVG}</button>'
+ + (f'<p class="bad" role="alert">{escape(error)}</p>' if error else "")
+ + "</div>")
+
+
+def _media_dirs_html(values: Sequence[str], errors: Sequence[str], note: str) -> str:
+ """媒体文件夹列表:每行一个输入框,行尾是移除键,列表下是「添加文件夹」。
+
+ 移除键和添加键都带 `hidden`,由页面脚本亮出来:没有脚本时它们什么都做不了,与其留
+ 两个按不动的键,不如只给一个输入框。第一行必填,后面的行留空就当没填;错误写在
+ 出错的那一行底下。首次运行页与配置页共用这一段。
+ """
+ title, help_text = _copy_for("media_dir", "媒体文件夹")
+ rows = list(values) or [""]
+ body = "".join(
+ _media_dir_row(value, errors[index] if index < len(errors) else "", first=index == 0)
+ for index, value in enumerate(rows))
+ return (
+ '<div class="field">'
+ f'<label for="f-media_dir"><span class="req" aria-hidden="true">*</span>{escape(title)}</label>'
+ f'<div class="dirs" id="dirs">{body}</div>'
+ '<button type="button" class="add" id="add-dir" hidden>添加文件夹</button>'
+ f'<template id="dir-row">{_media_dir_row("", "", first=False)}</template>'
+ + "".join(f'<p class="help">{escape(line)}</p>' for line in (help_text, note) if line)
+ + "</div>"
+ )
+
+
+def _media_dir_values(values: Mapping[str, object], default: str) -> list[str]:
+ """表单回显里的媒体文件夹:提交的是几行就几行,没提交过就一行默认值。"""
+ raw = values.get("media_dir")
+ if isinstance(raw, (list, tuple)):
+ return [str(item) for item in raw] or [default]
+ return [str(raw) if raw else default]
+
+
def _field_html(question, value: str, error: str, note: str) -> str:
key = escape(question.key, quote=True)
title, help_text = _copy_for(question.key, question.prompt)
@@ -216,8 +297,8 @@ def _field_html(question, value: str, error: str, note: str) -> str:
def setup_page(
- config, *, windows: bool, values: dict[str, str] | None = None,
- errors: dict[str, str] | None = None, scan_now: bool = True,
+ config, *, windows: bool, values: Mapping[str, object] | None = None,
+ errors: Mapping[str, object] | None = None, scan_now: bool = True,
) -> str:
"""首次运行表单。题目顺序、默认值与校验全部来自 `onboarding.questions()`。
@@ -230,27 +311,33 @@ def setup_page(
fields = []
if errors.get("data_root"):
fields.append(f'<p class="bad" role="alert">{escape(errors["data_root"])}</p>')
+ media_dirs: list[str] = []
for question in asked:
- value = values.get(question.key, question.default)
if distribution.standalone() and question.key in {"data_root", "host", "mdns_name"}:
value = {"data_root": str(config.data_root), "host": "1",
"mdns_name": config.server.mdns_name}[question.key]
fields.append(f'<input type="hidden" name="{question.key}" value="{escape(value, quote=True)}">')
continue
- note = ""
- if question.key == "media_dir" and not windows:
- note = onboarding.mounts_explanation(value or "你在上面填的目录")
- field = _field_html(question, value, errors.get(question.key, ""), note)
+ if question.key == "media_dir":
+ media_dirs = _media_dir_values(values, question.default)
+ row_errors = errors.get("media_dir", [])
+ note = "" if windows else onboarding.mounts_explanation(
+ [path for path in media_dirs if path] or ["你在上面填的目录"])
+ fields.append(_media_dirs_html(media_dirs, list(row_errors), note))
+ continue
+ value = str(values.get(question.key, question.default))
+ field = _field_html(question, value, str(errors.get(question.key, "")), "")
if distribution.standalone() and question.key == "port":
opened = " open" if errors.get("port") else ""
field = f'<details{opened}><summary>高级设置</summary>{field}</details>'
fields.append(field)
- media_value = values.get("media_dir") or next(
- (q.default for q in asked if q.key == "media_dir"), "")
- if distribution.standalone() or not media_value:
+ filled = [path for path in media_dirs if path]
+ if distribution.standalone() or not filled:
scan_text = "完成设置后扫描媒体文件夹"
+ elif len(filled) == 1:
+ scan_text = f"完成设置后扫描 <code>{escape(filled[0])}</code>"
else:
- scan_text = f"完成设置后扫描 <code>{escape(media_value)}</code>"
+ scan_text = f"完成设置后扫描这 {len(filled)} 个文件夹"
body = (
'<header><img class="mark" src="/peach-logo.png" alt="" width="40" height="40">'
"<h1>欢迎使用 Peach</h1>"
@@ -260,7 +347,6 @@ def setup_page(
+ _check_html("scan_now", scan_text, checked=scan_now)
+ '<p class="help">扫描只读取文件名、大小和修改时间,不改动任何媒体文件。</p>'
'<button type="submit">完成设置</button></form>'
- + _SETUP_SCRIPT
)
return _document("Peach · 首次运行", body)
@@ -286,7 +372,7 @@ def setup_done_page(applied, *, windows: bool, scan_requested: bool) -> str:
if scan_requested else
"<li>没有请求首次扫描;要扫就跑 <code>peach scan local</code>。</li>")
mounts = ("" if windows else
- f"<p>{escape(onboarding.mounts_explanation(config.mounts.get('local', '')))}</p>")
+ f"<p>{escape(onboarding.mounts_explanation(config.mounts.get('local', ())))}</p>")
body = (
"<h1>设置完成</h1>"
"<p>托盘正在停掉这条引导服务,改用正常的 Peach 服务;这个页面几秒后就会连不上,"
@@ -417,7 +503,9 @@ async def setup_submit(request: Request):
windows = os.name == "nt"
form = parse_qs((await request.body()).decode("utf-8", "replace"), keep_blank_values=True)
- submitted = {key: (value or [""])[0] for key, value in form.items()}
+ submitted: dict[str, object] = {key: (value or [""])[0] for key, value in form.items()}
+ # 媒体文件夹是一个列表:几行输入框同名提交,回显时也要原样给回几行。
+ submitted["media_dir"] = list(form.get("media_dir", []))
scan_now = "scan_now" in form
config = settings_file.active()
@@ -457,13 +545,25 @@ async def setup_submit(request: Request):
def _read_answers(
- config, submitted: dict[str, str], *, windows: bool,
-) -> tuple[object, dict[str, str]]:
- """逐字段校验,错误按字段收集。校验器和 CLI 问答用的是同一批。"""
+ config, submitted: Mapping[str, object], *, windows: bool,
+) -> tuple[object, dict[str, object]]:
+ """逐字段校验,错误按字段收集。校验器和 CLI 问答用的是同一批。
+
+ 媒体文件夹那一项是多行:错误是与行对应的列表,其余字段的错误是一句话。
+ """
values: dict[str, object] = {}
- errors: dict[str, str] = {}
+ errors: dict[str, object] = {}
for question in onboarding.questions(config, windows=windows):
- raw = submitted.get(question.key, "")
+ if question.key == "media_dir":
+ paths, problems = onboarding.read_media_dirs(
+ _media_dir_values(submitted, ""), validate=question.validate,
+ default=question.default)
+ if problems:
+ errors["media_dir"] = problems
+ else:
+ values["media_dirs"] = tuple(paths)
+ continue
+ raw = str(submitted.get(question.key, "") or "")
try:
values[question.key] = question.validate(raw if raw.strip() else question.default)
except ValueError as exc:
diff --git a/src/peach/scan.py b/src/peach/scan.py
index 2b011cf54..2825d0b00 100644
--- a/src/peach/scan.py
+++ b/src/peach/scan.py
@@ -20,11 +20,11 @@ from __future__ import annotations
import os
import sqlite3
import time
-from collections.abc import Callable, Mapping
+from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path, PureWindowsPath
-from .platform import is_windows_path, resolve_location
+from .platform import is_windows_path, resolve_location, resolve_root
VIDEO = {".mp4", ".m4v", ".mkv", ".avi", ".wmv", ".mov", ".ts", ".flv", ".rmvb", ".mpg",
".m2ts"}
@@ -59,9 +59,9 @@ def medium_of(name: str) -> str:
def check_scan_target(
- location: str, root: str, *, declared_roots: Mapping[str, str],
+ location: str, root: str, *, declared_roots: Mapping[str, Sequence[str]],
) -> None:
- """扫描根必须落在这个来源的声明根内,否则拒绝(ADR-0023 第 2 阶段的写入侧门槛)。"""
+ """扫描根必须落在这个来源的某个声明根内,否则拒绝(ADR-0023 第 2 阶段的写入侧门槛)。"""
declared = declared_roots.get(location)
if declared is None:
known = "、".join(sorted(declared_roots)) or "(设置文件里一个都没有)"
@@ -69,7 +69,7 @@ def check_scan_target(
actual = resolve_location(root, declared_roots)[0]
if actual != location:
raise ScanTargetError(
- f"✗ 扫描根与来源对不上:{location} 的声明根是 {declared},"
+ f"✗ 扫描根与来源对不上:{location} 的声明根是 {'、'.join(declared)},"
f"但要扫的是 {root}"
+ (f"(那是 {actual} 的地盘)" if actual else "(不在任何声明根下)")
)
@@ -77,50 +77,52 @@ def check_scan_target(
def ledger_root_for(
location: str, root: str | os.PathLike[str], *,
- declared_roots: Mapping[str, str], mounts: Mapping[str, str | Path],
- windows: bool | None = None,
+ declared_roots: Mapping[str, Sequence[str]],
+ mounts: Mapping[str, Sequence[str | Path]], windows: bool | None = None,
) -> str:
"""把用户给的目录换成账本口径的扫描根。
Windows 上任何绝对路径本来就是账本形态,相对路径先按当前目录补全。其他平台上
- 给的是本机目录(挂载点下的某一层),换成 `声明根\\相对路径`;没有挂载点或不在
- 挂载点下都拒绝——那种目录扫出来的行谁也翻译不回去。
+ 给的是本机目录(某个挂载点下的某一层),换成对应那个 `声明根\\相对路径`;没有
+ 挂载点或不在任何挂载点下都拒绝——那种目录扫出来的行谁也翻译不回去。
"""
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)
- mount = mounts.get(location)
- if mount and declared is not None:
+ declared = declared_roots.get(location, ())
+ location_mounts = tuple(mounts.get(location, ()))
+ for declared_root, mount in zip(declared, location_mounts):
try:
tail = Path(text).resolve().relative_to(Path(mount).resolve()).parts
except ValueError:
- pass
- else:
- return str(PureWindowsPath(declared, *tail))
+ continue
+ return str(PureWindowsPath(declared_root, *tail))
if is_windows_path(text):
return text
- if not mount:
+ if not location_mounts:
raise ScanTargetError(
f"✗ 来源 {location!r} 在本机没有挂载点,无法把 {text} 换成账本路径;"
f"先在 [media.mounts] 里声明它的落点")
- raise ScanTargetError(f"✗ {text} 不在来源 {location!r} 的挂载点 {mount} 之下")
+ shown = "、".join(os.fspath(mount) for mount in location_mounts)
+ raise ScanTargetError(f"✗ {text} 不在来源 {location!r} 的挂载点 {shown} 之下")
def walk_root_for(
- location: str, root: str, *, declared_roots: Mapping[str, str],
- mounts: Mapping[str, str | Path], windows: bool | None = None,
+ location: str, root: str, *, declared_roots: Mapping[str, Sequence[str]],
+ mounts: Mapping[str, Sequence[str | Path]], windows: bool | None = None,
) -> Path:
"""账本口径的扫描根在本机要遍历哪个目录。调用前先过 `check_scan_target`。"""
windows = os.name == "nt" if windows is None else windows
if windows:
return Path(root)
- mount = mounts.get(location)
- if not mount:
+ _location, index, tail = resolve_root(root, declared_roots)
+ location_mounts = tuple(mounts.get(location, ()))
+ if index >= len(location_mounts):
raise ScanTargetError(
- f"✗ 来源 {location!r} 在本机没有挂载点;先在 [media.mounts] 里声明它的落点")
- return Path(mount).joinpath(*resolve_location(root, declared_roots)[1])
+ f"✗ 来源 {location!r} 的第 {index + 1} 个声明根在本机没有挂载点;"
+ f"先在 [media.mounts] 里按顺序声明它的落点")
+ return Path(location_mounts[index]).joinpath(*tail)
@dataclass(frozen=True)
diff --git a/src/peach/settings_file.py b/src/peach/settings_file.py
index 403f9286b..9a06c5821 100644
--- a/src/peach/settings_file.py
+++ b/src/peach/settings_file.py
@@ -44,11 +44,12 @@ DIRECTORY_KEYS = (
#: `asset.location` -> 账本口径的声明根。键是 ledger 里的 `asset.location` 值,它本来
#: 就是挂载点 ID;值仍是 Windows 盘符形态,因为账本路径的形状是不变量(AGENTS.md)。
+#: 一个来源可以有多个声明根(两块硬盘都算 `local`),文件里写一个字符串或一个数组。
#: 本机落点由 `[media.mounts]` 按同一批 ID 给出,翻译在 `peach.platform`(ADR-0023 勘误)。
-DEFAULT_LOCATION_ROOTS: dict[str, str] = {
- "local": r"R:\media",
- "115": "B:/",
- "pikpak": "A:/",
+DEFAULT_LOCATION_ROOTS: dict[str, tuple[str, ...]] = {
+ "local": (r"R:\media",),
+ "115": ("B:/",),
+ "pikpak": ("A:/",),
}
#: `[media]` 下只有这两个子表,没有任何标量键。第一阶段的 `[media] R = '...'` 是盘符键,
@@ -165,10 +166,11 @@ class PeachConfig:
#: 数据根是被找到的,还是只是一个建议落点。
data_root_found: bool = False
directories: dict[str, str] = field(default_factory=dict)
- #: `asset.location` -> 本机挂载点,即该来源的声明根落在本机哪个目录。
- #: Windows 上通常为空:盘符本身就是挂载点,路径不需要翻译。
- mounts: dict[str, str] = field(default_factory=dict)
- locations: dict[str, str] = field(
+ #: `asset.location` -> 本机挂载点,即该来源的每个声明根落在本机哪个目录,按顺序
+ #: 与 `locations` 里的声明根一一对应。Windows 上通常为空:盘符本身就是挂载点。
+ mounts: dict[str, tuple[str, ...]] = field(default_factory=dict)
+ #: `asset.location` -> 账本口径的声明根,至少一个。
+ locations: dict[str, tuple[str, ...]] = field(
default_factory=lambda: dict(DEFAULT_LOCATION_ROOTS))
server: ServerSettings = ServerSettings()
replication: ReplicationSettings = ReplicationSettings()
@@ -260,6 +262,27 @@ 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, ...]]:
+ """`[media.locations]` / `[media.mounts]` 的值:一个字符串,或一个字符串数组。
+
+ 单个来源常常只有一个目录,写成字符串最好读;第二块硬盘加进来时改成数组即可。
+ 两张表的解析口径一致,数组里不能有空串、不能重复——那两种写法都说不清用户想要什么。
+ """
+ result: dict[str, tuple[str, ...]] = {}
+ for key, value in table.items():
+ if isinstance(value, str):
+ result[key] = (value,) if value else ()
+ 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):
+ raise _fail(path, f"`{prefix}{key}` 的数组里不能有空串")
+ if len(set(value)) != len(value):
+ raise _fail(path, f"`{prefix}{key}` 的数组里有重复的路径")
+ result[key] = tuple(value)
+ return result
+
+
def _merge(
data_root: Path, path: Path, present: bool, found: bool,
document: dict, environ: dict[str, str],
@@ -286,10 +309,13 @@ def _merge(
# 来源,内建默认那三个示例盘符不能从旁边混进来,否则陌生人的机器上会多出两个
# 永远脱盘的来源。没写这张表才退回内建默认。
if _LOCATIONS_KEY in media:
- locations = _string_map(_table(media, _LOCATIONS_KEY, path), path, "media.locations.")
+ locations = _root_map(_table(media, _LOCATIONS_KEY, path), path, "media.locations.")
+ empty = sorted(key for key, roots in locations.items() if not roots)
+ if empty:
+ raise _fail(path, "`[media.locations]` 里这些来源没有声明根:" + "、".join(empty))
else:
locations = dict(DEFAULT_LOCATION_ROOTS)
- mounts = _string_map(_table(media, _MOUNTS_KEY, path), path, "media.mounts.")
+ mounts = _root_map(_table(media, _MOUNTS_KEY, path), path, "media.mounts.")
unknown_mounts = sorted(set(mounts) - set(locations))
if unknown_mounts:
# 打错一个 ID 却静默忽略,同样是安静地脱盘。
@@ -297,6 +323,14 @@ def _merge(
"`[media.mounts]` 里有没在 `[media.locations]` 声明过的来源:"
+ "、".join(unknown_mounts)
))
+ for key, points in mounts.items():
+ # 落点按顺序对应声明根:数目不齐时无法判断哪个目录漏了,与其猜不如拒绝。
+ if points and len(points) != len(locations[key]):
+ raise _fail(path, (
+ f"`[media.mounts] {key}` 给了 {len(points)} 个落点,"
+ f"但 `[media.locations] {key}` 声明了 {len(locations[key])} 个根;"
+ "两边按顺序一一对应,要么数目相同,要么整项留空"
+ ))
server_table = _table(document, "server", path)
fallback = ServerSettings()
@@ -443,6 +477,20 @@ def _render_value(value: object) -> str:
return f'"{escaped}"'
+def _render_roots(pairs: dict[str, tuple[str, ...]]) -> list[str]:
+ """声明根与落点:只有一个就写成字符串,多个才写数组,文件保持最好读的形状。"""
+ rendered: dict[str, object] = {}
+ for key, roots in pairs.items():
+ if len(roots) == 1:
+ rendered[key] = roots[0]
+ elif not roots:
+ rendered[key] = ""
+ else:
+ rendered[key] = "[" + ", ".join(_render_value(root) for root in roots) + "]"
+ return [f"{_render_key(key)} = {value if isinstance(value, str) and value.startswith('[') else _render_value(value)}"
+ for key, value in rendered.items()]
+
+
def _render_key(key: str) -> str:
allowed = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")
return key if key and set(key) <= allowed else _render_value(key)
@@ -468,17 +516,19 @@ def render(config: PeachConfig) -> str:
"",
"[media.locations]",
"# asset.location -> 账本口径的声明根。改这里等于改账本口径,通常不要动。",
+ "# 一个来源有几个目录就写几个:local = ['D:\\Videos', 'E:\\Movies']。",
]
- lines += _render_pairs(dict(config.locations))
+ lines += _render_roots(dict(config.locations))
lines += [
"",
"[media.mounts]",
"# asset.location -> 本机挂载点:上面那个声明根落在本机的哪个目录。",
"# 例如 local = '/mnt/media' 时,R:\\media\\a.mp4 读作 /mnt/media/a.mp4。",
+ "# 声明了多个根就按同样的顺序给同样多个落点。",
"# 不写或留空表示本机没有这个来源,对应资产按「脱盘」处理,不报错。",
"# Windows 上整表为空:盘符本身就是挂载点,路径不需要翻译。",
]
- lines += _render_pairs(dict(config.mounts))
+ lines += _render_roots(dict(config.mounts))
lines += [
"",
"[server]",
@@ -521,7 +571,8 @@ def write(config: PeachConfig, *, force: bool = False) -> Path:
def capture_existing(
config: PeachConfig, *, replication_enabled: bool = True,
- overrides: dict[str, object] | None = None, mounts: dict[str, str] | None = None,
+ overrides: dict[str, object] | None = None,
+ mounts: dict[str, tuple[str, ...]] | None = None,
) -> PeachConfig:
"""把当前生效的配置整理成一份可写回的设置。
diff --git a/src/peach/web_batch.py b/src/peach/web_batch.py
index 2c6784832..d7df98802 100644
--- a/src/peach/web_batch.py
+++ b/src/peach/web_batch.py
@@ -315,14 +315,18 @@ def _restore_staged_media(staged):
os.replace(quarantine, original)
-def _online_source_roots() -> dict[str, Path]:
- """Return only declared physical roots that can be enumerated now."""
- roots: dict[str, Path] = {}
- for location, declaration in LOCATION_ROOT_DECLARATIONS.items():
- root = translate_ledger_path(declaration)
- if is_unmapped(root) or not root.is_dir() or not root_online(root):
- continue
- roots[location] = root
+def _online_source_roots() -> dict[str, tuple[Path, ...]]:
+ """Return only declared physical roots that can be enumerated now, per source."""
+ roots: dict[str, tuple[Path, ...]] = {}
+ for location, declarations in LOCATION_ROOT_DECLARATIONS.items():
+ online = []
+ for declaration in declarations:
+ root = translate_ledger_path(declaration)
+ if is_unmapped(root) or not root.is_dir() or not root_online(root):
+ continue
+ online.append(root)
+ if online:
+ roots[location] = tuple(online)
return roots
@@ -364,10 +368,10 @@ def cleanup_empty_source_directories() -> dict[str, object]:
"""
results: list[dict[str, object]] = []
total_scanned = total_removed = total_errors = 0
- for location, declaration in LOCATION_ROOT_DECLARATIONS.items():
- root = translate_ledger_path(declaration)
- mapped = not is_unmapped(root)
- online = bool(mapped and root.is_dir() and root_online(root))
+ for location, declarations in LOCATION_ROOT_DECLARATIONS.items():
+ roots = [translate_ledger_path(declaration) for declaration in declarations]
+ mapped = all(not is_unmapped(root) for root in roots)
+ online = mapped and all(root.is_dir() and root_online(root) for root in roots)
row: dict[str, object] = {
"location": location,
"mapped": mapped,
@@ -381,22 +385,23 @@ def cleanup_empty_source_directories() -> dict[str, object]:
continue
walk_errors: list[OSError] = []
- for directory, _subdirectories, _files in os.walk(
- root, topdown=False, onerror=walk_errors.append, followlinks=False):
- candidate = Path(directory)
- if candidate == root or candidate.is_symlink():
- continue
- row["scanned"] = int(row["scanned"]) + 1
- try:
- candidate.rmdir()
- except FileNotFoundError:
- # CloudDrive can remove the same empty directory concurrently.
- continue
- except OSError as error:
- if error.errno not in {errno.ENOTEMPTY, errno.EEXIST}:
- row["errors"] = int(row["errors"]) + 1
- else:
- row["removed"] = int(row["removed"]) + 1
+ for root in roots:
+ for directory, _subdirectories, _files in os.walk(
+ root, topdown=False, onerror=walk_errors.append, followlinks=False):
+ candidate = Path(directory)
+ if candidate == root or candidate.is_symlink():
+ continue
+ row["scanned"] = int(row["scanned"]) + 1
+ try:
+ candidate.rmdir()
+ except FileNotFoundError:
+ # CloudDrive can remove the same empty directory concurrently.
+ continue
+ except OSError as error:
+ if error.errno not in {errno.ENOTEMPTY, errno.EEXIST}:
+ row["errors"] = int(row["errors"]) + 1
+ else:
+ row["removed"] = int(row["removed"]) + 1
row["errors"] = int(row["errors"]) + len(walk_errors)
total_scanned += int(row["scanned"])
total_removed += int(row["removed"])
@@ -426,7 +431,7 @@ def _finish_purge(outcome):
snapshot.unlink(missing_ok=True)
except OSError:
pass
- source_roots = tuple(_online_source_roots().values())
+ source_roots = tuple(root for roots in _online_source_roots().values() for root in roots)
removed_directories: set[Path] = set()
for parent in outcome.pop("_parents"):
removed_directories.update(_remove_empty_ancestors(parent, source_roots))
diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.py
index d6eec90a1..9c4a6dddf 100644
--- a/src/peach/web_resource_sync.py
+++ b/src/peach/web_resource_sync.py
@@ -49,8 +49,12 @@ def source_is_online(location: str) -> bool:
declared = LOCATION_ROOT_DECLARATIONS.get(location)
if not declared:
return False
- resolved = translate_ledger_path(declared)
- return not is_unmapped(resolved) and root_online(resolved)
+ # 几个根都在才算在线:少一块盘就对账,那块盘上的文件会被整批判成丢失。
+ for root in declared:
+ resolved = translate_ledger_path(root)
+ if is_unmapped(resolved) or not root_online(resolved):
+ return False
+ return True
RESOURCE_SCAN_WORKERS = 8
diff --git a/src/peach/web_stats.py b/src/peach/web_stats.py
index 00aacfd66..12c183c32 100644
--- a/src/peach/web_stats.py
+++ b/src/peach/web_stats.py
@@ -171,16 +171,20 @@ _STORAGE_LABELS = {
def _storage_volumes() -> list[dict[str, object]]:
"""返回当前主机可验证的系统卷、资源盘和网盘容量。"""
- declarations = [("system", system_volume(), True)] + [
- (location, translate_ledger_path(root), False)
- for location, root in LOCATION_ROOT_DECLARATIONS.items()
+ declarations = [("system", _STORAGE_LABELS["system"], system_volume(), True)] + [
+ # 一个来源有几个根就几行;同名来源用序号区分,单根不加。
+ (location,
+ _STORAGE_LABELS.get(location, location) + (f" {index + 1}" if len(roots) > 1 else ""),
+ translate_ledger_path(root), False)
+ for location, roots in LOCATION_ROOT_DECLARATIONS.items()
+ for index, root in enumerate(roots)
]
volumes: list[dict[str, object]] = []
- for kind, root, is_system in declarations:
+ for kind, label, root, is_system in declarations:
mounted = not is_unmapped(root) and (is_system or root_online(root))
row: dict[str, object] = {
"kind": kind,
- "label": _STORAGE_LABELS[kind],
+ "label": label,
"root": str(root) if not is_unmapped(root) else None,
"online": mounted,
"free": None,
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 2d102c6c9..715be8d9a 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -136,7 +136,7 @@ class InitCommandTests(unittest.TestCase):
self.assertTrue(loaded.configured)
self.assertEqual(loaded.server.mdns_name, "peach-two")
self.assertEqual(loaded.server.port, 9443)
- self.assertEqual(loaded.mounts, {"local": "/mnt/media"})
+ self.assertEqual(loaded.mounts, {"local": ("/mnt/media",)})
# 全新机器不开复制:单机用户不该凭空多出一条同步路径。
self.assertFalse(loaded.replication.enabled)
@@ -155,8 +155,12 @@ class InitCommandTests(unittest.TestCase):
def test_mount_ids_keep_their_case(self):
"""来源 ID 不是盘符,`local` 不能被改写成 `LOCAL`。"""
self.assertEqual(
- cli._parse_mounts(["local=/mnt/res"], {"local": r"R:\media"}),
- {"local": "/mnt/res"})
+ cli._parse_mounts(["local=/mnt/res"], {"local": (r"R:\media",)}),
+ {"local": ("/mnt/res",)})
+ # 同一来源重复给,就按顺序对应它的几个声明根。
+ self.assertEqual(
+ cli._parse_mounts(["local=/mnt/a", "local=/mnt/b"], {"local": (r"R:\media", r"R:\media2")}),
+ {"local": ("/mnt/a", "/mnt/b")})
def test_the_new_ledger_is_readable_by_status(self):
self._init()
@@ -273,13 +277,18 @@ class InteractiveInitTests(unittest.TestCase):
@unittest.skipUnless(NATIVE_WINDOWS, "声明根要是真实存在的盘符目录,只有 Windows 造得出来")
def test_windows_flow_declares_the_directory_and_scans_it(self):
- code, output, prompts = self._run(["", str(self.media), "", "", "", ""], windows=True)
+ second = self.root / "more"
+ second.mkdir()
+ (second / "c.mp4").write_bytes(b"2")
+ code, output, prompts = self._run(
+ ["", str(self.media), str(second), "", "", "", "", ""], windows=True)
self.assertEqual(code, 0)
- self.assertEqual(len(prompts), 6)
- self.assertTrue(prompts[-1].startswith("现在扫描 "))
+ self.assertEqual(len(prompts), 8)
+ self.assertEqual(prompts[2], prompts[3], "追加目录问到回车为止")
+ self.assertTrue(prompts[-1].startswith("现在扫描 这 2 个文件夹"))
loaded = self._loaded()
self.assertTrue(loaded.present)
- self.assertEqual(loaded.locations, {"local": str(self.media)})
+ self.assertEqual(loaded.locations, {"local": (str(self.media), str(second))})
self.assertEqual(loaded.mounts, {})
self.assertEqual((loaded.server.host, loaded.server.port, loaded.server.mdns_name),
("0.0.0.0", 8900, "peach"))
@@ -289,19 +298,21 @@ class InteractiveInitTests(unittest.TestCase):
self.certs.assert_called_once()
# 账本里的路径就是本机路径,每一行都指向真实文件。
self.assertEqual(self._ledger_paths(),
- sorted([str(self.media / "b.jpg"), str(self.media / "sub" / "a.mp4")]))
+ sorted([str(self.media / "b.jpg"), str(self.media / "sub" / "a.mp4"),
+ str(second / "c.mp4")]))
self.assertIn("✓ local: 2 文件", output)
+ self.assertIn("✓ local: 1 文件", output)
self.assertIn("下一步", output)
- self.assertIn("扫描结果:", output)
+ self.assertEqual(output.count("扫描结果:"), 2, "每个目录各报一行")
self.assertNotIn("115", (self.data_root / "config.toml").read_text(encoding="utf-8"))
def test_posix_flow_keeps_the_ledger_shape_and_mounts_the_directory(self):
- code, output, _ = self._run(["", str(self.media), "2", "9443", "peach-two", ""],
+ code, output, _ = self._run(["", str(self.media), "", "2", "9443", "peach-two", ""],
windows=False)
self.assertEqual(code, 0)
loaded = self._loaded()
- self.assertEqual(loaded.locations, {"local": r"R:\media"})
- self.assertEqual(loaded.mounts, {"local": str(self.media)})
+ self.assertEqual(loaded.locations, {"local": (r"R:\media",)})
+ self.assertEqual(loaded.mounts, {"local": (str(self.media),)})
self.assertEqual((loaded.server.host, loaded.server.port, loaded.server.mdns_name),
("0.0.0.0", 9443, "peach-two"))
self.assertIn("本机挂载点", output)
@@ -310,12 +321,12 @@ class InteractiveInitTests(unittest.TestCase):
# 读取侧按同一套规则翻回去:声明根后的层级接到挂载点上。
for path in paths:
tail = PureWindowsPath(path).relative_to(PureWindowsPath(r"R:\media")).parts
- self.assertTrue(Path(loaded.mounts["local"]).joinpath(*tail).is_file(), path)
+ self.assertTrue(Path(loaded.mounts["local"][0]).joinpath(*tail).is_file(), path)
def test_an_invalid_media_directory_is_asked_again(self):
missing = self.root / "nope"
code, output, prompts = self._run(
- ["", str(missing), str(self.media), "", "", "", "n"], windows=NATIVE_WINDOWS)
+ ["", str(missing), str(self.media), "", "", "", "", "n"], windows=NATIVE_WINDOWS)
self.assertEqual(code, 0)
self.assertEqual(prompts.count("媒体文件夹(必须已经存在,可以在外置硬盘上)"), 2)
self.assertIn("目录不存在", output)
@@ -329,7 +340,7 @@ class InteractiveInitTests(unittest.TestCase):
self.assertFalse(self.data_root.exists())
def test_the_scan_can_be_declined(self):
- code, output, _ = self._run(["", str(self.media), "", "", "", "n"], windows=NATIVE_WINDOWS)
+ code, output, _ = self._run(["", str(self.media), "", "", "", "", "n"], windows=NATIVE_WINDOWS)
self.assertEqual(code, 0)
self.assertEqual(self._ledger_paths(), [])
self.assertNotIn("扫描结果", output)
@@ -356,7 +367,7 @@ class InteractiveInitTests(unittest.TestCase):
from peach.config import PeachSettings
from peach.platform import translate_roots
- self._run(["", str(self.media), "", "", "", ""], windows=NATIVE_WINDOWS)
+ self._run(["", str(self.media), "", "", "", "", ""], windows=NATIVE_WINDOWS)
loaded = self._loaded()
# POSIX 形态的声明根是 `R:\media`,翻回本机目录要读这份设置的 [media.mounts];
# 模块级 `active()` 指的是这台机器自己的设置,临时目录不在里面。
@@ -365,7 +376,7 @@ class InteractiveInitTests(unittest.TestCase):
self.addCleanup(active.stop)
settings = PeachSettings(
db_path=loaded.directory("database") / "ledger.db", configured=True, token="secret",
- allowed_media_roots=translate_roots(tuple(loaded.locations.values())),
+ allowed_media_roots=translate_roots(tuple(root for roots in loaded.locations.values() for root in roots)),
)
async def probe():
@@ -453,9 +464,10 @@ class ScanCommandTests(unittest.TestCase):
(self.media / "b.jpg").write_bytes(b"1")
config = settings_file.load_config(environ={}, strict=False)
declared = str(self.media) if NATIVE_WINDOWS else r"R:\media"
- mounts = {} if NATIVE_WINDOWS else {"local": Path(self.media)}
- fixed = replace(config, locations={"local": declared},
- mounts={key: str(value) for key, value in mounts.items()})
+ mounts = {} if NATIVE_WINDOWS else {"local": (Path(self.media),)}
+ fixed = replace(config, locations={"local": (declared,)},
+ mounts={key: tuple(str(item) for item in value)
+ for key, value in mounts.items()})
for target in (mock.patch.object(settings_file, "active", lambda: fixed),
mock.patch.object(cli, "location_mounts", lambda: mounts),
mock.patch.object(cli, "SETTINGS_ERROR", None)):
diff --git a/tests/test_config.py b/tests/test_config.py
index a9746f0ed..415f272c1 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -242,22 +242,55 @@ class BadFileTests(unittest.TestCase):
with TempTree() as tree:
tree.write("[media.mounts]\nlocal = '/mnt/res/media'\n")
loaded = tree.load()
- self.assertEqual(loaded.mounts, {"local": "/mnt/res/media"})
+ self.assertEqual(loaded.mounts, {"local": ("/mnt/res/media",)})
def test_a_newly_declared_location_can_be_mounted(self):
with TempTree() as tree:
tree.write(
"[media.locations]\nnas = 'N:/'\n[media.mounts]\nnas = '/mnt/nas'\n")
loaded = tree.load()
- self.assertEqual(loaded.locations["nas"], "N:/")
- self.assertEqual(loaded.mounts, {"nas": "/mnt/nas"})
+ self.assertEqual(loaded.locations["nas"], ("N:/",))
+ self.assertEqual(loaded.mounts, {"nas": ("/mnt/nas",)})
def test_a_declared_locations_table_is_authoritative(self):
"""`peach init` 的问答只声明 local;内建默认的示例盘符不得从旁边混进来。"""
with TempTree() as tree:
tree.write("[media.locations]\nlocal = 'D:\\Videos'\n")
loaded = tree.load()
- self.assertEqual(loaded.locations, {"local": r"D:\Videos"})
+ self.assertEqual(loaded.locations, {"local": (r"D:\Videos",)})
+
+ def test_a_location_may_declare_several_roots_with_matching_mounts(self):
+ """两块硬盘都是 `local`:声明根写数组,落点按同样的顺序写数组,写回时形状不变。"""
+ with TempTree() as tree:
+ tree.write("[media.locations]\nlocal = ['D:\\Videos', 'E:\\Movies']\n"
+ "[media.mounts]\nlocal = ['/mnt/a', '/mnt/b']\n")
+ loaded = tree.load()
+ self.assertEqual(loaded.locations, {"local": (r"D:\Videos", r"E:\Movies")})
+ self.assertEqual(loaded.mounts, {"local": ("/mnt/a", "/mnt/b")})
+ rendered = settings_file.render(loaded)
+ self.assertIn("local = ['D:\\Videos', 'E:\\Movies']", rendered)
+ self.assertIn("local = ['/mnt/a', '/mnt/b']", rendered)
+ tree.write(rendered)
+ self.assertEqual(tree.load().locations, loaded.locations)
+
+ def test_mount_count_must_match_the_declared_roots(self):
+ # 落点按顺序对应声明根:数目不齐时猜不出哪个目录漏了,直接拒绝。
+ with TempTree() as tree:
+ tree.write("[media.locations]\nlocal = ['D:\\Videos', 'E:\\Movies']\n"
+ "[media.mounts]\nlocal = '/mnt/a'\n")
+ with self.assertRaises(SettingsFileError) as caught:
+ tree.load()
+ self.assertIn("2 个根", str(caught.exception))
+ with TempTree() as tree:
+ tree.write("[media.locations]\nlocal = ['D:\\Videos', 'D:\\Videos']\n")
+ with self.assertRaises(SettingsFileError) as caught:
+ tree.load()
+ self.assertIn("重复", str(caught.exception))
+ with TempTree() as tree:
+ tree.write("[media.locations]\nlocal = []\n")
+ with self.assertRaises(SettingsFileError) as caught:
+ tree.load()
+ self.assertIn("没有声明根", str(caught.exception))
def test_without_a_locations_table_the_builtin_defaults_apply(self):
with TempTree() as tree:
@@ -323,13 +356,13 @@ class SerialisationTests(unittest.TestCase):
},
# 反斜杠和 Windows 盘符必须原样活过一次往返:序列化器要是把 `\m`
# 当转义处理,挂载点就会变成另一个目录。
- mounts={"local": r"D:\media", "115": "/mnt/115"},
+ mounts={"local": (r"D:\media",), "115": ("/mnt/115",)},
)
settings_file.write(captured)
reloaded = tree.load()
self.assertEqual(reloaded.server, captured.server)
self.assertEqual(reloaded.replication, captured.replication)
- self.assertEqual(reloaded.mounts, {"local": r"D:\media", "115": "/mnt/115"})
+ self.assertEqual(reloaded.mounts, {"local": (r"D:\media",), "115": ("/mnt/115",)})
self.assertEqual(reloaded.locations, captured.locations)
self.assertEqual(reloaded.directories, captured.directories)
self.assertTrue(reloaded.present)
@@ -388,7 +421,7 @@ class ModuleConstantTests(unittest.TestCase):
# 账本里的 `asset.path` 是 Windows 形态,声明根必须同口径,否则授权全落空。
self.assertEqual(set(config.LOCATION_ROOT_DECLARATIONS), {"local", "115", "pikpak"})
self.assertEqual(
- tuple(config.LOCATION_ROOT_DECLARATIONS.values()),
+ tuple(root for roots in config.LOCATION_ROOT_DECLARATIONS.values() for root in roots),
config.MEDIA_ROOT_DECLARATIONS,
)
diff --git a/tests/test_onboarding.py b/tests/test_onboarding.py
index aefa16f29..be1c7082c 100644
--- a/tests/test_onboarding.py
+++ b/tests/test_onboarding.py
@@ -139,24 +139,74 @@ class AskUntilValidTests(_Case):
class ConfigureTests(_Case):
def _answers(self, **overrides):
- base = dict(data_root=self.root / "peach-data", media_dir=self.media,
+ base = dict(data_root=self.root / "peach-data", media_dirs=(self.media,),
host="127.0.0.1", port=8900, mdns_name="peach")
base.update(overrides)
return onboarding.Answers(**base)
def test_windows_declares_the_directory_itself_and_leaves_mounts_empty(self):
prepared = onboarding.configure(self.config, self._answers(), windows=True)
- self.assertEqual(prepared.locations, {"local": str(self.media)})
+ self.assertEqual(prepared.locations, {"local": (str(self.media),)})
self.assertEqual(prepared.mounts, {})
- self.assertEqual(onboarding.scan_root(prepared), str(self.media))
+ self.assertEqual(onboarding.scan_roots(prepared), (str(self.media),))
def test_posix_keeps_the_ledger_shape_and_mounts_the_directory(self):
prepared = onboarding.configure(self.config, self._answers(), windows=False)
- self.assertEqual(prepared.locations, {"local": r"R:\media"})
- self.assertEqual(prepared.mounts, {"local": str(self.media)})
- self.assertEqual(onboarding.scan_root(prepared), r"R:\media")
+ self.assertEqual(prepared.locations, {"local": (r"R:\media",)})
+ self.assertEqual(prepared.mounts, {"local": (str(self.media),)})
+ self.assertEqual(onboarding.scan_roots(prepared), (r"R:\media",))
self.assertIn(str(self.media), onboarding.mounts_explanation(self.media))
+ def test_several_directories_all_belong_to_the_local_source(self):
+ """两块硬盘都是 `local`:Windows 上每个目录一个声明根,macOS 上声明根按序号生成。"""
+ second = self.root / "more"
+ second.mkdir()
+ answers = self._answers(media_dirs=(self.media, second))
+ windows = onboarding.configure(self.config, answers, windows=True)
+ self.assertEqual(windows.locations, {"local": (str(self.media), str(second))})
+ self.assertEqual(windows.mounts, {})
+ posix = onboarding.configure(self.config, answers, windows=False)
+ self.assertEqual(posix.locations, {"local": (r"R:\media", r"R:\media2")})
+ self.assertEqual(posix.mounts, {"local": (str(self.media), str(second))})
+ self.assertEqual(onboarding.scan_roots(posix), (r"R:\media", r"R:\media2"))
+ explanation = onboarding.mounts_explanation((self.media, second))
+ self.assertIn(r"R:\media2", explanation)
+ self.assertIn(str(second), explanation)
+
+ def test_directories_must_not_repeat_or_nest(self):
+ nested = self.media / "inner"
+ nested.mkdir()
+ other = self.root / "other"
+ other.mkdir()
+ self.assertEqual(onboarding.check_media_dirs((self.media, other)), {})
+ self.assertEqual(list(onboarding.check_media_dirs((self.media, self.media))), [1])
+ self.assertIn("重复", onboarding.check_media_dirs((self.media, self.media))[1])
+ problems = onboarding.check_media_dirs((self.media, nested))
+ self.assertEqual(list(problems), [1])
+ self.assertIn(str(self.media), problems[1])
+ # 父目录排在后面时,多余的仍是子目录那一行:用户后来给的父目录已经把它包住了。
+ self.assertEqual(list(onboarding.check_media_dirs((nested, self.media))), [0])
+
+ def test_form_rows_are_read_line_by_line_with_errors_kept_in_place(self):
+ validate = onboarding.media_dir_validator(windows=NATIVE_WINDOWS)
+ other = self.root / "other"
+ other.mkdir()
+ # 第一行留空取默认值,中间的空行当没填。
+ paths, problems = onboarding.read_media_dirs(
+ ["", "", str(other)], validate=validate, default=str(self.media))
+ self.assertEqual(paths, [self.media, other])
+ self.assertEqual(problems, [])
+ # 错误与提交的行一一对应:第三行不存在,第二行是空行也占一个位置。
+ _paths, problems = onboarding.read_media_dirs(
+ [str(self.media), "", str(self.root / "nope")], validate=validate)
+ self.assertEqual(problems[:2], ["", ""])
+ self.assertIn("目录不存在", problems[2])
+ (self.media / "inner").mkdir()
+ _paths, problems = onboarding.read_media_dirs(
+ [str(self.media), str(self.media / "inner")], validate=validate)
+ self.assertEqual(problems[0], "")
+ self.assertIn("已经在", problems[1])
+
def test_only_the_asked_settings_change_and_replication_stays_off(self):
prepared = onboarding.configure(
self.config, self._answers(host="0.0.0.0", port=9443, mdns_name="peach-two"), windows=True)
@@ -174,27 +224,42 @@ class ConfigureTests(_Case):
loaded = settings_file.load_config(
project_root=self.root / "app", environ={"PEACH_DATA_ROOT": str(self.root / "peach-data")})
self.assertTrue(loaded.present)
- self.assertEqual(loaded.locations, {"local": str(self.media)})
+ self.assertEqual(loaded.locations, {"local": (str(self.media),)})
self.assertEqual(loaded.mounts, {})
self.assertFalse(loaded.replication.enabled)
class InterviewTests(_Case):
def test_scripted_answers_drive_the_whole_interview(self):
- ask = scripted("", str(self.media), "2", "", "peach-two")
+ second = self.root / "more"
+ second.mkdir()
+ ask = scripted("", str(self.media), str(second), "", "2", "", "peach-two")
answers = onboarding.interview(self.config, ask, windows=NATIVE_WINDOWS, home=self.home,
report=lambda _: None)
self.assertEqual(answers, onboarding.Answers(
- data_root=self.root / "peach-data", media_dir=self.media, host="0.0.0.0",
+ data_root=self.root / "peach-data", media_dirs=(self.media, second), host="0.0.0.0",
port=8900, mdns_name="peach-two"))
+ # 媒体文件夹问完一个就问「再加一个」,回车结束;追加的目录和第一个走同一套校验。
self.assertEqual([prompt for prompt, _ in ask.seen], [
"数据目录(Peach 数据库、缓存和设置文件都放在这里)",
"媒体文件夹(必须已经存在,可以在外置硬盘上)",
+ "再加一个媒体文件夹(不加就直接回车)",
+ "再加一个媒体文件夹(不加就直接回车)",
"谁可以访问:1 = 只有这台电脑,2 = 同一局域网的设备",
"端口",
"局域网访问地址(<名字>.local,只在允许局域网访问时发布)",
])
+ def test_an_extra_directory_inside_the_first_is_asked_again(self):
+ nested = self.media / "inner"
+ nested.mkdir()
+ reports: list[str] = []
+ ask = scripted("", str(self.media), str(nested), "", "1", "", "")
+ answers = onboarding.interview(self.config, ask, windows=NATIVE_WINDOWS, home=self.home,
+ report=reports.append)
+ self.assertEqual(answers.media_dirs, (self.media,))
+ self.assertTrue(any("已经在" in line for line in reports), reports)
+
def test_console_ask_shows_the_default_and_treats_eof_as_abort(self):
with mock.patch("builtins.input", return_value="x") as prompt:
self.assertEqual(onboarding.console_ask("服务端口", "8900"), "x")
@@ -225,7 +290,7 @@ class ApplyTests(_Case):
self.addCleanup(patcher.stop)
def _answers(self, **overrides):
- base = dict(data_root=self.root / "peach-data", media_dir=self.media,
+ base = dict(data_root=self.root / "peach-data", media_dirs=(self.media,),
host="127.0.0.1", port=8900, mdns_name="peach")
base.update(overrides)
return onboarding.Answers(**base)
@@ -372,6 +437,14 @@ class SetupPageTests(_Case):
self.assertIn(f">{title}</", body)
self.assertIn("Peach 数据库、缓存和设置文件都放在这里。", body)
self.assertIn("可以是外置硬盘上的文件夹", body)
+ # 媒体文件夹是一个可加减的列表:默认一行,「添加文件夹」和移除键由页内脚本亮出来,
+ # 新行从 <template> 里克隆,所以没有脚本时页面只有一个输入框。
+ self.assertEqual(body.count('<div class="dir"><input name="media_dir"'), 2)
+ self.assertIn('<button type="button" class="add" id="add-dir" hidden>添加文件夹</button>', body)
+ self.assertIn('<template id="dir-row"><div class="dir">', body)
+ self.assertIn('class="rm" aria-label="移除这个文件夹" hidden>', body)
+ self.assertIn("template.content.firstElementChild.cloneNode(true)", body)
+ self.assertLess(body.index('id="dirs"'), body.index('id="add-dir"'))
# 品牌标记在标题上方,说明文字在标题下方。
self.assertIn('<img class="mark" src="/peach-logo.png"', body)
self.assertLess(body.index("<h1>"), body.index('class="lede"'))
@@ -410,6 +483,34 @@ class SetupPageTests(_Case):
self.assertFalse(missing.exists(), "校验不替人建目录")
self.assertFalse(self.data_root.exists(), "校验失败不落任何文件")
+ def test_two_directories_are_declared_together_and_shown_in_the_scan_label(self):
+ second = self.root / "more"
+ second.mkdir()
+ response = self._post("/setup", self._form(media_dir=[str(self.media), str(second)]))
+ self.assertEqual(response.status_code, 200, response.text)
+ loaded = self._loaded()
+ if NATIVE_WINDOWS:
+ self.assertEqual(loaded.locations, {"local": (str(self.media), str(second))})
+ else:
+ self.assertEqual(loaded.locations, {"local": (r"R:\media", r"R:\media2")})
+ self.assertEqual(loaded.mounts, {"local": (str(self.media), str(second))})
+
+ def test_a_nested_second_directory_is_rejected_on_its_own_row(self):
+ nested = self.media / "inner"
+ nested.mkdir()
+ response = self._post("/setup", self._form(media_dir=[str(self.media), str(nested)]))
+ self.assertEqual(response.status_code, 400)
+ body = response.text
+ self.assertEqual(body.count('<div class="dir"><input name="media_dir"'), 3, "两行都回显,外加模板")
+ self.assertIn("已经在", body)
+ # 错误挂在第二行底下,第一行不背锅。
+ first_row = body.index(f'value="{escape(str(self.media), quote=True)}"')
+ second_row = body.index(f'value="{escape(str(nested), quote=True)}"')
+ self.assertLess(first_row, body.index("已经在"))
+ self.assertLess(second_row, body.index("已经在"))
+ self.assertIn("完成设置后扫描这 2 个文件夹", body)
+ self.assertFalse(self.data_root.exists())
+
def test_a_disabled_lan_address_falls_back_to_the_default_name(self):
"""选「只有这台电脑」后地址框是禁用的,不随表单提交;服务端按默认值补上。"""
response = self._post("/setup", self._form(host="1", mdns_name=None))
@@ -468,7 +569,7 @@ class StandaloneConfigurationTests(_Case):
def setUp(self):
super().setUp()
from dataclasses import replace
- self.config = replace(self.config, locations={"local": str(self.media)},
+ self.config = replace(self.config, locations={"local": (str(self.media),)},
mounts={}, server=settings_file.ServerSettings(port=9123))
settings_file.write(self.config)
self.config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.config.data_root)})
@@ -497,6 +598,7 @@ class StandaloneConfigurationTests(_Case):
self.assertIn('<span class="pcheck"><input type="checkbox" name="scan_now" value="y">', page.text)
self.assertIn("<h2>运行信息</h2>", page.text)
self.assertIn("<dt>FFmpeg</dt>", page.text)
+ self.assertIn('id="add-dir"', page.text, "配置页的媒体文件夹同样是可加减的列表")
self.config.directory("state").mkdir(parents=True, exist_ok=True)
response = client.post("/configuration", headers=headers, data={
"revision": revision(self.config), "media_dir": str(self.media), "port": "9124"})
diff --git a/tests/test_platform.py b/tests/test_platform.py
index c2975a1df..b79daadca 100644
--- a/tests/test_platform.py
+++ b/tests/test_platform.py
@@ -10,12 +10,13 @@ from peach.media import FilesystemBackend, MediaOffline, MediaUnavailable
from peach.platform import (
MOUNTS_ENV,
UNMAPPED_ROOT,
- declared_root,
+ declared_roots_of,
is_unmapped,
is_windows_path,
location_mounts,
location_of,
resolve_location,
+ resolve_root,
root_online,
system_volume,
translate_ledger_path,
@@ -28,15 +29,20 @@ from peach.repository import MediaAsset
POSIX_ONLY = unittest.skipIf(os.name == "nt", "路径翻译只在非 Windows 上发生")
#: 测试里固定的账本口径声明根,和内建默认一致;不依赖本机 config.toml。
-LOCATIONS = {"local": r"R:\media", "115": "B:/", "pikpak": "A:/"}
+LOCATIONS = {"local": (r"R:\media",), "115": ("B:/",), "pikpak": ("A:/",)}
+
+
+def _roots(table):
+ """测试里写单个字符串更顺手;设置层一律是与声明根按序对应的元组。"""
+ return {key: (value,) if isinstance(value, str) else tuple(value) for key, value in table.items()}
def with_media(mounts, locations=None):
"""把设置层的 `[media.locations]` / `[media.mounts]` 钉死成给定值。"""
config = settings_file.load_config(environ={}, strict=False)
fixed = replace(
- config, mounts=dict(mounts),
- locations=dict(LOCATIONS if locations is None else locations),
+ config, mounts=_roots(mounts),
+ locations=_roots(LOCATIONS if locations is None else locations),
)
return patch.object(settings_file, "active", lambda: fixed)
@@ -75,10 +81,27 @@ class LocationResolutionTests(unittest.TestCase):
# 同一个盘但不在声明根下:`R:\Resources` 不是 `R:\media`。
self.assertIsNone(location_of(r"R:\Resources\Intake\one.mp4"))
- def test_declared_root_is_read_from_the_settings_layer(self):
+ def test_declared_roots_are_read_from_the_settings_layer(self):
with with_media({}):
- self.assertEqual(declared_root("local"), r"R:\media")
- self.assertIsNone(declared_root("online"))
+ self.assertEqual(declared_roots_of("local"), (r"R:\media",))
+ self.assertEqual(declared_roots_of("online"), ())
+
+ def test_a_source_with_two_roots_resolves_each_to_its_own_index(self):
+ roots = {"local": (r"R:\media", r"S:\more"), "115": ("B:/",)}
+ self.assertEqual(resolve_root(r"R:\media\a.mp4", roots), ("local", 0, ("a.mp4",)))
+ self.assertEqual(resolve_root(r"S:\more\x\b.mp4", roots), ("local", 1, ("x", "b.mp4")))
+ self.assertEqual(resolve_root("B:/c.mp4", roots), ("115", 0, ("c.mp4",)))
+ self.assertEqual(resolve_root(r"Z:\nope", roots), (None, -1, ()))
+
+ @POSIX_ONLY
+ def test_each_root_translates_to_the_mount_at_the_same_position(self):
+ with with_media({"local": ["/Volumes/A", "/Volumes/B"]},
+ {"local": [r"R:\media", r"R:\media2"]}):
+ self.assertEqual(translate_ledger_path(r"R:\media\one.mp4"), Path("/Volumes/A/one.mp4"))
+ self.assertEqual(translate_ledger_path(r"R:\media2\two.mp4"), Path("/Volumes/B/two.mp4"))
+ # 挂载表比声明根短:多出来的根按脱盘处理,不能悄悄落到别的目录。
+ with with_media({"local": ["/Volumes/A"]}, {"local": [r"R:\media", r"R:\media2"]}):
+ self.assertTrue(is_unmapped(translate_ledger_path(r"R:\media2\two.mp4")))
class MountSourceTests(unittest.TestCase):
@@ -87,14 +110,14 @@ class MountSourceTests(unittest.TestCase):
def test_settings_file_supplies_the_base_mapping(self):
with with_media({"local": "/mnt/res"}):
with patch.dict("os.environ", {MOUNTS_ENV: ""}):
- self.assertEqual(location_mounts(), {"local": Path("/mnt/res")})
+ self.assertEqual(location_mounts(), {"local": (Path("/mnt/res"),)})
def test_environment_still_wins_over_the_settings_file(self):
with with_media({"local": "/mnt/res", "115": "/mnt/115"}):
with patch.dict("os.environ", {MOUNTS_ENV: "local=/mnt/other"}):
self.assertEqual(
location_mounts(),
- {"local": Path("/mnt/other"), "115": Path("/mnt/115")})
+ {"local": (Path("/mnt/other"),), "115": (Path("/mnt/115"),)})
def test_a_fresh_machine_has_no_mounts_at_all(self):
"""内建默认为空:没挂的来源按脱盘处理,绝不猜一个本机路径。"""
diff --git a/tests/test_rm_ledger.py b/tests/test_rm_ledger.py
index 083a5e78d..e60977f7f 100644
--- a/tests/test_rm_ledger.py
+++ b/tests/test_rm_ledger.py
@@ -112,7 +112,7 @@ class ScanTargetTests(unittest.TestCase):
from peach import settings_file
config = settings_file.load_config(environ={}, strict=False)
- fixed = replace(config, locations={"local": r"R:\media", "115": "B:/"})
+ fixed = replace(config, locations={"local": (r"R:\media",), "115": ("B:/",)})
patcher = patch.object(settings_file, "active", lambda: fixed)
patcher.start()
self.addCleanup(patcher.stop)
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index d4f12ab22..a25576fdf 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -196,7 +196,7 @@ class WebDataTests(unittest.TestCase):
def test_stats_report_system_resource_and_cloud_volumes(self):
usage = type("Usage", (), {"free": 20, "total": 100})
- declarations = {"local": "R:/media", "115": "B:/", "pikpak": "A:/"}
+ declarations = {"local": ("R:/media", "S:/more"), "115": ("B:/",), "pikpak": ("A:/",)}
with mock.patch.object(web_stats, "LOCATION_ROOT_DECLARATIONS", declarations), \
mock.patch.object(web_stats, "system_volume", return_value=Path("X:/")), \
mock.patch.object(web_stats, "translate_ledger_path",
@@ -205,14 +205,15 @@ class WebDataTests(unittest.TestCase):
mock.patch("shutil.disk_usage", return_value=usage):
stats = rm_web.q_stats(self.contract)
+ # 同一来源的几个根各占一行,用序号区分;单根来源不带序号。
self.assertEqual(
[(row["kind"], row["label"]) for row in stats["storage_volumes"]],
- [("system", "系统盘"), ("local", "资源盘"),
+ [("system", "系统盘"), ("local", "资源盘 1"), ("local", "资源盘 2"),
("115", "115 网盘"), ("pikpak", "PikPak 网盘")],
)
self.assertEqual(stats["storage_summary"], {
- "volumes": 4, "online": 4, "measured": 4,
- "free": 80, "used": 320, "total": 400,
+ "volumes": 5, "online": 5, "measured": 5,
+ "free": 100, "used": 400, "total": 500,
})
def test_items_support_duration_range(self):
@@ -1026,7 +1027,7 @@ class WebDataTests(unittest.TestCase):
rm_web.w_feedback(self.contract, {"id": 1, "kind": "dispose"})
with mock.patch.object(
- web_batch, "LOCATION_ROOT_DECLARATIONS", {"local": str(source_root)}):
+ web_batch, "LOCATION_ROOT_DECLARATIONS", {"local": (str(source_root),)}):
result = rm_web.w_batch(self.contract, {"ids": [1], "operation": "delete"})
self.assertEqual(result["empty_dirs_removed"], 2)
@@ -1042,7 +1043,7 @@ class WebDataTests(unittest.TestCase):
offline = Path(self.tmp.name) / "offline"
with mock.patch.object(web_batch, "LOCATION_ROOT_DECLARATIONS", {
- "local": str(source_root), "115": str(offline),
+ "local": (str(source_root),), "115": (str(offline),),
}):
result = rm_web.cleanup_empty_source_directories()
diff --git a/tests/test_scan.py b/tests/test_scan.py
index 9bed84de0..95593669f 100644
--- a/tests/test_scan.py
+++ b/tests/test_scan.py
@@ -57,7 +57,7 @@ class WindowsShapeTests(_ScanCase):
"""Windows:声明根就是真实目录,路径原样进账本。"""
def test_rows_are_written_under_the_declared_root(self):
- declared = {"local": str(self.media)}
+ declared = {"local": (str(self.media),)}
result, output = self._scan(str(self.media), declared_roots=declared, windows=True)
self.assertEqual(result.files, 3)
self.assertEqual(result.total_bytes, 14)
@@ -72,12 +72,12 @@ class WindowsShapeTests(_ScanCase):
self.assertTrue(Path(path).is_file(), path)
def test_a_subdirectory_of_the_declared_root_is_accepted(self):
- declared = {"local": str(self.media)}
+ declared = {"local": (str(self.media),)}
result, _ = self._scan(str(self.media / "创作者"), declared_roots=declared, windows=True)
self.assertEqual(result.files, 1)
def test_rescanning_refreshes_instead_of_duplicating_and_counts_the_gone(self):
- declared = {"local": str(self.media)}
+ declared = {"local": (str(self.media),)}
self._scan(str(self.media), declared_roots=declared, windows=True)
(self.media / "notes.txt").unlink()
(self.media / "cover.jpg").write_bytes(b"1" * 8)
@@ -94,10 +94,10 @@ class WindowsShapeTests(_ScanCase):
class PosixShapeTests(_ScanCase):
"""macOS:账本里写 `R:\\media\\...`,遍历的是挂载点,读取侧按挂载表翻回去。"""
- DECLARED = {"local": r"R:\media"}
+ DECLARED = {"local": (r"R:\media",)}
def test_rows_keep_the_ledger_shape_and_translate_back_to_real_files(self):
- mounts = {"local": self.media}
+ mounts = {"local": (self.media,)}
result, _ = self._scan(r"R:\media", declared_roots=self.DECLARED, mounts=mounts,
windows=False)
self.assertEqual(result.files, 3)
@@ -110,7 +110,7 @@ class PosixShapeTests(_ScanCase):
self.assertTrue(self.media.joinpath(*tail).is_file(), path)
def test_a_local_directory_is_converted_to_the_ledger_shape(self):
- mounts = {"local": str(self.media)}
+ mounts = {"local": (str(self.media),)}
root = scan.ledger_root_for("local", self.media / "创作者",
declared_roots=self.DECLARED, mounts=mounts, windows=False)
self.assertEqual(root, r"R:\media\创作者")
@@ -123,17 +123,36 @@ class PosixShapeTests(_ScanCase):
self.assertIn("media.mounts", str(caught.exception))
self.assertEqual(self._paths(), {})
+ def test_a_second_root_maps_to_its_own_mount(self):
+ """两个目录都是 `local`:第二个挂载点对应第二个声明根,账本路径带序号前缀。"""
+ second = self.root / "more"
+ (second / "deep").mkdir(parents=True)
+ (second / "deep" / "c.mp4").write_bytes(b"2")
+ declared = {"local": (r"R:\media", r"R:\media2")}
+ mounts = {"local": (str(self.media), str(second))}
+ root = scan.ledger_root_for("local", second / "deep", declared_roots=declared,
+ mounts=mounts, windows=False)
+ self.assertEqual(root, r"R:\media2\deep")
+ result, _ = self._scan(root, declared_roots=declared, mounts=mounts, windows=False)
+ self.assertEqual(result.files, 1)
+ self.assertEqual(set(self._paths()), {r"R:\media2\deep\c.mp4"})
+ # 挂载表比声明根短:第二个根没有落点,扫描它必须拒绝而不是落到第一个目录。
+ with self.assertRaises(scan.ScanTargetError) as caught:
+ scan.walk_root_for("local", r"R:\media2", declared_roots=declared,
+ mounts={"local": (str(self.media),)}, windows=False)
+ self.assertIn("第 2 个声明根", str(caught.exception))
+
def test_a_directory_outside_the_mount_is_refused(self):
with self.assertRaises(scan.ScanTargetError) as caught:
scan.ledger_root_for("local", "/somewhere/else", declared_roots=self.DECLARED,
- mounts={"local": str(self.media)}, windows=False)
+ mounts={"local": (str(self.media),)}, windows=False)
self.assertIn("挂载点", str(caught.exception))
class ScanTargetTests(unittest.TestCase):
"""写入侧门槛:`location` 与扫描根必须对得上(ADR-0023 第 2 阶段),口径与脚本时期一致。"""
- DECLARED = {"local": r"R:\media", "115": "B:/"}
+ DECLARED = {"local": (r"R:\media",), "115": ("B:/",)}
def test_the_declared_root_and_its_subdirectories_are_accepted(self):
for location, root in (("local", r"R:\media"), ("local", r"R:\media\创作者"),