Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor: 首次运行的落盘逻辑下沉到 onboarding.apply,CLI 只负责打印

longmeidaoc76c47ad9ed2
diff --git a/src/peach/cli.py b/src/peach/cli.py
index fda9f939a..45dc6f04f 100644
--- a/src/peach/cli.py
+++ b/src/peach/cli.py
@@ -6,9 +6,10 @@ import sys
from datetime import datetime
from pathlib import Path
-from . import auth, certs, onboarding, scan, settings_file
+from . import auth, onboarding, scan, settings_file
from .api import create_app
from .config import (
+ CONFIGURED,
DATABASE_PATH,
MDNS_NAME,
MIGRATIONS_DIR,
@@ -71,9 +72,14 @@ def _serve(args: argparse.Namespace) -> int:
f"发布 peach.local 会指向一个连不上的地址。"
f"需要局域网访问就用 --host 0.0.0.0。"
)
+ # `--setup` 是托盘首启拉起的引导服务:只提供首次运行表单,不认发现到的数据根,
+ # 也不要口令。口令刻意置空而不是读文件——表单一提交就会生成一份口令,那之后要是
+ # 有人重启这条引导服务,读到新口令的它会把还没看到口令的用户关在门外。
+ # 安全边界由绑定地址给:这条服务只监听回环(`build_setup_service_specs`)。
settings = PeachSettings(
db_path=args.db,
- token=_serve_token(args),
+ token="" if args.setup else _serve_token(args),
+ configured=CONFIGURED and not args.setup,
docs_enabled=args.docs,
mdns_enabled=publish_mdns,
mdns_name=args.mdns_name,
@@ -282,13 +288,7 @@ def _resolved_config(
(`init --force` 是坏文件的唯一自救入口),但错误必须留下来:静默退回内建默认
再写回去,等于把旧文件里的坐标悄悄抹平。
"""
- environ = None if data_root is None else dict(
- os.environ, PEACH_DATA_ROOT=str(data_root))
- kwargs = {} if environ is None else {"environ": environ}
- try:
- return settings_file.load_config(**kwargs), None
- except settings_file.SettingsFileError as exc:
- return settings_file.load_config(**kwargs, strict=False), exc
+ return onboarding.resolve_config(data_root)
def _init(args: argparse.Namespace) -> int:
@@ -335,8 +335,6 @@ def _init(args: argparse.Namespace) -> int:
if not args.from_existing:
_create_data_tree(prepared)
else:
- # `--from-existing` 不建目录也不迁库,但口令要补:现有部署正是靠托盘绑局域网
- # 起服务的,没有这个文件下一次重启就会被 `_serve_token` 拒掉。
_announce_token(prepared)
path = settings_file.write(prepared, force=args.force)
print(f"设置文件:{path}")
@@ -367,19 +365,27 @@ def _init_interactive(
windows = os.name == "nt" if windows is None else windows
config, _broken = _resolved_config(None)
print("首次运行问答:每一题直接回车就接受方括号里的默认值。")
+ asked = onboarding.questions(config, windows=windows, home=home)
+ collected: dict[str, object] = {}
try:
- answers = onboarding.interview(config, ask, windows=windows, home=home)
+ for index, question in enumerate(asked):
+ collected[question.key] = onboarding.ask_until_valid(question, ask)
+ if index == 0:
+ # 数据根定了,设置文件在哪也就定了。这一题之后就判,别让人把剩下四题
+ # 答完才听到「文件已存在」——那四个答案会被整份丢掉。
+ config, _broken = _resolved_config(collected["data_root"])
+ if config.path.exists():
+ print(f"设置文件已存在:{config.path}")
+ print("要重新生成就跑 `peach init --force`;它会覆盖这个文件,不动数据。")
+ return 3
except onboarding.OnboardingAborted as exc:
raise SystemExit(f"{exc}已退出,没有写任何文件。") from None
- config, _broken = _resolved_config(answers.data_root)
- if config.path.exists():
- print(f"设置文件已存在:{config.path}")
- print("要重新生成就跑 `peach init --force`;它会覆盖这个文件,不动数据。")
- return 3
- prepared = onboarding.configure(config, answers, windows=windows)
- _create_data_tree(prepared)
- path = settings_file.write(prepared)
- print(f"设置文件:{path}")
+ answers = onboarding.Answers(**collected) # type: ignore[arg-type]
+ applied = onboarding.apply(config, answers, windows=windows)
+ prepared = applied.config
+ print(f"数据根:{prepared.data_root}")
+ _report_data_tree(applied.tree)
+ print(f"设置文件:{applied.settings_path}")
if not windows:
print(onboarding.mounts_explanation(answers.media_dir))
@@ -429,43 +435,43 @@ def _scan(args: argparse.Namespace) -> int:
def _create_data_tree(config: settings_file.PeachConfig) -> None:
- """建目录、把库迁到最新、生成本机 CA。已经有账本就不碰它。"""
- for key in settings_file.DIRECTORY_KEYS:
- config.directory(key).mkdir(parents=True, exist_ok=True)
- tls_dir = config.directory("secrets") / "tls"
- tls_dir.mkdir(parents=True, exist_ok=True)
+ """建目录、把库迁到最新、生成本机 CA。事情由 `onboarding.create_data_tree` 做,
+ 这里只把它做过的事说出来——托盘的设置页调同一个函数,两条前端不会各做一套。
+ """
print(f"数据根:{config.data_root}")
+ _report_data_tree(onboarding.create_data_tree(config))
+
- database = config.directory("database") / "ledger.db"
- if database.is_file():
- # 已有账本却在跑全新 init:不迁移、不备份、不覆盖,让人自己决定。
- print(f"账本已存在,跳过建库:{database}")
+def _report_data_tree(tree: onboarding.DataTree) -> None:
+ if tree.ledger_existed:
+ print(f"账本已存在,跳过建库:{tree.database}")
print("要为现有部署生成设置文件,用 `peach init --from-existing`。")
else:
- done = upgrade(database, MIGRATIONS_DIR)
- print(f"账本:{database}(已应用 {len(done)} 个迁移)")
+ print(f"账本:{tree.database}(已应用 {tree.migrations} 个迁移)")
+ if tree.ca_cert is not None:
+ print(f"本机 CA:{tree.ca_cert}")
+ else:
+ print(f"未生成本机 CA({tree.ca_error})。装好 openssl 后重跑 `peach init --force` 补上。")
+ _report_token(tree)
- try:
- files = certs.bootstrap_certificates(tls_dir, config.server.mdns_name + ".local")
- print(f"本机 CA:{files.ca_cert}")
- except (RuntimeError, OSError) as exc:
- # 没有 openssl 不该挡住初始化:HTTP 本地访问照样能用,装 openssl 后重跑即可。
- print(f"未生成本机 CA({exc})。装好 openssl 后重跑 `peach init --force` 补上。")
- _announce_token(config)
+def _report_token(tree: onboarding.DataTree) -> None:
+ """口令文件的路径。口令本身不打印,用 `peach token` 单独看。
+ 终端输出会进日志、截图和 issue,口令不该顺着这条路走出去。
+ """
+ print(f"访问口令:{tree.token_path}" + ("" if tree.token_created else "(沿用已有的那份)"))
+ print("绑局域网地址的服务必须读得到它,`peach token` 看内容。")
-def _announce_token(config: settings_file.PeachConfig) -> str:
- """确保口令文件存在,并把路径报出来。口令本身不打印,用 `peach token` 单独看。
- 终端输出会进日志、截图和 issue,口令不该顺着这条路走出去。
+def _announce_token(config: settings_file.PeachConfig) -> None:
+ """`--from-existing` 不建目录也不迁库,但口令要补:现有部署正是靠托盘绑局域网
+ 起服务的,没有这个文件下一次重启就会被 `_serve_token` 拒掉。
"""
secrets_dir = config.directory("secrets")
- token, created = auth.ensure_token(secrets_dir)
- path = auth.token_path(secrets_dir)
- print(f"访问口令:{path}" + ("" if created else "(沿用已有的那份)"))
+ _token, created = auth.ensure_token(secrets_dir)
+ print(f"访问口令:{auth.token_path(secrets_dir)}" + ("" if created else "(沿用已有的那份)"))
print("绑局域网地址的服务必须读得到它,`peach token` 看内容。")
- return token
def _token(args: argparse.Namespace) -> int:
@@ -563,6 +569,8 @@ def build_parser() -> argparse.ArgumentParser:
serve.add_argument("--db", type=Path, default=DEFAULT_DB)
serve.add_argument("--token", default="")
serve.add_argument("--docs", action="store_true")
+ serve.add_argument("--setup", action="store_true",
+ help="只提供首次运行表单:忽略发现到的数据根,也不要口令")
serve.add_argument("--no-mdns", action="store_true")
serve.add_argument("--shared-db", type=Path, default=SHARED_DATABASE_PATH)
serve.add_argument("--no-ledger-sync", action="store_true")
diff --git a/src/peach/onboarding.py b/src/peach/onboarding.py
index be32b65b4..44f43684c 100644
--- a/src/peach/onboarding.py
+++ b/src/peach/onboarding.py
@@ -1,9 +1,10 @@
"""首次运行问答:问什么、怎么校验、写出什么样的设置文件。
这里只有纯逻辑,不碰终端:`peach init` 的命令行问答是它的第一个前端,托盘首启打开的
-设置页是第二个,两边都调同一组函数——`questions()` 给出题目、默认值和校验器,
-`interview()` 用注入的 `ask` 把题目走一遍,`configure()` 把答案落成 `PeachConfig`。
-前端只负责把字串送进来、把错误显示出去。
+设置页(`routes_pages`)是第二个,两边都调同一组函数——`questions()` 给出题目、默认值
+和校验器,`interview()` 用注入的 `ask` 把题目走一遍,`configure()` 把答案落成
+`PeachConfig`,`apply()` 把它变成一台能直接起服务的机器(目录、账本、CA、口令、设置
+文件)。前端只负责把字串送进来、把结果和错误显示出去。
问答刻意只收最小集合:数据根、一个本地媒体目录、监听范围、端口、局域网名字。复制、
115、PikPak、writer 镜像与 SMB 一律保持默认关闭或留空——陌生人第一次跑不该被这些问题
@@ -17,12 +18,14 @@
"""
from __future__ import annotations
+import os
import re
from collections.abc import Callable
from dataclasses import dataclass, replace
from pathlib import Path
-from . import settings_file
+from . import auth, certs, settings_file
+from .migrations import upgrade
from .platform import is_windows_path
from .settings_file import PeachConfig
@@ -38,6 +41,12 @@ MAX_ATTEMPTS = 3
POSIX_LOCAL_DECLARED_ROOT = r"R:\media"
#: 本地来源的 ID。v1 只收一个目录,它就是 `asset.location = 'local'`。
LOCAL_LOCATION = "local"
+#: 迁移随代码走,不随数据走。这里不 import `peach.config`:那个模块的常量在进程启动
+#: 那一刻就定型了,而首次设置正是要改变它们指向的数据根。
+MIGRATIONS_DIR = settings_file.PROJECT_ROOT / "migrations"
+#: 「现在扫描」的一次性标记,落在 `<数据根>/state/`。设置页写它、托盘消费它:
+#: 设置页所在的引导服务在设置完成的那一刻就会被托盘停掉,扫描不能跑在它的进程里。
+SCAN_REQUEST_NAME = "first-scan.request"
_DNS_LABEL = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")
_HOST_CHOICES = {
@@ -211,12 +220,129 @@ def configure(config: PeachConfig, answers: Answers, *, windows: bool) -> PeachC
return replace(prepared, locations=locations)
+@dataclass(frozen=True)
+class DataTree:
+ """`create_data_tree()` 做了什么。前端自己决定这些事实怎么说出来。"""
+
+ data_root: Path
+ database: Path
+ #: 这次应用了几个迁移。账本本来就在时是 0。
+ migrations: int
+ ledger_existed: bool
+ token_path: Path
+ token_created: bool
+ #: 没有 openssl 时 CA 生成失败,`ca_cert` 为 None、`ca_error` 是原因。
+ ca_cert: Path | None
+ ca_error: str | None
+
+
+@dataclass(frozen=True)
+class Applied:
+ """一次完整的首次设置:目录、账本、CA、口令、设置文件都已落盘。"""
+
+ config: PeachConfig
+ settings_path: Path
+ tree: DataTree
+
+
+def resolve_config(
+ data_root: Path | None = None, environ: dict[str, str] | None = None,
+) -> tuple[PeachConfig, settings_file.SettingsFileError | None]:
+ """按给定数据根重新解析设置;文件坏了就退回内建默认并把错误一并交出。
+
+ `peach init` 与设置页都要在拿到数据根之后重新解析一次:数据根决定设置文件在哪,
+ 而进程启动时那一份是按发现顺序算的,用户完全可以填一个别的目录。
+ """
+ environ = dict(os.environ if environ is None else environ)
+ if data_root is not None:
+ environ["PEACH_DATA_ROOT"] = str(data_root)
+ try:
+ return settings_file.load_config(environ=environ), None
+ except settings_file.SettingsFileError as exc:
+ return settings_file.load_config(environ=environ, strict=False), exc
+
+
+def create_data_tree(config: PeachConfig) -> DataTree:
+ """建目录、把库迁到最新、生成本机 CA、确保口令存在。已经有账本就不碰它。
+
+ 只做事、不打印:`peach init` 把结果写到终端,设置页把同一批结果写进成功页。
+ """
+ for key in settings_file.DIRECTORY_KEYS:
+ config.directory(key).mkdir(parents=True, exist_ok=True)
+ tls_dir = config.directory("secrets") / "tls"
+ tls_dir.mkdir(parents=True, exist_ok=True)
+
+ database = config.directory("database") / "ledger.db"
+ existed = database.is_file()
+ # 已有账本却在跑全新 init:不迁移、不备份、不覆盖,让人自己决定。
+ applied = 0 if existed else len(upgrade(database, MIGRATIONS_DIR))
+
+ ca_cert: Path | None = None
+ ca_error: str | None = None
+ try:
+ ca_cert = certs.bootstrap_certificates(
+ tls_dir, config.server.mdns_name + ".local").ca_cert
+ except (RuntimeError, OSError) as exc:
+ # 没有 openssl 不该挡住初始化:HTTP 本地访问照样能用,装 openssl 后重跑即可。
+ ca_error = str(exc)
+
+ secrets_dir = config.directory("secrets")
+ _token, created = auth.ensure_token(secrets_dir)
+ return DataTree(
+ data_root=config.data_root, database=database, migrations=applied,
+ ledger_existed=existed, token_path=auth.token_path(secrets_dir),
+ token_created=created, ca_cert=ca_cert, ca_error=ca_error,
+ )
+
+
+def apply(
+ config: PeachConfig, answers: Answers, *, windows: bool, force: bool = False,
+) -> Applied:
+ """把答案变成一台可以直接起服务的机器:目录、账本、CA、口令、设置文件。
+
+ `config` 要按 `answers.data_root` 重新解析过(`resolve_config`)。CLI 问答和托盘的
+ 设置页都只调这一个函数,两条前端因此不可能在「首次运行到底做了什么」上分叉。
+ """
+ prepared = configure(config, answers, windows=windows)
+ tree = create_data_tree(prepared)
+ path = settings_file.write(prepared, force=force)
+ return Applied(config=prepared, settings_path=path, tree=tree)
+
+
+def scan_request_path(config: PeachConfig) -> Path:
+ return config.directory("state") / SCAN_REQUEST_NAME
+
+
+def request_first_scan(config: PeachConfig, location: str = LOCAL_LOCATION) -> Path:
+ """记下「用户要求首扫」。内容是来源 ID,托盘据此拉起 `peach scan <来源>`。"""
+ path = scan_request_path(config)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(location, encoding="utf-8")
+ return path
+
+
+def take_first_scan_request(config: PeachConfig) -> str | None:
+ """读走首扫标记并删掉它,没有就返回 None。只消费一次:删除在读取之后立刻发生,
+ 托盘的健康轮询每几秒跑一轮,留着它等于每一轮都再扫一遍整个媒体目录。
+ """
+ path = scan_request_path(config)
+ try:
+ location = path.read_text(encoding="utf-8").strip()
+ except OSError:
+ return None
+ try:
+ path.unlink()
+ except OSError:
+ return None
+ return location or None
+
+
def scan_root(config: PeachConfig) -> str:
"""首次扫描的账本口径根:就是 `local` 的声明根。本机目录由 `peach.scan` 按挂载表取。"""
return config.locations[LOCAL_LOCATION]
-def mounts_explanation(media_dir: Path) -> str:
+def mounts_explanation(media_dir: Path | str) -> str:
"""非 Windows 平台写出的两行为什么长那样,一句话说清。"""
return (f"账本用统一的 Windows 形态记路径({POSIX_LOCAL_DECLARED_ROOT}\\...),"
f"本机挂载点 [media.mounts] local = {media_dir} 负责翻译成真实文件。")
@@ -240,8 +366,10 @@ def is_interactive(stdin) -> bool:
__all__ = [
- "Answers", "Ask", "LOCAL_LOCATION", "MAX_ATTEMPTS", "OnboardingAborted",
- "POSIX_LOCAL_DECLARED_ROOT", "Question", "ask_until_valid", "configure",
- "console_ask", "default_media_dir", "interview", "is_interactive",
- "mounts_explanation", "questions", "scan_question", "scan_root",
+ "Answers", "Applied", "Ask", "DataTree", "LOCAL_LOCATION", "MAX_ATTEMPTS",
+ "OnboardingAborted", "POSIX_LOCAL_DECLARED_ROOT", "Question", "apply",
+ "ask_until_valid", "configure", "console_ask", "create_data_tree",
+ "default_media_dir", "interview", "is_interactive", "mounts_explanation",
+ "questions", "request_first_scan", "resolve_config", "scan_question",
+ "scan_request_path", "scan_root", "take_first_scan_request",
]
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 77454b036..7b0b45e92 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -103,7 +103,7 @@ class InitCommandTests(unittest.TestCase):
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name).resolve() / "peach-data"
# 证书生成要调 openssl;那是 `test_certs.py` 的事,这里只验初始化流程。
- patcher = mock.patch.object(cli.certs, "bootstrap_certificates")
+ patcher = mock.patch.object(cli.onboarding.certs, "bootstrap_certificates")
self.certs = patcher.start()
self.addCleanup(patcher.stop)
@@ -240,7 +240,7 @@ class InteractiveInitTests(unittest.TestCase):
(self.media / "sub").mkdir(parents=True)
(self.media / "sub" / "a.mp4").write_bytes(b"0" * 10)
(self.media / "b.jpg").write_bytes(b"1")
- patcher = mock.patch.object(cli.certs, "bootstrap_certificates")
+ patcher = mock.patch.object(cli.onboarding.certs, "bootstrap_certificates")
self.certs = patcher.start()
self.addCleanup(patcher.stop)
# 第一题的默认值要落在临时目录里,回车接受默认才不会碰真实数据根。
@@ -405,7 +405,7 @@ class InitDispatchTests(unittest.TestCase):
patcher = mock.patch.object(cli, "_init_interactive", return_value=0)
self.interactive = patcher.start()
self.addCleanup(patcher.stop)
- certs = mock.patch.object(cli.certs, "bootstrap_certificates")
+ certs = mock.patch.object(cli.onboarding.certs, "bootstrap_certificates")
certs.start()
self.addCleanup(certs.stop)