Peach: Local-first video metadata scraper and media manager.
feat(web): 取不到的链接可以勾选重试
longmeidao100b89d68ad1
diff --git a/src/peach/web_links.py b/src/peach/web_links.pyindex 81e56ebd3..81545ae81 100644--- a/src/peach/web_links.py+++ b/src/peach/web_links.py@@ -107,17 +107,28 @@ def _check_public(state: dict) -> dict:"total": state["total"],"gone": [dict(item) for item in state["gone"]],"unclear": [dict(item) for item in state["unclear"]],+ "scope": state.get("scope", "all"),**({"error": state["error"]} if state["status"] == "failed" else {}),}-def _run_link_check(contract: LinkContract, check_id: str) -> None:- """逐条联网重验。异常由 `BackgroundJob` 翻成 `failed` 状态,这里不再自己接。"""+def _run_link_check(contract: LinkContract, check_id: str,+ link_ids: list[int] | None = None) -> None:+ """逐条联网重验。异常由 `BackgroundJob` 翻成 `failed` 状态,这里不再自己接。++ 给了 `link_ids` 就只验点名的那几条,别的链接的判定由调用方原样带进初始状态。+ """job = contract.link_check+ query = ("SELECT l.id, l.link_kind, l.label, l.url, e.canonical_name AS entity "+ "FROM entity_link l JOIN entity e ON e.id=l.entity_id")with contract.read_connection() as connection:- rows = [dict(row) for row in connection.execute(- "SELECT l.id, l.link_kind, l.label, l.url, e.canonical_name AS entity "- "FROM entity_link l JOIN entity e ON e.id=l.entity_id ORDER BY l.id")]+ if link_ids is None:+ rows = [dict(row) for row in connection.execute(query + " ORDER BY l.id")]+ else:+ # 点名的链接可能在上一次检查之后已经被删掉;查不到就是不必再验。+ marks = ",".join("?" * len(link_ids))+ rows = [dict(row) for row in connection.execute(+ f"{query} WHERE l.id IN ({marks}) ORDER BY l.id", link_ids)]with job.editing(check_id) as state:if state is None:return@@ -140,6 +151,21 @@ def _run_link_check(contract: LinkContract, check_id: str) -> None:job.update(check_id, status="complete", completed_at=time.time())+def _retry_state(state: dict, link_ids: list[int]) -> dict:+ """重验这几条时的初始状态:把它们从上一次的结论里摘掉,别的原样留着。++ 留着是重点。「取不到」多半是站点挡爬虫或一次抖动,值得单独再问一次,但重问几条+ 不该让另外七百条的结论一起清零——那样每次重试都要再等好几分钟才能按删除。+ """+ targets = set(link_ids)+ return {+ "checked": 0, "total": len(link_ids), "scope": "retry",+ "gone": [dict(item) for item in state["gone"] if int(item["id"]) not in targets],+ "unclear": [dict(item) for item in state["unclear"]+ if int(item["id"]) not in targets],+ }++def w_links_check(contract: LinkContract, body=None):"""开始(或查询)一次死链检查。@@ -151,11 +177,31 @@ def w_links_check(contract: LinkContract, body=None):state = contract.link_check.snapshot()if state is None:return {"ok": True, "status": "idle", "check_id": "", "checked": 0,- "total": 0, "gone": [], "unclear": []}+ "total": 0, "gone": [], "unclear": [], "scope": "all"}return _check_public(state)++ if body.get("retry") is not None:+ state = contract.link_check.snapshot()+ if state is None or state["status"] != "complete":+ return {"ok": False, "error": "没有已完成的检查结果"}+ if body.get("check_id") != state["check_id"]:+ return {"ok": False, "error": "检查结果已过期,请重新检查"}+ # 只认这次结果里真有的那些行。前端传来的 id 决定要删哪几条结论,放行库里+ # 别的链接等于让一个请求把没检查过的东西也标成「已通过」。+ known = {int(item["id"]) for item in state["gone"]}+ known |= {int(item["id"]) for item in state["unclear"]}+ link_ids = [int(value) for value in body["retry"]+ if str(value).lstrip("-").isdigit() and int(value) in known]+ if not link_ids:+ return {"ok": False, "error": "没有可重试的链接"}+ return _check_public(contract.link_check.start(+ lambda check_id: _run_link_check(contract, check_id, link_ids),+ initial=_retry_state(state, link_ids), restart=True,+ ))+return _check_public(contract.link_check.start(lambda check_id: _run_link_check(contract, check_id),- initial={"checked": 0, "total": 0, "gone": [], "unclear": []},+ initial={"checked": 0, "total": 0, "gone": [], "unclear": [], "scope": "all"},restart=body.get("restart") is True,))diff --git a/tests/test_web_links.py b/tests/test_web_links.pyindex 8f8a57a64..c7efdf7c4 100644--- a/tests/test_web_links.py+++ b/tests/test_web_links.py@@ -148,6 +148,70 @@ class SummaryTests(unittest.TestCase):"""不可逆动作不接受默认参数。"""self.assertFalse(web_links.w_links_prune(self.contract, {})["ok"])+ def _finished_check(self):+ self.contract.link_check.state = {+ "check_id": "fresh", "status": "complete", "checked": 3, "total": 3,+ "scope": "all", "error": "",+ "gone": [{"id": 1, "entity": "凉森玲梦", "link_kind": "social",+ "label": "X @a", "url": "https://x.com/a", "note": "HTTP 404"}],+ "unclear": [+ {"id": 2, "entity": "凉森玲梦", "link_kind": "official",+ "label": "T-POWERS", "url": "https://www.t-powers.co.jp/talent/x/",+ "note": "HTTP 403"},+ {"id": 3, "entity": "MOODYZ", "link_kind": "official",+ "label": "官方网站", "url": "https://moodyz.com/", "note": "HTTP 500"},+ ],+ }++ def _retry(self, body):+ original_probe, original_interval = web_links._probe, web_links.CHECK_INTERVAL+ web_links._probe = lambda url, timeout=0: (+ (200, "") if "t-powers" in url else (500, ""))+ web_links.CHECK_INTERVAL = 0+ try:+ out = web_links.w_links_check(self.contract, body)+ thread = self.contract.link_check.thread+ if thread is not None:+ thread.join(5)+ finally:+ web_links._probe, web_links.CHECK_INTERVAL = original_probe, original_interval+ return out++ def test_retrying_the_picked_links_keeps_every_other_verdict(self):+ """重问几条不该让另外几百条的结论一起清零。++ 整批重跑要好几分钟;「取不到」多半是站点挡爬虫或一次抖动,值得单独再问一次。+ 如果重试把状态清空,删除失效链接就得再等一整轮才能按。+ """+ self._finished_check()+ started = self._retry({"retry": [2], "check_id": "fresh"})+ self.assertEqual((started["scope"], started["total"]), ("retry", 1))+ state = self.contract.link_check.snapshot()+ self.assertEqual(state["status"], "complete")+ self.assertEqual([item["id"] for item in state["gone"]], [1])+ self.assertEqual([item["id"] for item in state["unclear"]], [3])++ def test_a_retried_link_that_is_still_broken_comes_back(self):+ """重验没通过的要留在表里,否则一次重试就等于把它判成好的。"""+ self._finished_check()+ self._retry({"retry": [2, 3], "check_id": "fresh"})+ state = self.contract.link_check.snapshot()+ self.assertEqual([item["id"] for item in state["unclear"]], [3])+ self.assertEqual(state["unclear"][0]["note"], "HTTP 500")++ def test_retry_refuses_a_stale_result_or_an_unknown_link(self):+ """重试要改的是这一次结果里的行,别的 id 不该被一个请求标成已通过。"""+ self.assertFalse(web_links.w_links_check(+ self.contract, {"retry": [2]})["ok"])+ self._finished_check()+ stale = web_links.w_links_check(self.contract, {"retry": [2], "check_id": "old"})+ self.assertFalse(stale["ok"])+ self.assertIn("过期", stale["error"])+ unknown = web_links.w_links_check(+ self.contract, {"retry": [999], "check_id": "fresh"})+ self.assertFalse(unknown["ok"])+ self.assertEqual(self.contract.link_check.snapshot()["check_id"], "fresh")+if __name__ == "__main__":unittest.main()diff --git a/web/app.js b/web/app.jsindex c5c3ca6a7..46c3db21e 100644--- a/web/app.js+++ b/web/app.js@@ -3536,11 +3536,11 @@ async function wireLinkManager(){${hosts?`<div class="linkhosts"><span>最多的站点</span><b>${hosts}</b></div>`:''}`;}catch(error){summary.innerHTML=noteHtml(error.message,{variant:'error',label:'读取失败'})}- const row=item=>`<tr><td>${esc(item.entity)}</td><td>${esc(KINDS[item.link_kind]||item.link_kind)}</td>+ const row=(item,pick)=>`<tr>${pick?`<td class="linkpick"><input type="checkbox" data-link-id="${item.id}" aria-label="选择 ${esc(item.entity)} 的${esc(item.label||item.url)}"></td>`:''}<td>${esc(item.entity)}</td><td>${esc(KINDS[item.link_kind]||item.link_kind)}</td><td>${esc(item.label||'')}</td><td class="linknote">${esc(item.note)}</td><td class="linkurl"><a class="externallink" href="${esc(item.url)}" target="_blank" rel="noreferrer"><span data-middle-truncate>${esc(item.url)}</span>${icon('external-link','externalmark')}</a></td></tr>`;- const table=(title,items,hint)=>items.length?`<div class="linkgroup"><h4>${esc(title)} <b>${items.length}</b></h4>- <p>${esc(hint)}</p><div class="linktablewrap"><table class="linktable"><thead><tr><th>实体</th><th>类型</th><th>标签</th><th>结果</th><th>地址</th></tr></thead><tbody>${items.map(row).join('')}</tbody></table></div></div>`:'';+ const table=(title,items,hint,{pick=false,footer=''}={})=>items.length?`<div class="linkgroup"><h4>${esc(title)} <b>${items.length}</b></h4>+ <p>${esc(hint)}</p><div class="linktablewrap"><table class="linktable"><thead><tr>${pick?'<th class="linkpick"><input type="checkbox" id="linkPickAll" aria-label="全选取不到的链接"></th>':''}<th>实体</th><th>类型</th><th>标签</th><th>结果</th><th>地址</th></tr></thead><tbody>${items.map(item=>row(item,pick)).join('')}</tbody></table></div>${footer}</div>`:'';const render=payload=>{const running=payload.status==='running';@@ -3549,11 +3549,18 @@ async function wireLinkManager(){setActionBusy(button,running);if(payload.status==='idle'){result.innerHTML='';return}if(payload.status==='failed'){result.innerHTML=noteHtml(payload.error||'检查失败',{variant:'error',label:'检查失败'});return}- const progress=running?(payload.total?jobProgressHtml(`已检查 ${payload.checked.toLocaleString()} / ${payload.total.toLocaleString()} 条链接`,payload.checked,payload.total):loadingDotsHtml('正在检查链接')):'';+ const retrying=payload.scope==='retry';+ const progress=running?(payload.total?jobProgressHtml(`${retrying?'已重验':'已检查'} ${payload.checked.toLocaleString()} / ${payload.total.toLocaleString()} 条链接`,payload.checked,payload.total):loadingDotsHtml(retrying?'正在重验链接':'正在检查链接')):'';/* gone 和 unclear 必须分开摆:`linktr.ee` 回 403 是挡爬虫、`x.com` 回 500 是临时错误,链接本身好好的。混成一张表会让人顺手把好链接一起删掉。 */const gone=table('已失效',payload.gone||[],'上游明确回 404/410,页面确实没了。');- const unclear=table('取不到',payload.unclear||[],'一次访问没成功,但不等于没了:有的站挡爬虫,有的是临时错误。不会被删除,下次检查会重试。');+ /* 「取不到」大多是站点挡爬虫或一次抖动,换个时间再问一次就通了。重跑整批要好几+ 分钟,所以这里能挑着重试:勾中哪几条就只问哪几条,别的结论原样留着。 */+ const retryable=done?(payload.unclear||[]):[];+ const retryRow=retryable.length?`<div class="linkretryrow">+ <button class="resourceaction" type="button" id="linkRetryPicked" disabled>${icon('rotate-cw')}<span>重试选中的链接</span></button>+ <button class="resourceaction" type="button" id="linkRetryAll">${icon('rotate-cw')}<span>全部重试(${retryable.length})</span></button></div>`:'';+ const unclear=table('取不到',payload.unclear||[],'一次访问没成功,但不等于没了:有的站挡爬虫,有的是临时错误。这些链接不会被删除,勾选后可以只重试它们。',{pick:retryable.length>0,footer:retryRow});const apply=(done&&(payload.gone||[]).length)?`<div class="resourceapplyrow"><p>删除前会逐条重验一次;此操作不可撤销。</p><button class="resourceaction danger" type="button" id="linkPrune">删除 ${payload.gone.length} 条失效链接</button></div>`:'';const clean=(done&&!(payload.gone||[]).length&&!(payload.unclear||[]).length)?'<p class="resourcesyncok">全部链接都能打开。</p>':'';@@ -3570,6 +3577,31 @@ async function wireLinkManager(){}catch(error){setActionBusy(control,false);if(active())void wirePruneProgress();throw error}}});});+ const boxes=()=>[...result.querySelectorAll('[data-link-id]')];+ const picked=()=>boxes().filter(box=>box.checked).map(box=>Number(box.dataset.linkId));+ const all=$('#linkPickAll'),pickedButton=$('#linkRetryPicked');+ const syncPicks=()=>{+ const ids=picked(),total=boxes().length;+ if(pickedButton){pickedButton.disabled=!ids.length;+ pickedButton.querySelector('span').textContent=ids.length?`重试选中的 ${ids.length} 条`:'重试选中的链接'}+ if(all){all.checked=total>0&&ids.length===total;all.indeterminate=ids.length>0&&ids.length<total}+ };+ boxes().forEach(box=>box.addEventListener('change',syncPicks));+ all?.addEventListener('change',()=>{boxes().forEach(box=>box.checked=all.checked);syncPicks()});+ const retry=async(control,ids)=>{+ if(!ids.length)return;+ setActionBusy(control);+ try{+ const out=await api('/api/links/check',{method:'POST',body:JSON.stringify({retry:ids,check_id:payload.check_id})});+ if(!active())return;+ render(out);void poll();+ }catch(error){+ setActionBusy(control,false);+ if(active()){result.innerHTML=noteHtml(error.message,{variant:'error',label:'重试失败'});void poll()}+ }+ };+ pickedButton?.addEventListener('click',event=>void retry(event.currentTarget,picked()));+ $('#linkRetryAll')?.addEventListener('click',event=>void retry(event.currentTarget,retryable.map(item=>item.id)));};const ui=await import('/dist/peach-ui.js');diff --git a/web/css/22-followmanage.css b/web/css/22-followmanage.cssindex c5217f8d2..198d0a0cf 100644--- a/web/css/22-followmanage.css+++ b/web/css/22-followmanage.css@@ -437,6 +437,12 @@ details.fcred{display:block;min-width:0}.linktable td{padding:6px 10px;border-bottom:1px solid var(--line-soft);color:var(--ink-2)}.linktable tr:last-child td{border-bottom:0}.linktable .linknote{color:var(--drop);font-variant-numeric:tabular-nums}+/* 勾选格只放一个方框,宽度收到内容最小;表头那个是全选。 */+.linktable .linkpick{width:1%;padding-right:0}+.linktable .linkpick input{margin:0;display:block;accent-color:var(--ink)}+/* 重试条贴着表格底边,和「删除失效链接」那条操作条同一形态;负外边距是为了让它+ 顶到 .linkgroup 的内边距之外,跟分组框对齐。 */+.linkretryrow{display:flex;align-items:center;justify-content:flex-end;gap:8px;margin:12px -16px -16px;padding:12px 16px;border-top:1px solid var(--line-soft);background:var(--overlay-5)}/* 地址用中间截断而不是尾部省略:这张表要回答「哪一条坏了」,而`/official/talent/X` 与 `/talent/X` 的差别就在尾部,切掉尾部等于切掉答案。 */.linktable .linkurl{max-width:360px;overflow:hidden}