Peach: Local-first video metadata scraper and media manager.
refactor(web): 前端切 ES module,拆出 core.js
longmeidao3188be44ff5e
diff --git a/src/peach/api.py b/src/peach/api.pyindex 0d2d5f5f6..e8aa0d35a 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -364,10 +364,11 @@ def create_app(@app.api_route("/app.css", methods=["GET", "HEAD"])@app.api_route("/app.js", methods=["GET", "HEAD"])def app_asset(request: Request):- """页面拆出来的样式与脚本。和 index.html 同目录,同一套口令。+ """页面拆出来的样式与入口脚本。和 index.html 同目录,同一套口令。- 没有构建步骤:`app.js` 是普通脚本不是 module,顶层声明仍然是全局的,- 和内联时行为一致——内联事件处理器和跨函数调用都还指着同一批全局名字。+ 仍然没有构建步骤:`app.js` 现在是 ES module,浏览器原生解析 import,+ 拆出来的模块见下面的 `/js/{name}`。页面里没有任何内联事件处理器,+ 全部是 `.onclick=` 属性赋值,所以顶层声明不再是全局也不影响绑定。"""args = _first_query_values(request)if not _authorized(request, settings.token, args):@@ -382,6 +383,27 @@ def create_app(response.headers["Cache-Control"] = "no-store"return response+ @app.api_route("/js/{name}", methods=["GET", "HEAD"])+ def app_module(name: str, request: Request):+ """`app.js` 拆出来的 ES module。同一套口令。++ 文件名严格限制为一层平铺的 `[a-z0-9_-]+.js`:静态路由拼路径是典型的目录+ 穿越入口,与其在这里做 resolve 后再比较根目录,不如根本不接受分隔符。+ 前端模块规模不大,平铺够用。+ """+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return PlainTextResponse("需要 ?t=口令", status_code=401)+ if not re.fullmatch(r"[a-z0-9_-]+\.js", name):+ return PlainTextResponse("bad module name", status_code=404)+ path = settings.page_path.parent / "js" / name+ if not path.is_file():+ return PlainTextResponse("missing", status_code=404)+ response = FileResponse(path, media_type="text/javascript; charset=utf-8")+ # 和 index.html/app.js 同一口径:页面一变模块就跟着变,不能被旧缓存钉住。+ response.headers["Cache-Control"] = "no-store"+ return response+@app.api_route("/favicon.svg", methods=["GET", "HEAD"])def favicon():response = Response(web_contract.FAVICON, media_type="image/svg+xml")diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 066b20404..556ef3b6b 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -151,6 +151,9 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):(self.logo_root / "Studio_A.img.ct").write_text("image/png", encoding="utf-8")self.page = self.root / "index.html"self.page.write_text("<!doctype html><title>Peach test</title><main>ready</main>", encoding="utf-8")+ # 前端已拆成 ES module,`/js/{name}` 从页面同级的 js/ 取文件。+ (self.root / "js").mkdir()+ (self.root / "js" / "core.js").write_text("export const ok = 1;", encoding="utf-8")con = sqlite3.connect(self.db)con.executescript(BASE_SCHEMA)con.execute(@@ -254,6 +257,27 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(response.headers["content-type"], "image/png")self.assertTrue(response.content.startswith(b"\x89PNG\r\n\x1a\n"))+ async def test_front_end_modules_are_served_and_the_name_cannot_escape(self):+ """ES module 拆分之后新增的静态路由。++ 路径穿越是静态路由最典型的入口。这里不做 resolve 后比根目录,而是根本不接受+ 分隔符——名字必须是一层平铺的 `[a-z0-9_-]+.js`,别的一律 404。+ """+ served = await self.client.get("/js/core.js?t=secret")+ self.assertEqual(served.status_code, 200)+ self.assertTrue(served.headers["content-type"].startswith("text/javascript"))+ self.assertEqual(served.headers["cache-control"], "no-store")+ self.assertIn("export", served.text, "取回的必须是真的 module")++ for escape in ("..%2f..%2fapp.js", "..%5c..%5csecrets.json", "sub%2fmod.js",+ "Core.js", "core.mjs", "core.js.map"):+ denied = await self.client.get(f"/js/{escape}?t=secret")+ self.assertEqual(denied.status_code, 404, f"{escape} 不该被提供")++ async def test_front_end_modules_need_the_same_token_as_the_page(self):+ unauthorized = await self.client.get("/js/core.js")+ self.assertEqual(unauthorized.status_code, 401)+async def test_follow_avatar_redirects_only_after_the_official_resolver(self):denied = await self.client.get("/follow-avatar?service=fanbox&id=30917150")self.assertEqual(denied.status_code, 401)diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 2f824a31c..d2b32b198 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -943,10 +943,13 @@ class FollowSourceAddTests(FollowContractTests):class FollowWebSourceTests(unittest.TestCase):@classmethoddef setUpClass(cls):+ # 和 test_web_ui 同一口径:Web 表面是拼起来的一个契约,不是某个文件。+ # web/js 下的 ES module 用 glob 收,拆出新模块时不必回头改这里。web = ROOT / "web"+ sources = [web / "index.html", web / "app.css", web / "app.js"]+ sources.extend(sorted((web / "js").glob("*.js")))cls.page = chr(10).join(- (web / name).read_text(encoding="utf-8")- for name in ("index.html", "app.css", "app.js"))+ path.read_text(encoding="utf-8") for path in sources)def assertPageContains(self, needle, message=""):if needle not in self.page:diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex ec6f5eb84..f3a60e8cc 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -6,12 +6,15 @@ from pathlib import Pathclass WebUiSourceTests(unittest.TestCase):@classmethoddef setUpClass(cls):- # 页面已拆成 index.html + app.css + app.js。这些断言守的是「Web 表面」- # 这一个契约,不是某个文件,所以把三份源码接起来一起看。+ # 页面拆成 index.html + app.css + app.js + web/js 下的 ES module。这些断言+ # 守的是「Web 表面」这一个契约,不是某个文件,所以把所有源码接起来一起看。+ # 模块目录用 glob 而不是写死清单:再拆出新模块时不必回头改这里。写死的后果+ # 是断言悄悄扫不到新文件——它照样「通过」,但什么也没守住。web = Path(__file__).resolve().parents[1] / "web"+ sources = [web / "index.html", web / "app.css", web / "app.js"]+ sources.extend(sorted((web / "js").glob("*.js")))cls.page = chr(10).join(- (web / name).read_text(encoding="utf-8")- for name in ("index.html", "app.css", "app.js")+ path.read_text(encoding="utf-8") for path in sources)# 页面源断言必须自带有界失败信息。assertIn 失败时会把整个 index.html(约 189 KB)diff --git a/web/app.js b/web/app.jsindex 4bc0cb979..a32f03b7e 100644--- a/web/app.js+++ b/web/app.js@@ -1,53 +1,31 @@-const $=s=>document.querySelector(s);-const icon=(name,cls='')=>`<svg${cls?` class="${cls}"`:''} viewBox="0 0 24 24" aria-hidden="true"><use href="#i-${name}"/></svg>`;-const api=async(p,o)=>{- const response=await fetch(p,Object.assign({headers:{'Content-Type':'application/json'}},o||{}));- let payload=null;- try{payload=await response.json()}catch(_e){}- if(!response.ok){- const detail=payload&&(payload.message||payload.detail||payload.error);- throw new Error(detail||`请求失败(${response.status})`);- }- return payload;-};-const pageTitle=path=>{- const url=new URL(path,location.origin),parts=decodeURIComponent(url.pathname).split('/').filter(Boolean);- const fixed={stats:'统计',taste:'口味',review:'人工复核',duplicates:'重复文件','quality-goals':'高清版',- follow:'关注','follow-manage':'关注管理',playlists:'播放列表',performers:'女优',studios:'厂牌',- creators:'创作者',series:'系列',tags:'标签',unseen:'没看过','watch-later':'稍后看',flagged:'已标记',- immerse:'沉浸模式',mix:'Mix',item:'作品','resource-sync':'统计'};- const label=parts.length>1&&['performers','studios','creators','series'].includes(parts[0])- ? parts.slice(1).join('/') : fixed[parts[0]];- return label?`${label} · Peach`:'Peach · 蜜桃';-};-const syncPageTitle=path=>{document.title=pageTitle(path)};-const STATE_ROUTES={fresh:'/unseen',later:'/watch-later',flagged:'/flagged'};-const ROUTE_STATES=Object.fromEntries(Object.entries(STATE_ROUTES).map(([state,path])=>[path,state]));-const STATE_LABELS={fresh:'没看过',later:'稍后看',flagged:'已标记'};-const isCatalogPath=path=>path==='/'||Object.prototype.hasOwnProperty.call(ROUTE_STATES,path);+import {+ $,+ icon,+ api,+ pageTitle,+ syncPageTitle,+ STATE_ROUTES,+ ROUTE_STATES,+ STATE_LABELS,+ isCatalogPath,+ ENTITY_ROUTES,+ ROUTE_ENTITIES,+ entityPath,+ esc,+ SITE_FAVICONS,+ faviconUrl,+ faviconFallbackUrl,+ foldName,+ fmtDur,+ fmtClock,+ fmtSize,+ LOC,+} from './js/core.js';+const route=(path,replace=false)=>{history[replace?'replaceState':'pushState']({},'',path);syncPageTitle(path);queueMicrotask(()=>{syncHeaderActions();paintListTitle()});};-const ENTITY_ROUTES={performer:'performers',studio:'studios',creator:'creators',series:'series'};-const ROUTE_ENTITIES={performers:'performer',studios:'studio',creators:'creator',series:'series'};-const entityPath=(kind,name)=>`/${ENTITY_ROUTES[kind]||kind}/${encodeURIComponent(name)}`;-const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));-const SITE_FAVICONS={- 'kemono.cr':'https://kemono.cr/assets/favicon-CPB6l7kH.ico',- 'simpcity.cr':'https://simpcity.cr/data/assets/logo/favicon.png',- 'hanime1.me':'https://vdownload.hembed.com/image/icon/tab_logo.png?secure=EJYLwnrDlidVi_wFp3DaGw==,4867726124',-};-const faviconUrl=url=>{try{const parsed=new URL(url),host=parsed.hostname.replace(/^www\./,'');- return SITE_FAVICONS[host]||new URL('/favicon.ico',parsed).href}catch{return ''}};-const faviconFallbackUrl=domain=>`https://www.google.com/s2/favicons?domain=${encodeURIComponent(domain)}&sz=64`;-const foldName=s=>String(s??'').normalize('NFKC').trim().toLocaleLowerCase();-const fmtDur=s=>{if(!s)return'—';s=Math.round(s);const h=s/3600|0,m=(s%3600)/60|0,x=s%60;- return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`};-const fmtClock=s=>{s=Math.max(0,Math.floor(Number(s)||0));const h=s/3600|0,m=(s%3600)/60|0,x=s%60;- return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`};-const fmtSize=b=>b>=1099511627776?(b/1099511627776).toFixed(2)+' TB':b>=1073741824?(b/1073741824).toFixed(1)+' GB':(b/1048576|0)+' MB';-const LOC={local:'本地','115':'115',pikpak:'PikPak',online:'在线'};/* ── 脱盘模式 ─────────────────────────────────────────────────────────────────脱盘是来源级的:外置盘拔掉只影响 local,115/PikPak 照常可播;反过来也一样。diff --git a/web/index.html b/web/index.htmlindex 27c3ef877..84fe6d241 100644--- a/web/index.html+++ b/web/index.html@@ -153,6 +153,6 @@<script src="/vendor/videojs/8.23.9/video.min.js"></script><script src="/vendor/videojs/8.23.9/lang/zh-CN.js"></script>-<script src="/app.js"></script>+<script type="module" src="/app.js"></script></body></html>diff --git a/web/js/core.js b/web/js/core.jsnew file mode 100644index 000000000..db065140a--- /dev/null+++ b/web/js/core.js@@ -0,0 +1,76 @@+/* 前端最底层:DOM 取元素、请求、转义、格式化、路由常量。++ 没有构建步骤——浏览器原生 ES module,只是文件多了几个。这一层不许 import 任何+ 别的前端模块:它被所有域引用,一旦反向依赖就会绕成环。++ `route()` 没有放进来:它要调 syncHeaderActions/paintListTitle,那是 UI 层的事。 */+const $=s=>document.querySelector(s);+const icon=(name,cls='')=>`<svg${cls?` class="${cls}"`:''} viewBox="0 0 24 24" aria-hidden="true"><use href="#i-${name}"/></svg>`;+const api=async(p,o)=>{+ const response=await fetch(p,Object.assign({headers:{'Content-Type':'application/json'}},o||{}));+ let payload=null;+ try{payload=await response.json()}catch(_e){}+ if(!response.ok){+ const detail=payload&&(payload.message||payload.detail||payload.error);+ throw new Error(detail||`请求失败(${response.status})`);+ }+ return payload;+};+const pageTitle=path=>{+ const url=new URL(path,location.origin),parts=decodeURIComponent(url.pathname).split('/').filter(Boolean);+ const fixed={stats:'统计',taste:'口味',review:'人工复核',duplicates:'重复文件','quality-goals':'高清版',+ follow:'关注','follow-manage':'关注管理',playlists:'播放列表',performers:'女优',studios:'厂牌',+ creators:'创作者',series:'系列',tags:'标签',unseen:'没看过','watch-later':'稍后看',flagged:'已标记',+ immerse:'沉浸模式',mix:'Mix',item:'作品','resource-sync':'统计'};+ const label=parts.length>1&&['performers','studios','creators','series'].includes(parts[0])+ ? parts.slice(1).join('/') : fixed[parts[0]];+ return label?`${label} · Peach`:'Peach · 蜜桃';+};+const syncPageTitle=path=>{document.title=pageTitle(path)};+const STATE_ROUTES={fresh:'/unseen',later:'/watch-later',flagged:'/flagged'};+const ROUTE_STATES=Object.fromEntries(Object.entries(STATE_ROUTES).map(([state,path])=>[path,state]));+const STATE_LABELS={fresh:'没看过',later:'稍后看',flagged:'已标记'};+const isCatalogPath=path=>path==='/'||Object.prototype.hasOwnProperty.call(ROUTE_STATES,path);+const ENTITY_ROUTES={performer:'performers',studio:'studios',creator:'creators',series:'series'};+const ROUTE_ENTITIES={performers:'performer',studios:'studio',creators:'creator',series:'series'};+const entityPath=(kind,name)=>`/${ENTITY_ROUTES[kind]||kind}/${encodeURIComponent(name)}`;+const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));+const SITE_FAVICONS={+ 'kemono.cr':'https://kemono.cr/assets/favicon-CPB6l7kH.ico',+ 'simpcity.cr':'https://simpcity.cr/data/assets/logo/favicon.png',+ 'hanime1.me':'https://vdownload.hembed.com/image/icon/tab_logo.png?secure=EJYLwnrDlidVi_wFp3DaGw==,4867726124',+};+const faviconUrl=url=>{try{const parsed=new URL(url),host=parsed.hostname.replace(/^www\./,'');+ return SITE_FAVICONS[host]||new URL('/favicon.ico',parsed).href}catch{return ''}};+const faviconFallbackUrl=domain=>`https://www.google.com/s2/favicons?domain=${encodeURIComponent(domain)}&sz=64`;+const foldName=s=>String(s??'').normalize('NFKC').trim().toLocaleLowerCase();+const fmtDur=s=>{if(!s)return'—';s=Math.round(s);const h=s/3600|0,m=(s%3600)/60|0,x=s%60;+ return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`};+const fmtClock=s=>{s=Math.max(0,Math.floor(Number(s)||0));const h=s/3600|0,m=(s%3600)/60|0,x=s%60;+ return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`};+const fmtSize=b=>b>=1099511627776?(b/1099511627776).toFixed(2)+' TB':b>=1073741824?(b/1073741824).toFixed(1)+' GB':(b/1048576|0)+' MB';+const LOC={local:'本地','115':'115',pikpak:'PikPak',online:'在线'};++export {+ $,+ icon,+ api,+ pageTitle,+ syncPageTitle,+ STATE_ROUTES,+ ROUTE_STATES,+ STATE_LABELS,+ isCatalogPath,+ ENTITY_ROUTES,+ ROUTE_ENTITIES,+ entityPath,+ esc,+ SITE_FAVICONS,+ faviconUrl,+ faviconFallbackUrl,+ foldName,+ fmtDur,+ fmtClock,+ fmtSize,+ LOC,+};