Peach: Local-first video metadata scraper and media manager.
Merge branch 'master' into agent/claude/web-esm-modules
longmeidao7c06e0db30a0
diff --cc src/peach/api.pyindex e8aa0d35a,49faa2d8a..291dd73fc--- a/src/peach/api.py+++ b/src/peach/api.py@@@ -363,16 -411,12 +411,13 @@@ def create_app@app.api_route("/app.css", methods=["GET", "HEAD"])@app.api_route("/app.js", methods=["GET", "HEAD"])- def app_asset(request: Request):+ def app_asset(request: Request, args: dict[str, str] = Depends(require_asset_auth)):- """页面拆出来的样式与脚本。和 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):- return PlainTextResponse("需要 ?t=口令", status_code=401)name = request.url.path.lstrip("/")path = settings.page_path.parent / nameif not path.is_file():@@@ -383,27 -427,6 +428,24 @@@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。同一套口令。++ def app_module(name: str, args: dict[str, str] = Depends(require_asset_auth)):++ """`app.js` 拆出来的 ES module。和入口脚本同一套口令与 401 形态。++ 文件名严格限制为一层平铺的 `[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 --cc web/app.jsindex a32f03b7e,16fd3a864..13b3b33a8--- a/web/app.js+++ b/web/app.js@@@ -1,27 -1,44 +1,41 @@@-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 · 蜜桃';-};+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';++ /* 路由同时把页面表面写进 body[data-surface]:限宽等按表面生效的版式+ (管理页不全宽)靠它切换,不用每个渲染函数自己记得加类。+ 调用方有传 path 也有传 href 的,这里统一归一成 pathname。 */+ const syncPageTitle=path=>{+ document.title=pageTitle(path);+ document.body.dataset.surface=new URL(path,location.origin).pathname;+ paintNav();+ };+ /* 导航激活态必须在每次路由变化时重算:抽屉与窄栏的按钮是 buildBars 时+ 一次性画出来的,管理页不跑 buildBars,切页后它们会停留在上一个页面的+ 按下态(实测 /stats 下「首页」还亮着)。 */+ function paintNav(){+ document.querySelectorAll('.edge button[data-nav],#drawer .dnav button[data-nav]')+ .forEach(b=>b.setAttribute('aria-pressed',String(navOn(b.dataset.nav))));+ }-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 route=(path,replace=false)=>{history[replace?'replaceState':'pushState']({},'',path);syncPageTitle(path);queueMicrotask(()=>{syncHeaderActions();paintListTitle()});diff --cc web/index.htmlindex 84fe6d241,b37a92e80..eb11f3809--- a/web/index.html+++ b/web/index.html@@@ -151,8 -165,10 +165,10 @@@</div></section>+ <div class="toasts" id="toasts" role="status" aria-live="polite"></div>+<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 --cc web/js/core.jsindex db065140a,000000000..204d9bee8mode 100644,000000..100644--- a/web/js/core.js+++ b/web/js/core.js@@@ -1,76 -1,0 +1,74 @@@+/* 前端最底层: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,+};