Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(config): 按媒体配置解析路径并补齐 NAS 部署指引

longmeidao00ae3c4135b2
diff --git a/.claude/skills/peach-cross-platform/SKILL.md b/.claude/skills/peach-cross-platform/SKILL.md
index 392c8c514..48fa951d2 100644
--- a/.claude/skills/peach-cross-platform/SKILL.md
+++ b/.claude/skills/peach-cross-platform/SKILL.md
@@ -5,7 +5,7 @@ description: 在 macOS 上开工、改动路径解析或挂载判定、遇到 gi
# 跨 Windows / macOS 双机开发
-最后复核:2026-10-18
+最后复核:2026-10-24
证据来源:`src/peach/platform.py`、ADR-0017、2026-08-19 的 macOS 迁移实测、
2026-08-21 的 Windows 现状核对,以及 2026-09-14 用 junction 复现的临时目录别名。
@@ -16,8 +16,8 @@ description: 在 macOS 上开工、改动路径解析或挂载判定、遇到 gi
## 路径口径
-账本里的 `asset.path` **一律是 Windows 形态**:`R:\Media\...`(本地硬盘)、
-`B:\...`(115)、`A:\...`(PikPak)。
+账本里的 `asset.path` **一律是 Windows 形态**,例如 `R:\Media\...`。
+盘符与目录由媒体来源配置声明,来源与盘符没有固定对应关系。
不要为了 macOS 把账本改写成 POSIX 路径。翻译只发生在读取期,收敛在
`src/peach/platform.py` 一处;写回账本的索引脚本仍只在 Windows 上跑,路径口径
@@ -38,7 +38,7 @@ CloudDrive 在 Windows 是盘符、在 macOS 是 macFUSE 挂载点,这层不
判定。
- **挂载点「在不在」的判据是能否列出第一个条目**,不是 `is_dir()`。CloudDrive 掉线后
挂载点目录仍然存在,读一个条目才会报 `Device not configured`。见 `root_online`。
-- **磁盘闸门看系统盘**:Windows `C:`、macOS `/`,用 `system_volume()`。CloudDrive 的
+- **磁盘闸门看系统盘**:Windows 从系统目录查询所在卷、macOS 使用 `/`,用 `system_volume()`。CloudDrive 的
下载块缓存在两个平台都落在系统盘;写死 `C:/` 会让 macOS 侧直接抛 `FileNotFoundError`。
另外 `PidFileLock._running` 要吞掉 `OverflowError`:Windows 写下的 PID 可能超出 POSIX
diff --git a/README.en.md b/README.en.md
index bf3819d08..13864fd8a 100644
--- a/README.en.md
+++ b/README.en.md
@@ -112,6 +112,8 @@ Requires Git, uv and Python 3.14 or newer. See [running from source](docs/OPERAT
See [Docker deployment](docs/DOCKER.md) for setup and supported configurations.
+For LAN access on fnOS or another NAS, set Compose's `PEACH_BIND` to the NAS LAN IP; the default accepts connections only from the host. Run `peach token` in the container terminal to view the initial login token. Enter the actual container media path; no specific drive letters are required. See [NAS first run](docs/DOCKER.md#飞牛其他-nas-与局域网访问).
+
## FAQ
- **Will it change my files?** Scanning and filling in details leave originals untouched. Manual organization renames or moves files; emptying the trash deletes files, and resource-sync cleanup removes empty folders. Each requires confirmation.
diff --git a/README.md b/README.md
index 4dfa19df3..11b0b6803 100644
--- a/README.md
+++ b/README.md
@@ -112,6 +112,8 @@ macOS 可在本机构建独立 `.app` 与 DMG,内含 FFmpeg、ffprobe、untrun
部署步骤与支持范围见 [Docker 部署](docs/DOCKER.md)。
+飞牛或其他 NAS 从局域网访问时,需将 Compose 的 `PEACH_BIND` 设为 NAS 的局域网 IP;默认只接受宿主机访问。初始口令在容器终端运行 `peach token` 查看,媒体目录填写容器内实际路径,无需使用指定盘符。见 [NAS 首次运行](docs/DOCKER.md#飞牛其他-nas-与局域网访问)。
+
## 常见问题
- **会改我的文件吗?** 扫描、补资料不碰原文件。手动整理会改名或移动;清空回收站会删除文件,资源同步中的清理会删除空目录,均需确认。
diff --git a/compose.yaml b/compose.yaml
index 3c845b539..7aaf5ad01 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -6,6 +6,8 @@ services:
restart: unless-stopped
stop_grace_period: 75s
ports:
+ # NAS / 局域网:在 .env 中设置 PEACH_BIND 为宿主机的局域网 IP。
+ # 127.0.0.1 仅供宿主机访问;PEACH_PORT 可修改宿主机端口。
- "${PEACH_BIND:-127.0.0.1}:${PEACH_PORT:-8900}:8900"
volumes:
- peach-data:/data
diff --git a/docs/CLOUDDRIVE.md b/docs/CLOUDDRIVE.md
index b74e9f0f3..c604d623e 100644
--- a/docs/CLOUDDRIVE.md
+++ b/docs/CLOUDDRIVE.md
@@ -102,7 +102,7 @@ CloudDrive2 有三种缓存,各自单独设置,改了一个不会影响另
## 让网盘里的新文件自动入库
-Peach 不实时监视网盘目录,因为每列一次目录都是一次网络请求。如果希望 `B:`(115)和 `A:`(PikPak)里新存进去的文件立刻出现在 Peach,需要让 CloudDrive2 主动通知 Peach。
+Peach 不实时监视网盘目录,因为每列一次目录都是一次网络请求。如果希望网盘里新存进去的文件立刻出现在 Peach,需要让 CloudDrive2 主动通知 Peach。目录与来源取自媒体库配置,不要求固定盘符。
这个通知(webhook)是 CloudDrive2 的会员功能。不配置也不影响其他功能,新文件仍由定期的全量扫描发现。设计说明见 [ADR-0041](adr/0041-new-files-are-pushed-in-scanning-is-the-backstop.md)。
diff --git a/docs/DOCKER.md b/docs/DOCKER.md
index a4f378558..d6c2e421d 100644
--- a/docs/DOCKER.md
+++ b/docs/DOCKER.md
@@ -16,6 +16,24 @@ CloudDrive2 与 Peach 分别运行。NAS 已有 CloudDrive2 时直接复用;
## 首次运行与访问
+### 飞牛、其他 NAS 与局域网访问
+
+浏览器在另一台电脑上时,访问地址使用 NAS 的局域网 IP。Compose 默认的 `127.0.0.1` 只允许宿主机访问;容器显示运行成功不代表局域网端口已开放。
+
+在 `compose.yaml` 同目录创建 `.env`,将下面的示例 IP 和目录换成 NAS 的实际值。`PEACH_PORT` 是浏览器使用的宿主机端口,可自行选择:
+
+```dotenv
+PEACH_BIND=192.0.2.10
+PEACH_PORT=8900
+PEACH_MEDIA_ROOT=/srv/videos
+```
+
+`192.0.2.10` 是文档示例地址,不能直接用于部署。NAS 管理界面支持 Compose 环境变量时,也可在那里填写这三个值。应用配置并重新创建容器后,打开 `http://<NAS 局域网 IP>:<PEACH_PORT>`。不要在另一台电脑上用 `127.0.0.1` 访问 NAS。
+
+登录口令由 Peach 随机生成,没有通用初始密码。在 NAS 的容器管理界面打开 Peach 容器终端,运行 `peach token` 查看;通过宿主机 Compose 终端时运行 `docker compose exec peach peach token`。登录后设置访问密码。
+
+### 初始化与管理
+
使用 Compose 启动后,Peach 会为全新数据卷创建配置、数据库和随机登录口令。已有配置保持原值;如果已有数据库但缺少配置文件,服务拒绝启动,需要恢复配置文件。初始化日志只显示口令文件位置。
在容器终端运行 `peach token` 取得登录口令,在浏览器登录后设置访问密码。配置页要求登录,并且连接必须来自容器本机或私有网络;携带代理转发头的管理请求会被拒绝。通过配置页保存后,服务自动读取配置;勾选扫描时会启动资料处理。
@@ -38,6 +56,8 @@ docker compose exec peach python -c "from peach import settings_file as s; print
以下说明供手动编辑配置或在多台 Peach 之间对应已有媒体目录时参考。网页保存时会处理 `[media.locations]` 和 `[media.mounts]`:前者保存数据库中的路径前缀,后者保存实际读取文件的目录。Peach 数据库在所有系统上都使用 Windows 格式保存影片路径;Linux 无需创建相同的盘符或目录。
+全新配置不预设媒体目录。盘符不决定来源,115 与 PikPak 均可选择任意已挂载目录;容器内填写实际路径即可。文档中的盘符只是数据库路径示例。
+
以下三个路径各有用途。假设宿主机媒体目录为 `/srv/videos`,Compose 将它挂到容器 `/media`:
| 位置 | 示例 | 用途 |
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 5e9f3920e..13fa8b6c2 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -465,7 +465,7 @@ untrunc 按相同顺序查找,对应目录为 `tools/untrunc`。独立程序
- 浏览器不支持的 AVI、MKV 等格式,Peach 会转成兼容的 MP4 缓存起来再播放,**不会改动原始文件**。第一次播放前会先探测文件,最长 20 秒。
- 能保留的码流尽量保留:H.264(`yuv420p`/`yuvj420p`)视频不重新编码,AAC 音频直接复制,其他音频转成 AAC。需要重新编码视频时,自动模式依次尝试硬解加硬编、软解加硬编、全软件;Windows 使用 NVIDIA(`scale_cuda` + NVENC),Linux 使用可用 VAAPI 节点,macOS 使用 VideoToolbox。macOS 硬件编码通过实际合成帧探测,并禁止系统软件编码冒充硬件;H.264 输出采用 6 Mbit/s。AV1 硬解显式使用 FFmpeg 原生 `av1` 解码器,设备不支持时回退 dav1d 软件解码。
- 同时最多进行 2 个转码或探测,单次最长 1 小时,关掉播放页会取消对应的任务。
-- 115 和 PikPak 的视频通过 CloudDrive2 挂载的 `B:`、`A:` 播放。能不能播,以在 Peach 里实际打开一个已知视频为准。
+- 115 和 PikPak 的视频通过媒体库配置中声明的挂载目录播放。能不能播,以在 Peach 里实际打开一个已知视频为准。
Peach 配置「媒体库与入库 → 视频预览」中的「抽帧解码方式」与「应用与维护 → 视频播放」中的「转码方式」分别保存为运行 Peach 那台电脑的偏好,两者互不影响,均可选择「自动(硬件优先)」或软件。抽帧设置控制封面、九宫格与时间轴;扫描、读 NFO 和时长探测不依赖 GPU。播放设置只控制 Peach 服务端的整片与 HLS 转码,浏览器直接播放时自行选择解码方式。保存无需重启,对新任务生效;已生成的有效缓存继续使用,运行中的 FFmpeg 不被强行中断。macOS 抽帧在同一超时预算内尝试 VideoToolbox,Windows 抽帧对 H.264、HEVC、VP9、AV1 尝试 D3D11VA,失败后都回退软件;视频编码格式探测按文件大小和修改时间缓存。Windows 播放的自动档依次探测 NVENC、AMF、QSV 编码,三者都不可用时用 D3D11VA 解码再交给 libx264;AMF 只接受 AMD 显卡上的 D3D11 设备,Peach 按显卡序号逐个探测。偏好通过 `/api/media-processing` 的 GET/POST 读写,`preview_acceleration` 和 `playback_acceleration` 分别接受 `auto/software`;省略的字段保持现值。这个接口与时间轴缩略图的 `/api/thumbnail-jobs` 和 `/api/configuration/*` 一样只接受运行 Peach 的电脑发来的请求,其他设备即使已登录或处于开放访问也返回 403。`PEACH_TRANSCODE_BACKEND` 可用于管理员诊断,支持 `auto/software/nvenc/amf/qsv/vaapi/videotoolbox`,显式 `software` 会保持禁用硬件。
@@ -479,6 +479,8 @@ Peach 配置「媒体库与入库 → 视频预览」中的「抽帧解码方式
先点「预览」核对范围和逐文件变化,再确认执行。修改路径、来源或模板后须重新预览。目标已存在的条目跳过,已执行批次可用「回滚上一批」恢复名称、位置和账本路径。PikPak 界面仅提供预览,改名仍需官方核验通道。
+PikPak 官方核验通道使用「推送发现」中该媒体根对应的唯一 CloudDrive 路径前缀,支持自定义盘符与子目录。缺少映射或同一媒体根对应多条映射时拒绝执行。WebDAV 账号根由 CloudDrive 返回,认证直链须匹配 PikPak 官方域名和账号内路径;每批操作限于样本所属的媒体根。
+
## 资源同步与删除
哪些操作会删除文件、哪些不会,请在动手前看清楚。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index f94fbe0a5..47423d61b 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -1,5 +1,11 @@
# 复用清单
+## 媒体目录与整理路径映射
+
+PikPak 整理复用项目已有 `PushDiscoverySettings`、`CloudPrefix` 与 `map_cloud_path`,与推送发现共用配置,不引入第二份盘符或 CloudDrive 路径表。CloudDrive RPC 继续使用现有固定版本的 gRPC/protobuf;路径归属与账号内 WebDAV 目录核验属于 Peach 的写入边界。不同盘符、子目录、云端名称、越界与冲突由临时夹具和模拟 RPC 验证,不触碰真实账号或账本。
+
+Windows 系统卷通过系统原生 `GetWindowsDirectoryW` 获取,其他平台使用根卷。此改动没有新增第三方依赖;现有依赖版本与许可继续以 `pyproject.toml`、`uv.lock` 和下文登记为准。
+
## 文件名包装与补充回归
论坛 URL 包装与明确 BD Remux 尾部番号参考 [PR #123](https://github.com/peach-mitao/peach/pull/123),固定 revision 为 `edde1fffb2c4690b7b78224dbd70dd7dfed786b3`,沿用本仓库 AGPL-3.0-or-later 许可。包装只解开一层,内部重用现有文件名与用户识别规则;Remux 的括号番号必须是唯一发行身份。普通处理后缀、日期分隔符和「番号+片名」继续由既有解析器处理,不增加另一套处理词表或递归解析。
diff --git a/scripts/organize_library_dirs.py b/scripts/organize_library_dirs.py
index fa4b39465..d585f387b 100644
--- a/scripts/organize_library_dirs.py
+++ b/scripts/organize_library_dirs.py
@@ -525,7 +525,7 @@ def restore(pairs):
return failures
def staging_name(source):
- prefix = 'peach-organize-' if PureWindowsPath(source).drive.casefold() == 'a:' else '.peach-organize-'
+ prefix = 'peach-organize-' if resolve_root(source, location_roots())[0] == 'pikpak' else '.peach-organize-'
return prefix + hashlib.sha256(source.encode()).hexdigest()[:20]
@@ -784,7 +784,7 @@ def provider_moves(pairs, root, allow_intermediate=True):
result = []
for old, new in pairs:
source, target = PureWindowsPath(old), PureWindowsPath(new)
- if source.drive.casefold() == 'a:' and source.parent != target.parent and source.name != target.name:
+ if source.parent != target.parent and source.name != target.name:
if not allow_intermediate:
raise ValueError('目录折叠的改名中间路径需单独复核')
intermediate = str(source.with_name(target.name))
@@ -891,7 +891,7 @@ def run_apply(stage, backup, limit, seconds, location=None, retry_failed=False,
if organize.unverified_location(owner)})
if blocked:
raise ValueError('冻结批次含 ' + '、'.join(blocked) + ' 来源的操作,挂载改名无法核验云端结果;'
- 'A 盘须用 --location pikpak --pikpak-webdav 经官方通道执行,其他来源用 --location 限定')
+ 'PikPak 须用 --location pikpak --pikpak-webdav 经官方通道执行,其他来源用 --location 限定')
lock = PidFileLock(OUT/'directory-job.lock')
lock.acquire()
db = None
@@ -1020,7 +1020,7 @@ def run_rollback(stage, batch=None, backup=None, location=None, apply=False):
blocked = sorted({owner for *_, owner, _ in candidates if organize.unverified_location(owner)})
if blocked:
raise ValueError('撤回含 ' + '、'.join(blocked) + ' 来源的操作,挂载改名无法核验云端结果;'
- 'A 盘须用 --location pikpak --pikpak-webdav 经官方通道撤回')
+ 'PikPak 须用 --location pikpak --pikpak-webdav 经官方通道撤回')
lock = PidFileLock(OUT/'directory-job.lock')
lock.acquire()
db = None
@@ -1051,12 +1051,14 @@ def run_rollback(stage, batch=None, backup=None, location=None, apply=False):
lock.release()
def pikpak_channel(stage, batch):
- """A 盘批次的官方核验改名通道。"""
+ """PikPak 批次的官方核验改名通道。"""
from peach.organize_clouddrive import pikpak_renames
payload = json.loads((OUT/f'{stage}-{batch}-manifest.json').read_text(encoding='utf-8'))
- rows = [row for op in payload['operations'] for row in op['rows'] if row['path'].startswith('A:')]
+ roots = payload['roots'].get('pikpak', ())
+ rows = [row for op in payload['operations'] for row in op['rows']
+ if any(beneath(row['path'], root) for root in roots)]
if not rows:
- raise ValueError('冻结批次没有 A 盘资源')
+ raise ValueError('冻结批次没有已声明的 PikPak 资源')
return pikpak_renames(rows[0]['path'], payload['roots'])
def self_check():
@@ -1139,7 +1141,7 @@ if __name__ == '__main__':
parser.add_argument('--retry-failed', action='store_true')
parser.add_argument('--skip-collapses', action='store_true')
parser.add_argument('--pikpak-webdav', action='store_true',
- help='A 盘批次经 CloudDrive 官方改名与移动执行,并以官方完整目录核验;A 盘操作必须带它')
+ help='PikPak 批次经 CloudDrive 官方改名与移动执行,并以官方完整目录核验;PikPak 操作必须带它')
parser.add_argument('--batch', type=lambda value: value if re.fullmatch(r'[a-zA-Z0-9_-]+', value)
else parser.error('批次编号只能包含字母、数字、下划线与连字号'))
parser.add_argument('--rollback', action='store_true',
diff --git a/scripts/smoke_docker.py b/scripts/smoke_docker.py
index 7b993f1f0..12ad7a0d1 100644
--- a/scripts/smoke_docker.py
+++ b/scripts/smoke_docker.py
@@ -111,9 +111,10 @@ def main() -> None:
docker("exec", name, "ffmpeg", "-v", "error", "-f", "lavfi", "-i", "color=c=black:s=64x64:r=1",
"-t", "2", "-c:v", "libx264", "/data/smoke-media/fixture.mp4")
configuration = json.loads(request(name, "/api/configuration"))
+ assert configuration['media_sources'] == [], configuration['media_sources']
saved = json.loads(request(name, "/api/configuration", body={
"revision": configuration["revision"], "port": configuration["port"], "scan_now": True,
- "media_sources": [{"location": "local", "root": "R:\\media", "path": "/data/smoke-media"}],
+ "media_sources": [{"location": "local", "path": "/data/smoke-media"}],
}))
assert saved.get("saved"), saved
time.sleep(2)
diff --git a/src/peach/cli.py b/src/peach/cli.py
index 5bcd10fd4..1c8736d5c 100644
--- a/src/peach/cli.py
+++ b/src/peach/cli.py
@@ -314,10 +314,10 @@ def _parse_mounts(
key = key.strip()
if not separator or not key:
raise SystemExit(f"--mount 要写成 来源ID=路径,收到:{chunk}")
- if known and key not in known:
+ if key not in known:
raise SystemExit(
f"--mount 的来源 ID 未在 [media.locations] 声明:{key}"
- f"(已知:{'、'.join(sorted(known))})"
+ f"(已知:{'、'.join(sorted(known)) or '尚未声明媒体来源'})"
)
mounts.setdefault(key, []).append(value.strip())
return {key: tuple(item for item in values if item) for key, values in mounts.items()}
@@ -643,9 +643,9 @@ def _report_blanks(config: settings_file.PeachConfig) -> None:
table, _, name = dotted.partition(".")
if not getattr(getattr(config, table), name):
blanks.append(f" {dotted} 留空 → {effect};要填就重跑并加 {flag}")
- if not config.mounts and os.name != "nt":
+ if config.locations and not config.mounts and os.name != "nt":
# Windows 上盘符本身就是挂载点,空表是正常的,提示它只会让人去填没用的值。
- known = "、".join(sorted(config.locations)) or "local"
+ known = "、".join(sorted(config.locations))
blanks.append(
f" [media.mounts] 为空 → 无法读取媒体来源的目录;"
f"可用 --mount <媒体来源ID>=<媒体目录> 指定目录(已知来源:{known})"
diff --git a/src/peach/organize_clouddrive.py b/src/peach/organize_clouddrive.py
index f9712b957..f493df26b 100644
--- a/src/peach/organize_clouddrive.py
+++ b/src/peach/organize_clouddrive.py
@@ -8,7 +8,8 @@
from __future__ import annotations
from contextlib import closing, contextmanager
-from pathlib import PureWindowsPath
+from dataclasses import dataclass
+from pathlib import PurePosixPath, PureWindowsPath
import time
from urllib.parse import quote, unquote, urlsplit
@@ -24,6 +25,7 @@ from .follow_secrets import CredentialStore
from .config import DATABASE_PATH, SECRETS_DIR, STATE_DIR
from .peach_proxy import http_client
from .scripting import open_readonly
+from .push_discovery import CloudPrefix, PushDiscoverySettings, map_cloud_path, normalise_prefix
MAX_RESPONSE = 2 * 1024 * 1024
MAX_FILES = 10000
@@ -99,29 +101,78 @@ def _messages():
DownloadRequest, DownloadReply, ListRequest, ListReply, RenameRequest, MoveRequest = _messages()
+@dataclass(frozen=True)
+class PikPakPaths:
+ """已声明媒体根、CloudDrive 前缀和账号内 WebDAV 目录的对应关系。"""
+
+ root: str
+ remote: str
+ dav_root: str = ""
+
+ def __post_init__(self):
+ root = PureWindowsPath(self.root)
+ if not root.is_absolute() or root.drive.startswith('\\\\') or '..' in root.parts:
+ raise ValueError('PikPak 媒体根必须是已声明的 Windows 格式绝对路径')
+ for path in (self.remote, self.dav_root):
+ if path and (not path.startswith('/') or any(
+ part in ('.', '..') or '\\' in part or ':' in part
+ or any(ord(char) < 32 for char in part) for part in path.split('/'))):
+ raise ValueError('PikPak 云端目录格式无效')
+ if normalise_prefix(self.remote) == '/':
+ raise ValueError('PikPak 云端前缀不能是 CloudDrive 总根目录')
+
+ def relative(self, path: str) -> tuple[str, ...]:
+ item = PureWindowsPath(path)
+ if not item.is_absolute() or '..' in item.parts or any(
+ ':' in part or any(ord(char) < 32 for char in part) for part in item.parts[1:]):
+ raise ValueError('路径越出已声明的 PikPak 来源')
+ try:
+ return item.relative_to(PureWindowsPath(self.root)).parts
+ except ValueError:
+ raise ValueError('路径越出已声明的 PikPak 来源') from None
+
+ def cloud_path(self, path: str) -> str:
+ return normalise_prefix(self.remote) + ''.join('/' + part for part in self.relative(path))
+
+ def dav_path(self, path: str) -> str:
+ return self.dav_root.rstrip('/') + '/' + '/'.join(self.relative(path))
+
+
+def _configured_paths(sample_path: str, roots, prefixes) -> PikPakPaths:
+ """从当前 PikPak 媒体根选取样本所属的唯一云端映射。"""
+ sample = PureWindowsPath(sample_path)
+ candidates = [PureWindowsPath(root) for root in roots.get('pikpak', ())
+ if sample.is_relative_to(PureWindowsPath(root))]
+ if not candidates:
+ raise ValueError('认证样本不属于已声明的 PikPak 媒体根')
+ root = max(candidates, key=lambda item: len(item.parts))
+ matches = [entry for entry in prefixes if PureWindowsPath(entry.root) == root]
+ if len(matches) != 1:
+ raise ValueError('请在推送发现中为该 PikPak 媒体根配置唯一的 CloudDrive 路径前缀')
+ mapping = PikPakPaths(str(root), matches[0].prefix)
+ mapping.relative(sample_path)
+ return mapping
+
+
class PikPakDav:
- """A 盘的一次移动:官方接口提交一次,官方完整目录确认结果。
+ """已声明 PikPak 目录的一次移动:官方接口提交一次,官方完整目录确认结果。
`listing(path)` 返回官方目录的完整成员;`rename`/`move_remote` 提交同父改名与保留名称的
跨目录移动,回 `ACCEPTED`、`REJECTED` 或 `None`。
"""
- def __init__(self, http: httpx.Client, root: str, refresh, *, listing, rename, move_remote, confirm_attempts=1):
- self.http, self.root, self.refresh = http, PureWindowsPath(root), refresh
+ def __init__(self, http: httpx.Client, mapping: PikPakPaths, refresh, *, listing, rename, move_remote, confirm_attempts=1):
+ self.mapping = mapping
+ self.http, self.root, self.refresh = http, PureWindowsPath(mapping.root), refresh
self.rename = rename
self.listing = listing
self.move_remote = move_remote
if not 1 <= confirm_attempts <= 4:
raise ValueError('移动确认次数越出预算')
self.confirm_attempts = confirm_attempts
- if self.root != PureWindowsPath('A:\\'):
- raise ValueError('HTTPS WebDAV 整理只支持已声明的 A 盘根目录')
def url(self, path: str) -> str:
- item = PureWindowsPath(path)
- if item.drive.casefold() != self.root.drive.casefold() or '..' in item.parts or not item.is_absolute():
- raise ValueError('WebDAV 路径越出已声明来源')
- return DAV_ORIGIN + quote('/' + '/'.join(item.parts[1:]), safe='/@')
+ return DAV_ORIGIN + quote(self.mapping.dav_path(path), safe='/@')
def request(self, method, path, **kwargs):
try:
@@ -157,6 +208,9 @@ class PikPakDav:
return files
def ensure_parent(self, path):
+ self.mapping.relative(path)
+ if PureWindowsPath(path) == self.root:
+ return
parent = PureWindowsPath(path).parent
if parent == self.root:
return
@@ -238,16 +292,17 @@ class PikPakDav:
raise UnconfirmedMove('移动状态未确认,保留意图回执并停止;不重复操作、不写数据库') from None
-def _cloud_listing(cloud, path):
+def _cloud_listing(cloud, path, mapping):
"""逐层完整读取官方目录元数据并校验来源、父目录与重名。"""
- item = PureWindowsPath(path)
- if item.drive.casefold() != 'a:' or not item.is_absolute() or '..' in item.parts or len(item.parts) > 32:
- raise ValueError('官方目录路径越出 A 盘或超过层级预算')
+ relative = mapping.relative(path)
+ if len(relative) > 32:
+ raise ValueError('官方目录路径超过层级预算')
previous = None
- for parent in (*reversed(item.parents), item):
+ for depth in range(len(relative) + 1):
+ parent = PureWindowsPath(mapping.root, *relative[:depth])
if previous is not None and not any(PureWindowsPath(row['path']) == parent and row['directory'] for row in previous):
raise FileNotFoundError('官方父目录未列出所需目录')
- request = ListRequest(path=('/Pikpak/' + '/'.join(parent.parts[1:])).rstrip('/'), forceRefresh=True)
+ request = ListRequest(path=mapping.cloud_path(str(parent)), forceRefresh=True)
call = cloud.channel.unary_stream(SERVICE + 'GetSubFiles',
request_serializer=ListRequest.SerializeToString, response_deserializer=ListReply.FromString)
stream = call(request, timeout=15, metadata=(('authorization', 'Bearer ' + cloud.token),))
@@ -255,9 +310,8 @@ def _cloud_listing(cloud, path):
try:
for response in stream:
for member in response.subFiles:
- if not member.fullPathName.startswith('/Pikpak/'):
- raise ValueError('官方目录成员来自其他来源')
- name = PureWindowsPath('A:\\' + member.fullPathName[len('/Pikpak/'):].replace('/', '\\'))
+ name = PureWindowsPath(map_cloud_path(member.fullPathName,
+ (CloudPrefix(mapping.remote, mapping.root),)))
if name.parent != parent or str(name).casefold() in seen or member.size < 0:
raise ValueError('官方目录成员越界、重名或体积无效')
seen.add(str(name).casefold())
@@ -272,23 +326,24 @@ def _cloud_listing(cloud, path):
return previous
-def _fallback_samples():
+def _fallback_samples(mapping):
+ prefix = str(PureWindowsPath(mapping.root)).rstrip('\\') + '\\'
with closing(open_readonly(DATABASE_PATH)) as db:
return [row[0] for row in db.execute(
"SELECT path FROM asset WHERE location='pikpak' AND disposal IS NULL AND medium='image' "
- "AND path LIKE 'A:%' ORDER BY id LIMIT 2")]
+ "AND lower(substr(path,1,?))=lower(?) ORDER BY id LIMIT 2", (len(prefix), prefix))]
-def _move_remote(cloud, source, target):
+def _move_remote(cloud, source, target, mapping):
"""官方同来源移动保持原名,显式跳过冲突并关闭跨云及递归合并。"""
from . import downloads_clouddrive_pb2 as pb
old, new = PureWindowsPath(source), PureWindowsPath(target)
- if (old.drive.casefold() != 'a:' or new.drive.casefold() != 'a:' or not old.is_absolute()
- or not new.is_absolute() or '..' in old.parts or '..' in new.parts
- or old.name != new.name or old.parent == new.parent):
+ old_remote, new_remote = mapping.cloud_path(source), mapping.cloud_path(target)
+ if (old.name != new.name or old.parent == new.parent
+ or PureWindowsPath(mapping.root) in (old, new)):
raise ValueError('官方移动来源、父目录或文件名不符')
- request = MoveRequest(theFilePaths=['/Pikpak/' + '/'.join(old.parts[1:])],
- destPath=('/Pikpak/' + '/'.join(new.parent.parts[1:])).rstrip('/'),
+ request = MoveRequest(theFilePaths=[old_remote],
+ destPath=str(PurePosixPath(new_remote).parent),
conflictPolicy=2, moveAcrossClouds=False, handleConflictRecursively=False)
stub = cloud.channel.unary_unary(SERVICE + 'MoveFile', request_serializer=MoveRequest.SerializeToString,
response_deserializer=pb.FileOperationResult.FromString)
@@ -299,59 +354,56 @@ def _move_remote(cloud, source, target):
return _submission_status(error)
-def _rename_remote(cloud, source, target):
+def _rename_remote(cloud, source, target, mapping):
"""官方同父改名;`success=true` 只是提交结果,生效与否由调用方读官方目录确认。"""
from . import downloads_clouddrive_pb2 as pb
old, new = PureWindowsPath(source), PureWindowsPath(target)
- if (old.drive.casefold() != 'a:' or not old.is_absolute() or '..' in old.parts
- or old.parent != new.parent or '..' in new.parts):
- raise ValueError('官方改名只支持 A 盘内的同父目录')
+ old_remote = mapping.cloud_path(source)
+ mapping.relative(target)
+ if old.parent != new.parent or PureWindowsPath(mapping.root) in (old, new):
+ raise ValueError('官方改名只支持已声明来源内的同父目录')
stub = cloud.channel.unary_unary(SERVICE + 'RenameFile',
request_serializer=RenameRequest.SerializeToString, response_deserializer=pb.FileOperationResult.FromString)
try:
- reply = stub(RenameRequest(path='/Pikpak/' + '/'.join(old.parts[1:]), newName=new.name), timeout=15,
+ reply = stub(RenameRequest(path=old_remote, newName=new.name), timeout=15,
metadata=(('authorization', 'Bearer ' + cloud.token),))
return ACCEPTED if reply.success else REJECTED
except grpc.RpcError as error:
return _submission_status(error)
-def _refresh_listing(cloud, path):
- """限定 A 盘目录缓存过期后按完整祖先链读取实际成员。"""
+def _refresh_listing(cloud, path, mapping):
+ """使已声明目录的缓存过期,再按完整祖先链读取实际成员。"""
from . import downloads_clouddrive_pb2 as pb
- item = PureWindowsPath(path)
- if item.drive.casefold() != 'a:' or not item.is_absolute() or '..' in item.parts:
- raise ValueError('目录缓存范围越出 A 盘')
+ remote = mapping.cloud_path(path)
stub = cloud.channel.unary_unary(SERVICE + 'ForceExpireDirCache',
request_serializer=pb.FileRequest.SerializeToString, response_deserializer=Empty.FromString)
try:
- stub(pb.FileRequest(path=('/Pikpak/' + '/'.join(item.parts[1:])).rstrip('/')),
+ stub(pb.FileRequest(path=remote),
timeout=15, metadata=(('authorization', 'Bearer ' + cloud.token),))
except grpc.RpcError as error:
if error.code() != grpc.StatusCode.NOT_FOUND:
raise OSError('目录缓存刷新未取得:' + error.code().name) from None
- return _cloud_listing(cloud, path)
+ return _cloud_listing(cloud, path, mapping)
-def _download_headers(cloud, sample_path):
+def _download_headers(cloud, sample_path, mapping):
paths = [sample_path]
stub = cloud.channel.unary_unary(SERVICE + 'GetDownloadUrlPath',
request_serializer=DownloadRequest.SerializeToString, response_deserializer=DownloadReply.FromString)
for index in range(3):
if index >= len(paths):
break
- path = PureWindowsPath(paths[index])
- if path.drive.casefold() != 'a:' or not path.is_absolute() or '..' in path.parts:
- raise ValueError('认证样本越出 A 盘来源')
- relative = '/' + '/'.join(path.parts[1:])
+ path = paths[index]
+ relative = mapping.dav_path(path)
try:
- reply = stub(DownloadRequest(path='/Pikpak' + relative, get_direct_url=True), timeout=15,
+ reply = stub(DownloadRequest(path=mapping.cloud_path(path), get_direct_url=True), timeout=15,
metadata=(('authorization', 'Bearer ' + cloud.token),))
except grpc.RpcError as error:
if error.code() != grpc.StatusCode.NOT_FOUND:
raise ValueError('既有 CloudDrive 直链认证未取得') from None
if index == 0:
- paths.extend(p for p in _fallback_samples() if p != sample_path)
+ paths.extend(p for p in _fallback_samples(mapping) if p != sample_path)
continue
url = urlsplit(reply.directUrl)
if url.hostname != 'dav.mypikpak.com' or url.scheme not in ('http', 'https') or url.username or url.query or unquote(url.path) != relative:
@@ -368,22 +420,32 @@ def _download_headers(cloud, sample_path):
@contextmanager
def pikpak_renames(sample_path: str, roots):
"""仅显式启用的目录批次复用既有 CloudDrive 认证。"""
- if tuple(roots.get('pikpak', ())) != ('A:\\',):
- raise ValueError('PikPak 来源根必须唯一声明为 A 盘')
+ prefixes = PushDiscoverySettings(STATE_DIR).load(roots).prefixes
+ mapping = _configured_paths(sample_path, roots, prefixes)
credential = CredentialStore(SECRETS_DIR).load(CLOUDDRIVE_CREDENTIAL)
if not credential or not credential.values.get('token'):
raise ValueError('既有 CloudDrive 令牌未取得')
address = DownloadSettings(STATE_DIR).load().clouddrive_address or discover()
with CloudDriveClient(address, credential.values['token'], timeout=15) as cloud:
- info = cloud.find('/Pikpak')
+ info = cloud.find(mapping.remote)
if info is None or info.CloudAPI.name.casefold() != 'webdav':
raise ValueError('既有 PikPak WebDAV 来源未取得')
- headers = _download_headers(cloud, sample_path)
+ account_root = info.CloudAPI.path if info.CloudAPI.HasField('path') else ''
+ if not account_root and info.isCloudRoot:
+ account_root = mapping.remote
+ if not account_root:
+ raise ValueError('CloudDrive 未返回 WebDAV 账号根目录')
+ try:
+ tail = PurePosixPath(mapping.remote).relative_to(PurePosixPath(account_root))
+ except ValueError:
+ raise ValueError('CloudDrive 路径前缀不属于返回的账号根目录') from None
+ mapping = PikPakPaths(mapping.root, mapping.remote, '/' + '/'.join(tail.parts))
+ headers = _download_headers(cloud, sample_path, mapping)
with http_client(root=SECRETS_DIR, headers=headers, timeout=20, follow_redirects=False) as http:
- dav = PikPakDav(http, 'A:\\', lambda path: _refresh_listing(cloud, path),
- listing=lambda path: _cloud_listing(cloud, path),
- rename=lambda source, target: _rename_remote(cloud, source, target),
- move_remote=lambda source, target: _move_remote(cloud, source, target),
+ dav = PikPakDav(http, mapping, lambda path: _refresh_listing(cloud, path, mapping),
+ listing=lambda path: _cloud_listing(cloud, path, mapping),
+ rename=lambda source, target: _rename_remote(cloud, source, target, mapping),
+ move_remote=lambda source, target: _move_remote(cloud, source, target, mapping),
confirm_attempts=4)
with organize.verified_renames('pikpak', dav.move):
yield dav
diff --git a/src/peach/platform.py b/src/peach/platform.py
index 29915f8ed..072fa31d5 100644
--- a/src/peach/platform.py
+++ b/src/peach/platform.py
@@ -1,7 +1,7 @@
"""把数据库中的媒体路径转换为当前系统可以读取的文件路径。
-账本里的 `asset.path` 一律是 Windows 形态的绝对路径:`R:\\media\\...`(本地硬盘)、
-`A:\\...`(PikPak)、`B:\\...`(115)。这是不变量,不随平台改写。
+账本里的 `asset.path` 一律是 Windows 形态的绝对路径,前缀取自媒体目录配置。
+来源由配置声明,与具体盘符无关;读取时按本机挂载目录转换。
`asset.location` 保存媒体来源的键,例如 local、115、pikpak(见 `media_sources.SOURCE_REGISTRY`)。
`[media.locations]` 保存每个来源在数据库中的目录前缀;`[media.mounts]` 保存本机实际目录。
@@ -153,9 +153,16 @@ def within_root(path: Path, root: Path) -> bool:
def system_volume() -> Path:
"""磁盘闸门看的那块盘。
- CloudDrive 会把下载块缓存到系统盘:Windows 是 `C:`,macOS 是根卷。
+ Windows 读取系统目录所在卷,其他平台使用根卷。
"""
- return Path("C:/") if os.name == "nt" else Path("/")
+ if os.name != "nt":
+ return Path("/")
+ import ctypes
+ buffer = ctypes.create_unicode_buffer(32768)
+ length = ctypes.windll.kernel32.GetWindowsDirectoryW(buffer, len(buffer))
+ if not 0 < length < len(buffer):
+ raise OSError("未取得 Windows 系统目录")
+ return Path(PureWindowsPath(buffer.value).anchor)
def is_windows_path(raw: str | os.PathLike[str]) -> bool:
diff --git a/src/peach/server.py b/src/peach/server.py
index 9a7d25426..86581b24e 100644
--- a/src/peach/server.py
+++ b/src/peach/server.py
@@ -84,6 +84,10 @@ def main(argv: list[str] | None = None) -> int:
for signum in (signal.SIGTERM, signal.SIGINT):
signal.signal(signum, lambda *_: stopping.set())
initialize()
+ print(f"Peach 服务监听:{args.host}:{args.port}。容器外部访问地址以宿主机端口映射为准。", flush=True)
+ print("首次登录:在运行 Peach 的环境中执行 peach token 查看口令,登录后设置访问密码。", flush=True)
+ if os.environ.get('PEACH_DISTRIBUTION') == 'docker':
+ print("NAS / 局域网访问:Compose 的 PEACH_BIND 应为宿主机局域网 IP;127.0.0.1 只允许宿主机访问。", flush=True)
return supervise(args.host, args.port, stopping)
diff --git a/src/peach/settings_file.py b/src/peach/settings_file.py
index 2969e2403..eb4781eb3 100644
--- a/src/peach/settings_file.py
+++ b/src/peach/settings_file.py
@@ -47,11 +47,7 @@ DIRECTORY_KEYS = (
#: 值是数据库 asset.path 中保存的目录前缀;各系统均使用 Windows 格式。
#: 一个来源有多个目录时写数组;[media.mounts] 按同一顺序保存本机实际目录。
#: peach.platform 在读取文件前转换路径(ADR-0023 勘误)。
-DEFAULT_LOCATION_ROOTS: dict[str, tuple[str, ...]] = {
- "local": (r"R:\media",),
- "115": ("B:/",),
- "pikpak": ("A:/",),
-}
+DEFAULT_LOCATION_ROOTS: dict[str, tuple[str, ...]] = {}
#: `[media]` 下按子表保存路径、媒体库与读取策略,没有标量键。第一阶段的 `[media] R = '...'` 是盘符键,
#: 键空间和 location ID 不同,静默接受只会让整台机器脱盘,所以要显式报升级提示。
@@ -232,7 +228,7 @@ class PeachConfig:
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` -> 数据库中的目录前缀,至少一个。
+ #: `asset.location` -> 用户声明的数据库目录前缀;未添加媒体目录时为空。
locations: dict[str, tuple[str, ...]] = field(
default_factory=lambda: dict(DEFAULT_LOCATION_ROOTS))
server: ServerSettings = ServerSettings()
@@ -370,9 +366,7 @@ def _merge(
"路径填写该来源的本机媒体目录,例如 "
"`local = '/mnt/media'`"
))
- # 文件里写了 `[media.locations]` 就以它为准:`peach init` 的问答只声明用户给过的
- # 来源,内建默认那三个示例盘符不能从旁边混进来,否则陌生人的机器上会多出两个
- # 永远脱盘的来源。没写这张表才退回内建默认。
+ # 来源只取用户声明;未填写路径表时没有媒体目录。
if _LOCATIONS_KEY in media:
locations = _root_map(_table(media, _LOCATIONS_KEY, path), path, "media.locations.")
empty = sorted(key for key, roots in locations.items() if not roots)
diff --git a/src/peach/web_batch.py b/src/peach/web_batch.py
index 815e475ed..3c1b33e72 100644
--- a/src/peach/web_batch.py
+++ b/src/peach/web_batch.py
@@ -203,7 +203,7 @@ def _quarantine_media(original: Path, *, location: str | None = None) -> Path:
"""同目录改名不支持时,小文件先保留本地完整备份再删除原文件。"""
key = uuid.uuid4().hex
name = (f'peach-purge-{key}.peach-quarantine'
- if location == 'pikpak' or PureWindowsPath(str(original)).drive.casefold() == 'a:'
+ if location == 'pikpak'
else f'.{original.name}.peach-purge-{key}.tmp')
quarantine = original.with_name(name)
try:
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 719c08699..8a4dd00f3 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -128,8 +128,11 @@ class InitCommandTests(unittest.TestCase):
self.assertIn("下一步", output)
self.certs.assert_called_once()
- def test_fresh_init_output_is_readable_by_the_settings_layer(self):
- self._init("--mdns-name", "peach-two", "--port", "9443",
+ def test_declared_mount_output_is_readable_by_the_settings_layer(self):
+ self.root.mkdir()
+ (self.root / "config.toml").write_text(
+ "[media.locations]\nlocal = ['P:\\Library']\n", encoding="utf-8")
+ self._init("--force", "--mdns-name", "peach-two", "--port", "9443",
"--mount", "local=/mnt/media")
loaded = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.root)})
self.assertTrue(loaded.present)
@@ -145,7 +148,7 @@ class InitCommandTests(unittest.TestCase):
with self.assertRaises(SystemExit) as caught:
self._init("--mount", "locla=/mnt/media")
self.assertIn("locla", str(caught.exception))
- self.assertIn("local", str(caught.exception))
+ self.assertIn("尚未声明媒体来源", str(caught.exception))
def test_mount_without_an_equals_sign_is_refused(self):
with self.assertRaises(SystemExit) as caught:
@@ -441,8 +444,7 @@ class InitDispatchTests(unittest.TestCase):
self._run(["init", "--data-root", str(self.root), "--no-input", "--force"], tty=True), 0)
self.interactive.assert_not_called()
loaded = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.root)})
- # 非交互设置写出三个来源的默认数据库路径前缀。
- self.assertEqual(set(loaded.locations), {"local", "115", "pikpak"})
+ self.assertEqual(loaded.locations, {})
class ScanCommandTests(unittest.TestCase):
diff --git a/tests/test_config.py b/tests/test_config.py
index ff2dab8ee..e224ec930 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -138,7 +138,8 @@ class DefaultsAreGenericTests(unittest.TestCase):
self.assertEqual(loaded.server.mdns_name, "peach")
self.assertEqual(loaded.server.review_writer_origin, "")
self.assertEqual(loaded.server.review_writer_proxy, "")
- # 一台新机器什么都没挂:所有来源按脱盘处理,不报错也不猜路径。
+ # 一台新机器只使用用户主动添加的目录。
+ self.assertEqual(loaded.locations, {})
self.assertEqual(loaded.mounts, {})
self.assertEqual(loaded.replication.smb_host, "")
self.assertEqual(loaded.replication.smb_user, "")
@@ -261,7 +262,7 @@ class BadFileTests(unittest.TestCase):
def test_mounts_are_keyed_by_location_id(self):
with TempTree() as tree:
- tree.write("[media.mounts]\nlocal = '/mnt/res/media'\n")
+ tree.write("[media.locations]\nlocal = 'D:\\Videos'\n[media.mounts]\nlocal = '/mnt/res/media'\n")
loaded = tree.load()
self.assertEqual(loaded.mounts, {"local": ("/mnt/res/media",)})
@@ -313,11 +314,16 @@ class BadFileTests(unittest.TestCase):
tree.load()
self.assertIn("没有配置目录前缀", str(caught.exception))
- def test_without_a_locations_table_the_builtin_defaults_apply(self):
+ def test_without_a_locations_table_no_media_roots_are_declared(self):
with TempTree() as tree:
tree.write("[server]\nport = 9100\n")
loaded = tree.load()
- self.assertEqual(loaded.locations, settings_file.DEFAULT_LOCATION_ROOTS)
+ self.assertEqual(loaded.locations, {})
+
+ def test_empty_media_roots_survive_config_roundtrip(self):
+ with TempTree() as tree:
+ tree.write(settings_file.render(tree.load()))
+ self.assertEqual(tree.load().locations, {})
def test_lenient_load_falls_back_to_builtin_defaults(self):
"""坏文件不能让进程连 Peach 数据目录都不知道——发现顺序不看文件内容。"""
@@ -368,6 +374,7 @@ class ConfiguredStateTests(unittest.TestCase):
class SerialisationTests(unittest.TestCase):
def test_render_then_load_returns_the_same_values(self):
with TempTree() as tree:
+ tree.write("[media.locations]\nlocal = 'D:\\media'\n'115' = 'Q:\\Cloud'\n")
captured = settings_file.capture_existing(
tree.load(),
overrides={
@@ -379,7 +386,7 @@ class SerialisationTests(unittest.TestCase):
# 当转义处理,挂载点就会变成另一个目录。
mounts={"local": (r"D:\media",), "115": ("/mnt/115",)},
)
- settings_file.write(captured)
+ settings_file.write(captured, force=True)
reloaded = tree.load()
self.assertEqual(reloaded.server, captured.server)
self.assertEqual(reloaded.replication, captured.replication)
@@ -440,11 +447,19 @@ class ModuleConstantTests(unittest.TestCase):
def test_location_declarations_stay_in_ledger_shape(self):
# `asset.path` 与配置中的路径前缀均使用 Windows 格式,供目录访问权限检查匹配。
- self.assertEqual(set(config.LOCATION_ROOT_DECLARATIONS), {"local", "115", "pikpak"})
- self.assertEqual(
- tuple(root for roots in config.LOCATION_ROOT_DECLARATIONS.values() for root in roots),
- config.MEDIA_ROOT_DECLARATIONS,
- )
+ with TempTree() as tree:
+ tree.write("[media.locations]\nlocal = ['P:\\Library']\npikpak = ['Q:\\Cloud']\n")
+ try:
+ with patch.dict(os.environ, {"PEACH_DATA_ROOT": str(tree.data_root)}):
+ settings_file.reset_cache()
+ reloaded = importlib.reload(config)
+ self.assertEqual(reloaded.LOCATION_ROOT_DECLARATIONS,
+ {"local": (r"P:\Library",), "pikpak": (r"Q:\Cloud",)})
+ self.assertEqual(reloaded.MEDIA_ROOT_DECLARATIONS,
+ (r"P:\Library", r"Q:\Cloud"))
+ finally:
+ settings_file.reset_cache()
+ importlib.reload(config)
def test_settings_dataclass_reports_the_configured_state(self):
from peach.config import PeachSettings
diff --git a/tests/test_downloads_clouddrive_organize.py b/tests/test_downloads_clouddrive_organize.py
index 3e75e4b42..1751a22d2 100644
--- a/tests/test_downloads_clouddrive_organize.py
+++ b/tests/test_downloads_clouddrive_organize.py
@@ -1,4 +1,4 @@
-"""A 盘官方移动:冲突、成员核验、确定性拒绝与状态未知、路径边界。"""
+"""已声明来源的官方移动:冲突、成员核验、确定性拒绝与状态未知、路径边界。"""
import unittest
from pathlib import PureWindowsPath
from types import SimpleNamespace
@@ -12,6 +12,8 @@ from peach.organize_clouddrive import (ACCEPTED, DAV_ORIGIN, REJECTED, MoveNotEx
UnconfirmedMove)
from peach import organize_clouddrive
+MAPPING = organize_clouddrive.PikPakPaths('A:\\', '/Pikpak')
+
class Status(grpc.RpcError):
def __init__(self, code):
@@ -21,6 +23,98 @@ class Status(grpc.RpcError):
return self._code
+class ConfiguredPaths(unittest.TestCase):
+ def setUp(self):
+ self.mapping = organize_clouddrive.PikPakPaths('P:\\Library', '/My cloud/Movies', '/Movies')
+
+ def test_custom_drive_subdirectory_and_remote_name(self):
+ self.assertEqual(self.mapping.cloud_path('p:\\library\\人名\\a.mp4'), '/My cloud/Movies/人名/a.mp4')
+ self.assertEqual(self.mapping.dav_path('P:\\Library\\人名\\a.mp4'), '/Movies/人名/a.mp4')
+ dav = PikPakDav(Mock(), self.mapping, Mock(), listing=Mock(), rename=Mock(), move_remote=Mock())
+ self.assertEqual(unquote(dav.url('P:\\Library\\a b.mp4')), DAV_ORIGIN + '/Movies/a b.mp4')
+ dav.ensure_parent('P:\\Library\\a.mp4')
+ dav.listing.assert_not_called()
+
+ def test_paths_outside_the_declared_directory_are_rejected(self):
+ for path in ('A:\\a.mp4', 'P:\\LibraryOther\\a.mp4', 'P:\\Library\\..\\a.mp4',
+ 'P:Library\\a.mp4', 'P:\\Library\\a.mp4:secret'):
+ with self.subTest(path=path), self.assertRaises(ValueError):
+ self.mapping.cloud_path(path)
+
+ def test_mapping_comes_from_the_samples_declared_root(self):
+ roots = {'pikpak': ('P:\\Library', 'Q:\\Second')}
+ prefixes = (organize_clouddrive.CloudPrefix('/My cloud/Movies', 'P:\\Library'),
+ organize_clouddrive.CloudPrefix('/Another account', 'Q:\\Second'))
+ selected = organize_clouddrive._configured_paths('Q:\\Second\\a.mp4', roots, prefixes)
+ self.assertEqual((selected.root, selected.remote), ('Q:\\Second', '/Another account'))
+ for mappings in ((), prefixes + (organize_clouddrive.CloudPrefix('/Duplicate', 'Q:\\Second'),)):
+ with self.subTest(mappings=mappings), self.assertRaises(ValueError):
+ organize_clouddrive._configured_paths('Q:\\Second\\a.mp4', roots, mappings)
+
+ def test_protocol_requests_use_the_configured_remote_directory(self):
+ cloud = Mock(token='test-token')
+ cloud.channel.unary_unary.return_value.return_value = SimpleNamespace(success=True)
+ organize_clouddrive._move_remote(cloud, 'P:\\Library\\old\\a.mp4',
+ 'P:\\Library\\new\\a.mp4', self.mapping)
+ request = cloud.channel.unary_unary.return_value.call_args.args[0]
+ self.assertEqual(list(request.theFilePaths), ['/My cloud/Movies/old/a.mp4'])
+ self.assertEqual(request.destPath, '/My cloud/Movies/new')
+ organize_clouddrive._rename_remote(cloud, 'P:\\Library\\old\\a.mp4',
+ 'P:\\Library\\old\\b.mp4', self.mapping)
+ request = cloud.channel.unary_unary.return_value.call_args.args[0]
+ self.assertEqual((request.path, request.newName), ('/My cloud/Movies/old/a.mp4', 'b.mp4'))
+
+ def test_custom_root_directory_listing_stays_within_mapping(self):
+ cloud = Mock(token='test-token')
+ stream = OfficialDirectoryEvidence.Stream([
+ SimpleNamespace(fullPathName='/My cloud/Movies/a.mp4', size=20, isDirectory=False)])
+ cloud.channel.unary_stream.return_value.return_value = stream
+ self.assertEqual(organize_clouddrive._cloud_listing(cloud, 'P:\\Library', self.mapping),
+ [dict(path='P:\\Library\\a.mp4', size=20, directory=False)])
+ request = cloud.channel.unary_stream.return_value.call_args.args[0]
+ self.assertEqual(request.path, '/My cloud/Movies')
+ self.assertTrue(stream.cancelled)
+
+ def test_custom_root_authentication_checks_account_relative_path(self):
+ cloud = Mock(token='test-token')
+ cloud.channel.unary_unary.return_value.return_value = SimpleNamespace(
+ directUrl=DAV_ORIGIN + '/Movies/a.mp4', userAgent='',
+ additionalHeaders={'Authorization': 'test-credential'})
+ headers = organize_clouddrive._download_headers(cloud, 'P:\\Library\\a.mp4', self.mapping)
+ self.assertEqual(headers, {'Authorization': 'test-credential'})
+ request = cloud.channel.unary_unary.return_value.call_args.args[0]
+ self.assertEqual(request.path, '/My cloud/Movies/a.mp4')
+
+ def test_declared_root_cannot_be_a_move_target(self):
+ cloud = Mock(token='test-token')
+ with self.assertRaises(ValueError):
+ organize_clouddrive._move_remote(cloud, 'P:\\Library\\nested\\Library',
+ 'P:\\Library', self.mapping)
+ cloud.channel.unary_unary.assert_not_called()
+
+ def test_channel_uses_the_configured_webdav_account_subdirectory(self):
+ from peach import downloads_clouddrive_pb2 as pb
+ roots = {'pikpak': ('P:\\Library',)}
+ prefix = organize_clouddrive.CloudPrefix('/Renamed account/Movies', 'P:\\Library')
+ with patch.object(organize_clouddrive, 'PushDiscoverySettings') as settings, \
+ patch.object(organize_clouddrive, 'CredentialStore') as credentials, \
+ patch.object(organize_clouddrive, 'DownloadSettings') as downloads, \
+ patch.object(organize_clouddrive, 'CloudDriveClient') as client, \
+ patch.object(organize_clouddrive, '_download_headers', return_value={}) as headers, \
+ patch.object(organize_clouddrive, 'http_client'), \
+ patch.object(organize_clouddrive.organize, 'verified_renames'):
+ settings.return_value.load.return_value = SimpleNamespace(prefixes=(prefix,))
+ credentials.return_value.load.return_value = SimpleNamespace(values={'token': 'test-token'})
+ downloads.return_value.load.return_value = SimpleNamespace(clouddrive_address='http://example.test')
+ cloud = client.return_value.__enter__.return_value
+ cloud.find.return_value = pb.CloudDriveFile(isDirectory=True,
+ CloudAPI=pb.CloudAPI(name='WebDAV', path='/Renamed account'))
+ with organize_clouddrive.pikpak_renames('P:\\Library\\a.mp4', roots) as dav:
+ self.assertEqual(dav.url('P:\\Library\\a.mp4'), DAV_ORIGIN + '/Movies/a.mp4')
+ cloud.find.assert_called_once_with('/Renamed account/Movies')
+ self.assertEqual(headers.call_args.args[2].dav_root, '/Movies')
+
+
class OfficialMoves(unittest.TestCase):
def setUp(self):
self.entries = {'A:\\old': True, 'A:\\old\\film.mp4': 20, 'A:\\new': True}
@@ -28,7 +122,7 @@ class OfficialMoves(unittest.TestCase):
self.refresh = Mock()
self.http = httpx.Client(transport=httpx.MockTransport(self.handle), follow_redirects=False)
self.addCleanup(self.http.close)
- self.dav = PikPakDav(self.http, 'A:\\', self.refresh, listing=self.listing,
+ self.dav = PikPakDav(self.http, MAPPING, self.refresh, listing=self.listing,
rename=Mock(side_effect=self.relocate),
move_remote=Mock(side_effect=self.relocate))
@@ -189,7 +283,7 @@ class OfficialMoveProtocol(unittest.TestCase):
def test_conflict_skip_and_false_optional_flags_are_encoded(self):
cloud = Mock(token='test-token')
cloud.channel.unary_unary.return_value.return_value = SimpleNamespace(success=True)
- self.assertEqual(organize_clouddrive._move_remote(cloud, 'A:\\old\\film.mp4', 'A:\\new\\film.mp4'), ACCEPTED)
+ self.assertEqual(organize_clouddrive._move_remote(cloud, 'A:\\old\\film.mp4', 'A:\\new\\film.mp4', MAPPING), ACCEPTED)
request = cloud.channel.unary_unary.return_value.call_args.args[0]
self.assertEqual(list(request.theFilePaths), ['/Pikpak/old/film.mp4'])
self.assertEqual(request.destPath, '/Pikpak/new')
@@ -202,10 +296,10 @@ class OfficialMoveProtocol(unittest.TestCase):
cloud = Mock(token='test-token')
for target in ('R:\\film.mp4', 'A:\\new\\other.mp4', 'A:\\old\\film.mp4', 'A:\\new\\..\\film.mp4'):
with self.subTest(target=target), self.assertRaises(ValueError):
- organize_clouddrive._move_remote(cloud, 'A:\\old\\film.mp4', target)
+ organize_clouddrive._move_remote(cloud, 'A:\\old\\film.mp4', target, MAPPING)
for target in ('A:\\new\\title.mp4', 'R:\\old\\title.mp4'):
with self.subTest(target=target), self.assertRaises(ValueError):
- organize_clouddrive._rename_remote(cloud, 'A:\\old\\film.mp4', target)
+ organize_clouddrive._rename_remote(cloud, 'A:\\old\\film.mp4', target, MAPPING)
cloud.channel.unary_unary.assert_not_called()
def test_rpc_timeout_has_no_automatic_resubmission(self):
@@ -214,7 +308,7 @@ class OfficialMoveProtocol(unittest.TestCase):
cloud = Mock(token='test-token')
cloud.channel.unary_unary.return_value.side_effect = Status(grpc.StatusCode.DEADLINE_EXCEEDED)
target = 'A:\\new\\film.mp4' if submit is organize_clouddrive._move_remote else 'A:\\old\\title.mp4'
- self.assertIsNone(submit(cloud, 'A:\\old\\film.mp4', target))
+ self.assertIsNone(submit(cloud, 'A:\\old\\film.mp4', target, MAPPING))
cloud.channel.unary_unary.return_value.assert_called_once()
def test_request_rejections_are_deterministic(self):
@@ -224,21 +318,21 @@ class OfficialMoveProtocol(unittest.TestCase):
with self.subTest(code=code, submit=submit.__name__):
cloud = Mock(token='test-token')
cloud.channel.unary_unary.return_value.side_effect = Status(code)
- self.assertEqual(submit(cloud, 'A:\\old\\film.mp4', target), REJECTED)
+ self.assertEqual(submit(cloud, 'A:\\old\\film.mp4', target, MAPPING), REJECTED)
def test_rename_reply_maps_to_submission_status(self):
for success, expected in ((True, ACCEPTED), (False, REJECTED)):
with self.subTest(success=success):
cloud = Mock(token='test-token')
cloud.channel.unary_unary.return_value.return_value = SimpleNamespace(success=success)
- self.assertEqual(organize_clouddrive._rename_remote(cloud, 'A:\\old\\film.mp4', 'A:\\old\\title.mp4'), expected)
+ self.assertEqual(organize_clouddrive._rename_remote(cloud, 'A:\\old\\film.mp4', 'A:\\old\\title.mp4', MAPPING), expected)
request = cloud.channel.unary_unary.return_value.call_args.args[0]
self.assertEqual((request.path, request.newName), ('/Pikpak/old/film.mp4', 'title.mp4'))
def test_cache_scope_rejects_another_drive(self):
cloud = Mock(token='test-token')
with self.assertRaises(ValueError):
- organize_clouddrive._refresh_listing(cloud, 'B:\\MVP')
+ organize_clouddrive._refresh_listing(cloud, 'B:\\MVP', MAPPING)
cloud.channel.unary_unary.assert_not_called()
@@ -266,7 +360,7 @@ class OfficialDirectoryEvidence(unittest.TestCase):
self.cloud.channel.unary_stream.return_value = read
def test_ancestor_listings_confirm_the_complete_unicode_directory(self):
- rows = organize_clouddrive._cloud_listing(self.cloud, 'A:\\old\\creator@handle')
+ rows = organize_clouddrive._cloud_listing(self.cloud, 'A:\\old\\creator@handle', MAPPING)
self.assertEqual(rows, [dict(path='A:\\old\\creator@handle\\film.mp4', directory=False, size=20)])
self.assertEqual(self.paths, [('/Pikpak', True), ('/Pikpak/old', True), ('/Pikpak/old/creator@handle', True)])
self.assertTrue(all(stream.cancelled for stream in self.streams))
@@ -274,18 +368,18 @@ class OfficialDirectoryEvidence(unittest.TestCase):
def test_missing_ancestor_does_not_read_an_unverified_child(self):
self.entries['/Pikpak/old'] = []
with self.assertRaises(FileNotFoundError):
- organize_clouddrive._cloud_listing(self.cloud, 'A:\\old\\creator@handle')
+ organize_clouddrive._cloud_listing(self.cloud, 'A:\\old\\creator@handle', MAPPING)
self.assertEqual(len(self.paths), 2)
def test_foreign_drive_never_uses_the_existing_credential(self):
with self.assertRaises(ValueError):
- organize_clouddrive._cloud_listing(self.cloud, 'R:\\Media')
+ organize_clouddrive._cloud_listing(self.cloud, 'R:\\Media', MAPPING)
self.assertFalse(self.paths)
def test_duplicate_members_stop_and_cancel_the_stream(self):
self.entries['/Pikpak/old/creator@handle'] *= 2
with self.assertRaises(ValueError):
- organize_clouddrive._cloud_listing(self.cloud, 'A:\\old\\creator@handle')
+ organize_clouddrive._cloud_listing(self.cloud, 'A:\\old\\creator@handle', MAPPING)
self.assertTrue(all(stream.cancelled for stream in self.streams))
@@ -300,7 +394,7 @@ class AuthenticationSamples(unittest.TestCase):
stub = cloud.channel.unary_unary.return_value
stub.side_effect = [self.Missing(), reply]
with patch.object(organize_clouddrive, '_fallback_samples', return_value=['A:\\available\\image.jpg']):
- headers = organize_clouddrive._download_headers(cloud, 'A:\\moved\\image.jpg')
+ headers = organize_clouddrive._download_headers(cloud, 'A:\\moved\\image.jpg', MAPPING)
self.assertEqual(headers, {'Authorization': 'test-credential'})
self.assertEqual([c.args[0].path for c in stub.call_args_list], ['/Pikpak/moved/image.jpg', '/Pikpak/available/image.jpg'])
@@ -309,11 +403,11 @@ class AuthenticationSamples(unittest.TestCase):
stub = cloud.channel.unary_unary.return_value
stub.side_effect = self.Missing()
with patch.object(organize_clouddrive, '_fallback_samples', return_value=['A:\\first.jpg', 'A:\\second.jpg']), self.assertRaises(ValueError):
- organize_clouddrive._download_headers(cloud, 'A:\\moved.jpg')
+ organize_clouddrive._download_headers(cloud, 'A:\\moved.jpg', MAPPING)
self.assertEqual(stub.call_count, 3)
def test_foreign_download_source_is_rejected(self):
cloud = Mock(token='test-token')
cloud.channel.unary_unary.return_value.return_value = SimpleNamespace(directUrl='https://example.test/image.jpg', additionalHeaders={}, userAgent='')
with self.assertRaises(ValueError):
- organize_clouddrive._download_headers(cloud, 'A:\\image.jpg')
+ organize_clouddrive._download_headers(cloud, 'A:\\image.jpg', MAPPING)
diff --git a/tests/test_platform.py b/tests/test_platform.py
index 4a322abf8..87a20cbca 100644
--- a/tests/test_platform.py
+++ b/tests/test_platform.py
@@ -30,7 +30,7 @@ from peach.repository import MediaAsset
POSIX_ONLY = unittest.skipIf(os.name == "nt", "路径翻译只在非 Windows 上发生")
-#: 测试固定使用程序默认的数据库路径前缀,不依赖本机 config.toml。
+#: 测试显式声明数据库路径前缀,不依赖本机 config.toml。
LOCATIONS = {"local": (r"R:\media",), "115": ("B:/",), "pikpak": ("A:/",)}
@@ -188,7 +188,28 @@ class TranslationTests(unittest.TestCase):
self.assertEqual(translate_ledger_path("/tmp/one.mp4"), Path("/tmp/one.mp4"))
def test_system_volume_is_the_disk_gate_target(self):
- self.assertEqual(system_volume(), Path("C:/") if os.name == "nt" else Path("/"))
+ volume = system_volume()
+ self.assertTrue(volume.is_absolute())
+ self.assertTrue(volume.is_dir())
+ self.assertEqual(volume, Path(volume.anchor))
+
+
+class SystemVolumeTests(unittest.TestCase):
+ @unittest.skipUnless(os.name == 'nt', 'Windows 系统目录 API')
+ def test_system_directory_can_be_on_another_drive(self):
+ import ctypes
+ def windows_directory(buffer, size):
+ buffer.value = 'Z:\\Windows'
+ return len(buffer.value)
+ with patch.object(ctypes.windll.kernel32, 'GetWindowsDirectoryW', side_effect=windows_directory):
+ self.assertEqual(system_volume(), Path('Z:/'))
+
+ @unittest.skipUnless(os.name == 'nt', 'Windows 系统目录 API')
+ def test_missing_system_directory_is_reported(self):
+ import ctypes
+ with patch.object(ctypes.windll.kernel32, 'GetWindowsDirectoryW', return_value=0):
+ with self.assertRaises(OSError):
+ system_volume()
class RootBoundaryTests(unittest.TestCase):
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 24584377f..a1f5d7db3 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -864,13 +864,14 @@ class LibraryDirectoryTests(unittest.TestCase):
script = self.script
with tempfile.TemporaryDirectory() as directory:
root = Path(directory).resolve()
- source, target = r'A:\outer\outer', r'A:\outer'
+ source, target = r'P:\outer\outer', r'P:\outer'
def translate(path):
- return root.joinpath(*PureWindowsPath(path).parts[1:]) if PureWindowsPath(path).drive.casefold() == 'a:' else Path(path)
+ return root.joinpath(*PureWindowsPath(path).parts[1:]) if PureWindowsPath(path).drive.casefold() == 'p:' else Path(path)
translate(source).mkdir(parents=True)
media = translate(source) / 'film.mp4'
media.write_bytes(b'media')
- with mock.patch.object(script, 'translate_ledger_path', side_effect=translate):
+ with mock.patch.object(script, 'translate_ledger_path', side_effect=translate), \
+ mock.patch.object(script, 'location_roots', return_value={'pikpak': ('P:\\',)}):
for steps in (0, 1, 2):
pairs, state = script.collapse_moves(source, target)
self.assertTrue(Path(state['temporary']).name.startswith('peach-organize-'))
@@ -885,7 +886,7 @@ class LibraryDirectoryTests(unittest.TestCase):
script = self.script
with tempfile.TemporaryDirectory() as directory:
root = Path(directory).resolve()
- source, target = r'A:\old\account', r'A:\new\collection'
+ source, target = r'P:\old\account', r'P:\new\collection'
def translate(path):
return root.joinpath(*PureWindowsPath(path).parts[1:])
translate(source).mkdir(parents=True)
@@ -893,17 +894,17 @@ class LibraryDirectoryTests(unittest.TestCase):
media = translate(source) / 'film.mp4'
media.write_bytes(b'media')
with mock.patch.object(script, 'translate_ledger_path', side_effect=translate):
- pairs = script.provider_moves([(source,target)], 'A:\\')
- self.assertEqual(pairs, [(source,r'A:\old\collection'),(r'A:\old\collection',target)])
+ pairs = script.provider_moves([(source,target)], 'P:\\')
+ self.assertEqual(pairs, [(source,r'P:\old\collection'),(r'P:\old\collection',target)])
for steps in (0, 1, 2):
for old, new in pairs[:steps]:
translate(old).rename(translate(new))
with mock.patch.object(script.organize, '_rename', side_effect=lambda old,new:translate(old).rename(translate(new))):
self.assertEqual(script.restore(pairs), [])
self.assertEqual(media.read_bytes(), b'media')
- translate(r'A:\old\collection').mkdir()
+ translate(r'P:\old\collection').mkdir()
with self.assertRaises(FileExistsError):
- script.provider_moves([(source,target)], 'A:\\')
+ script.provider_moves([(source,target)], 'P:\\')
def test_fc_short_parts_require_matching_parent_and_publisher(self):
row = dict(code=None, studio=None, name='@fc1780822_1.mp4',
diff --git a/tests/test_trash_junk.py b/tests/test_trash_junk.py
index 0f6cd29dc..3651e568c 100644
--- a/tests/test_trash_junk.py
+++ b/tests/test_trash_junk.py
@@ -310,18 +310,27 @@ class TrashJunkTests(unittest.TestCase):
self.assertEqual(path.read_bytes(),b'confirmed promotion')
self.assertFalse(quarantine.exists())
- def test_a_drive_isolation_uses_a_bounded_normal_component(self):
+ def test_pikpak_isolation_uses_a_bounded_normal_component(self):
from pathlib import PureWindowsPath
from peach import web_batch
- original=PureWindowsPath('a:\\作品\\'+'长'*200+'.jpg')
+ original=PureWindowsPath('p:\\作品\\'+'长'*200+'.jpg')
with mock.patch.object(web_batch.os,'rename') as rename:
- quarantine=web_batch._quarantine_media(original)
+ quarantine=web_batch._quarantine_media(original,location='pikpak')
self.assertEqual(quarantine.parent,original.parent)
self.assertLess(len(quarantine.name),80)
self.assertFalse(quarantine.name.startswith('.'))
self.assertEqual(quarantine.suffix,'.peach-quarantine')
rename.assert_called_once_with(original,quarantine)
+ def test_local_a_drive_does_not_select_pikpak_isolation(self):
+ from pathlib import PureWindowsPath
+ from peach import web_batch
+ original = PureWindowsPath('A:\\Movies\\attachment.jpg')
+ with mock.patch.object(web_batch.os, 'rename'):
+ quarantine = web_batch._quarantine_media(original, location='local')
+ self.assertTrue(quarantine.name.startswith('.attachment.jpg.peach-purge-'))
+ self.assertEqual(quarantine.suffix, '.tmp')
+
def test_only_exact_tool_quarantine_names_are_skipped(self):
from peach import scan
for name in ('peach-purge-film.mp4','peach-purge-'+('a'*32)+'.mp4','作品.peach-quarantine'):