Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix: 完整验证网盘首启、路径校验和制品配置往返

longmeidao75e67e89670d
diff --git a/scripts/smoke_desktop.py b/scripts/smoke_desktop.py
index 50c087e2a..8d4f70050 100644
--- a/scripts/smoke_desktop.py
+++ b/scripts/smoke_desktop.py
@@ -5,7 +5,6 @@ import argparse
import json
import http.cookiejar
import os
-import re
from pathlib import Path
import socket
import subprocess
@@ -53,7 +52,7 @@ def main() -> int:
time.sleep(.25)
with opener.open(base + "/", timeout=5) as response:
assert 'action="/setup"' in response.read().decode("utf-8")
- form = {"media_dir": str(media), "port": str(port)}
+ form = {"media_dir": str(media), "media_location": "115", "port": str(port)}
request = urllib.request.Request(base + "/setup",
data=urllib.parse.urlencode(form).encode(), headers={"Origin": base})
with opener.open(request, timeout=60) as response:
@@ -75,17 +74,25 @@ def main() -> int:
for path in ("/", "/app.css", "/app.js", "/dist/peach-ui.js", "/api/items"):
with opener.open(base + path, timeout=10) as response:
assert response.status == 200, path
- with opener.open(base + "/configuration", timeout=5) as response:
- page = response.read().decode("utf-8")
- revision = re.search(r'name="revision" value="([a-f0-9]+)"', page).group(1)
- request = urllib.request.Request(base + "/configuration",
- data=urllib.parse.urlencode({**form, "revision": revision}).encode(), headers={"Origin": base})
+ with opener.open(base + "/api/configuration", timeout=5) as response:
+ configuration = json.load(response)
+ assert configuration['media_sources'][0]['location'] == '115'
+ second = root / 'pikpak'
+ second.mkdir()
+ sources = configuration['media_sources'] + [{'location': 'pikpak', 'path': str(second)}]
+ request = urllib.request.Request(base + "/api/configuration",
+ data=json.dumps({'media_sources': sources, 'port': port,
+ 'revision': configuration['revision']}).encode(),
+ headers={"Origin": base, 'Content-Type': 'application/json'})
with opener.open(request, timeout=10) as response:
- assert "配置已保存" in response.read().decode("utf-8")
+ assert json.load(response)['saved']
+ with opener.open(base + '/api/configuration', timeout=5) as response:
+ saved = json.load(response)
+ assert [row['location'] for row in saved['media_sources']] == ['115', 'pikpak']
assert (data / "config.previous.toml").is_file()
assert (data / "state" / "configuration-reload.request").is_file()
print(json.dumps({"ok": True, "version": health.get("version"),
- "checks": ["oobe", "migrations", "serve", "automatic-login", "pages", "island", "items", "configuration"]}))
+ "checks": ["oobe", "migrations", "serve", "automatic-login", "pages", "island", "items", "clouddrive-configuration"]}))
finally:
process.terminate()
process.wait(timeout=15)
diff --git a/src/peach/media_configuration.py b/src/peach/media_configuration.py
index 412786ddc..2dccb1405 100644
--- a/src/peach/media_configuration.py
+++ b/src/peach/media_configuration.py
@@ -1,7 +1,7 @@
"""媒体来源表单与配置映射;来源 ID 直接沿用扫描及流量策略。"""
from __future__ import annotations
-from pathlib import Path, PureWindowsPath, PurePosixPath
+from pathlib import Path, PurePath, PureWindowsPath, PurePosixPath
from typing import Any
from . import platform
@@ -28,16 +28,18 @@ def validate(raws: object, *, windows: bool) -> tuple[dict, dict, list[str]]:
locations: dict[str, list[str]] = {}
mounts: dict[str, list[str]] = {}
errors = [""] * len(raws)
- seen: list[tuple[int, PureWindowsPath, Path]] = []
+ seen: list[tuple[PureWindowsPath, PurePath]] = []
for index, row in enumerate(raws):
try:
if not isinstance(row, dict):
raise ValueError("媒体来源格式不正确")
location = row.get("location")
- if location not in dict(SOURCE_OPTIONS):
+ if not isinstance(location, str) or location not in dict(SOURCE_OPTIONS):
raise ValueError("请选择本地磁盘、115 或 PikPak")
text = str(row.get("path", "")).strip()
root = text if windows else str(row.get("root", "")).strip()
+ if any(ord(char) < 32 for char in text + root):
+ raise ValueError("路径不能包含控制字符")
if not platform.is_windows_path(root) or ".." in PureWindowsPath(root).parts:
raise ValueError("账本根目录必须是绝对盘符路径,例如 B:\\")
path = PureWindowsPath(text) if windows else PurePosixPath(text)
@@ -46,13 +48,13 @@ def validate(raws: object, *, windows: bool) -> tuple[dict, dict, list[str]]:
if ".." in path.parts:
raise ValueError("挂载点不能包含上级目录 ..")
declared = PureWindowsPath(root)
- for _, other_root, other_path in seen:
+ for other_root, other_path in seen:
if (declared == other_root or declared.is_relative_to(other_root)
or other_root.is_relative_to(declared)):
raise ValueError("账本根目录与另一行重复或重叠")
if path == other_path or path.is_relative_to(other_path) or other_path.is_relative_to(path):
raise ValueError("本机挂载点与另一行重复或重叠")
- seen.append((index, declared, path))
+ seen.append((declared, path))
locations.setdefault(location, []).append(str(declared))
if not windows:
mounts.setdefault(location, []).append(str(path))
diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.py
index fbf711c38..749a6c0f8 100644
--- a/src/peach/routes_pages.py
+++ b/src/peach/routes_pages.py
@@ -497,9 +497,11 @@ def setup_done_page(applied, *, windows: bool, scan_requested: bool) -> str:
"<code>peach init --force</code> 补上。局域网设备要装这份 CA 才不报证书错。")
scan = ("<li>首次扫描已排队,托盘会在服务起来之后在后台跑,期间页面照常能用。</li>"
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>")
+ "<li>没有请求首次扫描;要扫就跑 <code>peach scan configured</code>。</li>")
+ from .media_configuration import rows
+ mounts = ("" if windows else '<dl class="facts">' + ''.join(
+ f'<dt>{escape(row["location"])} · {escape(row["root"])}</dt><dd>{escape(row["path"])}</dd>'
+ for row in rows(config, windows=False)) + '</dl>')
body = (
"<h1>设置完成</h1>"
"<p>托盘正在停掉这条引导服务,改用正常的 Peach 服务;这个页面几秒后就会连不上,"
diff --git a/tests/test_configuration_sources.py b/tests/test_configuration_sources.py
index 670f0cb35..68172e096 100644
--- a/tests/test_configuration_sources.py
+++ b/tests/test_configuration_sources.py
@@ -3,6 +3,7 @@ from dataclasses import replace
from pathlib import Path
import tempfile
import unittest
+from types import SimpleNamespace
from unittest.mock import patch
from peach import media_configuration as media_config, onboarding, settings_file
@@ -28,6 +29,8 @@ class MediaConfigurationTests(unittest.TestCase):
def test_invalid_and_overlapping_roots_return_row_errors(self):
for rows in ([{"location": "bad", "path": "B:/"}],
+ [{"location": [], "path": "B:/"}],
+ [{"location": "115", "path": "B:/bad\u0000file"}],
[{"location": "115", "path": "../115"}],
[{"location": "115", "path": "B:/"}, {"location": "local", "path": "b:/Movies"}]):
self.assertTrue(media_config.validate(rows, windows=True)[2])
@@ -64,3 +67,17 @@ class MediaConfigurationTests(unittest.TestCase):
self.assertIn('value="115" selected', html)
self.assertIn('name="media_root"', html)
self.assertIn('value="B:/"', html)
+
+ def test_cloud_only_completion_page_shows_its_mount_and_scan_command(self):
+ from peach.routes_pages import setup_done_page
+ with tempfile.TemporaryDirectory() as directory:
+ base = Path(directory).resolve()
+ config = replace(settings_file.load_config(environ={"PEACH_DATA_ROOT": str(base)}),
+ locations={"115": ("B:/",)}, mounts={"115": ("/Volumes/115",)})
+ tree = SimpleNamespace(database=base / 'ledger.db', ledger_existed=False, migrations=0,
+ ca_cert=None, ca_error='unavailable', token_path=base / 'token')
+ with patch('peach.distribution.standalone', return_value=False):
+ html = setup_done_page(SimpleNamespace(config=config, tree=tree), windows=False, scan_requested=False)
+ self.assertIn('/Volumes/115', html)
+ self.assertIn('peach scan configured', html)
+ self.assertNotIn('peach scan local', html)