Peach: Local-first video metadata scraper and media manager.
fix: 托盘生产配置入口与缺失依赖下载引导
longmeidaof68f7cf9c95b
diff --git a/README.en.md b/README.en.mdindex a49a7cfdf..f29948b89 100644--- a/README.en.md+++ b/README.en.md@@ -35,6 +35,8 @@ Peach is a single-user, local-first media system. Search, play and organize mediCloudDrive · 115 and CloudDrive · PikPak connect through mounted local folders. Sign in and mount them in CloudDrive first, then add the folders to Peach. Local disks alone also work.+Tray-managed services let you adjust media sources under Manage → Configuration on the host computer, including through its LAN hostname. Setup and configuration provide download links when dependencies are not detected, with mount drivers shown for the host operating system.+Follow sources include FANBOX, Patreon, SubscribeStar, Kemono, Pawchive, Coomer, the Rule34 family and F95zone. Availability depends on the site and your access rights. See [source collection](docs/SOURCING.md) for supported workflows and boundaries.## Quick startdiff --git a/README.md b/README.mdindex 5d152821a..cfdecdd37 100644--- a/README.md+++ b/README.md@@ -35,6 +35,8 @@ Peach 是单用户、本地优先的个人媒体系统。在自己的电脑上CloudDrive · 115 与 CloudDrive · PikPak 按本机文件夹接入;先在 CloudDrive 登录并挂载,再交给 Peach 索引。也可以只使用本地磁盘。+托盘管理的服务可在本机通过「管理 → 配置」调整媒体来源;使用局域网域名打开也能进入。首启页和配置页检测缺失依赖时提供下载链接,挂载驱动提示按操作系统显示。+关注来源包括 FANBOX、Patreon、SubscribeStar,以及 Kemono、Pawchive、Coomer、Rule34 系列与 F95zone。来源可用性受站点和使用者权限限制;采集边界与支持情况见 [来源采集](docs/SOURCING.md)。## 快速开始diff --git a/docs/FRONTEND.md b/docs/FRONTEND.mdindex 6eef29f45..4e4e6e485 100644--- a/docs/FRONTEND.md+++ b/docs/FRONTEND.md@@ -28,7 +28,7 @@ island。原因是那一套一上来就打 `/api/items`,而未配置的机器配置好之后改文件夹与端口走 `/configuration`:那是主站里的一屏(管理菜单 → 配置),由 `frontend/src/islands/configuration.tsx` 渲染,数据契约是 `/api/configuration`-(`src/peach/routes_configuration.py`)。服务端按两道门放行——只有独立包、只有回环地址——+(`src/peach/routes_configuration.py`)。服务端按两道门放行:托盘管理的服务、发起连接的是本机。并在 `/healthz` 里按调用方回 `configurable`,遗留层据此决定菜单里列不列这一项。表单校验的原因由服务端按字段给(400 的 `errors`),island 写回原位,不在前端复制判定。浏览器直接导航撞上 `HTTPException` 时,`api.py` 的处理器按 `Accept` 回一张 HTML 错误页diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex e0a234804..931f67a08 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -15,7 +15,7 @@1. 在 CloudDrive 中登录网盘并建立挂载点,打开「启动时自动挂载」。步骤见[CloudDrive 官方帮助](https://www.clouddrive2.com/help.html)。-2. 在 Peach 首次设置页或独立包的「管理 → 配置」中添加文件夹,选择对应来源。+2. 在 Peach 首次设置页或托盘管理服务的「管理 → 配置」中添加文件夹,选择对应来源。115 使用来源 ID `115`,PikPak 使用 `pikpak`,本地磁盘使用 `local`;每个来源可有多个互不重叠的根。3. Windows 填本机盘符路径。macOS 的「本机文件夹」填本机挂载点,「Windows 中的对应路径」填该来源原有的Windows 盘符根,例如 `B:\` 对应 `/Volumes/CloudDrive/115`、`A:\` 对应@@ -24,9 +24,13 @@Windows 的 Peach 与 CloudDrive 应在同一普通用户会话下运行;提升权限的进程可能看不到挂载盘。5. 勾选扫描时,托盘顺序扫描配置内的在线来源,离线根跳过。恢复挂载后可再次勾选扫描并保存。+选择网盘来源时,首启页与配置页按本机系统检测 CloudDrive 和挂载驱动;未检测到安装会提供带外链图标的下载入口。+Windows 读取软件安装清单识别 WinFsp,macOS 检查 macFUSE 安装目录;便携版 CloudDrive 可通过 PATH 检测。+安装证据与挂载在线状态分别显示。运行信息中缺少 FFmpeg 或 ffprobe 时提供 FFmpeg 工具包下载;首次设置缺少 OpenSSL 时提供下载入口。+离线来源允许保留配置,重叠盘符根或本机挂载点会在对应行报错。来源判定沿用 `asset.location`,115/PikPak 进入既有网盘流量策略。保存配置不修改已有资产的来源归属和账本路径。-源码部署使用配置文件管理;首次网页引导支持相同来源,终端 `peach init` 的目录问答用于本地来源。+直接运行 CLI 的部署使用配置文件管理;首次网页引导支持相同来源,终端 `peach init` 的目录问答用于本地来源。对应 macOS 配置示例:@@ -58,7 +62,9 @@ pikpak = ['/Volumes/CloudDrive/PikPak']那些目录、`[media.mounts]` 为空;macOS 上声明根是 `R:\media`(第二个起 `R:\media2`……)、目录按同样顺序写进 `[media.mounts] local`。页面上的媒体文件夹是可加减的列表,配置页同样。配置页在主站里:管理菜单 → 配置(`/configuration`),只在运行 Peach 的这台电脑上、- 且只有独立包才出现;数据走 `/api/configuration`,保存后写重启标记由托盘接手。+ 且由托盘管理的服务才出现;数据走 `/api/configuration`,保存后写重载标记由托盘接手。+ 本机可使用配置的 `.local` 域名、回环地址或服务绑定 IP;通过连接两端 IP 判定本机,其他设备仍不可访问配置接口。+ 正式托盘服务保持其 HTTPS 地址与访问端口;独立测试包可在配置页修改本机端口。每行文件夹旁的「选择文件夹」让运行 Peach 的这台电脑弹系统对话框(Windows 资源管理器、macOS Finder),走 `/api/pick-folder`,同样只对本机开放;首启页也有这颗键。复制、writer 镜像、SMB 一律不问,保持关闭或留空。建目录、迁库、生成 CA 与口令、写设置文件diff --git a/docs/REUSE.md b/docs/REUSE.mdindex d78fa6a13..3145f6bfc 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -14,6 +14,13 @@真实 Git 临时仓库回归覆盖缺声明、双语缺一、虚假 updated、暂存但未提交、重命名与无影响原因;不写真实 ledger,不改生产。维护流程见 HANDOFF「README 维护」。+- 配置访问判定复用 ASGI 连接的 `client` / `server` 地址与 Python 标准库 `ipaddress`,不新增依赖。+ 本机连接匹配回环地址或服务端 IP;Host 只校验托盘配置的域名或绑定地址,不能用来证明调用方在本机。+ 配置保存复用修订号校验、原子替换与 `SetupGate` 重载标记;托盘子服务通过 `PEACH_TRAY_MANAGED` 声明重载能力。+ 安装检测复用标准库 `winreg`、`shutil.which` 和安装目录,媒体工具复用 `FFmpegResolver`;不把脱盘判为未安装。+ 下载入口核验于 2026-09-06:[CloudDrive](https://www.clouddrive2.com/download.html)、[WinFsp](https://winfsp.dev/rel/)、+ [macFUSE](https://macfuse.github.io/)、[FFmpeg](https://ffmpeg.org/download.html)、[OpenSSL](https://openssl-library.org/source/)。+- 发行身份继续复用 Javinizer-Go v1.5.1 与 Seesaa 原始 DTO;数字前缀等价属于 Peach 领域 policy,不新增依赖。真实 r18dev 快照中请求 `390JAC-040` 却返回 `JAC-040`/`118jac040`;Jackson 表中两者是不同商品行。查询回退不能承担身份确认;所有响应按原始查询检查,MGStage 官方详情路径可佐证展示编号别名。diff --git a/frontend/src/islands/configuration.tsx b/frontend/src/islands/configuration.tsxindex 02df698e2..47121e0fc 100644--- a/frontend/src/islands/configuration.tsx+++ b/frontend/src/islands/configuration.tsx@@ -1,7 +1,7 @@/* 配置页(`/configuration`):这台电脑的媒体文件夹与本机端口,加一块运行信息。** 数据契约在 `/api/configuration`(`src/peach/routes_configuration.py`)。服务端按两道门- * 放行:只有独立包、且只有从运行 Peach 的这台电脑打开时 `editable` 才为真;其它情况+ * 放行:托盘管理的服务、且从运行 Peach 的这台电脑打开时 `editable` 才为真;其它情况* 表单不画,只留一句为什么和运行信息。保存成功后 Peach 会重启,这里给一句持久 Note、* 一条新地址的链接,并在托盘换好进程后自己跳过去。*@@ -19,8 +19,10 @@ export interface ConfigurationProps {}export interface ConfigurationFact {- term: string;- value: string;+ term: string;+ value: string;+ download_url?: string;+ download_label?: string;}export interface ConfigurationData {@@ -33,6 +35,8 @@ export interface ConfigurationData {media_sources?: { location: string; root: string; path: string; online?: boolean }[];windows?: boolean;port: number;+ port_editable?: boolean;+ mount_dependencies?: { name: string; available: boolean; download_url: string }[];facts: ConfigurationFact[];}@@ -80,7 +84,7 @@ function Facts({ facts }: { facts: ConfigurationFact[] }) {{facts.map((fact) => (<><dt>{fact.term}</dt>- <dd>{fact.value}</dd>+ <dd>{fact.value}{fact.download_url ? <span class="confighelp"> <a href={fact.download_url} target="_blank" rel="noreferrer">{fact.download_label}<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-external-link" /></svg></a></span> : null}</dd></>))}</dl>@@ -289,10 +293,11 @@ function ConfigurationForm({ data, receipt }: { data: ConfigurationData; receipt</div><button type="button" class="geist-button configadd" onClick={add}>添加文件夹</button>{kinds.some((kind) => kind === '115' || kind === 'pikpak') ? <p class="confighelp">先在 CloudDrive 登录网盘并完成挂载。<a href="https://www.clouddrive2.com/help.html" target="_blank" rel="noreferrer">挂载帮助<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-external-link" /></svg></a></p> : null}+ {kinds.some((kind) => kind === '115' || kind === 'pikpak') ? data.mount_dependencies?.filter((dependency) => !dependency.available).map((dependency) => <p class="confighelp">未检测到 {dependency.name}。<a href={dependency.download_url} target="_blank" rel="noreferrer">下载 {dependency.name}<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-external-link" /></svg></a></p>) : null}{data.windows === false ? <p class="confighelp">本机文件夹是这台电脑读取媒体的位置。Windows 中的对应路径用于匹配馆藏中已有的路径,例如 B:\ 对应本机挂载文件夹。</p> : null}</div>- <div class="configfield">- <label for="configPort">本机访问端口</label>+ {data.port_editable !== false ? <div class="configfield">+ <label for="configPort">本机访问端口</label><inputid="configPort"class="geist-input"@@ -303,8 +308,8 @@ function ConfigurationForm({ data, receipt }: { data: ConfigurationData; receiptonInput={(event) => setPort(event.currentTarget.value)}/>{portError ? <p class="configbad" role="alert">{portError}</p> : null}- <p class="confighelp">浏览器地址里冒号后面的数字,一般不用改。</p>- </div>+ <p class="confighelp">浏览器地址里冒号后面的数字,一般不用改。</p>+ </div> : null}<label class="configcheck"><span class="pcheck"><input type="checkbox" checked={scanNow} onChange={(event) => setScanNow(event.currentTarget.checked)} />@@ -315,7 +320,7 @@ function ConfigurationForm({ data, receipt }: { data: ConfigurationData; receipt{failure ? <Html html={noteHtml(failure, { variant: 'error', label: '没有保存' })} /> : null}</div><div class="geist-fieldset-footer" data-geist-fieldset-footer>- <p>保存后 Peach 会重新启动,端口改了就用新地址打开。</p>+ <p>{data.port_editable === false ? '保存后 Peach 会重新载入配置。' : '保存后 Peach 会重新启动,端口改了就用新地址打开。'}</p><button type="submit" class="geist-button primary" ref={saveButton}>保存配置</button></div></form>diff --git a/frontend/test/configuration.test.tsx b/frontend/test/configuration.test.tsxindex 044f1fb76..7f1f9cfb6 100644--- a/frontend/test/configuration.test.tsx+++ b/frontend/test/configuration.test.tsx@@ -42,6 +42,30 @@ afterEach(() => {vi.unstubAllGlobals();});+it('托盘管理访问端口时仅展示媒体配置和对应保存说明', () => {+ const { el } = mount({ port_editable: false });+ expect(el.querySelector('#configPort')).toBeNull();+ expect(el.textContent).toContain('保存后 Peach 会重新载入配置。');+ expect(el.querySelector('form')).not.toBeNull();+});++it('缺失依赖提供带图标的新窗口下载链接且已安装依赖不提示', () => {+ const { el } = mount({+ media_sources: [{ location: '115', root: 'B:\\', path: 'B:\\' }],+ mount_dependencies: [+ { name: 'CloudDrive', available: false, download_url: 'https://www.clouddrive2.com/download.html' },+ { name: 'WinFsp', available: true, download_url: 'https://winfsp.dev/rel/' },+ ],+ facts: [{ term: 'FFmpeg', value: '未找到 FFmpeg', download_url: 'https://ffmpeg.org/download.html', download_label: '下载 FFmpeg' }],+ });+ for (const href of ['https://www.clouddrive2.com/download.html', 'https://ffmpeg.org/download.html']) {+ const link = el.querySelector(`a[href="${href}"]`);+ expect(link?.getAttribute('target')).toBe('_blank');+ expect(link?.querySelector('use')?.getAttribute('href')).toBe('#i-external-link');+ }+ expect(el.textContent).not.toContain('下载 WinFsp');+});+describe('配置页取数', () => {it('首屏走 /api/configuration 并带上中止信号', async () => {const fetch = fetchMock(200, data());diff --git a/src/peach/media_configuration.py b/src/peach/media_configuration.pyindex baf0f57e3..cb31d3e9a 100644--- a/src/peach/media_configuration.py+++ b/src/peach/media_configuration.py@@ -2,6 +2,8 @@from __future__ import annotationsfrom pathlib import Path, PurePath, PureWindowsPath, PurePosixPath+import shutil+import sysfrom typing import Anyfrom . import platform@@ -10,6 +12,46 @@ SOURCE_OPTIONS = (("local", "本地磁盘"), ("115", "CloudDrive · 115"),("pikpak", "CloudDrive · PikPak"))+def _windows_installed_names() -> list[str]:+ """从 Windows 安装清单读取软件名称,不读取命令、账户或凭据。"""+ if sys.platform != "win32":+ return []+ import winreg+ names = []+ for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):+ for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY):+ try:+ with winreg.OpenKey(hive, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",+ 0, winreg.KEY_READ | view) as key:+ for index in range(winreg.QueryInfoKey(key)[0]):+ try:+ with winreg.OpenKey(key, winreg.EnumKey(key, index)) as child:+ names.append(str(winreg.QueryValueEx(child, "DisplayName")[0]).lower())+ except OSError:+ continue+ except OSError:+ continue+ return names+++def mount_dependencies(*, system: str | None = None) -> list[dict[str, Any]]:+ """安装证据与挂载在线状态分别检测;只返回当前操作系统需要的依赖。"""+ system = system or sys.platform+ if system == "win32":+ names = _windows_installed_names()+ cloud = any(name.startswith("clouddrive") for name in names)+ driver, installed, url = "WinFsp", any(name.startswith("winfsp") for name in names), "https://winfsp.dev/rel/"+ elif system == "darwin":+ cloud = any((base / app).is_dir() for base in (Path("/Applications"), Path.home() / "Applications")+ for app in ("CloudDrive.app", "CloudDrive2.app"))+ driver, installed, url = "macFUSE", Path("/Library/Filesystems/macfuse.fs").is_dir(), "https://macfuse.github.io/"+ else:+ return []+ cloud = cloud or any(shutil.which(name) for name in ("clouddrive", "clouddrive2", "CloudDrive"))+ return [{"name": "CloudDrive", "available": bool(cloud), "download_url": "https://www.clouddrive2.com/download.html"},+ {"name": driver, "available": installed, "download_url": url}]++def rows(config, *, windows: bool, probe: bool = False) -> list[dict[str, Any]]:result = []for location, roots in config.locations.items():diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.pyindex f7145d3c8..9cf28f070 100644--- a/src/peach/routes_configuration.py+++ b/src/peach/routes_configuration.py@@ -1,7 +1,7 @@"""本机配置的 JSON 契约:读取、校验、原子保存与托盘重启请求。页面本体是 `frontend/src/islands/configuration.tsx`,挂在主站的 `/configuration` 路由里-(ADR-0022);这里只回数据。两道门都在服务端:只放行回环地址,只在独立包里可写。+(ADR-0022);这里只回数据。两道门都在服务端:只放行本机连接,只在托盘管理的服务里可写。手机上的管理菜单不列这一页,靠的是 `/healthz` 的 `configurable`,但那只是入口的显隐,拒绝写入的判定在这里。"""@@ -9,6 +9,7 @@ from __future__ import annotationsfrom dataclasses import replaceimport hashlib+import ipaddressimport osimport shutilimport threading@@ -18,44 +19,65 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Requestfrom . import distribution, folder_picker, onboarding, settings_file, media_configurationfrom .routes_auth import require_auth-from .routes_pages import runtime_facts+from .routes_pages import runtime_fact_entriesrouter = APIRouter()_SAVE_LOCK = threading.Lock()RELOAD_NAME = onboarding.RELOAD_NAME-#: 不在独立包里时页面上代替表单的那句话。+#: 直接由 CLI 管理的服务使用设置文件。FILE_MANAGED_NOTICE = "此部署通过配置文件管理服务,请在本机编辑下方的设置文件。"+def managed_configuration() -> bool:+ """托盘负责消费配置保存后的重载标记。"""+ return distribution.standalone() or os.environ.get("PEACH_TRAY_MANAGED") == "1"++def revision(config) -> str:return hashlib.sha256(config.path.read_bytes()).hexdigest()-def loopback_client(request: Request) -> bool:- """请求来自运行 Peach 的这台电脑。`/healthz` 与两个端点共用同一判据。"""- if not request.client or request.client.host not in {"127.0.0.1", "::1"}:+def local_client(request: Request) -> bool:+ """按连接两端的 IP 识别本机;Host 只用于校验允许的入口名称。"""+ if not request.client:return False- if distribution.standalone() and request.url.hostname not in {"127.0.0.1", "localhost", "::1"}:+ server = request.scope.get("server")+ try:+ peer = ipaddress.ip_address(request.client.host)+ bound = ipaddress.ip_address(server[0]) if server else None+ except ValueError:+ # ASGI 测试或非 IP 绑定没有可比较的服务端 IP;回环客户端仍可识别。+ bound = None+ try:+ peer = ipaddress.ip_address(request.client.host)+ except ValueError:+ return False+ if not peer.is_loopback and (peer != bound or peer.is_unspecified):return False+ if managed_configuration():+ name = request.app.state.settings.mdns_name.lower().removesuffix(".local")+ hosts = {"127.0.0.1", "localhost", "::1", f"{name}.local"}+ if bound and not bound.is_unspecified:+ hosts.add(str(bound))+ if (request.url.hostname or "").lower().rstrip(".") not in hosts:+ return Falsereturn Truedef local_only(request: Request) -> None:- if not request.client or request.client.host not in {"127.0.0.1", "::1"}:+ if not local_client(request):raise HTTPException(403, "请在运行 Peach 的电脑上打开配置")- if distribution.standalone() and request.url.hostname not in {"127.0.0.1", "localhost", "::1"}:- raise HTTPException(403, "请使用本机地址打开配置")def configurable(request: Request) -> bool:- """这次请求的发起方能不能改这台机器的配置:独立包、已配置、且来自回环地址。"""- return (distribution.standalone() and bool(request.app.state.settings.configured)- and loopback_client(request))+ """配置只向已配置的托盘服务的本机调用方开放。"""+ return (managed_configuration() and bool(request.app.state.settings.configured)+ and local_client(request))def snapshot(config) -> dict[str, Any]:"""配置页首屏要的一切:当前值、修订号、可写与否,以及这台机器的运行信息。"""- editable = distribution.standalone()+ editable = managed_configuration()media = config.mounts.get("local") or config.locations.get("local", ())return {"editable": editable,@@ -63,9 +85,11 @@ def snapshot(config) -> dict[str, Any]:"revision": revision(config),"media_dirs": list(media),"media_sources": media_configuration.rows(config, windows=os.name == "nt", probe=True),+ "mount_dependencies": media_configuration.mount_dependencies(),"windows": os.name == "nt","port": config.server.port,- "facts": [{"term": term, "value": value} for term, value in runtime_facts(config)],+ "port_editable": distribution.standalone(),+ "facts": runtime_fact_entries(config),}@@ -96,8 +120,11 @@ def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, Aelse:validated["media_dirs"] = pathstry:- port = onboarding.validate_port(str(body.get("port", "")))- onboarding.check_available_port(port, config.server.port)+ port = onboarding.validate_port(str(body.get("port", config.server.port)))+ if distribution.standalone():+ onboarding.check_available_port(port, config.server.port)+ elif port != config.server.port:+ raise ValueError("访问端口由托盘管理")validated["port"] = portexcept ValueError as exc:errors["port"] = str(exc)@@ -116,7 +143,7 @@ def pick_folder(request: Request, body: dict[str, Any] = Body(default_factory=di_args=Depends(require_auth)):"""让运行 Peach 的这台电脑弹系统文件夹对话框,选中的绝对路径交回页面。- 只对回环地址开放:否则局域网里任何人都能让这台电脑弹窗。首启页和配置页共用这一条,+ 只对本机连接开放:系统对话框显示在运行 Peach 的电脑上。首启页和配置页共用这一条,所以不要求独立包。对话框是模态的,一次只开一个;用户取消时 `path` 为 None。"""local_only(request)@@ -135,7 +162,7 @@ def pick_folder(request: Request, body: dict[str, Any] = Body(default_factory=didef save_configuration(request: Request, body: dict[str, Any] = Body(default_factory=dict),_args=Depends(require_auth)):local_only(request)- if not distribution.standalone():+ if not managed_configuration():raise HTTPException(409, "此部署通过配置文件管理服务")same_origin(request)with _SAVE_LOCK:@@ -174,5 +201,6 @@ def save_configuration(request: Request, body: dict[str, Any] = Body(default_fac(config.directory("state") / RELOAD_NAME).write_text("reload", encoding="utf-8")except OSError as exc:raise HTTPException(500, f"配置保存失败:{exc}") from exc- return {"saved": True, "url": f"http://127.0.0.1:{prepared.server.port}/",+ url = f"http://127.0.0.1:{prepared.server.port}/" if distribution.standalone() else str(request.base_url)+ return {"saved": True, "url": url,"revision": revision(prepared)}diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.pyindex ab152a90e..3dc3da889 100644--- a/src/peach/routes_pages.py+++ b/src/peach/routes_pages.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport hashlibimport os+import shutilfrom collections.abc import Mapping, Sequenceimport re@@ -202,6 +203,8 @@ _SETUP_SCRIPT = """<script>});var cloudHelp=document.getElementById('cloudHelp');if(cloudHelp){cloudHelp.hidden=!Array.from(list.querySelectorAll('select[name="media_location"]')).some(function(select){return select.value!=='local';});}+ var cloudDependencies=document.getElementById('cloudDependencies');+ if(cloudDependencies&&cloudHelp){cloudDependencies.hidden=cloudHelp.hidden;}};list.addEventListener('change',refresh);/* 「选择文件夹」让运行 Peach 的这台电脑弹系统对话框,把选中的绝对路径填回这一行:@@ -350,10 +353,30 @@ def runtime_facts(config) -> tuple[tuple[str, str], ...]:)+def runtime_fact_entries(config) -> list[dict[str, str]]:+ """运行信息中的缺失依赖附带官方下载入口。"""+ from .ffmpeg import FFmpegResolver+ entries = [{"term": term, "value": value} for term, value in runtime_facts(config)]+ resolver = FFmpegResolver(config.directory("tools") / "ffmpeg")+ missing = [name for name, choice in (("FFmpeg", resolver.ffmpeg()), ("ffprobe", resolver.ffprobe()))+ if choice is None]+ if missing:+ entry = next(row for row in entries if row["term"] == "FFmpeg")+ entry.update(value="未找到 " + "、".join(missing) + ";转码、媒体信息与缩略图需要 FFmpeg 工具包。",+ download_url="https://ffmpeg.org/download.html", download_label="下载 FFmpeg")+ return entries+++def dependency_link(url: str, label: str) -> str:+ return (f'<a href="{escape(url, quote=True)}" target="_blank" rel="noreferrer">{escape(label)}'+ '<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M15 3h6v6M10 14 21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg></a>')++def runtime_facts_html(config) -> str:return ("<h2>运行信息</h2><dl>"- + "".join(f"<dt>{escape(term)}</dt><dd>{escape(value)}</dd>"- for term, value in runtime_facts(config))+ + "".join(f'<dt>{escape(row["term"])}</dt><dd class="help">{escape(row["value"])}'+ + (' ' + dependency_link(row["download_url"], row["download_label"]) if row.get("download_url") else '')+ + '</dd>' for row in runtime_fact_entries(config))+ "</dl>")@@ -401,11 +424,19 @@ def _media_dirs_html(values: Sequence[str], errors: Sequence[str], note: str, *,'<p class="help" id="cloudHelp" hidden>先在 CloudDrive 登录网盘并完成挂载。''<a href="https://www.clouddrive2.com/help.html" target="_blank" rel="noreferrer">挂载帮助''<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M15 3h6v6M10 14 21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg></a></p>'+ + '<div id="cloudDependencies" hidden>' + mount_dependencies_html(windows=windows) + '</div>'+ "".join(f'<p class="help">{escape(line)}</p>' for line in (help_text, note) if line)+ "</div>")+def mount_dependencies_html(*, windows: bool) -> str:+ from .media_configuration import mount_dependencies+ return ''.join('<p class="help">未检测到 ' + escape(row['name']) + '。'+ + dependency_link(row['download_url'], '下载 ' + row['name']) + '</p>'+ for row in mount_dependencies(system='win32' if windows else 'darwin') if not row['available'])++def _media_dir_values(values: Mapping[str, object], default: str) -> list[str]:"""表单回显里的媒体文件夹:提交的是几行就几行,没提交过就一行默认值。"""raw = values.get("media_dir")@@ -512,7 +543,9 @@ def setup_done_page(applied, *, windows: bool, scan_requested: bool) -> str:else f"Peach 数据库:{tree.database}(已应用 {tree.migrations} 个迁移)")ca = (f"本机 CA:{tree.ca_cert}" if tree.ca_cert is not Noneelse f"未生成本机 CA({tree.ca_error});装好 openssl 后跑 "- "<code>peach init --force</code> 补上。局域网设备要装这份 CA 才不报证书错。")+ "<code>peach init --force</code> 补上。局域网设备要装这份 CA 才不报证书错。"+ + ('<span class="help">' + dependency_link('https://openssl-library.org/source/', '下载 OpenSSL') + '</span>'+ if not shutil.which('openssl') and (windows or not Path('/usr/bin/openssl').is_file()) else ''))scan = ("<li>首次扫描已排队,托盘会在服务起来之后在后台跑,期间页面照常能用。</li>"if scan_requested else"<li>没有请求首次扫描;要扫就跑 <code>peach scan configured</code>。</li>")diff --git a/src/peach/tray.py b/src/peach/tray.pyindex ee25a0544..7c73ee7d1 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -282,6 +282,7 @@ class ServiceManager:# A frozen tray must not pass its one-file bootloader state to Peach.exe.environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"environment.update(self._extra_env)+ environment["PEACH_TRAY_MANAGED"] = "1"return environmentdef start_missing(self) -> None:@@ -721,9 +722,8 @@ class SetupGate:还没齐就原地等下一轮,而不是拿一组缺文件的规格去启动。mDNS 名同理由这里传进规格:明文口的跳转目标必须是人刚填的那个名字。"""- from .distribution import standalonereload_path = self.config.directory("state") / onboarding.RELOAD_NAME- if not self._waiting and not (standalone() and reload_path.is_file()):+ if not self._waiting and not reload_path.is_file():return Falseconfig = self._load()if needs_setup(config):@@ -740,7 +740,7 @@ class SetupGate:)self.manager.start_missing()reload_path.unlink(missing_ok=True)- self.notify(f"首次设置完成,正在启动服务:{normal_url(config)}", "Peach")+ self.notify(f"配置已载入,正在启动服务:{normal_url(config)}", "Peach")self.start_first_scan(config)return Truediff --git a/tests/test_onboarding.py b/tests/test_onboarding.pyindex 1ab84db38..66cd16fa5 100644--- a/tests/test_onboarding.py+++ b/tests/test_onboarding.py@@ -638,6 +638,39 @@ class SetupPageTests(_Case):class StandaloneConfigurationTests(_Case):+ def test_missing_media_tools_have_download_links_in_json_and_setup_facts(self):+ from peach.routes_pages import runtime_fact_entries, runtime_facts_html+ for missing_ffmpeg, missing_probe in ((True, True), (False, True), (False, False)):+ with self.subTest(ffmpeg=missing_ffmpeg, probe=missing_probe), mock.patch(+ "peach.ffmpeg.FFmpegResolver.ffmpeg", return_value=None if missing_ffmpeg else object()), mock.patch(+ "peach.ffmpeg.FFmpegResolver.ffprobe", return_value=None if missing_probe else object()):+ fact = next(row for row in runtime_fact_entries(self.config) if row['term'] == 'FFmpeg')+ html = runtime_facts_html(self.config)+ self.assertEqual('download_url' in fact, missing_ffmpeg or missing_probe)+ self.assertEqual('https://ffmpeg.org/download.html' in html, missing_ffmpeg or missing_probe)+ if missing_ffmpeg or missing_probe:+ self.assertIn('target="_blank"', html)+ self.assertIn('<svg aria-hidden="true"', html)++ def test_mount_downloads_follow_os_and_detected_installation(self):+ from peach.media_configuration import mount_dependencies+ from peach.routes_pages import mount_dependencies_html+ with mock.patch("peach.media_configuration._windows_installed_names", return_value=[]), mock.patch(+ "peach.media_configuration.shutil.which", return_value=None):+ windows = mount_dependencies(system='win32')+ self.assertEqual([row['name'] for row in windows], ['CloudDrive', 'WinFsp'])+ self.assertTrue(all(not row['available'] for row in windows))+ self.assertIn('下载 WinFsp', mount_dependencies_html(windows=True))+ self.assertNotIn('macFUSE', mount_dependencies_html(windows=True))+ with mock.patch("peach.media_configuration._windows_installed_names", return_value=['clouddrive', 'winfsp 2026']):+ self.assertTrue(all(row['available'] for row in mount_dependencies(system='win32')))+ self.assertEqual(mount_dependencies_html(windows=True), '')+ with mock.patch("peach.media_configuration.Path.is_dir", return_value=False), mock.patch(+ "peach.media_configuration.shutil.which", return_value=None):+ self.assertEqual([row['name'] for row in mount_dependencies(system='darwin')], ['CloudDrive', 'macFUSE'])+ self.assertIn('下载 macFUSE', mount_dependencies_html(windows=False))+ self.assertNotIn('WinFsp', mount_dependencies_html(windows=False))+def setUp(self):super().setUp()from dataclasses import replace@@ -651,13 +684,77 @@ class StandaloneConfigurationTests(_Case):self.config.data_root, self.config.path, True, True,settings_file._read_document(self.config.path), {})).start()- def client(self, *, token="test-token", address="127.0.0.1"):+ def client(self, *, token="test-token", address="127.0.0.1", base_url="http://localhost", server=None):from fastapi.testclient import TestClientfrom peach.api import create_appfrom peach.config import PeachSettings- return TestClient(create_app(PeachSettings(configured=True, token=token,- db_path=self.config.data_root / "database" / "ledger.db")),- client=(address, 12345), base_url="http://localhost")+ app = create_app(PeachSettings(configured=True, token=token, mdns_name="peach-writer",+ db_path=self.config.data_root / "database" / "ledger.db"))+ if server:+ @app.middleware("http")+ async def connection_address(request, call_next):+ request.scope["server"] = (server, 443)+ return await call_next(request)+ return TestClient(app, client=(address, 12345), base_url=base_url)++ def test_local_mdns_connection_shares_configuration_access_for_read_save_and_picker(self):+ headers = {"X-Token": "test-token"}+ with self.client(address="192.0.2.10", server="192.0.2.10",+ base_url="https://peach-writer.local") as client:+ self.assertTrue(client.get("/healthz").json()["configurable"])+ self.assertEqual(client.get("/api/configuration").status_code, 401)+ response = client.get("/api/configuration", headers=headers)+ self.assertEqual(response.status_code, 200)+ with mock.patch("peach.folder_picker.pick_folder", return_value=str(self.media)):+ picked = client.post("/api/pick-folder", headers=headers, json={})+ self.assertEqual(picked.status_code, 200, picked.text)+ saved = client.post("/api/configuration", headers=headers, json={+ "revision": response.json()["revision"], "media_dirs": [str(self.media)], "port": "9123"})+ self.assertEqual(saved.status_code, 200, saved.text)++ def test_configuration_connection_gate_rejects_remote_and_untrusted_hosts(self):+ cases = [+ ("192.0.2.11", "192.0.2.10", "peach-writer.local", False),+ ("192.0.2.10", "192.0.2.10", "example.org", False),+ ("192.0.2.10", "192.0.2.10", "192.0.2.10", True),+ ("127.0.0.1", "127.0.0.1", "peach-writer.local", True),+ ("::1", "::1", "localhost", True),+ ("0.0.0.0", "0.0.0.0", "peach-writer.local", False),+ ]+ for peer, server, host, allowed in cases:+ with self.subTest(peer=peer, host=host), self.client(+ address=peer, server=server, base_url=f"https://{host}") as client:+ headers = {"X-Token": "test-token", "X-Forwarded-For": server}+ self.assertEqual(client.get("/healthz", headers=headers).json()["configurable"], allowed)+ self.assertEqual(client.get("/api/configuration", headers=headers).status_code,+ 200 if allowed else 403)+ if not allowed:+ for path in ("/api/configuration", "/api/pick-folder"):+ self.assertEqual(client.post(path, headers=headers, json={}).status_code, 403)++ def test_tray_managed_source_configuration_keeps_the_https_origin_and_managed_port(self):+ from peach.routes_configuration import RELOAD_NAME+ with mock.patch("peach.distribution.standalone", return_value=False), mock.patch.dict(+ os.environ, {"PEACH_TRAY_MANAGED": "1"}), self.client(+ address="192.0.2.10", server="192.0.2.10", base_url="https://peach-writer.local") as client:+ headers = {"X-Token": "test-token"}+ self.assertTrue(client.get("/healthz").json()["configurable"])+ snapshot = client.get("/api/configuration", headers=headers).json()+ self.assertTrue(snapshot["editable"])+ self.assertFalse(snapshot["port_editable"])+ body = {"revision": snapshot["revision"], "media_dirs": [str(self.media)], "port": "9124"}+ self.assertEqual(client.post("/api/configuration", headers=headers, json=body).status_code, 400)+ with mock.patch("peach.onboarding.check_available_port") as check:+ saved = client.post("/api/configuration", headers=headers, json={**body, "port": "9123"})+ check.assert_not_called()+ self.assertEqual(saved.status_code, 200, saved.text)+ self.assertEqual(saved.json()["url"], "https://peach-writer.local/")+ self.assertTrue((self.config.directory("state") / RELOAD_NAME).is_file())+ with mock.patch("peach.distribution.standalone", return_value=False), mock.patch.dict(+ os.environ, {"PEACH_TRAY_MANAGED": ""}), self.client() as client:+ self.assertFalse(client.get("/healthz").json()["configurable"])+ self.assertFalse(client.get("/api/configuration", headers=headers).json()["editable"])+ self.assertEqual(client.post("/api/configuration", headers=headers, json=body).status_code, 409)def test_the_configuration_page_is_a_screen_of_the_app_and_its_data_a_json_contract(self):"""`/configuration` 是主站外壳里的一屏,表单由 island 画;真相只在 `/api/configuration`。"""diff --git a/tests/test_tray.py b/tests/test_tray.pyindex 9d11b9413..ed3607097 100644--- a/tests/test_tray.py+++ b/tests/test_tray.py@@ -515,6 +515,25 @@ class SetupGateTests(unittest.TestCase):self.assertFalse(gate.poll(), "设置还没做完,轮询不动任何东西")self.assertEqual([spec.name for spec in manager.specs], ["setup"])+ def test_configured_source_tray_consumes_reload_once_and_marks_its_services(self):+ config = self._config()+ settings_file.write(config)+ config = self._config()+ self._tls(config)+ config.directory("state").mkdir(parents=True, exist_ok=True)+ reload_path = config.directory("state") / onboarding.RELOAD_NAME+ reload_path.write_text("reload", encoding="utf-8")+ manager = ServiceManager((), log_dir=config.directory("logs"),+ popen=Mock(), health_get=lambda *a, **k: Response())+ gate = SetupGate(manager, config, waiting=False, load=self._config)+ with patch("peach.tray.lan_ipv4", return_value="192.0.2.10"), patch(+ "peach.distribution.standalone", return_value=False):+ self.assertTrue(gate.poll())+ self.assertFalse(gate.poll())+ self.assertFalse(reload_path.exists())+ self.assertEqual(manager.child_environment()["PEACH_TRAY_MANAGED"], "1")+ self.assertTrue(manager.specs)+def test_a_finished_setup_switches_to_the_normal_services_and_runs_the_first_scan(self):config = self._config()manager = ServiceManager(build_setup_service_specs(config),diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.jsindex 60058fff4..28071b5a1 100644--- a/web/dist/peach-ui.js+++ b/web/dist/peach-ui.js@@ -480,7 +480,19 @@ function Qe({ facts: e }) {class: "geist-fieldset-content",children: [/* @__PURE__ */ U(W, { html: n("configFactsTitle", "运行信息") }), /* @__PURE__ */ U("dl", {class: "configfacts",- children: e.map((e) => /* @__PURE__ */ U(M, { children: [/* @__PURE__ */ U("dt", { children: e.term }), /* @__PURE__ */ U("dd", { children: e.value })] }))+ children: e.map((e) => /* @__PURE__ */ U(M, { children: [/* @__PURE__ */ U("dt", { children: e.term }), /* @__PURE__ */ U("dd", { children: [e.value, e.download_url ? /* @__PURE__ */ U("span", {+ class: "confighelp",+ children: [" ", /* @__PURE__ */ U("a", {+ href: e.download_url,+ target: "_blank",+ rel: "noreferrer",+ children: [e.download_label, /* @__PURE__ */ U("svg", {+ "aria-hidden": "true",+ viewBox: "0 0 24 24",+ children: /* @__PURE__ */ U("use", { href: "#i-external-link" })+ })]+ })]+ }) : null] })] }))})]})});@@ -757,13 +769,35 @@ function tt({ data: e, receipt: t }) {})]})]}) : null,+ c.some((e) => e === "115" || e === "pikpak") ? e.mount_dependencies?.filter((e) => !e.available).map((e) => /* @__PURE__ */ U("p", {+ class: "confighelp",+ children: [+ "未检测到 ",+ e.name,+ "。",+ /* @__PURE__ */ U("a", {+ href: e.download_url,+ target: "_blank",+ rel: "noreferrer",+ children: [+ "下载 ",+ e.name,+ /* @__PURE__ */ U("svg", {+ "aria-hidden": "true",+ viewBox: "0 0 24 24",+ children: /* @__PURE__ */ U("use", { href: "#i-external-link" })+ })+ ]+ })+ ]+ })) : null,e.windows === !1 ? /* @__PURE__ */ U("p", {class: "confighelp",children: "本机文件夹是这台电脑读取媒体的位置。Windows 中的对应路径用于匹配馆藏中已有的路径,例如 B:\\ 对应本机挂载文件夹。"}) : null]}),- /* @__PURE__ */ U("div", {+ e.port_editable === !1 ? null : /* @__PURE__ */ U("div", {class: "configfield",children: [/* @__PURE__ */ U("label", {@@ -815,7 +849,7 @@ function tt({ data: e, receipt: t }) {}), /* @__PURE__ */ U("div", {class: "geist-fieldset-footer","data-geist-fieldset-footer": !0,- children: [/* @__PURE__ */ U("p", { children: "保存后 Peach 会重新启动,端口改了就用新地址打开。" }), /* @__PURE__ */ U("button", {+ children: [/* @__PURE__ */ U("p", { children: e.port_editable === !1 ? "保存后 Peach 会重新载入配置。" : "保存后 Peach 会重新启动,端口改了就用新地址打开。" }), /* @__PURE__ */ U("button", {type: "submit",class: "geist-button primary",ref: k,