Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor(web): 路由模块共用的入口函数收进 web_entry

longmeidao9aeef20f03e4
diff --git a/src/peach/routes_auth.py b/src/peach/routes_auth.py
index 980855464..c4febaa18 100644
--- a/src/peach/routes_auth.py
+++ b/src/peach/routes_auth.py
@@ -15,6 +15,7 @@ from collections import OrderedDict
import threading
import time
from . import access
+from .web_entry import board_entry_style
from starlette.concurrency import run_in_threadpool
from urllib.parse import parse_qs
@@ -82,9 +83,15 @@ class AssetLoginRequired(Exception):
"""页面资产(app.css/app.js)未授权:401 形态是 PlainText 提示。"""
+def same_origin(request: Request) -> None:
+ """浏览器发来的写请求必须来自 Peach 自己的页面:带了别处的 Origin 就拒。"""
+ origin = request.headers.get("origin")
+ if request.headers.get("sec-fetch-site") == "cross-site" or (origin and origin.rstrip("/") != str(request.base_url).rstrip("/")):
+ raise HTTPException(403, "请从 Peach 配置页提交")
+
+
def require_auth(request: Request) -> dict[str, str]:
if request.method not in {"GET", "HEAD", "OPTIONS"}:
- from .routes_configuration import same_origin
same_origin(request)
args = _first_query_values(request)
if not _authorized(request, request.app.state.settings.token, args):
@@ -118,7 +125,6 @@ def set_auth_cookie(response: Response, request: Request, *, days: int = 30, log
def login_html(next_path: str, *, invalid: bool = False) -> str:
- from .routes_pages import board_entry_style
safe_next = html.escape(next_path, quote=True)
error = '<p role="alert">访问密码不正确</p>' if invalid else ""
return (
@@ -185,7 +191,6 @@ def login(request: Request, next: str = "/"):
@router.post("/login")
async def login_submit(request: Request):
- from .routes_configuration import same_origin
same_origin(request)
_login_attempt(request)
token = request.app.state.settings.token
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index 03935ffde..55ef9cc35 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -20,8 +20,8 @@ from fastapi.responses import JSONResponse
from filelock import FileLock, Timeout
from . import access, distribution, folder_picker, onboarding, settings_file, media_configuration
-from .routes_auth import require_auth
-from .routes_pages import runtime_fact_entries
+from .routes_auth import require_auth, same_origin
+from .web_entry import runtime_fact_entries
from . import release_updates, standalone_update, peach_proxy, desktop_startup, desktop_uninstall
router = APIRouter()
@@ -267,13 +267,6 @@ def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, A
return errors, validated
-def same_origin(request: Request) -> None:
- """浏览器发来的写请求必须来自 Peach 自己的页面:带了别处的 Origin 就拒。"""
- origin = request.headers.get("origin")
- if request.headers.get("sec-fetch-site") == "cross-site" or (origin and origin.rstrip("/") != str(request.base_url).rstrip("/")):
- raise HTTPException(403, "请从 Peach 配置页提交")
-
-
@router.post("/api/configuration/access")
def save_access(request: Request, body: dict[str, Any] = Body(default_factory=dict),
_args=Depends(require_auth)):
diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.py
index 269db3dfe..a2c3e023d 100644
--- a/src/peach/routes_pages.py
+++ b/src/peach/routes_pages.py
@@ -37,6 +37,7 @@ from fastapi.responses import (
from . import auth, distribution, onboarding, settings_file
from .config import PROJECT_ROOT
from .routes_auth import require_asset_auth, require_page_auth, set_auth_cookie
+from .web_entry import board_entry_style, runtime_fact_entries
from .web_state import FAVICON
router = APIRouter()
@@ -362,12 +363,6 @@ def _document(title: str, body: str) -> str:
f'<style>{_board_button_rules()}</style><style>{facts_css}</style></head><body><svg width="0" height="0" aria-hidden="true" style="position:absolute">{symbols}</svg><main>{body}</main>{_SETUP_SCRIPT}{_SHARED_SCRIPT}</body></html>\n')
-def board_entry_style() -> str:
- """入口页内联公共视觉层。首启和登录页不加载 app.js,样式得随 HTML 一起送到。"""
- css = (PROJECT_ROOT / "web/board-entry.css").read_text(encoding="utf-8")
- return f'<style id="boardEntryStyles">{css}</style>'
-
-
def _check_html(name: str, text_html: str, *, checked: bool) -> str:
"""站内共用的自绘勾选框:文字与框同属一个 label,没有点不到的缝。"""
return (f'<label class="check"><span class="pcheck"><input type="checkbox" name="{name}" value="y"'
@@ -375,38 +370,6 @@ def _check_html(name: str, text_html: str, *, checked: bool) -> str:
+ f'><span aria-hidden="true">{_CHECK_SVG}</span></span><span>{text_html}</span></label>')
-def runtime_facts(config) -> tuple[tuple[str, str], ...]:
- """这台机器上 Peach 的位置与版本:设置完成页和 `/api/configuration` 共用同一份。"""
- from . import __version__
- import platform as system_platform
- from .ffmpeg import FFmpegResolver
-
- available = FFmpegResolver(config.directory("tools") / "ffmpeg").ffmpeg() is not None
- ffmpeg = "可用" if available else "未安装;MP4 可直接播放,转码和缩略图需要安装 FFmpeg。"
- return (
- ("版本", __version__),
- ("操作系统", system_platform.system()),
- ("数据目录", str(config.data_root)),
- ("设置文件", str(config.path)),
- ("日志目录", str(config.directory("logs"))),
- ("FFmpeg", ffmpeg),
- )
-
-
-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>')
diff --git a/src/peach/web_entry.py b/src/peach/web_entry.py
new file mode 100644
index 000000000..b40b05d1b
--- /dev/null
+++ b/src/peach/web_entry.py
@@ -0,0 +1,48 @@
+"""入口页共用件:首启、登录与配置页都要的内联样式和运行信息。
+
+这些页面不加载 `app.js`,样式得随 HTML 一起送到;运行信息则被首启完成页、登录页
+和 `/api/configuration` 共用。三个路由模块都要,就不能住在其中任何一个里:那会让
+路由层互相导入成环。放在 web 层,路由模块单向依赖它,`tests/test_module_layering.py`
+守着这个方向。
+"""
+from __future__ import annotations
+
+from .config import PROJECT_ROOT
+
+
+def board_entry_style() -> str:
+ """入口页内联公共视觉层。首启和登录页不加载 app.js,样式得随 HTML 一起送到。"""
+ css = (PROJECT_ROOT / "web/board-entry.css").read_text(encoding="utf-8")
+ return f'<style id="boardEntryStyles">{css}</style>'
+
+
+def runtime_facts(config) -> tuple[tuple[str, str], ...]:
+ """这台机器上 Peach 的位置与版本:设置完成页和 `/api/configuration` 共用同一份。"""
+ from . import __version__
+ import platform as system_platform
+ from .ffmpeg import FFmpegResolver
+
+ available = FFmpegResolver(config.directory("tools") / "ffmpeg").ffmpeg() is not None
+ ffmpeg = "可用" if available else "未安装;MP4 可直接播放,转码和缩略图需要安装 FFmpeg。"
+ return (
+ ("版本", __version__),
+ ("操作系统", system_platform.system()),
+ ("数据目录", str(config.data_root)),
+ ("设置文件", str(config.path)),
+ ("日志目录", str(config.directory("logs"))),
+ ("FFmpeg", ffmpeg),
+ )
+
+
+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
diff --git a/tests/test_configuration_sources.py b/tests/test_configuration_sources.py
index 30bef9c35..159d5fd51 100644
--- a/tests/test_configuration_sources.py
+++ b/tests/test_configuration_sources.py
@@ -11,7 +11,7 @@ from peach import media_configuration as media_config, onboarding, settings_file
class MediaConfigurationTests(unittest.TestCase):
def test_setup_mapping_fields_follow_the_server_operating_system(self):
- from peach import routes_pages
+ from peach import routes_pages, web_entry
with tempfile.TemporaryDirectory() as directory:
config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(Path(directory).resolve())})
windows = routes_pages.setup_page(config, windows=True)
@@ -23,7 +23,7 @@ class MediaConfigurationTests(unittest.TestCase):
self.assertIn('new MutationObserver(enhance)', windows)
self.assertIn('id="i-chevron-down"', windows)
self.assertIn('.help a:hover{text-decoration:underline;', windows)
- facts = dict(routes_pages.runtime_facts(config))
+ facts = dict(web_entry.runtime_facts(config))
self.assertIn('操作系统', facts)
self.assertIn('设置文件', facts)
diff --git a/tests/test_module_layering.py b/tests/test_module_layering.py
index 6f804c367..701bbb13e 100644
--- a/tests/test_module_layering.py
+++ b/tests/test_module_layering.py
@@ -241,6 +241,26 @@ class LayeringTests(unittest.TestCase):
"非 web 模块不得依赖 web 层:把共享的纯规则下沉到 catalog_rules 一类的策略模块",
)
+ def test_route_modules_only_depend_on_the_auth_routes(self):
+ """路由层内部也是单向的:`routes_auth` 在最下面,别的 `routes_*` 只许 import 它。
+
+ `same_origin` 曾住在 `routes_configuration`,登录路由要用就在函数里反向 import;
+ `board_entry_style` 与运行信息住在 `routes_pages`,配置路由同样反向去拿。三个模块
+ 于是成了一个靠函数内 import 撑住的环——import 图上看不出来,读代码的人也说不清
+ 谁在谁上面。共享件下沉到 web 层(`web_entry`),路由模块之间只剩鉴权依赖这一个方向。
+ 函数内的 import 一样算:`_local_imports` 扫整棵语法树,不只看文件顶部。
+ """
+ offenders = []
+ for path in sorted(SOURCE_ROOT.glob("routes_*.py")):
+ module = path.stem
+ allowed = set() if module == "routes_auth" else {"routes_auth"}
+ for imported in sorted(_local_imports(path) & ROUTE_MODULES - allowed):
+ offenders.append(f"{module} → {imported}")
+ self.assertEqual(
+ offenders, [],
+ "routes_* 之间只许依赖 routes_auth:两个路由都要的东西下沉到 web_* 模块",
+ )
+
def test_catalog_rules_depends_on_nothing_inside_peach(self):
"""最底下那层必须是纯的:只要它开始 import 别的 Peach 模块,就不再是策略了。"""
self.assertEqual(
diff --git a/tests/test_onboarding.py b/tests/test_onboarding.py
index 086396995..31db61998 100644
--- a/tests/test_onboarding.py
+++ b/tests/test_onboarding.py
@@ -691,7 +691,8 @@ class StandaloneConfigurationTests(_Case):
self.assertEqual(client.get(f"/api/configuration/{path}",headers={"X-Token":"test-token"}).status_code,403)
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
+ from peach.routes_pages import runtime_facts_html
+ from peach.web_entry import runtime_fact_entries
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(
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 85aa12457..771043171 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -11684,7 +11684,7 @@ class BoardStyleIsolationTests(unittest.TestCase):
root = Path(__file__).resolve().parents[1]
html = (root / "web/index.html").read_text(encoding="utf-8")
self.assertIn('<link rel="stylesheet" href="/board.css">', html)
- entry = (root / "src/peach/routes_pages.py").read_text(encoding="utf-8")
+ entry = (root / "src/peach/web_entry.py").read_text(encoding="utf-8")
self.assertIn("return f'<style id=\"boardEntryStyles\">{css}</style>'", entry)
for path in sorted((root / "web").rglob("*")):
if path.suffix not in {".js", ".css", ".html"} or "dist" in path.parts: