Peach: Local-first video metadata scraper and media manager.
fix(web): 实体别名页面统一到规范地址
longmeidaod95ab774fbec
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex dfe51f48b..0e99f1cb3 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -455,6 +455,8 @@ Python 复用 MIT 许可的 [Ruff](https://docs.astral.sh/ruff/) 0.16.10,版## 厂牌名称身份+实体资料页的旧名与大小写变体按账本规范名统一地址:服务端复用 `RedirectResponse` 与 `resolve_entity`,站内复用实体控制器的 replace 导航;查询与片段保留,歧义或未知身份不重定向。规范名沿用账本,不新增独立 slug。+作品列表、分页与筛选统计复用 `entities.resolve_entity` 将名称解析为实体 ID,再用 `web_entity.scope_predicate` 获取关系范围;五类资料实体共用此入口,厂牌覆盖旗下各级 label,事务所覆盖成员作品。未取得唯一身份时返回空集合。`entities.studio_name_key` 与 `studio_identity_ids` 供入库、元数据落地、名称解析和 `merge_studio_name_variants.py` 共用:NFKC、符号写法及唯一登记别名映射到规范身份。官方标题确认的 [ATTACKERS](https://attackers.net/)、[PREMIUM](https://premium-beauty.com/) 日英并写名和 [kawaii*](https://kawaiikawaii.jp/) 星号写法纳入精确映射。名称冲突保留来源原文;括号两侧须各自唯一指向同一实体;`AVOP` 跨厂牌共用,不作为合并证据。复用项目实体合并、字段归属、SQLite 备份和复核 CSV,无新增依赖。diff --git a/frontend/e2e/entity-filter.test.ts b/frontend/e2e/entity-filter.test.tsindex ef4702105..d829458ad 100644--- a/frontend/e2e/entity-filter.test.ts+++ b/frontend/e2e/entity-filter.test.ts@@ -106,6 +106,22 @@ describe('实体页筛选浮层', () => {before(async () => { browser = await launch(); });after(async () => { await browser?.close(); });+ for (const viewport of [DESKTOP, PHONE]) {+ it(`${viewport.mobile ? '手机' : '桌面'}别名地址归一保留参数与片段,后退回到入口`, { timeout: 60_000 }, async () => {+ const opened = await visit(browser, '/', viewport);+ try {+ const { page } = opened;+ await serve(page);+ const suffix = '?sort=release&dir=asc&tag=a%2Fb&offset=48#works';+ await page.goto(new URL('/performers/OldName' + suffix, page.url()).href, { waitUntil: 'load' });+ await page.waitForURL(url => url.pathname === PATH && url.search + url.hash === suffix);+ await page.locator('[data-entity-filter-glass] [data-entity-readout]').waitFor();+ await page.goBack({ waitUntil: 'load' });+ assert.equal(new URL(page.url()).pathname, '/');+ } finally { await opened.close(); }+ });+ }+it('骨架里那块浮层换成真浮层时不跳:大小、离资料卡的距离与作品网格的上沿都留在原位', { timeout: 60_000 }, async () => {const opened = await visit(browser, '/', DESKTOP);try {diff --git a/frontend/src/application/entity.js b/frontend/src/application/entity.jsindex 71eb9cde4..26cf87371 100644--- a/frontend/src/application/entity.js+++ b/frontend/src/application/entity.js@@ -242,7 +242,7 @@ export function connectPhotoController(){controller:{context:()=>{const context=currentBarsContext();return context.type==='entity'?context:null},live:(kind,name)=>entityState.entityPageLive(kind,name),current:()=>entityState.entityPageCurrent(),- route:(path,replace=false)=>navigationState.route(path,replace),search:()=>location.search,+ route:(path,replace=false)=>navigationState.route(path,replace),suffix:()=>location.search+location.hash,restoreHomeContext:()=>writeShell({barsContext:{type:'home',filters:state}}),releaseBodyPreviews:()=>releaseHoverPreviews($('#index [data-entity-body]')),push:pushEntityPage,state:()=>({seed:String(state.seed||''),jav:state.jav==='1'}),diff --git a/frontend/src/react/entity-page/entity-controller.ts b/frontend/src/react/entity-page/entity-controller.tsindex a08a50c88..57deb5728 100644--- a/frontend/src/react/entity-page/entity-controller.ts+++ b/frontend/src/react/entity-page/entity-controller.ts@@ -13,7 +13,7 @@ export interface EntityControllerPorts {live(kind: string, name: string): boolean;current(): boolean;route(path: string, replace?: boolean): void;- search(): string;+ suffix(): string;restoreHomeContext(): void;releaseBodyPreviews(): void;push(patch: Partial<EntityOpeningProps>): void;@@ -78,7 +78,7 @@ export function createEntityController(ports: EntityControllerPorts, helpers: EnsetJavLayout: value => { ports.setJavLayout(value); ports.push({ javLayout: ports.javLayout() }) },setPhotoLayout: value => { ports.setPhotoLayout(value); ports.syncPhotoWalls() },openEntity: (target, to, replace = false) => {- if (replace) ports.route(entityPath(target, to) + ports.search(), true);+ if (replace) ports.route(entityPath(target, to) + ports.suffix(), true);else ports.openEntity(target, to);},painted: (view, wall) => {diff --git a/frontend/src/react/entity-page/entity-page-view.tsx b/frontend/src/react/entity-page/entity-page-view.tsxindex 8c98e8e6d..1d0a5a35d 100644--- a/frontend/src/react/entity-page/entity-page-view.tsx+++ b/frontend/src/react/entity-page/entity-page-view.tsx@@ -41,7 +41,8 @@ export function EntityPage(props: EntityPageProps) {/* 名字对不上任何一位时 `/api/entity` 回 `{error}`:整块换成壳里那一屏空态,骨架不留着闪。空态是遗留层的标记,不放进 React 子树的样式范围。 */const missing = !!entity.data?.error;- const redirect = entity.data?.redirect;+ const canonical = entity.data?.canonical_name;+ const redirect = entity.data?.redirect ?? (canonical && canonical !== name ? { kind, name: canonical } : undefined);const { actions } = props;useLayoutEffect(() => { if (missing) actions.missing() }, [actions, missing]);/* 换到规范资料页排到微任务里:壳换页会重排页头与选中态,那一路可能走到批量条的 `flushSync`,diff --git a/frontend/test/react/entity-controller.test.ts b/frontend/test/react/entity-controller.test.tsindex c3156e3c3..5ae89e34f 100644--- a/frontend/test/react/entity-controller.test.ts+++ b/frontend/test/react/entity-controller.test.ts@@ -22,7 +22,7 @@ function setup() {let context: EntityContext | null = { kind: 'creator', name: '甲', filters: { ...emptyEntityFilters(), tag: 'one' } };let seed = '7', live = true, current = true, photos = false;const ports: EntityControllerPorts = {- context: () => context, live: () => live, current: () => current, route: vi.fn(), search: () => '?media=online',+ context: () => context, live: () => live, current: () => current, route: vi.fn(), suffix: () => '?media=online#works',restoreHomeContext: vi.fn(), releaseBodyPreviews: vi.fn(), push: vi.fn(), state: () => ({ seed, jav: false }),preferences: () => ({ revision: 3, feedRevision: 2, photoSize: 'small', photoLayout: 'fixed', followImagesOnly: false,javLayout: 'cover', javLayouts: [], photoLayouts: [], states: [], peopleLayout: 'compact',@@ -87,7 +87,7 @@ describe('实体与索引域控制', () => {expect(actions.reshuffleVideos()).toBe('31');expect(ports.push).toHaveBeenLastCalledWith(expect.objectContaining({ seed: '31' }));actions.openEntity('creator', '乙', true);- expect(ports.route).toHaveBeenLastCalledWith('/creators/%E4%B9%99?media=online', true);+ expect(ports.route).toHaveBeenLastCalledWith('/creators/%E4%B9%99?media=online#works', true);actions.avatarChanged();expect(ports.dropBars).toHaveBeenCalledOnce();});diff --git a/frontend/test/react/entity-page.test.tsx b/frontend/test/react/entity-page.test.tsxindex e8f3468ed..7d0fd192d 100644--- a/frontend/test/react/entity-page.test.tsx+++ b/frontend/test/react/entity-page.test.tsx@@ -199,6 +199,20 @@ describe('首屏', () => {expect(page.host.querySelector('[data-entity-hero]')).toBeNull();});+ it.each(['performer', 'creator', 'studio', 'series', 'agency'])('别名入口替换为 %s 的规范资料页', async kind => {+ const page = await open({ entity: entity({ kind, canonical_name: 'Canonical' }) }, { kind, name: 'Alias' });+ expect(page.props.actions.openEntity).toHaveBeenCalledExactlyOnceWith(kind, 'Canonical', true);+ expect(page.props.actions.missing).not.toHaveBeenCalled();+ expect(cards(page.props)).toEqual([]);+ });++ it('规范名入口直接显示资料页', async () => {+ const page = await open();+ expect(page.props.actions.openEntity).not.toHaveBeenCalled();+ expect(cards(page.props)).toEqual(['1', '2', '3']);+ expect(readout(page.props)).toBe('视频 · 3');+ });+it('资料、作品第一页、整组照片与新作在挂载前取齐,挂上之后不再补请求', async () => {const page = await open({ feed: { items: [{ id: 31, has_cover: true }] } });expect(page.calls('/api/entity')).toHaveLength(1);diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.pyindex 4526a013a..06f0a092d 100644--- a/src/peach/routes_pages.py+++ b/src/peach/routes_pages.py@@ -23,6 +23,7 @@ from collections.abc import Mapping, Sequenceimport refrom pathlib import Path+from urllib.parse import quotefrom fastapi import APIRouter, Depends, HTTPException, Requestfrom fastapi.responses import (@@ -36,6 +37,7 @@ from fastapi.responses import (from . import distribution, onboarding, settings_filefrom .config import PROJECT_ROOT+from .entities import resolve_entityfrom .routes_auth import require_asset_auth, require_page_auth, set_auth_cookiefrom .web_entry import page_shell, runtime_fact_entriesfrom .web_state import FAVICON@@ -670,4 +672,20 @@ def client_route(request: Request, item_id: int | None = None,playlist_id: int | None = None, playlist_item_id: int | None = None,kind: str | None = None, name: str | None = None, code: str | None = None,args: dict[str, str] = Depends(require_page_auth)):+ settings = request.app.state.settings+ if name and "name" in request.path_params and settings.configured and not (settings.token and args.get("t")):+ from .web_entity import INDEX_ENTITY_KINDS++ prefix = request.url.path.split("/", 2)[1]+ entity_kind = {**INDEX_ENTITY_KINDS, "series": "series"}.get(prefix)+ if entity_kind:+ with request.app.state.web_contract.read_connection() as connection:+ entity = resolve_entity(connection, entity_kind, name)+ if entity is not None and entity["canonical_name"] != name:+ raw_query = request.scope.get("query_string", b"").decode("utf-8")+ query = f"?{raw_query}" if raw_query else ""+ response = RedirectResponse(+ f"/{prefix}/{quote(entity['canonical_name'], safe='')}" + query, status_code=307)+ response.headers["Cache-Control"] = "no-store"+ return responsereturn index(request, args)diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex a045d0220..b06380ad8 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -1759,6 +1759,49 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(response.status_code, 307, (index, method))self.assertEqual(response.headers['location'], f'/{index}?q=A%2FB&view=cloud')+ async def test_entity_alias_urls_redirect_to_canonical_names_and_keep_query(self):+ await self.client.post('/login', content='token=secret&next=%2F',+ headers={'Content-Type': 'application/x-www-form-urlencoded'})+ kinds = [('performer', 'performers'), ('creator', 'creators'), ('studio', 'studios'),+ ('series', 'series'), ('agency', 'agencies')]+ canonical = 'Canonical / 名%? #&'+ with closing(sqlite3.connect(self.db)) as connection, connection:+ for entity_id, (kind, prefix) in enumerate(kinds, 300):+ connection.execute('INSERT INTO entity(id,kind,canonical_name,normalized_name) VALUES(?,?,?,?)',+ (entity_id, kind, canonical, canonical.casefold()))+ connection.execute("INSERT INTO entity_alias VALUES(?,?,?,'test',1)",+ (entity_id, f'old-{kind}', f'old-{kind}'))+ query = '?tag=a%2Fb&tag=second&media=photos&set=9&offset=48&sort=release&dir=asc'+ for kind, prefix in kinds:+ names = [f'old-{kind}'] + ([canonical.upper()] if kind == 'studio' else [])+ target = f'/{prefix}/{quote(canonical, safe="")}' + query+ for name in names:+ for method in ('GET', 'HEAD'):+ response = await self.client.request(method, f'/{prefix}/{quote(name, safe="")}' + query,+ follow_redirects=False)+ self.assertEqual(response.status_code, 307, (kind, name, method))+ self.assertEqual(response.headers['location'], target)+ self.assertEqual(response.headers['cache-control'], 'no-store')+ response = await self.client.get(target, follow_redirects=False)+ self.assertEqual(response.status_code, 200, kind)+ if kind != 'series':+ response = await self.client.get(f'/{prefix}?name=old-{kind}', follow_redirects=False)+ self.assertEqual(response.status_code, 200, kind)+ self.assertNotIn('location', response.headers)++ async def test_unknown_or_ambiguous_entity_urls_keep_the_page_shell(self):+ await self.client.post('/login', content='token=secret&next=%2F',+ headers={'Content-Type': 'application/x-www-form-urlencoded'})+ with closing(sqlite3.connect(self.db)) as connection, connection:+ for entity_id in (300, 301):+ connection.execute('INSERT INTO entity(id,kind,canonical_name,normalized_name) VALUES(?,?,?,?)',+ (entity_id, 'studio', f'Studio {entity_id}', f'studio {entity_id}'))+ connection.execute("INSERT INTO entity_alias VALUES(?,'Shared','shared','test',1)", (entity_id,))+ for name in ('Missing', 'Shared'):+ response = await self.client.get('/studios/' + name, follow_redirects=False)+ self.assertEqual(response.status_code, 200)+ self.assertNotIn('location', response.headers)+async def test_client_routes_serve_the_single_page_surface(self):await self.client.post("/login", content="token=secret&next=%2F",diff --git a/web/dist/peach-app.js b/web/dist/peach-app.jsindex f26233fe3..d405c1a5b 100644--- a/web/dist/peach-app.js+++ b/web/dist/peach-app.js@@ -48155,27 +48155,30 @@ function uwe(e, t, n) {//#endregion//#region src/react/entity-page/entity-page-view.tsxfunction dwe(e) {- let { kind: t, name: n } = e, r = dt(nF(t, n)), i = !!r.data?.error, a = r.data?.redirect, { actions: o } = e;+ let { kind: t, name: n } = e, r = dt(nF(t, n)), i = !!r.data?.error, a = r.data?.canonical_name, o = r.data?.redirect ?? (a && a !== n ? {+ kind: t,+ name: a+ } : void 0), { actions: s } = e;return (0, b.useLayoutEffect)(() => {- i && o.missing();- }, [o, i]), (0, b.useLayoutEffect)(() => {- if (!a) return;+ i && s.missing();+ }, [s, i]), (0, b.useLayoutEffect)(() => {+ if (!o) return;let e = !0;return queueMicrotask(() => {- e && o.openEntity(a.kind, a.name, !0);+ e && s.openEntity(o.kind, o.name, !0);}), () => {e = !1;};}, [- o,- a?.kind,- a?.name+ s,+ o?.kind,+ o?.name]), r.isError ? /* @__PURE__ */ (0, x.jsx)(qj, {message: R(r.error),onRetry: () => {r.refetch();}- }) : !r.data || i || a ? null : /* @__PURE__ */ (0, x.jsx)(mwe, {+ }) : !r.data || i || o ? null : /* @__PURE__ */ (0, x.jsx)(mwe, {...e,entity: r.data});@@ -93265,7 +93268,7 @@ function Brt(e, t, n) {e.setPhotoLayout(t), e.syncPhotoWalls();},openEntity: (t, n, r = !1) => {- r ? e.route(Dt(t, n) + e.search(), !0) : e.openEntity(t, n);+ r ? e.route(Dt(t, n) + e.suffix(), !0) : e.openEntity(t, n);},painted: (t, n) => {let r = e.photoViewActive();@@ -93741,7 +93744,7 @@ function _it() {live: (e, t) => o7.entityPageLive(e, t),current: () => o7.entityPageCurrent(),route: (e, t = !1) => Q.route(e, t),- search: () => location.search,+ suffix: () => location.search + location.hash,restoreHomeContext: () => kc({ barsContext: {type: "home",filters: H