Peach: Local-first video metadata scraper and media manager.
fix(entity): 人物页整页骨架带上新作那一行,资料与新作一次画齐
longmeidao6263f04bb95c
diff --git a/frontend/e2e/design.test.ts b/frontend/e2e/design.test.tsindex 50aad3fd8..37552a857 100644--- a/frontend/e2e/design.test.ts+++ b/frontend/e2e/design.test.ts@@ -1276,43 +1276,63 @@ describe('设计决定', () => {}});- it('订阅了的人物页先按真卡轮廓占住新作那一行,数据到了行高不变、封面不再等第二遍', { timeout: 60_000 }, async () => {+ it('有新作的人物页整页骨架里就留着新作那一行,数据到了一次换齐、行高不变、封面不再等第二遍', { timeout: 60_000 }, async () => {const name = '七沢みあ';const opened = await visit(browser, '/', DESKTOP);try {- await opened.page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {- id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],- user_aliases: [], asset_count: 0, tags: [], related_performers: [], links: [],- metadata: {}, has_image: false, has_avatar: false, avatar_focus: null,- representative_asset_id: null, entry_links: [], feed: { following: true },- } }));+ await opened.page.route(/\/api\/feeds\/rows/, (route) => route.fulfill({ json: {+ ok: true, entities: [{ id: 90_001, kind: 'performer', names: [name] }] } }));let release = () => {};const held = new Promise<void>((resolve) => { release = resolve; });- await opened.page.route(/\/api\/feeds\/discoveries\?/, async (route) => {+ await opened.page.route(/\/api\/entity\?/, async (route) => {await held;- await route.fulfill({ json: { ok: true, more: false, items: [{+ await route.fulfill({ json: {+ id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],+ user_aliases: [], asset_count: 0, tags: [], related_performers: [], links: [],+ metadata: {}, has_image: false, has_avatar: false, avatar_focus: null,+ representative_asset_id: null, entry_links: [], feed: { following: true },+ } });+ });+ await opened.page.route(/\/api\/feeds\/discoveries\?/, (route) => route.fulfill({ json: {+ ok: true, more: false, items: [{id: 1, code: 'ABC-001', title: '标题', link: 'https://javdb.com/v/x', cover_url: null,has_cover: true, cover_frame: null, poster_box: null, release_date: '2026-09-01',studio: '厂牌', performers: name, source_name: '', read: false, ignored: false,- scrape_error: null }] } });- });- // 封面比数据晚到一截:骨架要等它,而不是先换上真卡、再在封面格里微光一遍。+ scrape_error: null }] } }));+ // 封面比数据晚到一截:整页要等它,而不是先换上真卡、再在封面格里微光一遍。await opened.page.route(/\/cover\?code=ABC-001/, async (route) => {await new Promise((resolve) => setTimeout(resolve, 400));await route.fulfill({ contentType: 'image/png', body: Buffer.from(PIXEL, 'base64') });});await opened.page.goto(new URL(`/performers/${encodeURIComponent(name)}`,opened.page.url()).href, { waitUntil: 'load' });- const row = opened.page.locator('[data-feed-new]');- await row.locator('.feednewskeleton').first().waitFor({ timeout: 15_000 });- const before = await row.evaluate((element) => element.getBoundingClientRect().height);+ const skeleton = opened.page.locator('[data-skeleton="entity/performer"]');+ await skeleton.locator('.feednew .feednewskeleton').first().waitFor({ timeout: 15_000 });+ const before = await skeleton.evaluate((element) => {+ const row = element.querySelector('.feednew')!;+ return { height: row.getBoundingClientRect().height,+ between: !!row.previousElementSibling?.matches('[data-filter-frame]')+ && !!row.nextElementSibling?.matches('.entitysection') };+ });+ assert.ok(before.between, '骨架里的新作那一行不在筛选框和作品之间');+ // 画好的页面上那一行一出现就得是真卡:再露一回它自己的骨架,就是同一行等了两遍。+ await opened.page.evaluate(() => {+ const seen = { second: false };+ (window as unknown as { feedSeen: typeof seen }).feedSeen = seen;+ new MutationObserver(() => {+ if (document.querySelector('[data-feed-new] .feednewskeleton')) seen.second = true;+ }).observe(document.querySelector('#index')!, { childList: true, subtree: true });+ });release();+ const row = opened.page.locator('[data-feed-new]');await row.locator('[data-feed-id]').waitFor({ timeout: 15_000 });const after = await row.evaluate((element) => ({height: element.getBoundingClientRect().height, busy: element.getAttribute('aria-busy'),- waiting: element.querySelectorAll('[data-feed-id] .pic.imgwait').length }));- assert.equal(after.height, before, '占位行和到货的那一行不一样高,下面的作品网格会跳');+ waiting: element.querySelectorAll('[data-feed-id] .pic.imgwait').length,+ second: (window as unknown as { feedSeen: { second: boolean } }).feedSeen.second }));+ assert.equal(after.height, before.height, '占位行和到货的那一行不一样高,下面的作品网格会跳');assert.equal(after.busy, null);+ assert.equal(after.second, false, '整页画出来之后新作那一行又单独骨架了一轮');assert.equal(after.waiting, 0, '骨架退场后封面格里又微光了一遍');assert.deepEqual(opened.problems, []);} finally {diff --git a/src/peach/web_feeds.py b/src/peach/web_feeds.pyindex a20fa7ff2..739b08227 100644--- a/src/peach/web_feeds.py+++ b/src/peach/web_feeds.py@@ -358,6 +358,35 @@ def q_feed_discoveries(contract, args) -> dict:} for row in rows[:limit]]}+def q_feed_rows(contract, args) -> dict:+ """资料页上会出现新作那一行的实体,连同规范名与全部别名。++ 骨架在资料到达之前就要知道这一页有没有那一行:不留位,整页画出来时那一行从中间+ 顶进来;每页都留,没有新作的又得在画出来时收掉。判据和按人取新作的那一份同一套+ (`LISTED`、未忽略),名单放在服务端,换一台设备打开也是同一份。页面按地址里的+ 名字比对,所以别名一起给:从别名链接进来的那一页也认得出是同一位。+ """+ hidden = web_settings.hidden_compilations(contract.database)+ with contract.database.read_connection() as connection:+ feeds.register_functions(connection, hidden)+ rows = connection.execute(+ "SELECT e.id, e.kind, e.canonical_name FROM entity e WHERE e.id IN ("+ "SELECT de.entity_id FROM feed_discovery_entity de"+ " JOIN feed_discovery d ON d.id=de.discovery_id"+ f" WHERE d.ignored_at IS NULL AND {' AND '.join(LISTED)})"+ " ORDER BY e.id").fetchall()+ names = {int(row["id"]): [row["canonical_name"]] for row in rows}+ for alias in connection.execute(+ "SELECT entity_id, alias FROM entity_alias WHERE entity_id IN"+ f" ({','.join('?' * len(names))}) ORDER BY entity_id, alias",+ tuple(names)).fetchall() if names else ():+ if alias["alias"] not in names[int(alias["entity_id"])]:+ names[int(alias["entity_id"])].append(alias["alias"])+ return {"ok": True, "entities": [+ {"id": int(row["id"]), "kind": row["kind"], "names": names[int(row["id"])]}+ for row in rows]}++def _studio_name(connection, name: str) -> str:"""来源给的厂牌名换成账本里那个厂牌的规范名,和资产卡上写的是同一个。diff --git a/src/peach/web_router.py b/src/peach/web_router.pyindex 5dd404634..1d43b1cb5 100644--- a/src/peach/web_router.py+++ b/src/peach/web_router.py@@ -45,6 +45,7 @@ from .web_entity import (from .web_feeds import (q_feed_check,q_feed_discoveries,+ q_feed_rows,q_feeds,w_feed_check,w_feed_discovery,@@ -298,6 +299,7 @@ GET_HANDLERS = {"/api/feeds": q_feeds,"/api/feeds/check": q_feed_check,"/api/feeds/discoveries": q_feed_discoveries,+ "/api/feeds/rows": q_feed_rows,"/api/follow": q_follow,"/api/follow/credentials": q_follow_credentials,"/api/follow/tags": q_follow_tags,diff --git a/tests/test_feeds_web.py b/tests/test_feeds_web.pyindex 21ab2c295..80535d417 100644--- a/tests/test_feeds_web.py+++ b/tests/test_feeds_web.py@@ -280,6 +280,27 @@ class FeedWebTest(FeedWebFixture):{"entity": entity_id + 1})self.assertEqual(nobody["items"], [])+ def test_the_row_list_names_whoever_still_has_a_listed_new_release(self):+ with self.contract.database.write_transaction() as connection:+ entity_id = int(connection.execute(+ "INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at)"+ " VALUES('performer','深田えいみ',peach_normalize('深田えいみ'),?,?)",+ (feeds.stamp(), feeds.stamp())).lastrowid)+ connection.execute(+ "INSERT INTO entity_alias(entity_id,alias,normalized_alias,source)"+ " VALUES(?,'Eimi Fukada',peach_normalize('Eimi Fukada'),'test')", (entity_id,))+ self.assertEqual(dispatch_api_get(self.contract, "/api/feeds/rows", {})["entities"], [])+ self._add(entity_id=entity_id)+ self._check()+ rows = dispatch_api_get(self.contract, "/api/feeds/rows", {})["entities"]+ self.assertEqual(rows, [{"id": entity_id, "kind": "performer",+ "names": ["深田えいみ", "Eimi Fukada"]}])+ # 那几部都忽略掉,她的页面上就没有那一行了,名单跟着不再有她。+ ids = [item["id"] for item in dispatch_api_get(+ self.contract, "/api/feeds/discoveries", {"entity": entity_id})["items"]]+ dispatch_api_post(self.contract, "/api/feeds/discovery", {"action": "ignore", "ids": ids})+ self.assertEqual(dispatch_api_get(self.contract, "/api/feeds/rows", {})["entities"], [])+def test_removing_a_source_keeps_the_new_releases_it_found(self):self._add()self._check()diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 3022ea359..7cceeb6a1 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -903,7 +903,7 @@ class WebDataTests(unittest.TestCase):"/api/links/prune", "/api/resource-sync/apply","/api/follow/tags", "/api/follow/authors","/api/taste", "/api/settings", "/api/links", "/api/organize",- "/api/feeds", "/api/feeds/check", "/api/feeds/discoveries",+ "/api/feeds", "/api/feeds/check", "/api/feeds/discoveries", "/api/feeds/rows",})self.assertEqual(set(rm_web.POST_HANDLERS), {"/api/library-processing", "/api/thumbnail-jobs", "/api/media-repair",diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 58f51e3ab..e56d0ae43 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -2300,7 +2300,7 @@ class WebUiSourceTests(unittest.TestCase):def test_entity_loading_and_detail_autoplay_share_their_entry_contracts(self):self.assertPageContains("showEntityLoading(ROUTE_ENTITIES[path.split('/')[1]])")- self.assertPageContains('showEntityLoading(kind);')+ self.assertPageContains('showEntityLoading(kind,name);')self.assertPageContains('appSettings.detailAutoplay=appSettings.detailAutoplay!==false;')self.assertPageContains('mountDetailPlayer(it,vv,appSettings.detailAutoplay)')self.assertPageContains('mountDetailPlayer(item,followVideo,appSettings.detailAutoplay,{')diff --git a/web/app.js b/web/app.jsindex b994b3945..4b16a6836 100644--- a/web/app.js+++ b/web/app.js@@ -4783,25 +4783,38 @@ const feedNewSkeletonHtml=()=>`<div class="feednewrow srow" aria-hidden="true">$<div class="meta"><div class="mtext"><span class="t"><span class="skeleton"></span></span><div class="s mono"><span class="skeleton">​</span></div></div></div></article>`.repeat(FEED_SKELETON_CARDS)}</div>`;+/* 资料页上会有新作那一行的那几位,名单由服务端给(`/api/feeds/rows`),几台设备看到的+ 是同一份。资料页的骨架照它留出那一行,资料回来时那一行不会从中间顶进来。 */+let feedRowNames=null;+async function loadFeedRowNames(){+ const data=await api('/api/feeds/rows').catch(()=>null);+ if(data&&!data.error)feedRowNames=new Set((data.entities||[])+ .flatMap(entity=>entity.names.map(name=>`${entity.kind}/${foldName(name)}`)));+ return feedRowNames;+}+const hasFeedRow=(kind,name)=>!!name&&!!feedRowNames?.has(`${kind}/${foldName(name)}`);+const feedNewSkeletonSection=()=>`<section class="feednew">${feedNewSkeletonHtml()}</section>`;/* 拉取由定时器做,页面只读已经发现的那些:进这一页顺手发一轮请求,等于把用户的每次刷新都变成对别人服务器的一次拉取,而订阅的间隔本来就是按天算的。 */-async function renderFeedNew(host,entityId){- if(!host)return;- host.dataset.feedEntity=entityId?String(entityId):'';+async function loadFeedNew(entityId,preload){const query=new URLSearchParams({limit:'12'});if(entityId)query.set('entity',String(entityId));const data=await api('/api/feeds/discoveries?'+query).catch(()=>null);- // 取数期间人已经离开了这一页:首页那一行不画到管理区上,人物页那一行的容器已经换掉。- if(!host.isConnected||host.id==='feedNew'&&!isCatalogPath(location.pathname))return;const items=data&&!data.error?(data.items||[]):[];const html=`<div class="feednewrow srow">${items.map(feedNewCardHtml).join('')}</div>`;// 骨架还占着时,先把头几张封面取到手再整行换掉:否则骨架退场、真卡进来,封面格里// 又是一轮微光,同一行等了两遍。慢的那几张不等满,到点照换,剩下的留给卡片自己的等待态。- if(items.length&&host.getAttribute('aria-busy')==='true'){- await preloadImages(html,FEED_SKELETON_CARDS,FEED_COVER_WAIT);- if(!host.isConnected||host.id==='feedNew'&&!isCatalogPath(location.pathname))return;- }+ if(preload&&items.length)await preloadImages(html,FEED_SKELETON_CARDS,FEED_COVER_WAIT);+ return {items,html};+}+/* `loaded` 是随资料页整页一起取好的那一份,给了就不再取。 */+async function renderFeedNew(host,entityId,loaded){+ if(!host)return;+ host.dataset.feedEntity=entityId?String(entityId):'';+ const {items,html}=loaded||await loadFeedNew(entityId,host.getAttribute('aria-busy')==='true');+ // 取数期间人已经离开了这一页:首页那一行不画到管理区上,人物页那一行的容器已经换掉。+ if(!host.isConnected||host.id==='feedNew'&&!isCatalogPath(location.pathname))return;host.removeAttribute('aria-busy');if(!items.length){host.hidden=true;host.innerHTML='';return}host.hidden=false;@@ -8105,15 +8118,26 @@ function wireNamePicker(kind,current,mine){也看不出右边还有。首页筛选条本来就这么做,资料页的标签行是同一条,用同一段。 *//* 等着的这一下浮层也得是整块的:下半要到列表回来才画的话,上半的下沿在等的那几秒里留着两个直角,读起来是这块浮层缺了一半。这一页的作品多时那几秒不算短。 */-function showEntityLoading(kind){+function showEntityLoading(kind,name){const head=collectionHeaderHtml({readout:' ',loading:true,filterRow:'bottom'});const body=kind==='agency'?indexSkeletonHtml({kind:'performers',layout:peopleIndexLayout()}):pageSkeletonHtml('正在读取作品',{cards:true,className:'catalog-skeleton postercard-skeleton'});const placeholder=entitySkeletonHtml(kind,head,body);if($('#index').firstElementChild?.dataset.skeleton!==`entity/${kind}`){- $('#index').innerHTML=placeholder;fitSkeleton($('#index'));- }+ $('#index').innerHTML=placeholder;+ syncEntitySkeletonFeed(kind,name);+ fitSkeleton($('#index'));+ }else syncEntitySkeletonFeed(kind,name);+}+/* 新作那一行在骨架里的位置和画好的页面一样:筛选框之下、作品之上。名单晚到或换了+ 一位时只增删这一段,骨架其余部分不重画,微光不从头再闪。 */+function syncEntitySkeletonFeed(kind,name){+ const skeleton=$('#index').firstElementChild;+ if(skeleton?.dataset.skeleton!==`entity/${kind}`)return;+ const row=skeleton.querySelector('.feednew'),wanted=hasFeedRow(kind,name);+ if(wanted&&!row)skeleton.querySelector('.entitysection')?.insertAdjacentHTML('beforebegin',feedNewSkeletonSection());+ else if(!wanted&&row)row.remove();}async function openEntity(kind,name,push=true){releaseHoverPreviews();@@ -8130,13 +8154,19 @@ async function openEntity(kind,name,push=true){document.body.classList.add('entity-open');$('#stats').hidden=true;$('#index').hidden=false;$('#grid').innerHTML='';$('#combo').innerHTML='';$('#count').textContent='';$('#loadSentinel').hidden=true;- showEntityLoading(kind);+ showEntityLoading(kind,name);detailReturnBarsContext=null;entityJavLayout=false;agencyRosterView='people';const seq=++entityRequestSeq;+ // 名单每进一页重取一遍,下一页用的就是服务端的现状;第一次进页时手里还没有,到了照它补齐骨架。+ void loadFeedRowNames().then(()=>{if(seq===entityRequestSeq)syncEntitySkeletonFeed(kind,name)});const [d,items,photos]=await Promise.all([- api(`/api/entity?kind=${encodeURIComponent(kind)}&name=${encodeURIComponent(name)}`),+ // 新作那一行跟资料一起到:资料一回来就接着取这一页的新作和头几张封面,和作品、图集并行,+ // 三样齐了整页一次画出,不再是整页先出来、那一行再单独等一轮。+ api(`/api/entity?kind=${encodeURIComponent(kind)}&name=${encodeURIComponent(name)}`).then(async d=>{+ if(d&&!d.error&&d.id)d.feedNew=await loadFeedNew(d.id,true);+ return d}),fetchEntityItems(kind,name,filters),api(`/api/photos?kind=${encodeURIComponent(kind)}&name=${encodeURIComponent(name)}`)]);if(d.error||seq!==entityRequestSeq||@@ -8302,16 +8332,14 @@ async function openEntity(kind,name,push=true){${related?`<div class="entityfoot" aria-label="同台艺人"><div class="relatedpeople">${related}</div></div>`:''}</section><div class="combo entitycombo"></div><section class="entitytagbar" aria-label="媒体与标签">${mediaToggle}${mediaToggle?'<span class="sep" aria-hidden="true"></span>':''}<div class="filterscroll"><div class="viewpills entityviews" role="group" aria-label="观看状态">${VIEW_PILLS.map(v=>`<button type="button" class="pill" data-entity-state="${v.k}" aria-pressed="${(filters.state||'')===v.k}">${v.label}</button>`).join('')}<span class="sep" aria-hidden="true"></span></div><div class="tagscroll entitytags">${tags}</div></div></section>- ${d.feed?.following- ?`<section class="feednew" data-feed-new aria-label="未入库的新作" aria-busy="true">${feedNewSkeletonHtml()}</section>`- :'<section class="feednew" data-feed-new aria-label="未入库的新作" hidden></section>'}+ <section class="feednew" data-feed-new aria-label="未入库的新作" hidden></section><div class="entitysection"></div>`;/* 圆框角上那个加号。自动挑的那张按来源优先级来,而那个顺序回答的是「先试哪一张」,不是「哪一张适合当头像」:图库排第一的常是写真封面,同一个人往下翻几张就有片商的正脸原图。换完重进这一页——头像索引在服务端已经失效过一次,重画才读得到新图。 *//* 关注的这位有新作、库里还没有文件时,那一行摆在资料卡和作品之间:它讲的是这个人,但不是这一页的正文。一条都没有就整块不出(`renderFeedNew` 自己判)。 */- if(d.id)void renderFeedNew($('#index').querySelector('[data-feed-new]'),Number(d.id));+ if(d.id)void renderFeedNew($('#index').querySelector('[data-feed-new]'),Number(d.id),d.feedNew);const pickerHost=$('#index').querySelector('[data-avatar-picker]');if(pickerHost&&d.id)import('/dist/peach-ui.js').then(ui=>ui.mountIsland('avatar-picker',pickerHost,{kind,entityId:Number(d.id),name:d.canonical_name||name,