Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: resolve ledger drive letters against the local mounts

Peach local maintenance03c3b9fac21f
diff --git a/scripts/creator_boards.py b/scripts/creator_boards.py
index 920aab0eb..9b73e8879 100644
--- a/scripts/creator_boards.py
+++ b/scripts/creator_boards.py
@@ -25,6 +25,7 @@ from peach.jobs import (
SourceAccessPolicy,
require_free_space,
)
+from peach.platform import system_volume
from peach.media import remap_managed_path
@@ -152,7 +153,7 @@ def _existing_video_boards(output_dir: Path) -> set[str]:
def build_from_videos(args: argparse.Namespace, ffmpeg: str, ffprobe: str) -> int:
- require_free_space(Path("C:/"), args.min_free)
+ require_free_space(system_volume(), args.min_free)
source_sql, source_parameters = SourceAccessPolicy().sql_filter(
args.location, args.allow_metered
)
@@ -184,7 +185,7 @@ def build_from_videos(args: argparse.Namespace, ffmpeg: str, ffprobe: str) -> in
captured: dict[tuple[str, float], Path] = {}
started = time.time()
# 抽帧触发的云盘块缓存落在系统盘,起跑线检查拦不住;边跑边看,触线让未开始的帧直接跳过。
- guard = DiskGuard(Path("C:/"), args.min_free, args.disk_check_secs)
+ guard = DiskGuard(system_volume(), args.min_free, args.disk_check_secs)
stop = threading.Event()
stopped_reason = ""
diff --git a/scripts/probe.py b/scripts/probe.py
index 93f321731..023c7f896 100644
--- a/scripts/probe.py
+++ b/scripts/probe.py
@@ -21,6 +21,7 @@ from peach.jobs import (
SourceAccessPolicy,
require_free_space,
)
+from peach.platform import system_volume
from peach.media import resolve_case_insensitive
@@ -128,7 +129,7 @@ def run(args: argparse.Namespace) -> int:
choice = FFmpegResolver(FFMPEG_DIR).ffprobe()
if choice is None:
raise RuntimeError("ffprobe unavailable")
- require_free_space(Path("C:/"), args.min_free)
+ require_free_space(system_volume(), args.min_free)
source_sql, source_parameters = SourceAccessPolicy().sql_filter(
args.location, args.allow_metered
)
@@ -180,7 +181,7 @@ def run(args: argparse.Namespace) -> int:
counters = {"done": 0, "failed": 0}
started = time.time()
# 探测本身产物很小,但它触发的云盘块缓存会落在系统盘;边跑边看,不只查起跑线。
- guard = DiskGuard(Path("C:/"), args.min_free, args.disk_check_secs)
+ guard = DiskGuard(system_volume(), args.min_free, args.disk_check_secs)
stop = threading.Event()
stop_reason: list[str] = []
diff --git a/scripts/sheets.py b/scripts/sheets.py
index c84baf3af..b2fd1dbad 100644
--- a/scripts/sheets.py
+++ b/scripts/sheets.py
@@ -26,6 +26,7 @@ from peach.jobs import (
SourceAccessPolicy,
require_free_space,
)
+from peach.platform import system_volume
from peach.media import resolve_case_insensitive
@@ -147,7 +148,7 @@ def run(args: argparse.Namespace) -> int:
ffmpeg = resolver.ffmpeg()
if ffmpeg is None:
raise RuntimeError("ffmpeg unavailable")
- require_free_space(Path("C:/"), args.min_free)
+ require_free_space(system_volume(), args.min_free)
source_sql, source_parameters = SourceAccessPolicy().sql_filter(
args.location, args.allow_metered
)
@@ -202,7 +203,7 @@ def run(args: argparse.Namespace) -> int:
failure_reasons: Counter[str] = Counter()
started = time.time()
# 起跑线检查拦不住运行期把盘吃光的第三方缓存;这里边跑边看。
- guard = DiskGuard(Path("C:/"), args.min_free, args.disk_check_secs)
+ guard = DiskGuard(system_volume(), args.min_free, args.disk_check_secs)
stop = threading.Event()
stop_reason: list[str] = []
diff --git a/scripts/test.sh b/scripts/test.sh
new file mode 100644
index 000000000..4468214f7
--- /dev/null
+++ b/scripts/test.sh
@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+# macOS/Linux 的唯一测试入口,与 Windows 的 scripts/test.ps1 同一套契约:
+# 从 Git common directory 定位主目录的 .venv,强制加载当前 worktree 的 src,
+# 并核对 peach.__file__ 确实来自这个 worktree。worktree 不复制 .venv。
+set -euo pipefail
+
+WORKTREE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+
+GIT_COMMON_RAW="$(git -C "$WORKTREE_ROOT" rev-parse --git-common-dir)"
+if [[ -z "$GIT_COMMON_RAW" ]]; then
+ echo "无法定位 Peach 主工作树。" >&2
+ exit 1
+fi
+if [[ "$GIT_COMMON_RAW" = /* ]]; then
+ GIT_COMMON="$GIT_COMMON_RAW"
+else
+ GIT_COMMON="$WORKTREE_ROOT/$GIT_COMMON_RAW"
+fi
+GIT_COMMON="$(cd "$GIT_COMMON" && pwd)"
+MAIN_ROOT="$(dirname "$GIT_COMMON")"
+
+PYTHON="$MAIN_ROOT/.venv/bin/python"
+if [[ ! -x "$PYTHON" ]]; then
+ echo "Peach 主项目 venv 不存在:$PYTHON" >&2
+ exit 1
+fi
+
+SOURCE_ROOT="$WORKTREE_ROOT/src"
+export PYTHONPATH="$SOURCE_ROOT"
+
+cd "$WORKTREE_ROOT"
+LOADED_MODULE="$("$PYTHON" -c 'import peach; print(peach.__file__)')"
+if [[ "$LOADED_MODULE" != "$SOURCE_ROOT/"* ]]; then
+ echo "测试加载了错误源码:$LOADED_MODULE;预期位于 $SOURCE_ROOT" >&2
+ exit 1
+fi
+
+echo "Peach source: $LOADED_MODULE"
+exec "$PYTHON" -m unittest discover -s tests -p 'test_*.py' -v
diff --git a/src/peach/config.py b/src/peach/config.py
index 4dca0ae32..6e85efa10 100644
--- a/src/peach/config.py
+++ b/src/peach/config.py
@@ -2,9 +2,19 @@ import os
from dataclasses import dataclass
from pathlib import Path
+from .platform import translate_ledger_path, translate_roots
+
PROJECT_ROOT = Path(__file__).resolve().parents[2]
-DATA_ROOT = Path(os.environ.get("PEACH_DATA_ROOT", r"R:\peach-data"))
+
+# 运行数据目录按平台给默认值,两个平台各自持有一份可独立运行的 peach-data。
+# `PEACH_DATA_ROOT` 覆盖默认值;worktree 也靠这个绝对路径找到同一份数据。
+_WINDOWS_DATA_ROOT = Path(r"R:\peach-data")
+_POSIX_DATA_ROOT = Path.home() / "Desktop" / "lmd.gg" / "peach" / "peach-data"
+DATA_ROOT = Path(
+ os.environ.get("PEACH_DATA_ROOT")
+ or (_WINDOWS_DATA_ROOT if os.name == "nt" else _POSIX_DATA_ROOT)
+)
DATABASE_DIR = DATA_ROOT / "database"
DATABASE_PATH = DATABASE_DIR / "ledger.db"
GENERATED_DIR = DATA_ROOT / "generated"
@@ -20,6 +30,18 @@ TRANSCODE_DIR = GENERATED_DIR / "transcodes"
COVER_DIR = GENERATED_DIR / "covers"
MIGRATIONS_DIR = PROJECT_ROOT / "migrations"
+# 媒体来源只用账本口径(Windows 盘符)声明一次,本机挂载点由 platform 层翻译:
+# `R:` 本地硬盘、`B:` 115、`A:` PikPak;后两者在 macOS 上是 CloudDrive 的 macFUSE 挂载点。
+# 键是 ledger 的 `asset.location`,脱盘模式按来源逐个判定,不是全局开关。
+LOCATION_ROOT_DECLARATIONS: dict[str, str] = {
+ "local": r"R:\media",
+ "115": "B:/",
+ "pikpak": "A:/",
+}
+MEDIA_ROOT_DECLARATIONS: tuple[str, ...] = tuple(LOCATION_ROOT_DECLARATIONS.values())
+# 2026-08 仓库/数据拆分前写入 ledger 的旧快照根;运行时只做受控前缀重映射。
+LEGACY_SNAPSHOT_DECLARATIONS: tuple[str, ...] = (r"R:\Resources\Intake\snapshots",)
+
@dataclass(frozen=True)
class PeachSettings:
@@ -33,10 +55,12 @@ class PeachSettings:
mdns_port: int = 80
mdns_address: str | None = None
tls_enabled: bool = False
- allowed_media_roots: tuple[Path, ...] = (Path(r"R:\media"), Path("B:/"), Path("A:/"))
+ # 本机挂载不到的来源不进授权列表,对应资产按「脱盘」处理而不是报错。
+ allowed_media_roots: tuple[Path, ...] = translate_roots(MEDIA_ROOT_DECLARATIONS)
snapshot_root: Path = GENERATED_DIR / "snapshots"
- # 2026-08 仓库/数据拆分前写入 ledger 的旧路径;运行时只做受控前缀重映射。
- legacy_snapshot_roots: tuple[Path, ...] = (Path(r"R:\Resources\Intake\snapshots"),)
+ legacy_snapshot_roots: tuple[Path, ...] = tuple(
+ translate_ledger_path(root) for root in LEGACY_SNAPSHOT_DECLARATIONS
+ )
poster_root: Path = GENERATED_DIR / "posters"
avatar_root: Path = GENERATED_DIR / "avatars"
logo_root: Path = GENERATED_DIR / "logos"
diff --git a/src/peach/jobs.py b/src/peach/jobs.py
index 1bb4ee575..ca780fdd3 100644
--- a/src/peach/jobs.py
+++ b/src/peach/jobs.py
@@ -123,6 +123,10 @@ class PidFileLock:
return False
except PermissionError:
return True
+ except OverflowError:
+ # 锁文件可能是 Windows 那台写的,PID 会超出 POSIX 的 pid_t 范围。
+ # 超界的 PID 一定不是本机活进程,按「已死」清理,而不是让整轮任务崩掉。
+ return False
return True
@staticmethod
diff --git a/src/peach/media.py b/src/peach/media.py
index d7650f862..953d9991b 100644
--- a/src/peach/media.py
+++ b/src/peach/media.py
@@ -4,17 +4,27 @@ from __future__ import annotations
import os
from dataclasses import dataclass
from functools import lru_cache
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
from typing import Protocol, Sequence
+from .platform import (
+ is_unmapped,
+ is_windows_path,
+ root_online,
+ translate_ledger_path,
+ within_root,
+)
from .repository import LedgerRepository, MediaAsset
from .segments import HLS_SEGMENT_SECONDS
from .stash import StashClient
def normalized_path(path: Path | str) -> Path:
- """Windows 离线/云盘可能让 realpath 失败;仍保留绝对路径安全边界。"""
- candidate = Path(path)
+ """Windows 离线/云盘可能让 realpath 失败;仍保留绝对路径安全边界。
+
+ 账本里的盘符路径先按本机挂载点翻译,macOS 上才不会被当成当前目录下的相对路径。
+ """
+ candidate = translate_ledger_path(path)
try:
return candidate.resolve()
except OSError:
@@ -106,6 +116,18 @@ class MediaUnavailable(RuntimeError):
pass
+class MediaOffline(MediaUnavailable):
+ """来源盘整体不可达(脱盘),不是这一个文件缺失。
+
+ 脱盘只影响挂在该盘上的资产:本地硬盘拔掉时,115/PikPak 的云端资产照常可播。
+ """
+
+ def __init__(self, asset_id: int, source: str):
+ super().__init__(asset_id)
+ self.asset_id = asset_id
+ self.source = source
+
+
class MediaBackend(Protocol):
name: str
@@ -144,14 +166,35 @@ class FilesystemBackend:
else normalized_path(raw)
)
roots = (self.snapshot_root,) if thumbnail else self.allowed_roots
- if not any(path == root or root in path.parents for root in roots):
- raise MediaUnavailable(asset.id)
+ if not any(within_root(path, root) for root in roots):
+ self._raise_unavailable(asset.id, raw, thumbnail)
if path.is_file():
return path
matched = _case_insensitive_match(str(path.parent), path.name)
if matched is not None:
return path.parent / matched
- raise MediaUnavailable(asset.id)
+ self._raise_unavailable(asset.id, raw, thumbnail)
+
+ def _raise_unavailable(self, asset_id: int, raw: str, thumbnail: bool) -> None:
+ """来源盘整体不可达时报 MediaOffline,单个文件缺失仍报 MediaUnavailable。"""
+ if not thumbnail and is_windows_path(raw):
+ translated = translate_ledger_path(raw)
+ source = PureWindowsPath(raw).drive
+ if is_unmapped(translated):
+ raise MediaOffline(asset_id, source)
+ candidate = normalized_path(raw)
+ for root in self.allowed_roots:
+ if within_root(candidate, root):
+ if not root_online(root):
+ raise MediaOffline(asset_id, source)
+ break
+ raise MediaUnavailable(asset_id)
+
+ def source_status(self) -> tuple[dict[str, object], ...]:
+ """当前授权根的在线状态;脱盘模式的判据只有这一份。"""
+ return tuple(
+ {"root": str(root), "online": root_online(root)} for root in self.allowed_roots
+ )
def stream_candidates(self, asset: MediaAsset) -> Sequence[StreamCandidate]:
try:
diff --git a/src/peach/platform.py b/src/peach/platform.py
new file mode 100644
index 000000000..6a1080f09
--- /dev/null
+++ b/src/peach/platform.py
@@ -0,0 +1,137 @@
+"""账本盘符与本机挂载点之间的受控映射。
+
+账本里的 `asset.path` 一律是 Windows 形态的绝对路径:`R:\\Media\\...`(本地硬盘)、
+`A:\\...`(PikPak)、`B:\\...`(115)。2026-08 起同一份账本要在 macOS 上读,而
+CloudDrive 在两个平台的挂载方式完全不同:Windows 是盘符,macOS 是 macFUSE 挂载点。
+
+Peach 不重写账本,只在**读取时**把盘符映射到本机挂载点。写回账本的索引脚本仍然只在
+Windows 上运行,账本因此保持单一路径口径。
+
+没有对应挂载点的盘符会被映射到 `UNMAPPED_ROOT` 下,一定通不过 `allowed_media_roots`
+授权,于是该来源整体按「脱盘」处理,而不是意外落到当前工作目录下的同名相对路径。
+"""
+from __future__ import annotations
+
+import os
+from functools import lru_cache
+from pathlib import Path, PureWindowsPath
+
+# 盘符 -> 本机挂载点。Windows 上恒为空:盘符本身就是挂载点,不需要任何转换。
+_DEFAULT_DRIVE_MAP: dict[str, str] = (
+ {}
+ if os.name == "nt"
+ else {
+ "R": "/Volumes/RESOURCES",
+ "A": str(Path.home() / "Desktop" / "IMSL" / "Pikpak"),
+ "B": str(Path.home() / "Desktop" / "IMSL" / "115"),
+ }
+)
+
+# 未映射盘符的落点。刻意选一个不可能存在的绝对路径,让授权和存在性检查都必然失败。
+UNMAPPED_ROOT = Path("/nonexistent/peach-unmapped-drive")
+
+
+@lru_cache(maxsize=8)
+def _parse_override(raw: str) -> tuple[tuple[str, str], ...]:
+ """`PEACH_DRIVE_MAP=R=/Volumes/RESOURCES,B=/Users/me/115` 形式的覆盖。"""
+ pairs: list[tuple[str, str]] = []
+ for chunk in raw.split(","):
+ drive, separator, mount = chunk.partition("=")
+ drive = drive.strip()
+ if not separator or len(drive) != 1 or not drive.isalpha():
+ continue
+ pairs.append((drive.upper(), mount.strip()))
+ return tuple(pairs)
+
+
+def drive_map() -> dict[str, Path]:
+ """当前生效的盘符映射;空值表示显式声明「本机没有这个来源」。"""
+ merged = dict(_DEFAULT_DRIVE_MAP)
+ merged.update(dict(_parse_override(os.environ.get("PEACH_DRIVE_MAP", ""))))
+ return {drive: Path(mount) for drive, mount in merged.items() if mount}
+
+
+def root_online(root: Path) -> bool:
+ """挂载点在不在。
+
+ 目录存在还不够:CloudDrive 掉线后挂载点目录仍然在,但读第一个条目就报错
+ `Device not configured`。判据统一成「能否列出一个条目」。
+ """
+ try:
+ with os.scandir(root) as entries:
+ next(iter(entries), None)
+ except OSError:
+ return False
+ return True
+
+
+def within_root(path: Path, root: Path) -> bool:
+ """路径是否落在授权根内。
+
+ 字面比较先走一遍;不匹配时用 inode 比较兜底,因为账本里是 `R:\\Media`
+ 而授权根是 `/Volumes/RESOURCES/media`,exFAT/NTFS 大小写不敏感、pathlib 不是。
+ """
+ if path == root or root in path.parents:
+ return True
+ depth = len(root.parts)
+ if len(path.parts) < depth:
+ return False
+ try:
+ return Path(*path.parts[:depth]).samefile(root)
+ except OSError:
+ return False
+
+
+def system_volume() -> Path:
+ """磁盘闸门看的那块盘。
+
+ CloudDrive 会把下载块缓存到系统盘:Windows 是 `C:`,macOS 是根卷。
+ """
+ return Path("C:/") if os.name == "nt" else Path("/")
+
+
+def is_windows_path(raw: str | os.PathLike[str]) -> bool:
+ text = os.fspath(raw)
+ return len(text) >= 3 and text[0].isalpha() and text[1] == ":" and text[2] in "\\/"
+
+
+def is_unmapped(path: Path) -> bool:
+ return path == UNMAPPED_ROOT or UNMAPPED_ROOT in path.parents
+
+
+def translate_ledger_path(raw: str | os.PathLike[str]) -> Path:
+ """把账本里的 Windows 路径翻译成本机路径;非 Windows 形态原样返回。"""
+ text = os.fspath(raw)
+ if os.name == "nt" or not is_windows_path(text):
+ return Path(text)
+ parts = PureWindowsPath(text).parts
+ drive = parts[0][0].upper()
+ rest = parts[1:]
+ root = drive_map().get(drive)
+ if root is None:
+ return UNMAPPED_ROOT.joinpath(drive, *rest)
+ return root.joinpath(*rest)
+
+
+def translate_roots(roots) -> tuple[Path, ...]:
+ """翻译一组授权根,丢掉本机没有挂载的来源。"""
+ translated = [translate_ledger_path(root) for root in roots]
+ return tuple(path for path in translated if not is_unmapped(path))
+
+
+def media_root_status(roots) -> tuple[dict[str, object], ...]:
+ """每个声明来源的可达性;`/api/index` 靠它决定要不要把本地筛选置灰。"""
+ status: list[dict[str, object]] = []
+ for root in roots:
+ raw = os.fspath(root)
+ path = translate_ledger_path(raw)
+ mapped = not is_unmapped(path)
+ status.append(
+ {
+ "declared": raw,
+ "resolved": str(path) if mapped else None,
+ "mapped": mapped,
+ "online": bool(mapped and path.is_dir()),
+ }
+ )
+ return tuple(status)
diff --git a/tests/test_media.py b/tests/test_media.py
index 0f3b5557a..45d0d5696 100644
--- a/tests/test_media.py
+++ b/tests/test_media.py
@@ -1,3 +1,4 @@
+import os
import tempfile
import unittest
from pathlib import Path
@@ -85,7 +86,7 @@ class MediaEngineTests(unittest.TestCase):
def test_ffmpeg_resolver_uses_managed_bundle(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
- binary = root / "bin" / "ffmpeg.exe"
+ binary = root / "bin" / ("ffmpeg.exe" if os.name == "nt" else "ffmpeg")
binary.parent.mkdir()
binary.write_bytes(b"test")
with patch.dict("os.environ", {"PEACH_FFMPEG": ""}, clear=False), \
@@ -105,7 +106,10 @@ class MediaEngineTests(unittest.TestCase):
legacy = root / "old" / "snapshots"
raw = legacy / "cloud" / "local" / "aa" / "one.jpg"
expected = current / "cloud" / "local" / "aa" / "one.jpg"
- self.assertEqual(remap_managed_path(raw, current, (legacy,)), expected)
+ self.assertEqual(
+ remap_managed_path(raw, current, (legacy,)),
+ normalized_path(expected),
+ )
unrelated = root / "untrusted" / "one.jpg"
self.assertEqual(remap_managed_path(unrelated, current, (legacy,)), unrelated.resolve())
@@ -118,7 +122,9 @@ class MediaEngineTests(unittest.TestCase):
real.write_bytes(b"test")
backend = FilesystemBackend([root], root / "snapshots")
result = backend.stream_candidates(MediaAsset(1, str(root / "abw-118.mp4"), None))
- self.assertEqual(Path(result[0].uri).name, "ABW-118.MP4")
+ opened = Path(result[0].uri)
+ self.assertTrue(opened.is_file())
+ self.assertEqual(opened.name.casefold(), "abw-118.mp4")
# 完全缺失的名字仍应拒绝
self.assertEqual(
backend.stream_candidates(MediaAsset(2, str(root / "nope.mp4"), None)), ()
diff --git a/tests/test_platform.py b/tests/test_platform.py
new file mode 100644
index 000000000..0984db36c
--- /dev/null
+++ b/tests/test_platform.py
@@ -0,0 +1,134 @@
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from peach.media import FilesystemBackend, MediaOffline, MediaUnavailable
+from peach.platform import (
+ UNMAPPED_ROOT,
+ is_unmapped,
+ is_windows_path,
+ root_online,
+ system_volume,
+ translate_ledger_path,
+ translate_roots,
+ within_root,
+)
+from peach.repository import MediaAsset
+
+
+POSIX_ONLY = unittest.skipIf(os.name == "nt", "盘符翻译只在非 Windows 上发生")
+
+
+class DriveTranslationTests(unittest.TestCase):
+ def test_windows_path_shape_is_recognised(self):
+ self.assertTrue(is_windows_path(r"R:\Media\one.mp4"))
+ self.assertTrue(is_windows_path("B:/one.mp4"))
+ self.assertFalse(is_windows_path("/Volumes/RESOURCES/media/one.mp4"))
+ self.assertFalse(is_windows_path("relative/one.mp4"))
+
+ @POSIX_ONLY
+ def test_ledger_drive_is_mapped_to_the_local_mount(self):
+ with patch.dict("os.environ", {"PEACH_DRIVE_MAP": "R=/mnt/res,B=/mnt/115"}):
+ self.assertEqual(
+ translate_ledger_path(r"R:\Media\创作者\one.mp4"),
+ Path("/mnt/res/Media/创作者/one.mp4"),
+ )
+ self.assertEqual(translate_ledger_path("B:/x/one.mp4"), Path("/mnt/115/x/one.mp4"))
+
+ @POSIX_ONLY
+ def test_unmapped_drive_never_becomes_a_relative_path(self):
+ """没有挂载点的盘符必须落到不可达根,否则会被当成当前目录下的同名文件。"""
+ with patch.dict("os.environ", {"PEACH_DRIVE_MAP": "R=/mnt/res"}):
+ path = translate_ledger_path(r"Z:\secret\one.mp4")
+ self.assertTrue(path.is_absolute())
+ self.assertTrue(is_unmapped(path))
+ self.assertTrue(str(path).startswith(str(UNMAPPED_ROOT)))
+
+ @POSIX_ONLY
+ def test_unmapped_roots_are_dropped_from_authorisation(self):
+ with patch.dict("os.environ", {"PEACH_DRIVE_MAP": "R=/mnt/res,A=,B="}):
+ roots = translate_roots((r"R:\media", "B:/", "A:/"))
+ self.assertEqual(roots, (Path("/mnt/res/media"),))
+
+ def test_posix_path_passes_through_untouched(self):
+ 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("/"))
+
+
+class RootBoundaryTests(unittest.TestCase):
+ def test_within_root_accepts_exact_and_nested(self):
+ root = Path("/mnt/res/media")
+ self.assertTrue(within_root(root, root))
+ self.assertTrue(within_root(root / "a" / "b.mp4", root))
+
+ def test_within_root_rejects_sibling_and_shorter_paths(self):
+ root = Path("/mnt/res/media")
+ self.assertFalse(within_root(Path("/mnt/res/other/b.mp4"), root))
+ self.assertFalse(within_root(Path("/mnt"), root))
+
+ def test_within_root_survives_case_only_differences_on_insensitive_mounts(self):
+ """账本写 `R:\\Media`,授权根是 `.../media`;大小写不敏感的挂载必须仍然放行。"""
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp) / "media"
+ root.mkdir()
+ shouting = Path(tmp) / "MEDIA" / "one.mp4"
+ insensitive = (Path(tmp) / "MEDIA").is_dir()
+ self.assertEqual(within_root(shouting, root), insensitive)
+
+ def test_root_online_needs_a_readable_mount_not_just_a_directory(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.assertTrue(root_online(Path(tmp)))
+ self.assertFalse(root_online(Path(tmp)))
+ self.assertFalse(root_online(UNMAPPED_ROOT))
+
+
+class OfflineModeTests(unittest.TestCase):
+ """脱盘是来源级判定:一个盘不在,不影响其他盘上的资产。"""
+
+ def _backend(self, tmp: Path) -> FilesystemBackend:
+ return FilesystemBackend([tmp], tmp / "snapshots")
+
+ @POSIX_ONLY
+ def test_asset_on_an_unmapped_drive_reports_offline(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ backend = self._backend(Path(tmp))
+ with patch.dict("os.environ", {"PEACH_DRIVE_MAP": "R=/mnt/res"}):
+ with self.assertRaises(MediaOffline) as caught:
+ backend.file_for(MediaAsset(1, r"Z:\video\one.mp4", None))
+ self.assertEqual(caught.exception.source, "Z:")
+ self.assertEqual(caught.exception.asset_id, 1)
+
+ @POSIX_ONLY
+ def test_asset_on_a_detached_but_mapped_drive_reports_offline(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ detached = Path(tmp) / "gone"
+ backend = FilesystemBackend([detached], Path(tmp) / "snapshots")
+ with patch.dict("os.environ", {"PEACH_DRIVE_MAP": f"R={detached}"}):
+ with self.assertRaises(MediaOffline):
+ backend.file_for(MediaAsset(2, r"R:\video\one.mp4", None))
+
+ @POSIX_ONLY
+ def test_missing_file_on_a_live_drive_is_not_offline(self):
+ """单个文件丢失和整块盘不在必须分开报,否则前端会误显示脱盘模式。"""
+ with tempfile.TemporaryDirectory() as tmp:
+ live = Path(tmp)
+ backend = FilesystemBackend([live], live / "snapshots")
+ with patch.dict("os.environ", {"PEACH_DRIVE_MAP": f"R={live}"}):
+ with self.assertRaises(MediaUnavailable) as caught:
+ backend.file_for(MediaAsset(3, r"R:\nope.mp4", None))
+ self.assertNotIsInstance(caught.exception, MediaOffline)
+
+ def test_source_status_reports_each_root_separately(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ live = Path(tmp)
+ dead = live / "gone"
+ status = FilesystemBackend([live, dead], live / "snapshots").source_status()
+ self.assertEqual([row["online"] for row in status], [True, False])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_tray.py b/tests/test_tray.py
index fe32e209c..a07c6d5e9 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -1,3 +1,4 @@
+import os
import tempfile
import threading
import time
@@ -52,7 +53,10 @@ class TrayTests(unittest.TestCase):
manager.stop_owned()
process.terminate.assert_called_once()
- @patch("peach.tray.ctypes.windll.user32.SetProcessDpiAwarenessContext")
+ @unittest.skipUnless(
+ os.name == "nt", "DPI 声明与单实例锁是 Windows 托盘专属能力"
+ )
+ @patch("peach.tray.ctypes.windll.user32.SetProcessDpiAwarenessContext", create=True)
def test_hidpi_prefers_per_monitor_v2(self, set_context):
set_context.return_value = True
self.assertEqual(enable_hidpi(), "per-monitor-v2")
@@ -80,6 +84,9 @@ class TrayTests(unittest.TestCase):
self.assertEqual(icon.notify.call_count, 2)
icon.update_menu.assert_called_once()
+ @unittest.skipUnless(
+ os.name == "nt", "DPI 声明与单实例锁是 Windows 托盘专属能力"
+ )
def test_single_instance_rejects_second_windows_lock(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "tray.lock"