Peach: Local-first video metadata scraper and media manager.
feat(setup): 首启的题目与提交走 JSON 接口
longmeidao61bfe517afdc
diff --git a/docs/FRONTEND.md b/docs/FRONTEND.mdindex 2a9fa1d72..b64a499a3 100644--- a/docs/FRONTEND.md+++ b/docs/FRONTEND.md@@ -38,6 +38,7 @@ Peach 按 [ADR-0031](adr/0031-frontend-react-boardui-tailwind.md) 逐页接入 R独立页面,HTML 与样式都自包含在 `src/peach/routes_pages.py`,只借入口包 `/dist/peach-entry.js` 的 `attachOverlayScrollbar`、`wireCollapse` 与 Geist Select 画整页滚动条、「高级设置」的折叠和媒体来源下拉(入口包再从 `/js/core.js`、`/js/ui-sounds.js` 取字形与音效),此外不引 `web/` 的资产,也不是island。原因是那一套一上来就打 `/api/items`,而未配置的机器还没有数据库;它也没有客户端状态,原生 `<form method="post">` 不写一行 JS 就能工作。设置成功以浏览器 cookie 登录并跳入馆藏。+同一张表单的题目与提交另有 JSON 契约 `GET /api/setup/questions`、`POST /api/setup`,形态见 `docs/OPERATIONS.md`「首次设置的内部流程」;这张页面本身走表单提交,不读它们。它的配色 token 从 `web/css/01-base.css` 的 `:root` 两段抽出来,跟随系统深浅色。### 配置页diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex af80c9096..3d69263ab 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -307,6 +307,9 @@ Peach 按下面的顺序找 FFmpeg 和 ffprobe:- 托盘启动时读一次设置文件,由 `tray.needs_setup()` 判断:**没有 `config.toml` 且没有数据库**才算需要首次设置。不用 `PeachConfig.configured` 判断:托盘的单实例锁一启动就会在数据根下建出 `state/`,一次失败的启动就可能让下一次误判成已配置;反过来,没有 `config.toml` 的老部署数据库还在,不能被拖进首次设置。- 需要设置时,托盘不构建正常的服务规格(全新机器上 `build_service_specs()` 会因为缺 TLS 材料抛 `FileNotFoundError`),而是启动 `peach serve --setup --host 127.0.0.1 --port <设置里的端口,默认 8900> --no-mdns --no-ledger-sync`,再把浏览器打开到 `http://127.0.0.1:<端口>/`。这条引导服务没有 TLS,口令强制为空,安全边界就是回环绑定地址。- 首页是首次设置表单,提交到 `POST /setup`:已配置时返回 404,非回环来源返回 403,设置文件已存在返回 409。成功页的入口带 `/?onboarding=1`;选了导入浏览器历史则先去 `/taste?onboarding=1`。安装教程通过专用状态接口读取各项的实际状态。+- 同一张表单另有 JSON 契约,与 `POST /setup` 共用守卫(`routes_pages._setup_guard`)和校验落盘(`_complete_setup`):已配置 404,非回环来源 403,独立包地址栏主机名不是回环写法 403;提交另查 Origin(403)与设置文件已存在(409)。两条都在 `/api/` 下,错误一律回 JSON。+ - `GET /api/setup/questions` 给出画表单要的数据:`questions` 按 `onboarding.questions()` 的顺序列出每题的 `key`、`label`、`help`(说明行列表)、`default`、`required`、`advanced`(是否折进「高级设置」)、`input`(`text`、`number`、`choice`、`folders`)、`prefix`、`suffix`,`host` 另带按页面顺序排好的 `options`,`mdns_name` 另带 `visible_when: {"host": "2"}`;另有 `media_sources`、`media_source_default`、`media_root`(非 Windows 的对应路径格,Windows 为 `null`)、`cloud`(提示、帮助链接与缺失的挂载软件 `dependencies`)、`windows`、`standalone`,以及三个开关的初始值 `access_enabled`(host 默认是局域网就开)、`scan_now`、`history_guide`。+ - `POST /api/setup` 收同名字段:`media_dir` 是 `{path, location, root}` 行列表(`location` 缺省为 `local`),`access_enabled`、`scan_now`、`history_guide` 是布尔,选了「只有这台电脑」可不传 `mdns_name`。400 回 `{"error", "errors"}`:`errors` 按题目 key,访问密码在 `access_password`,`media_dir` 与提交的行一一对应、没错的行是空串;整表不成立(超过 100 行)时只有一句,长度与行数不等。`apply` 失败回 400,错误在 `data_root`。200 回 `url`、`scan_requested`、`history_guide`、`standalone`、`redirect`(独立包为入口地址,其余为 `null`,跳转时长由前端定)与运行信息 `facts`(同 `/api/configuration` 的 `facts`)。- 建目录(`database`、`generated`、`sources`、`state`、`secrets`、`logs`、`tools`、`review`)、迁移数据库、生成 CA 与口令、写设置文件,都由 `onboarding.apply()` 完成;CLI 和设置页调用同一个函数,只是输出方式不同。问答的题目、默认值和写文件逻辑在 `src/peach/onboarding.py`。- Windows 上 `peach init` 写出的 `[media.locations] local` 直接是那些目录,`[media.mounts]` 为空;macOS 上声明目录是 `R:\media`(第二个起 `R:\media2`……),本机目录按同样顺序写进 `[media.mounts] local`。复制、writer 镜像、SMB 一律不问,保持关闭或留空。- 切换由 `tray.SetupGate` 负责,Windows 托盘与 macOS 菜单栏共用。它挂在健康轮询里(Windows 10 秒、macOS 5 秒),每轮重新 `settings_file.load_config()`;不再需要设置时,停掉引导服务,按新数据根构建正常规格并启动,托盘进程本身不重启。diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.pyindex 1892ac937..ccb33074c 100644--- a/src/peach/routes_pages.py+++ b/src/peach/routes_pages.py@@ -233,13 +233,20 @@ def _copy_for(key: str, fallback: str) -> tuple[str, str]:return _SETUP_COPY.get(key, (fallback, ""))+#: 非 Windows 上每行媒体来源多出的那一格:账本里的 Windows 形态路径。+_MEDIA_ROOT_LABEL = "Windows 中的对应路径"+_MEDIA_ROOT_PLACEHOLDER = "例如 B:\\"+#: 非 Windows 上媒体库底下多出的一句说明:本机挂载点和账本路径是两回事。+_POSIX_MEDIA_NOTE = "本机文件夹是这台电脑读取媒体的位置;Windows 中的对应路径用于匹配馆藏中已有的路径。"++def _media_dir_row(value: str, error: str, *, first: bool, location: str = "local", root: str = "", windows: bool = True) -> str:from .media_configuration import SOURCE_OPTIONSsource = '<select name="media_location" aria-label="媒体来源">' + ''.join(f'<option value="{key}"{" selected" if key == location else ""}>{label}</option>'for key, label in SOURCE_OPTIONS) + '</select>'- mapping = (f'<label>Windows 中的对应路径<span class="entry-input"><input name="media_root" type="text" aria-label="Windows 中的对应路径" '- f'placeholder="例如 B:\\" value="{escape(root, quote=True)}"></span></label>') if not windows else ''+ mapping = (f'<label>{_MEDIA_ROOT_LABEL}<span class="entry-input"><input name="media_root" type="text" aria-label="{_MEDIA_ROOT_LABEL}" '+ f'placeholder="{_MEDIA_ROOT_PLACEHOLDER}" value="{escape(root, quote=True)}"></span></label>') if not windows else ''attrs = ' id="f-media_dir" required' if first else ' aria-label="媒体库"'return (f'<div class="dir"><span class="entry-input"><input name="media_dir" type="text"{attrs} autocomplete="off" 'f'spellcheck="false" aria-invalid="{"true" if error else "false"}" '@@ -270,8 +277,8 @@ def _media_dirs_html(values: Sequence[str], errors: Sequence[str], note: str, *,f'<div class="dirs" id="dirs">{body}</div>''<button type="button" class="add" id="add-dir" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>添加媒体库</button>'f'<template id="dir-row">{_media_dir_row("", "", first=False, windows=windows)}</template>'- '<p class="help" id="cloudHelp" hidden>先在 CloudDrive 登录网盘并完成挂载。'- '<a href="https://www.clouddrive2.com/help.html" target="_blank" rel="noreferrer">挂载帮助'+ f'<p class="help" id="cloudHelp" hidden>{_CLOUD_HELP}'+ f'<a href="{_CLOUD_HELP_URL}" target="_blank" rel="noreferrer">{_CLOUD_HELP_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></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)@@ -279,11 +286,24 @@ def _media_dirs_html(values: Sequence[str], errors: Sequence[str], note: str, *,)-def mount_dependencies_html(*, windows: bool) -> str:+#: 有一行媒体来源选了云盘时,媒体库底下出现的那句提示和它的帮助链接。+_CLOUD_HELP = "先在 CloudDrive 登录网盘并完成挂载。"+_CLOUD_HELP_URL = "https://www.clouddrive2.com/help.html"+_CLOUD_HELP_LABEL = "挂载帮助"+++def missing_mount_dependencies(*, windows: bool) -> list[dict[str, str]]:+ """云盘挂载缺的软件:每项一句「未检测到」和它的下载入口。首启页与 `/api/setup/questions` 共用。"""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'])+ return [{"name": row["name"], "message": f"未检测到 {row['name']}。",+ "download_url": row["download_url"], "download_label": f"下载 {row['name']}"}+ for row in mount_dependencies(system='win32' if windows else 'darwin') if not row['available']]+++def mount_dependencies_html(*, windows: bool) -> str:+ return ''.join('<p class="help">' + escape(row['message'])+ + dependency_link(row['download_url'], row['download_label']) + '</p>'+ for row in missing_mount_dependencies(windows=windows))def _media_dir_values(values: Mapping[str, object], default: str) -> list[str]:@@ -294,9 +314,28 @@ def _media_dir_values(values: Mapping[str, object], default: str) -> list[str]:return [str(raw) if raw else default]+def _question_view(question) -> dict[str, str]:+ """一道题在页面上的题面、说明、控件种类和输入框前后缀。首启页与 `/api/setup/questions` 读同一份。"""+ title, help_text = _copy_for(question.key, question.prompt)+ view = {"label": title, "help": help_text, "input": "text", "prefix": "", "suffix": ""}+ if question.key == "media_dir":+ view["input"] = "folders"+ elif question.key == "host":+ view["input"] = "choice"+ elif question.key == "port":+ view.update(input="number", prefix="localhost:")+ elif question.key == "mdns_name":+ view.update(prefix="http://" if distribution.standalone() else "https://", suffix=".local")+ if distribution.standalone():+ view["help"] = ("其他设备打开这个地址时要加上上面的端口,例如 "+ "http://peach.local:8900。首次连接请允许 Windows 专用网络访问。")+ return view++def _field_html(question, value: str, error: str, note: str) -> str:key = escape(question.key, quote=True)- title, help_text = _copy_for(question.key, question.prompt)+ view = _question_view(question)+ title, help_text = view["label"], view["help"]star = '<span class="req" aria-hidden="true">*</span>'if question.key == "host":labels = dict(onboarding.HOST_OPTIONS)@@ -309,18 +348,15 @@ def _field_html(question, value: str, error: str, note: str) -> str:f'{options}</div>')label = f'<span class="legend field-label" id="l-{key}">{escape(title)}</span>'else:- kind = "number" if question.key == "port" else "text"- control = (f'<input id="f-{key}" name="{key}" type="{kind}" required autocomplete="off" '+ control = (f'<input id="f-{key}" name="{key}" type="{view["input"]}" required autocomplete="off" 'f'spellcheck="false" aria-invalid="{"true" if error else "false"}" 'f'value="{escape(value, quote=True)}">')- if question.key == "mdns_name":- scheme = "http" if distribution.standalone() else "https"- control = f'<div class="affix"><span>{scheme}://</span>{control}<span>.local</span></div>'- if distribution.standalone():- help_text = ("其他设备打开这个地址时要加上上面的端口,例如 "- "http://peach.local:8900。首次连接请允许 Windows 专用网络访问。")- elif question.key == "port":- control = f'<div class="affix"><span>localhost:</span>{control}</div>'+ if view["prefix"] or view["suffix"]:+ control = ('<div class="affix">'+ + (f'<span>{escape(view["prefix"])}</span>' if view["prefix"] else '')+ + control+ + (f'<span>{escape(view["suffix"])}</span>' if view["suffix"] else '')+ + '</div>')else:control = f'<span class="entry-input">{control}</span>'label = f'<label class="field-label" for="f-{key}">{escape(title)}{star}</label>'@@ -330,6 +366,15 @@ def _field_html(question, value: str, error: str, note: str) -> str:return f'<div class="field" id="field-{key}">{label}{control}{tail}</div>'+def _access_on_by_default(asked) -> bool:+ """访问密码开关第一次出现时开不开:host 默认是局域网(`"2"`)就开。++ 独立包默认对局域网监听,明文 HTTP 又没有别的门,所以默认对局域网开放时默认要密码。+ """+ host_default = next((question.default for question in asked if question.key == "host"), "2")+ return host_default == "2"++def setup_page(config, *, windows: bool, values: Mapping[str, object] | None = None,errors: Mapping[str, object] | None = None, scan_now: bool = True,@@ -353,8 +398,7 @@ def setup_page(if question.key == "media_dir":media_dirs = _media_dir_values(values, question.default)row_errors = errors.get("media_dir", [])- fields.append(_media_dirs_html(media_dirs, list(row_errors), "" if windows else- "本机文件夹是这台电脑读取媒体的位置;Windows 中的对应路径用于匹配馆藏中已有的路径。",+ fields.append(_media_dirs_html(media_dirs, list(row_errors), "" if windows else _POSIX_MEDIA_NOTE,locations=values.get("media_location", ()), roots=values.get("media_root", ()), windows=windows))continuevalue = str(values.get(question.key, question.default))@@ -363,13 +407,10 @@ def setup_page(fields.append(f'<details{opened}><summary><span class="setting-title">高级设置</span>{_CHEVRON_SVG}</summary>'+ "".join(advanced) + "</details>")access_error = str(errors.get("access_password", ""))- host_value = next((str(values.get(question.key, question.default))- for question in asked if question.key == "host"), "2")- # 独立包默认对局域网监听,明文 HTTP 又没有别的门。第一次打开这张表时把密码- # 开关按 host 的默认值打开;表单回填时用户自己的选择说了算,`values` 非空就- # 只看 `access_enabled`——复选框不勾是不提交的,那正是「他关掉了」。+ # 表单回填时用户自己的选择说了算,`values` 非空就只看 `access_enabled`——+ # 复选框不勾是不提交的,那正是「他关掉了」。第一次打开按 host 的默认值定。access_enabled = (values.get("access_enabled") == "y" or bool(access_error)- or (not values and host_value == "2"))+ or (not values and _access_on_by_default(asked)))access_hidden = "" if access_enabled else " hidden"access_disabled = "" if access_enabled else " disabled"fields.insert(1, '<div class="field access-field">'@@ -417,7 +458,7 @@ def setup_page(def setup_done_page(applied, *, windows: bool, scan_requested: bool, history_guide: bool = False) -> str:"""成功页:扫描是否已排队、进入 Peach 的入口,运行信息默认折叠。口令不显示在页面上。"""config = applied.config- destination = escape(_normal_url(config) + ('taste?onboarding=1' if history_guide else '?onboarding=1'), quote=True)+ destination = escape(_setup_destination(config, history_guide=history_guide), quote=True)destination_label = '导入浏览器历史记录' if history_guide else '进入 Peach'scan = ("首次扫描已排队,在后台整理媒体库,期间可以照常使用 Peach。" if scan_requestedelse "稍后在配置页开始扫描媒体库。")@@ -434,6 +475,11 @@ def setup_done_page(applied, *, windows: bool, scan_requested: bool, history_guireturn _document("Peach · 设置完成", body)+def _setup_destination(config, *, history_guide: bool) -> str:+ """完成页的入口:进馆藏,或者选了导入浏览器历史就先去口味页。都带 `onboarding=1`。"""+ return _normal_url(config) + ('taste?onboarding=1' if history_guide else '?onboarding=1')++def _normal_url(config) -> str:"""设置完成之后本机浏览器要去的地址。@@ -580,17 +626,13 @@ async def copy_editor_save(request: Request, args: dict[str, str] = Depends(requreturn JSONResponse({"error": str(error)}, status_code=409)[email protected]("/setup")-async def setup_submit(request: Request):- """首次运行表单的提交端点。落盘逻辑全在 `peach.onboarding`,这里只做守卫和渲染。-- 三道守卫,形态各不相同因为原因各不相同:已经配置过的机器上这个端点根本不存在- (404,不是「禁止」——把它做成一条可探测的 403 等于对外宣告这里有个初始化入口);- 非回环调用方是 403(引导服务只绑 127.0.0.1,能走到这里说明有人转发了它);- 设置文件已经在了是 409(并发提交或刷新重发,不能覆盖别人刚写好的那份)。+def _setup_guard(request: Request, *, submit: bool) -> None:+ """首启的三个端点(`POST /setup`、`GET /api/setup/questions`、`POST /api/setup`)共用的守卫。- 扫描不在这里跑:这条引导服务在设置完成的那一刻就会被托盘停掉,跑在它进程里的- 扫描会跟着一起死。这里只写一个标记,由托盘切到正常服务之后消费。+ 形态各不相同因为原因各不相同:已经配置过的机器上这些端点根本不存在(404,不是+ 「禁止」——把它做成一条可探测的 403 等于对外宣告这里有个初始化入口);非回环调用方是+ 403(引导服务只绑 127.0.0.1,能走到这里说明有人转发了它);独立包认地址栏里的主机名,+ 不是回环写法也是 403。提交再看 Origin:从别的页面发来的表单不收。"""settings = request.app.state.settingsif settings.configured:@@ -600,24 +642,28 @@ async def setup_submit(request: Request):raise HTTPException(status_code=403, detail="setup is loopback-only")if distribution.standalone() and request.url.hostname not in _LOOPBACK:raise HTTPException(status_code=403, detail="请使用本机地址打开设置")+ if not submit:+ returnorigin = request.headers.get("origin")if origin and origin.rstrip("/") != str(request.base_url).rstrip("/"):raise HTTPException(status_code=403, detail="请从 Peach 设置页提交")- windows = os.name == "nt"- form = parse_qs((await request.body()).decode("utf-8", "replace"), keep_blank_values=True)- submitted: dict[str, object] = {key: (value or [""])[0] for key, value in form.items()}- # 媒体文件夹是一个列表:几行输入框同名提交,回显时也要原样给回几行。- submitted["media_dir"] = list(form.get("media_dir", []))- for key in ("media_location", "media_root"):- if key in form:- submitted[key] = list(form[key])- scan_now = "scan_now" in form- config = settings_file.active()+def _complete_setup(+ request: Request, config, submitted: Mapping[str, object], *, windows: bool,+ password_enabled: bool, scan_now: bool,+) -> tuple[object, dict[str, object]]:+ """校验一份首启提交,全对就落盘。返回 `(applied, errors)`,两者恰有一个有内容。++ `submitted` 是表单口径的扁平 dict:媒体文件夹三列是列表,其余是字串。错误按题目的+ key 收集,访问密码的错误在 `access_password`;先报全部字段错误,字段都对了才看设置+ 文件在不在(409,并发提交或刷新重发,不能覆盖别人刚写好的那份)。++ 扫描不在这里跑:这条引导服务在设置完成的那一刻就会被托盘停掉,跑在它进程里的+ 扫描会跟着一起死。这里只写一个标记,由托盘切到正常服务之后消费。+ """answers, errors = _read_answers(config, submitted, windows=windows)from . import access- password_enabled = "access_enabled" in formpassword = str(submitted.get("access_password", "")) if password_enabled else ""confirmation = str(submitted.get("access_confirm", "")) if password_enabled else ""try:@@ -632,11 +678,7 @@ async def setup_submit(request: Request):except ValueError as exc:errors["port"] = str(exc)if errors:- return HTMLResponse(- setup_page(config, windows=windows, values=submitted, errors=errors,- scan_now=scan_now),- status_code=400,- )+ return None, errors# 数据根决定设置文件在哪,所以拿到它之后要按它重新解析一次,不能沿用进程启动# 那一刻按发现顺序算出来的这份。resolved, _broken = onboarding.resolve_config(answers.data_root)@@ -646,16 +688,136 @@ async def setup_submit(request: Request):applied = onboarding.apply(resolved, answers, windows=windows,access_password=password)except (OSError, RuntimeError) as exc:- return HTMLResponse(setup_page(config, windows=windows, values=submitted,- errors={"data_root": str(exc)}, scan_now=scan_now), status_code=400)+ return None, {"data_root": str(exc)}if scan_now:onboarding.request_first_scan(applied.config, "configured" if answers.media_sources is not None else "local")+ return applied, {}++[email protected]("/setup")+async def setup_submit(request: Request):+ """首次运行表单的提交端点:守卫见 `_setup_guard`,校验与落盘见 `_complete_setup`,这里只做渲染。"""+ _setup_guard(request, submit=True)+ windows = os.name == "nt"+ form = parse_qs((await request.body()).decode("utf-8", "replace"), keep_blank_values=True)+ submitted: dict[str, object] = {key: (value or [""])[0] for key, value in form.items()}+ # 媒体文件夹是一个列表:几行输入框同名提交,回显时也要原样给回几行。+ submitted["media_dir"] = list(form.get("media_dir", []))+ for key in ("media_location", "media_root"):+ if key in form:+ submitted[key] = list(form[key])+ scan_now = "scan_now" in form++ config = settings_file.active()+ applied, errors = _complete_setup(request, config, submitted, windows=windows,+ password_enabled="access_enabled" in form, scan_now=scan_now)+ if errors:+ return HTMLResponse(+ setup_page(config, windows=windows, values=submitted, errors=errors,+ scan_now=scan_now),+ status_code=400,+ )response = HTMLResponse(setup_done_page(applied, windows=windows, scan_requested=scan_now,history_guide=submitted.get("history_guide") == "y"))response.headers["Cache-Control"] = "no-store"return response[email protected]("/api/setup/questions")+def setup_questions(request: Request):+ """首启表单要画的一切:题目与顺序、默认值、题面与说明、可选项、平台差异与开关初始态。++ 页面骨架上的固定文案(标题、按钮、「完成设置后」那一组、访问密码分区的几句话)归前端;+ 这里给的是随平台、打包形态、本机已装软件或题目定义而变的那部分。守卫与提交端点相同,+ 只是不看 Origin:配置完成后这里 404,运行事实不再对外。+ """+ _setup_guard(request, submit=False)+ windows = os.name == "nt"+ asked = onboarding.questions(settings_file.active(), windows=windows)+ host_labels = dict(onboarding.HOST_OPTIONS)+ from .media_configuration import SOURCE_OPTIONS+ items = []+ for question in asked:+ view = _question_view(question)+ note = _POSIX_MEDIA_NOTE if question.key == "media_dir" and not windows else ""+ item: dict[str, object] = {+ "key": question.key, "label": view["label"],+ "help": [line for line in (view["help"], note) if line],+ "default": question.default,+ # 星号与 `required` 跟着输入框走:两段式单选总有一项选中,不标。+ "required": question.key != "host",+ # 只有媒体库露在外面,其余四项都有能直接用的默认值,折进「高级设置」。+ "advanced": question.key != "media_dir",+ "input": view["input"], "prefix": view["prefix"], "suffix": view["suffix"],+ }+ if question.key == "host":+ item["options"] = [{"value": choice, "label": host_labels[choice]} for choice in _HOST_ORDER]+ if question.key == "mdns_name":+ # 局域网地址只在选了「同一局域网的设备」时显示并提交;不提交时服务端按默认值补。+ item["visible_when"] = {"host": "2"}+ items.append(item)+ return JSONResponse({+ "windows": windows,+ "standalone": distribution.standalone(),+ "questions": items,+ "media_sources": [{"value": value, "label": label} for value, label in SOURCE_OPTIONS],+ "media_source_default": "local",+ "media_root": None if windows else {"label": _MEDIA_ROOT_LABEL, "placeholder": _MEDIA_ROOT_PLACEHOLDER},+ "cloud": {"help": _CLOUD_HELP, "link": {"url": _CLOUD_HELP_URL, "label": _CLOUD_HELP_LABEL},+ "dependencies": missing_mount_dependencies(windows=windows)},+ "access_enabled": _access_on_by_default(asked),+ "scan_now": True,+ "history_guide": False,+ })+++def _json_text(value: object) -> str:+ return "" if value is None else str(value)++[email protected]("/api/setup")+async def setup_submit_json(request: Request):+ """`POST /setup` 的 JSON 版:同一组守卫、同一份校验与落盘,错误按题目 key 回给页面写回原位。++ 正文形态见 `docs/OPERATIONS.md`「首次设置的内部流程」。这里把它换成表单口径的扁平+ dict 再交 `_complete_setup`,所以同一份输入在两个端点上得到同一组错误文案。+ """+ _setup_guard(request, submit=True)+ try:+ body = await request.json()+ except ValueError:+ body = None+ if not isinstance(body, dict):+ raise HTTPException(status_code=400, detail="请求正文要是 JSON 对象")+ rows = body.get("media_dir")+ rows = [row if isinstance(row, dict) else {} for row in rows] if isinstance(rows, list) else []+ submitted: dict[str, object] = {+ key: _json_text(body[key])+ for key in ("data_root", "host", "port", "mdns_name", "access_password", "access_confirm")+ if body.get(key) is not None}+ submitted["media_dir"] = [_json_text(row.get("path")) for row in rows]+ submitted["media_location"] = [_json_text(row.get("location", "local")) for row in rows]+ submitted["media_root"] = [_json_text(row.get("root")) for row in rows]+ scan_now = body.get("scan_now") is True+ history_guide = body.get("history_guide") is True+ windows = os.name == "nt"+ applied, errors = _complete_setup(request, settings_file.active(), submitted, windows=windows,+ password_enabled=body.get("access_enabled") is True, scan_now=scan_now)+ if errors:+ raise HTTPException(status_code=400, detail={"message": "有几项需要修改", "errors": errors})+ destination = _setup_destination(applied.config, history_guide=history_guide)+ standalone = distribution.standalone()+ return JSONResponse({+ "url": destination,+ "scan_requested": scan_now,+ "history_guide": history_guide,+ "standalone": standalone,+ # 独立包的完成页过一会儿自己跳到入口,与 HTML 完成页的 meta refresh 同一判据;时长由前端定。+ "redirect": destination if standalone else None,+ "facts": runtime_fact_entries(applied.config),+ })++def _setup_media_source_errors(dirs: Sequence[str], kinds: object,problems: Sequence[str], validate) -> list[str]:"""首启的本地来源必须真的可读;CloudDrive 来源仍可离线保存。diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 01ec28a50..384b2bdbd 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -2607,6 +2607,12 @@ PUBLIC_ROUTES = {# 首次运行表单的提交端点。这台机器那时还没有口令可验;它自己有三道守卫:# 已配置过就 404、非回环调用方 403、设置文件已存在 409。("POST", "/setup"),+ # 同一张表单的 JSON 契约:读题与提交。这台机器那时同样没有口令可验,与 `POST /setup`+ # 共用 `routes_pages._setup_guard`:已配置过就 404、非回环调用方 403、独立包的非回环+ # 主机名 403;提交再看 Origin(403)与设置文件已存在(409)。配置完成后读题也是 404,+ # 平台、打包形态与挂载软件这些运行事实不外露。+ ("GET", "/api/setup/questions"),+ ("POST", "/api/setup"),# 登录页在拿到会话之前就要出图,书签与历史记录也从这三个固定路径取图标。# 它们发的是随仓库分发的品牌资源,不读账本。("GET,HEAD", "/favicon.ico"),diff --git a/tests/test_onboarding.py b/tests/test_onboarding.pyindex 18f55e808..dd12bbf45 100644--- a/tests/test_onboarding.py+++ b/tests/test_onboarding.py@@ -366,13 +366,8 @@ class ApplyTests(_Case):self.assertEqual(config.server.port, 8900, "坏文件退回内建默认")[email protected](HAS_HTTP_DEPS, "需要 fastapi 与 httpx")-class SetupPageTests(_Case):- """首次运行表单的 HTTP 契约:页面字段、逐字段校验、守卫与落盘。-- 这一层和 `peach init` 的问答共用 `peach.onboarding`,所以这里断言的是「页面渲染- 出来的字段和 `questions()` 同名同序」,而不是另抄一份字段清单去比对。- """+class _SetupHttpCase(_Case):+ """首启服务的 HTTP 夹具:临时数据根、证书生成打桩、没有口令的应用。"""def setUp(self):super().setUp()@@ -385,7 +380,7 @@ class SetupPageTests(_Case):self.addCleanup(active.stop)self.data_root = self.root / "peach-data"- def _client(self, *, configured: bool = False, client=("127.0.0.1", 12345)):+ def _client(self, *, configured: bool = False, client=("127.0.0.1", 12345), base_url="http://test"):import httpxfrom peach.api import create_app@@ -397,7 +392,16 @@ class SetupPageTests(_Case):))return httpx.AsyncClient(transport=httpx.ASGITransport(app=app, client=client),- base_url="http://test")+ base_url=base_url)++ def _send(self, method, path, *, headers=None, data=None, json=None, **kwargs):+ import asyncio++ async def run():+ async with self._client(**kwargs) as client:+ return await client.request(method, path, headers=headers, data=data, json=json)++ return asyncio.run(run())def _get(self, path, **kwargs):import asyncio@@ -426,6 +430,15 @@ class SetupPageTests(_Case):def _loaded(self):return settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.data_root)})+[email protected](HAS_HTTP_DEPS, "需要 fastapi 与 httpx")+class SetupPageTests(_SetupHttpCase):+ """首次运行表单的 HTTP 契约:页面字段、逐字段校验、守卫与落盘。++ 这一层和 `peach init` 的问答共用 `peach.onboarding`,所以这里断言的是「页面渲染+ 出来的字段和 `questions()` 同名同序」,而不是另抄一份字段清单去比对。+ """+def test_the_first_run_page_renders_every_question_plus_the_scan_checkbox(self):response = self._get("/")self.assertEqual(response.status_code, 200)@@ -754,6 +767,252 @@ class SetupPageTests(_Case):self.assertEqual(self._loaded().server.port, 8900, "第二次提交不得改掉已写好的设置")[email protected](HAS_HTTP_DEPS, "需要 fastapi 与 httpx")+class SetupJsonContractTests(_SetupHttpCase):+ """首启的 JSON 契约:`GET /api/setup/questions` 与 `POST /api/setup`。++ 两条路径与 `POST /setup` 共用守卫、校验与落盘,所以同一份输入在 HTML 端点和 JSON+ 端点上必须得到同一组错误;页面能画的内容,题目端点都要给全。+ """++ QUESTIONS = "/api/setup/questions"+ SUBMIT = "/api/setup"++ def _rows(self, *paths, location="local"):+ return [{"path": str(path), "location": location,+ "root": "" if NATIVE_WINDOWS else "R:\\media" + (str(index + 1) if index else "")}+ for index, path in enumerate(paths)]++ def _body(self, **overrides):+ body = {"data_root": str(self.data_root), "media_dir": self._rows(self.media),+ "host": "1", "port": "8900", "mdns_name": "peach", "scan_now": True}+ body.update(overrides)+ return {key: value for key, value in body.items() if value is not None}++ @staticmethod+ def _as_form(body):+ """同一份提交的表单写法:三列媒体字段同名重复,勾选项不勾就不提交。"""+ form: dict[str, object] = {}+ for key, value in body.items():+ if key == "media_dir":+ form["media_dir"] = [row["path"] for row in value]+ form["media_location"] = [row["location"] for row in value]+ form["media_root"] = [row["root"] for row in value]+ elif value is True:+ form[key] = "y"+ elif value is not False:+ form[key] = str(value)+ return form++ def _errors_both_ways(self, body, **kwargs):+ """把同一份输入交给两个端点,返回 (HTML 端点交给页面的 errors, JSON 端点的 errors)。"""+ with mock.patch.object(routes_pages, "setup_page", wraps=routes_pages.setup_page) as page:+ html = self._send("POST", "/setup", data=self._as_form(body), **kwargs)+ self.assertEqual(html.status_code, 400, html.text[:200])+ page.assert_called_once()+ response = self._send("POST", self.SUBMIT, json=body, **kwargs)+ self.assertEqual(response.status_code, 400, response.text)+ self.assertEqual(response.json()["error"], "有几项需要修改")+ self.assertFalse((self.data_root / "config.toml").exists(), "校验失败不写设置")+ return page.call_args.kwargs["errors"], response.json()["errors"]++ def test_the_questions_cover_every_field_in_order_with_defaults_and_copy(self):+ response = self._send("GET", self.QUESTIONS)+ self.assertEqual(response.status_code, 200, response.text)+ self.assertEqual(response.headers["cache-control"], "no-store")+ data = response.json()+ asked = onboarding.questions(self.config, windows=NATIVE_WINDOWS)+ questions = data["questions"]+ self.assertEqual([item["key"] for item in questions], [question.key for question in asked])+ self.assertEqual([item["default"] for item in questions], [question.default for question in asked])+ self.assertEqual([item["label"] for item in questions], ["数据目录", "媒体库", "谁可以访问", "端口", "局域网访问地址"])+ by_key = {item["key"]: item for item in questions}+ self.assertEqual([key for key, item in by_key.items() if not item["required"]], ["host"])+ self.assertEqual([key for key, item in by_key.items() if not item["advanced"]], ["media_dir"])+ self.assertEqual(by_key["host"]["options"], [{"value": "2", "label": "同一局域网的设备"},+ {"value": "1", "label": "只有这台电脑"}])+ self.assertEqual((by_key["port"]["input"], by_key["port"]["prefix"]), ("number", "localhost:"))+ self.assertEqual((by_key["mdns_name"]["prefix"], by_key["mdns_name"]["suffix"]), ("https://", ".local"))+ self.assertEqual(by_key["mdns_name"]["visible_when"], {"host": "2"})+ self.assertEqual(by_key["media_dir"]["input"], "folders")+ self.assertEqual(data["windows"], NATIVE_WINDOWS)+ self.assertFalse(data["standalone"])+ self.assertEqual([row["value"] for row in data["media_sources"]], ["local", "115", "pikpak"])+ self.assertEqual(data["media_source_default"], "local")+ if NATIVE_WINDOWS:+ self.assertIsNone(data["media_root"])+ self.assertEqual(len(by_key["media_dir"]["help"]), 1)+ else:+ self.assertEqual(data["media_root"]["label"], "Windows 中的对应路径")+ self.assertIn("本机文件夹是这台电脑读取媒体的位置", by_key["media_dir"]["help"][-1])+ self.assertEqual(data["cloud"]["link"]["url"], "https://www.clouddrive2.com/help.html")+ # 默认对局域网开放,所以访问密码开关第一次出现就开着;扫描默认勾上,导入历史默认不勾。+ self.assertEqual((data["access_enabled"], data["scan_now"], data["history_guide"]), (True, True, False))+ # 页面上的题面与说明就是这一份。+ page = self._get("/").text+ for item in questions:+ self.assertIn(f">{escape(item['label'])}<", page)+ for line in item["help"]:+ self.assertIn(escape(line), page)+ self.assertIn(escape(data["cloud"]["help"]), page)++ def test_the_questions_list_missing_mount_software_with_download_links(self):+ rows = [{"name": "CloudDrive", "available": True, "download_url": "https://www.clouddrive2.com/download.html"},+ {"name": "WinFsp", "available": False, "download_url": "https://winfsp.dev/rel/"}]+ with mock.patch("peach.media_configuration.mount_dependencies", return_value=rows):+ data = self._send("GET", self.QUESTIONS).json()+ page = self._get("/").text+ self.assertEqual(data["cloud"]["dependencies"], [{+ "name": "WinFsp", "message": "未检测到 WinFsp。",+ "download_url": "https://winfsp.dev/rel/", "download_label": "下载 WinFsp"}])+ self.assertIn("未检测到 WinFsp。", page)+ self.assertNotIn("未检测到 CloudDrive", page)++ def test_the_standalone_package_gets_its_own_address_form_in_the_questions(self):+ with mock.patch.object(distribution, "standalone", return_value=True):+ data = self._send("GET", self.QUESTIONS, base_url="http://127.0.0.1:8900").json()+ self.assertTrue(data["standalone"])+ mdns = next(item for item in data["questions"] if item["key"] == "mdns_name")+ self.assertEqual(mdns["prefix"], "http://")+ self.assertIn("http://peach.local:8900", mdns["help"][0])++ def test_the_questions_are_guarded_like_the_form_but_ignore_the_origin(self):+ cases = (+ ("已配置", {"configured": True}, 404, "not found"),+ ("非回环调用方", {"client": ("198.51.100.7", 51000)}, 403, "setup is loopback-only"),+ )+ for name, kwargs, status, message in cases:+ with self.subTest(name):+ response = self._send("GET", self.QUESTIONS, headers={"Accept": "text/html"}, **kwargs)+ self.assertEqual(response.status_code, status)+ self.assertEqual(response.json(), {"error": message}, "/api/ 下一律回 JSON")+ with self.subTest("独立包的非回环主机名"), mock.patch.object(distribution, "standalone", return_value=True):+ response = self._send("GET", self.QUESTIONS, base_url="http://peach.local:8900")+ self.assertEqual((response.status_code, response.json()), (403, {"error": "请使用本机地址打开设置"}))+ with self.subTest("读题不看 Origin"):+ response = self._send("GET", self.QUESTIONS, headers={"Origin": "http://elsewhere.example"})+ self.assertEqual(response.status_code, 200)++ def test_the_submission_is_guarded_like_the_form(self):+ cases = (+ ("已配置", {"configured": True}, 404, "not found"),+ ("非回环调用方", {"client": ("198.51.100.7", 51000)}, 403, "setup is loopback-only"),+ ("别的页面发来", {"headers": {"Origin": "http://elsewhere.example"}}, 403, "请从 Peach 设置页提交"),+ )+ for name, kwargs, status, message in cases:+ with self.subTest(name):+ response = self._send("POST", self.SUBMIT, json=self._body(), **kwargs)+ self.assertEqual((response.status_code, response.json()), (status, {"error": message}))+ with self.subTest("独立包的非回环主机名"), mock.patch.object(distribution, "standalone", return_value=True):+ response = self._send("POST", self.SUBMIT, json=self._body(), base_url="http://peach.local:8900")+ self.assertEqual((response.status_code, response.json()), (403, {"error": "请使用本机地址打开设置"}))+ self.assertFalse(self.data_root.exists(), "被守卫挡下的提交不落任何文件")+ with self.subTest("不是 JSON 对象"):+ response = self._send("POST", self.SUBMIT, json=["not", "an", "object"])+ self.assertEqual((response.status_code, response.json()), (400, {"error": "请求正文要是 JSON 对象"}))++ def test_a_second_json_submission_refuses_to_overwrite_the_settings_file(self):+ first = self._send("POST", self.SUBMIT, json=self._body(), headers={"Origin": "http://test"})+ self.assertEqual(first.status_code, 200, first.text)+ again = self._send("POST", self.SUBMIT, json=self._body(port="9100"))+ self.assertEqual((again.status_code, again.json()), (409, {"error": "settings file already exists"}))+ self.assertEqual(self._loaded().server.port, 8900)++ def test_the_same_input_brings_the_same_messages_from_the_form_and_the_json_endpoint(self):+ a_file = self.root / "not-a-folder"+ a_file.write_text("x", encoding="utf-8")+ nested = self.media / "inner"+ nested.mkdir()+ cases = {+ "目录不存在与端口越界": self._body(media_dir=self._rows(self.root / "nope"), port="0"),+ "超过 100 行": self._body(media_dir=self._rows(*[self.media] * 101)),+ "第二行嵌在第一行里": self._body(media_dir=self._rows(self.media, nested)),+ "云盘行不是绝对路径": self._body(media_dir=self._rows(self.media) + [+ {"path": "relative", "location": "115", "root": "" if NATIVE_WINDOWS else "R:\\cloud"}]),+ "开关开着没填密码": self._body(access_enabled=True),+ "两次密码不一致": self._body(access_enabled=True, access_password="first-password",+ access_confirm="other-password"),+ "密码太短": self._body(access_enabled=True, access_password="short", access_confirm="short"),+ "高级设置的端口越界": self._body(port="99999", history_guide=True),+ "局域网地址不合规": self._body(host="2", mdns_name="-bad-"),+ "谁可以访问不认识": self._body(host="9"),+ "数据目录是文件": self._body(data_root=str(a_file)),+ }+ expected_keys = {+ "目录不存在与端口越界": {"media_dir", "port"}, "超过 100 行": {"media_dir"},+ "第二行嵌在第一行里": {"media_dir"}, "云盘行不是绝对路径": {"media_dir"},+ "开关开着没填密码": {"access_password"}, "两次密码不一致": {"access_password"},+ "密码太短": {"access_password"}, "高级设置的端口越界": {"port"},+ "局域网地址不合规": {"mdns_name"}, "谁可以访问不认识": {"host"}, "数据目录是文件": {"data_root"},+ }+ for name, body in cases.items():+ with self.subTest(name):+ html, data = self._errors_both_ways(body)+ self.assertEqual(data, html)+ self.assertEqual(set(data), expected_keys[name])+ # 媒体库的错误按行对齐;整表不成立时只有一句,长度与行数不等。+ _html, rows = self._errors_both_ways(cases["第二行嵌在第一行里"])+ self.assertEqual(len(rows["media_dir"]), 2)+ self.assertEqual(rows["media_dir"][0], "")+ self.assertTrue(rows["media_dir"][1])+ _html, table = self._errors_both_ways(cases["超过 100 行"])+ self.assertEqual(table["media_dir"], ["请添加 1 到 100 个媒体文件夹"])++ def test_an_occupied_port_on_the_standalone_package_is_the_same_message_both_ways(self):+ import socket+ with socket.socket() as holder, mock.patch.object(distribution, "standalone", return_value=True):+ holder.bind(("127.0.0.1", 0))+ holder.listen()+ port = holder.getsockname()[1]+ html, data = self._errors_both_ways(self._body(port=str(port)), base_url="http://127.0.0.1:8900")+ self.assertEqual(data, html)+ self.assertEqual(data, {"port": "这个端口已被占用,请换一个端口"})++ def test_a_failed_apply_is_reported_on_the_data_root_both_ways(self):+ with mock.patch.object(onboarding, "apply", side_effect=OSError("数据目录写不进去")):+ html, data = self._errors_both_ways(self._body())+ self.assertEqual(data, html)+ self.assertEqual(data, {"data_root": "数据目录写不进去"})++ def test_a_valid_json_submission_returns_the_entry_address_and_runtime_facts(self):+ from peach import access+ from peach.web_entry import runtime_fact_entries+ response = self._send("POST", self.SUBMIT, json=self._body(+ access_enabled=True, access_password="correct-password", access_confirm="correct-password"))+ self.assertEqual(response.status_code, 200, response.text)+ self.assertEqual(response.headers["cache-control"], "no-store")+ data = response.json()+ self.assertEqual({key: data[key] for key in ("url", "scan_requested", "history_guide", "standalone", "redirect")},+ {"url": "http://127.0.0.1:8900/?onboarding=1", "scan_requested": True,+ "history_guide": False, "standalone": False, "redirect": None})+ self.assertEqual([row["term"] for row in data["facts"]],+ [row["term"] for row in runtime_fact_entries(self._loaded())])+ self.assertIn(str(self.data_root), [row["value"] for row in data["facts"]])+ self.assertTrue((self.data_root / "state" / onboarding.SCAN_REQUEST_NAME).is_file())+ policy = access.load(self.data_root / "secrets" / "access.json")+ self.assertEqual(policy["mode"], "password")+ self.assertNotIn("correct-password", response.text, "回话里不带密码")++ def test_the_history_guide_without_a_scan_leads_to_the_taste_page(self):+ with mock.patch('peach.web_stats.w_taste_refresh') as refresh:+ response = self._send("POST", self.SUBMIT, json=self._body(scan_now=False, history_guide=True))+ self.assertEqual(response.status_code, 200, response.text)+ data = response.json()+ self.assertEqual((data["url"], data["scan_requested"], data["history_guide"], data["redirect"]),+ ("http://127.0.0.1:8900/taste?onboarding=1", False, True, None))+ self.assertFalse((self.data_root / "state" / onboarding.SCAN_REQUEST_NAME).exists())+ refresh.assert_not_called()++ def test_the_standalone_package_is_told_to_redirect_to_the_entry_address(self):+ with mock.patch.object(distribution, "standalone", return_value=True):+ response = self._send("POST", self.SUBMIT, json=self._body(), base_url="http://127.0.0.1:8900")+ self.assertEqual(response.status_code, 200, response.text)+ data = response.json()+ self.assertEqual((data["standalone"], data["scan_requested"], data["history_guide"]), (True, True, False))+ self.assertEqual(data["redirect"], data["url"])+ self.assertEqual(data["url"], "http://127.0.0.1:8900/?onboarding=1")++class StandaloneConfigurationTests(_Case):def test_automatic_update_settings_roundtrip_and_access_boundaries(self):from peach.automatic_updates import AutomaticUpdates