Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat: 死链分「搬走了」与「没了」,资料页链接按实体类型分工

longmeidaoae2f5f53fde3
diff --git a/docs/STATUS.md b/docs/STATUS.md
index e41167f0e..1b678bcab 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -19,6 +19,7 @@
## 已核验能力
+- 2026-09-01 死链分「搬走了」和「没了」,资料页链接按实体类型分工,管理页新增链接管理。**404 复查**:新增 `rediscover_entity_links.py`,从死链所在站点的索引页逐层上溯找锚点,候选必须回 200 **且标题里有这个人的名字**——列表页 `/talent/` 同样回 200,少了这一关四百个人会被改写成同一个链接。84 条 official 404 里只有 5 条真的还在,全是 T-POWERS 的同一种结构变更(`/official/talent/X` → `/talent/X/`)。第一版还把 `上川星空` 的 KRONE 死链「修」成了 `x.com/tenma_yui2`:人是对的(`天馬ゆい` 就在账本别名里),但那不是事务所页面,结果会是一条标着「KRONE(クローネ)」、点开却是 Twitter 的 official 链接——比死链更糟,因为它看起来是对的。已加同站约束(`registrable` 取末两段,`co.jp` 这类二级后缀取三段,`evil-t-powers.co.jp` 不算同站)。**资料页分工**:社媒收成纯图标;官网在厂牌页只显示大写域名、不放图标(那一页的头像就是厂牌 logo,再放同品牌小图标是把一件事说两遍),在女优页保留图标与事务所名(头像是人,不构成重复)。别名去掉「别名 ·」前缀、空则整行不出;馆藏检索词整行删除;数字提到正文色;同台艺人不再显示部数。**外链圆标**:新增 `link_marks.py` 与 `/link-mark`,把单色字形 favicon 做成「品牌色底 + 白色主体」。实测 T-POWERS 带透明且只有一种绿,做得出;HEYZO 是白底多色字形,抠图会反转成一团糟,因此判据收成「有真透明 + 色相簇 ≤ 2」,不满足就原样缩放,取不到就回落地球——半吊子的抠图比原图更难看。端点按**链接 id** 解析地址,绝不接受前端递来的 URL(和 `/follow-stream` 同一条规矩,否则就是一个任意地址抓取的口子),顺带浏览器不再直接向对方站点发请求。**管理页**:`web_links.py` 提供 `/api/links`(纯读库的分布概览)、`/api/links/check`(后台线程 + 可轮询,七百多条要几分钟)、`/api/links/prune`(删除前逐条重验,只接受刚跑完那次的 `check_id`);面板放在资源同步上方、沿用同一套盒子,结果分成「已失效」和「取不到」两张表,后者不删只重试。表里的地址用 Geist 中间截断——`/official/talent/X` 与 `/talent/X` 的差别就在尾部。
- 2026-09-01 非原生容器的浏览器转码已改为性能优先:缓存未命中时以可取消 ffprobe 探测,H.264 8-bit 视频优先直接复制到 MP4,AAC 同时复制;其他 Windows 视频先走 CUDA/NVDEC + `scale_cuda` + H.264 NVENC `p1`,解码器不支持时保留 NVENC 编码,两条失败才回退原 `libx264 veryfast`,macOS 保持封装复制或软件转码。真实 CloudDrive POC 中,H.264/AAC 的 30 秒 MKV 片段封装耗时 0.64 秒,1080p HEVC 的 30 秒硬件转码耗时 1.60 秒;生产源码对 1 MB、3.8 秒 AVI 的实际策略为 `ffprobe → cuda-nvenc`,含网盘首次读取和进程启动共 5.59 秒,输出 H.264 `yuv420p` + AAC,临时缓存已删除。变基后工作树与集成后主目录 Windows 正式全量均为 1586 项通过、13 项按平台跳过;生产托盘已正常重启并重新拥有 80/443,项目 CA 严格 HTTPS `/healthz` 返回 200、0.7.13、writer、非只读。未替换 EXE,未写真实 ledger、候选或原媒体,旧转码缓存继续有效。
- 2026-09-01 图片灯箱按用户截图再次纠偏:女优/厂牌本地照片和关注在线图片继续复用同一套 Swiper 14.2.0;首次重叠的根因是只等脚本、不等样式就构造轮播,现在 CSS/JS 同时就绪后才初始化,并用 scoped flex 结构保证任一时刻只画一张主图。上一张、下一张和关闭统一为 48 px、黑色 60% 覆盖层圆钮,首尾无效方向完全隐藏;信息、页码和缩放回到底部,缩放条按原图像素显示 10%–400%,补齐「适应窗口」与「原大小」,主图切换时把当前缩略图主动滚到中央。沉浸动作列只共享 48/24 px 几何,保留白色 10% tonal 表面。`catalog` 588 项、`follow` 501 项(1 项按平台跳过)及 Windows 正式全量 1587 项(13 项按平台跳过)通过;未新增依赖、API 或 ledger 字段,未写真实 ledger、候选或媒体。
- 2026-09-01 资料页移动端按 beeg 收口,链接改为写入前必须能打开:窄屏改单列居中、头像在名字上方(左像右文是给宽屏的,手机上 92 px 头像旁只剩两百多像素,别名和链接被挤成两三行);社媒收成 42×42 纯图标,handle 变成 sr-only 加 `title`(handle 是网址的一部分,写出来只是把 URL 抄一遍);删掉外链箭头;X 改用内联品牌 SVG——它本来就挡 favicon 请求,资料页上那个空白白圆就是它,而 416 条社媒里 372 条是 x.com/twitter.com。`.sorts .javlayout` 补 `flex:none`:`.sorts` 是不换行的横向滚动条,`.javlayout` 是带 `min-width:0` 的 fieldset,两条合起来允许它被压到内容宽度以下,窄屏上三个 34 px 版式按钮叠在一起并压住「发行时间」;`.sorts button` 早有 `flex:0 0 auto`,但 fieldset 不是 button,选不到它。375 px 实测横向溢出 0、版式组右缘 177 < 「发行时间」左缘 188,桌面 1280 px 仍是两列左对齐。**用户由一条 404 揭出的数据事故**:首批 703 条链接一条都没验就装进了账本,逐条实测 708 条里 152 条打不开(21%),其中 126 条 404 是确证已没了、26 条只是取不到(`linktr.ee` 403 挡爬虫、`facebook.com` 400、`x.com` 500、连接失败与超时各一)。根因是把 minnano-av 的旧快照当成现在的事实——T-POWERS 改过站,`/official/talent/X` 早已 404,正确形态是 `/talent/X/`,而资料页上它和好链接一模一样。可达性门槛因此放进安装器(所有来源进入账本的唯一入口),并新增 `--prune-dead`;「取不到不等于没了」写成 `is_gone` 判据,只有 404/410 才算删除依据。清理 126 条待用户授权。
diff --git a/scripts/harvest_performer_links.py b/scripts/harvest_performer_links.py
index 9d9cb6aaa..b5d2aa2cc 100644
--- a/scripts/harvest_performer_links.py
+++ b/scripts/harvest_performer_links.py
@@ -26,6 +26,7 @@ from urllib.parse import quote, urlsplit
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from peach.catalog_rules import is_jav_code # noqa: E402
+from peach.entities import name_chain # noqa: E402
from peach.config import STATE_DIR # noqa: E402
from peach.http import HttpRequest, HttpxTransport # noqa: E402
from peach.jobs import job_main # noqa: E402
@@ -49,44 +50,6 @@ def search_url(name: str) -> str:
return SEARCH + quote(name, encoding="utf-8")
-KANA = re.compile(r"[぀-ゟ゠-ヿ]")
-KANJI = re.compile(r"[一-鿿]")
-
-
-def name_rank(name: str) -> int:
- """名字对日文站的可用程度,越小越先试。
-
- 账本里 performer 的规范名是简体中文(`凉森玲梦`、`释爱丽丝`),日文站按它一个都搜不到;
- 真正能用的日文写法在 `entity_alias` 里(`涼森れむ`、`釈アリス`)。实测 12 位只有 1 位
- 命中,就是因为直接拿规范名去搜。
-
- 汉字加假名混排的是艺名本身,最可靠;纯假名是读音,能搜到但更容易撞名;纯汉字既可能
- 是日文也可能是简体中文,放在后面;罗马字对日文站基本无效,排最后。
- """
- kana, kanji = bool(KANA.search(name)), bool(KANJI.search(name))
- if kana and kanji:
- return 0
- if kana:
- return 1
- if kanji:
- return 2
- return 3
-
-
-def name_chain(canonical: str, aliases: list[str]) -> list[str]:
- """去重后按可用程度排序的候选名字,罗马字不进链。
-
- 罗马字留着只会白跑一次往返,并且它落空后混进未取得,看起来像是「这个人查不到」,
- 而实际上是「我们从没用她的日文名查过」。
- """
- seen: list[str] = []
- for name in [canonical, *aliases]:
- name = (name or "").strip()
- if name and name not in seen and name_rank(name) < 3:
- seen.append(name)
- return sorted(seen, key=name_rank)
-
-
def actress_id(final_url: str) -> str:
"""唯一命中时最终地址里的女优编号;停在检索页就返回空。"""
match = ACTRESS_PAGE.search(urlsplit(final_url).path)
diff --git a/scripts/rediscover_entity_links.py b/scripts/rediscover_entity_links.py
new file mode 100644
index 000000000..bc4e78c27
--- /dev/null
+++ b/scripts/rediscover_entity_links.py
@@ -0,0 +1,229 @@
+"""死链里有多少只是站点改了结构、页面其实还在。
+
+`install_entity_links.py --prune-dead` 只回答「这条打不开」,回答不了「它是没了还是搬走了」。
+两者的处置完全相反:真没了该删,搬走了该改地址。用户由 T-POWERS 一例看出这个区别——
+`/official/talent/涼森れむ` 回 404,而 `/talent/涼森れむ/` 好好地开着,同一个人、同一个站。
+
+判据是**站点自己承认这个人**,不是我们拼出一个能打开的地址:
+
+1. 拿这个人的日文名(账本规范名是简体中文,日文写法在 `entity_alias` 里)。
+2. 在死链所在站点的索引页里找锚点——href 或锚文本含这个名字。索引页从死链的父级路径
+ 逐层上溯再加站点根,因为艺人页几乎总挂在某个列表下面。
+3. 候选必须回 200 **且标题里有这个人的名字**。少了这一条,`/talent/` 这种列表页本身
+ 也会 200,然后 400 个人全被改写成同一个列表地址。
+
+改地址是有风险的动作:一条指向别人的链接比一条死链更糟,因为它看起来是对的。所以这里
+只产出复核表,不写账本;写入仍走 `install_entity_links.py`,再过一次可达性门槛。
+"""
+from __future__ import annotations
+
+import argparse
+import re
+import sqlite3
+import sys
+import time
+from pathlib import Path
+from urllib.parse import unquote, urljoin, urlsplit
+
+import httpx
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from peach.entities import name_chain # noqa: E402
+from peach.review_csv import write_rows # noqa: E402
+
+USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/128.0 Safari/537.36")
+ANCHOR = re.compile(r'<a\s[^>]*href=["\']([^"\']+)["\']([^>]*)>(.*?)</a>', re.S | re.I)
+TITLE = re.compile(r"<title[^>]*>(.*?)</title>", re.S | re.I)
+FIELDS = ("entity_id", "kind", "name", "link_kind", "label", "url", "evidence",
+ "old_url", "matched_name", "found_via", "verdict")
+
+
+def fetch(url: str, timeout: float = 12.0) -> tuple[int, str, str]:
+ """(status, 正文, 最终地址)。每个请求新建 client——失败的连接会漏池槽。"""
+ try:
+ with httpx.Client(follow_redirects=True, timeout=timeout,
+ limits=httpx.Limits(max_connections=4,
+ max_keepalive_connections=0)) as client:
+ response = client.get(url, headers={"User-Agent": USER_AGENT})
+ except Exception:
+ return 0, "", url
+ return response.status_code, response.text, str(response.url)
+
+
+def registrable(host: str) -> str:
+ """粗粒度的「同一个站」:取末两段,日本的二级后缀再多取一段。
+
+ 不引 publicsuffix 依赖——这里只需要把 `www.t-powers.co.jp` 和 `t-powers.co.jp` 判成
+ 一家、把 `x.com` 判成另一家,而不需要处理公共后缀列表的全部边角。
+ """
+ parts = host.casefold().split(".")
+ if len(parts) >= 3 and parts[-2] in {"co", "or", "ne", "ac", "go", "com", "net", "org"}:
+ return ".".join(parts[-3:])
+ return ".".join(parts[-2:])
+
+
+def same_site(candidate: str, original: str) -> bool:
+ a = registrable(urlsplit(candidate).hostname or "")
+ b = registrable(urlsplit(original).hostname or "")
+ return bool(a) and a == b
+
+
+def index_candidates(url: str) -> list[str]:
+ """从死链逐层上溯的索引页,最深的先试。
+
+ 艺人页几乎总挂在某个列表下面,而站点改版通常只动其中一层
+ (`/official/talent/X` → `/talent/X/`),上一层的列表往往原地还在。
+ """
+ parts = urlsplit(url)
+ root = f"{parts.scheme}://{parts.netloc}"
+ out: list[str] = []
+ segments = [s for s in parts.path.split("/") if s]
+ for cut in range(len(segments) - 1, -1, -1):
+ candidate = root + "/" + "/".join(segments[:cut]) + ("/" if cut else "")
+ if candidate not in out:
+ out.append(candidate)
+ if root + "/" not in out:
+ out.append(root + "/")
+ return out[:4]
+
+
+def anchors_naming(html: str, base: str, names: list[str]) -> list[tuple[str, str]]:
+ """索引页里提到这些名字的链接,返回 (绝对地址, 命中的名字)。
+
+ href 也要看:日文站的艺人页地址常常就是 URL 编码后的名字,而锚文本可能只是一张图。
+ """
+ found: list[tuple[str, str]] = []
+ for match in ANCHOR.finditer(html):
+ href = match.group(1)
+ text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", match.group(3))).strip()
+ haystack = text + " " + unquote(href)
+ for name in names:
+ if name and name in haystack:
+ target = urljoin(base, href)
+ if urlsplit(target).scheme in {"http", "https"}:
+ found.append((target, name))
+ break
+ return found
+
+
+def confirms(html: str, names: list[str]) -> str:
+ """页面标题里有没有这个人的名字;有就返回命中的写法。
+
+ 列表页同样回 200。少了这一条,`/talent/` 本身会被当成每个人的新地址。
+ """
+ match = TITLE.search(html)
+ title = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", match.group(1))).strip() if match else ""
+ # 站点常把姓与名之间加空格(`涼森 れむ`),逐字比会漏掉。
+ squeezed = title.replace(" ", "").replace(" ", "")
+ for name in names:
+ if name and (name in title or name.replace(" ", "") in squeezed):
+ return title[:90]
+ return ""
+
+
+def rediscover(record: dict, interval: float, timeout: float) -> dict:
+ """给一条死链找回它现在的地址。就地返回一行复核结果。"""
+ names = record["chain"]
+ row = {field: "" for field in FIELDS}
+ row.update(entity_id=record["entity_id"], kind=record["kind"], name=record["name"],
+ link_kind=record["link_kind"], label=record["label"],
+ old_url=record["url"], verdict="未取得")
+ if not names:
+ row["evidence"] = "没有可用于日文站的名字"
+ return row
+
+ seen: set[str] = set()
+ for index in index_candidates(record["url"]):
+ status, html, final = fetch(index, timeout)
+ time.sleep(interval)
+ if status != 200 or not html:
+ continue
+ for target, matched in anchors_naming(html, final, names):
+ if target in seen or target.rstrip("/") == record["url"].rstrip("/"):
+ continue
+ # 修复的定义是「在同一个站点上找到新地址」,不是「找到关于这个人的另一个链接」。
+ # 实测 KRONE 的索引页里 `上川星空` 那一条指向她的 X 账号——人是对的(`天馬ゆい`
+ # 就在账本别名里),但那不是事务所页面。照单收下会留下一条标着「KRONE(クローネ)」、
+ # 点开却是 Twitter 的 official 链接,比一条死链更糟:它看起来是对的。
+ if not same_site(target, record["url"]):
+ continue
+ seen.add(target)
+ hit_status, hit_html, hit_final = fetch(target, timeout)
+ time.sleep(interval)
+ if hit_status != 200:
+ continue
+ title = confirms(hit_html, names)
+ if title:
+ row.update(url=hit_final, matched_name=matched, found_via=index,
+ verdict="ok",
+ evidence=f"站点索引 {index} 指向该页,标题自述「{title}」;"
+ f"旧址 {record['url']} 回 404")
+ return row
+ if len(seen) > 30:
+ break
+ row["evidence"] = f"在 {len(seen)} 个候选里没有标题自述该人的页面"
+ return row
+
+
+def load_dead(connection: sqlite3.Connection) -> list[dict]:
+ aliases: dict[int, list[str]] = {}
+ for entity_id, alias in connection.execute(
+ "SELECT entity_id, alias FROM entity_alias ORDER BY confidence DESC, alias"):
+ aliases.setdefault(entity_id, []).append(alias)
+ out = []
+ for link_id, entity_id, kind, name, link_kind, label, url in connection.execute(
+ "SELECT l.id, e.id, e.kind, e.canonical_name, l.link_kind, l.label, l.url "
+ "FROM entity_link l JOIN entity e ON e.id=l.entity_id ORDER BY l.id"):
+ out.append({"link_id": link_id, "entity_id": entity_id, "kind": kind, "name": name,
+ "link_kind": link_kind, "label": label, "url": url,
+ "chain": name_chain(name, aliases.get(entity_id, []))})
+ return out
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--database", type=Path, required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--dead-list", type=Path, required=True,
+ help="entity-link-check CSV,只处理其中 status 为 404/410 的行")
+ parser.add_argument("--limit", type=int, default=0)
+ parser.add_argument("--interval", type=float, default=0.4)
+ parser.add_argument("--timeout", type=float, default=12.0)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ from peach.review_csv import read_rows
+
+ args = build_parser().parse_args(argv)
+ gone = {row["url"] for row in read_rows(args.dead_list)
+ if str(row.get("status") or "") in {"404", "410"}}
+ connection = sqlite3.connect(f"file:{args.database}?mode=ro", uri=True)
+ try:
+ targets = [record for record in load_dead(connection)
+ if record["url"] in gone]
+ finally:
+ connection.close()
+ if args.limit:
+ targets = targets[:args.limit]
+ print(f"待复查 {len(targets)} 条 404")
+
+ results = []
+ for index, record in enumerate(targets, 1):
+ row = rediscover(record, args.interval, args.timeout)
+ results.append(row)
+ mark = "搬走了" if row["verdict"] == "ok" else "没找到"
+ print(f"{index:>3}/{len(targets)} {record['name'][:10]:<10} {mark} "
+ f"{str(row['url'])[:56]}")
+
+ write_rows(args.output, FIELDS, results)
+ moved = [row for row in results if row["verdict"] == "ok"]
+ print({"复查": len(results), "实际还在(换了地址)": len(moved),
+ "确实没了": len(results) - len(moved), "output": str(args.output)})
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 477dc62c4..776613db1 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -17,7 +17,8 @@ SCOPES: dict[str, tuple[str, ...]] = {
"catalog": ("test_ad_judgement.py", "test_duplicate_identity_merge.py",
"test_entity_merge.py", "test_fastapi_api.py", "test_migrations.py",
"test_review_mirror.py", "test_rm_ledger.py", "test_rm_web.py",
- "test_entity_link_install.py",
+ "test_entity_link_install.py", "test_web_links.py",
+ "test_link_marks.py",
"test_review_csv.py", "test_related.py",
"test_taste_history.py", "test_web_ui.py", "test_web_resource_sync.py",
"test_web_review.py", "test_web_settings.py"),
@@ -35,7 +36,8 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_duplicate_identity_merge.py", "test_entity_merge.py",
"test_stash_entity_import.py", "test_migrations.py",
"test_entity_link_install.py", "test_studio_site_harvest.py",
- "test_performer_link_harvest.py"),
+ "test_performer_link_harvest.py",
+ "test_link_rediscovery.py"),
"tooling": ("test_scripts.py", "test_agent_worktree.py", "test_dependency_policy.py",
"test_restart_windows_tray.py",
"test_versioning.py",
diff --git a/src/peach/api.py b/src/peach/api.py
index 6fc17c740..92ea07679 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -12,7 +12,7 @@ from contextlib import asynccontextmanager
from functools import partial
from pathlib import Path
from typing import Any
-from urllib.parse import parse_qs, quote, unquote
+from urllib.parse import parse_qs, quote, unquote, urlsplit
from fastapi import Body, Depends, FastAPI, HTTPException, Request
from fastapi.responses import (
@@ -23,7 +23,13 @@ from fastapi.staticfiles import StaticFiles
from browserexport.common import BrowserexportError
from . import __version__, web_contract, web_follow
-from .config import LOCATION_ROOT_DECLARATIONS, PROJECT_ROOT, PeachSettings
+from . import link_marks
+from .config import (
+ GENERATED_DIR,
+ LOCATION_ROOT_DECLARATIONS,
+ PROJECT_ROOT,
+ PeachSettings,
+)
from .ffmpeg import FFmpegResolver
from .follow import FollowSourceError
from .follow_scheduler import FollowUpdateScheduler
@@ -797,6 +803,43 @@ def create_app(
response.headers["Cache-Control"] = "public, no-cache"
return response
+ @app.api_route("/link-mark", methods=["GET", "HEAD"])
+ def link_mark(id: int = 0, args: dict[str, str] = Depends(require_auth)):
+ """资料页外链的圆标:站点 favicon,能上色就上色。
+
+ 地址只从账本按链接 id 解析,绝不接受前端递过来的 URL——和 `/follow-stream`
+ 同一条规矩,否则这就是一个任意地址抓取的口子。
+ """
+ with database.read_connection() as connection:
+ row = connection.execute(
+ "SELECT url FROM entity_link WHERE id=?", (id,)).fetchone()
+ if row is None:
+ return JSONResponse({"error": "no such link"}, status_code=404)
+
+ root = GENERATED_DIR / "link-marks"
+ cached = link_marks.cached_path(root, row["url"])
+ if cached is None:
+ return JSONResponse({"error": "unavailable"}, status_code=404)
+ if not link_marks.is_fresh(cached):
+ source = urlsplit(row["url"])
+ try:
+ upstream = http_transport.client.get(
+ f"{source.scheme}://{source.netloc}/favicon.ico",
+ headers={"User-Agent": "Peach/0.2"}, timeout=8, follow_redirects=True)
+ data = upstream.content if upstream.status_code == 200 else b""
+ except (OSError, httpx.HTTPError):
+ data = b""
+ made = (link_marks.render_mark(data) or link_marks.plain_mark(data)) if data else None
+ if made:
+ root.mkdir(parents=True, exist_ok=True)
+ cached.write_bytes(made)
+ elif not cached.exists():
+ # 取不到就让前端露出下面的地球图标,不要留一个空白圆。
+ return JSONResponse({"error": "unavailable"}, status_code=404)
+ result = FileResponse(cached, media_type="image/png")
+ result.headers["Cache-Control"] = "public, no-cache"
+ return result
+
@app.api_route("/item/{item_id}", methods=["GET", "HEAD"])
@app.api_route("/mix/{seed_id}/{mix_item_id}", methods=["GET", "HEAD"])
@app.api_route("/parts/{part_seed_id}/{part_item_id}", methods=["GET", "HEAD"])
diff --git a/src/peach/entities.py b/src/peach/entities.py
index 9796572b3..610b0af78 100644
--- a/src/peach/entities.py
+++ b/src/peach/entities.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import re
from datetime import datetime, timezone
from sqlite3 import Connection
@@ -9,6 +10,48 @@ def normalize_entity_name(name: str) -> str:
return str(name).strip().casefold()
+KANA = re.compile(r"[぀-ゟ゠-ヿ]")
+KANJI = re.compile(r"[一-鿿]")
+
+
+def name_rank(name: str) -> int:
+ """这个写法对日文站有多可用,越小越先试。
+
+ 账本里 performer 的规范名是简体中文(`凉森玲梦`、`释爱丽丝`),日文站按它一个都
+ 搜不到;真正能用的日文写法在 `entity_alias` 里(`涼森れむ`、`釈アリス`)。实测拿
+ 规范名直接搜,12 位只命中 1 位;改用日文写法后同样 12 位全中。
+
+ 汉字加假名混排的是艺名本身,最可靠;纯假名是读音,能搜到但更容易撞名;纯汉字既可能
+ 是日文也可能是简体中文,放在后面;罗马字对日文站基本无效,排最后。
+ """
+ kana, kanji = bool(KANA.search(name)), bool(KANJI.search(name))
+ if kana and kanji:
+ return 0
+ if kana:
+ return 1
+ if kanji:
+ return 2
+ return 3
+
+
+def name_chain(canonical: str, aliases: list[str]) -> list[str]:
+ """去重后按可用程度排序的候选名字,罗马字不进链。
+
+ 罗马字留着只会白跑一次往返,并且它落空后混进未取得,看起来像是「这个人查不到」,
+ 而实际上是「我们从没用她的日文名查过」。
+
+ 放在实体层而不是某个脚本里:`harvest_performer_links` 和 `rediscover_entity_links`
+ 都要用它。此前它住在前者、后者靠改 `sys.path` 反向 import——依赖门槛把它算成外部
+ 模块是对的,那种导入既依赖 path 顺序,工具也读不懂。
+ """
+ seen: list[str] = []
+ for name in [canonical, *aliases]:
+ name = (name or "").strip()
+ if name and name not in seen and name_rank(name) < 3:
+ seen.append(name)
+ return sorted(seen, key=name_rank)
+
+
PERSON_ENTITY_KINDS = frozenset({"creator", "performer"})
INVALID_PERSON_ENTITY_NAMES = frozenset({"画像を拡大する"})
diff --git a/src/peach/link_marks.py b/src/peach/link_marks.py
new file mode 100644
index 000000000..62907e301
--- /dev/null
+++ b/src/peach/link_marks.py
@@ -0,0 +1,147 @@
+"""外链图标:把站点 favicon 做成资料页上能看的一枚圆标。
+
+用户指出资料页上的 favicon 不好看,并给了 beeg 的做法作参照——
+`cdn.../tag_full/34.svg` 是一块品牌色实心底 + 白色 logo 路径。那是 beeg 逐个平台
+手工做的 SVG;我们有八十多个不同主机,只能自动近似。
+
+**只在有把握时才套这个处理。** 实测三种形态:
+
+ T-POWERS 48×48,带透明通道,不透明像素只有一种绿 → alpha 就是现成遮罩,效果好
+ HEYZO 32×32,全不透明,白底 + 品牌粉的多色字形 → 抠图会反转,出来一团糟
+ MOODYZ favicon 根本不是有效图片 → 什么都做不了
+
+所以判据是「单色字形 + 有真透明」。不满足就原样转出 favicon——半吊子的抠图比原图更难看。
+
+服务端做还有两个附带好处:浏览器不再直接向对方站点发请求(不泄露正在看谁的资料页),
+以及结果可以按主机缓存,不必每次开页都去取一遍。
+"""
+from __future__ import annotations
+
+import colorsys
+import hashlib
+import io
+import time
+from pathlib import Path
+from urllib.parse import urlsplit
+
+MARK_SIZE = 64
+#: 主体像素的色相要多集中才算「单色字形」。实测 T-POWERS 是 1 簇,HEYZO 是 4 簇。
+MAX_HUE_BUCKETS = 2
+#: 透明像素要占到这么多,alpha 才算真的是遮罩而不是压缩噪点。
+MIN_TRANSPARENT = 0.15
+CACHE_TTL = 30 * 24 * 3600
+
+
+def cache_key(url: str) -> str:
+ """按主机缓存,不按完整地址——同一个站的每条链接共用一枚图标。"""
+ host = (urlsplit(url).hostname or "").casefold().removeprefix("www.")
+ return hashlib.sha256(host.encode("utf-8")).hexdigest()[:32] if host else ""
+
+
+def _body_pixels(image):
+ """返回 (主体坐标, 是否靠 alpha 判定的)。"""
+ width, height = image.size
+ pixels = image.load()
+ transparent = sum(1 for y in range(height) for x in range(width)
+ if pixels[x, y][3] < 128)
+ if transparent > MIN_TRANSPARENT * width * height:
+ return [(x, y) for y in range(height) for x in range(width)
+ if pixels[x, y][3] >= 128], True
+ # 全不透明时只能拿四角当底色去猜主体。实测这条路在多色 logo 上会反转,
+ # 所以它的结果不参与「有把握」的判定,只用来兜底。
+ corners = [pixels[0, 0], pixels[width - 1, 0],
+ pixels[0, height - 1], pixels[width - 1, height - 1]]
+ background = tuple(sum(corner[i] for corner in corners) // 4 for i in range(3))
+ return [(x, y) for y in range(height) for x in range(width)
+ if sum(abs(pixels[x, y][i] - background[i]) for i in range(3)) > 110], False
+
+
+def brand_colour(image, body) -> tuple[tuple[int, int, int], int]:
+ """主体里最常见的那个饱和色,以及色相簇的个数。
+
+ 簇数就是「这是不是单色字形」的度量:纯黑白 logo 没有可用色,多色 logo 簇数会散开。
+ """
+ pixels = image.load()
+ buckets: dict[tuple[int, int, int], int] = {}
+ for x, y in body:
+ red, green, blue = pixels[x, y][:3]
+ _hue, light, saturation = colorsys.rgb_to_hls(red / 255, green / 255, blue / 255)
+ if saturation > 0.25 and 0.15 < light < 0.85:
+ key = (red // 32 * 32, green // 32 * 32, blue // 32 * 32)
+ buckets[key] = buckets.get(key, 0) + 1
+ if not buckets:
+ return (60, 60, 64), 0
+ return max(buckets, key=buckets.get), len(buckets)
+
+
+def render_mark(data: bytes, size: int = MARK_SIZE) -> bytes | None:
+ """favicon → 「品牌色圆底 + 白色主体」的 PNG;没把握就返回 None。"""
+ from PIL import Image, ImageDraw
+
+ try:
+ image = Image.open(io.BytesIO(data))
+ image.load()
+ except Exception:
+ return None
+ image = image.convert("RGBA")
+ body, from_alpha = _body_pixels(image)
+ if not body or not from_alpha:
+ return None
+ colour, clusters = brand_colour(image, body)
+ if clusters == 0 or clusters > MAX_HUE_BUCKETS:
+ return None
+
+ width, height = image.size
+ mask = Image.new("L", (width, height), 0)
+ painter = mask.load()
+ for x, y in body:
+ painter[x, y] = 255
+ mask = mask.resize((size, size), Image.LANCZOS)
+
+ # 圆用四倍尺寸画再缩,边缘才不是锯齿。
+ circle = Image.new("L", (size * 4, size * 4), 0)
+ ImageDraw.Draw(circle).ellipse((0, 0, size * 4 - 1, size * 4 - 1), fill=255)
+ circle = circle.resize((size, size), Image.LANCZOS)
+
+ out = Image.new("RGBA", (size, size), (0, 0, 0, 0))
+ out.paste(Image.new("RGBA", (size, size), colour + (255,)), (0, 0), circle)
+ out.paste(Image.new("RGBA", (size, size), (255, 255, 255, 255)), (0, 0), mask)
+ buffer = io.BytesIO()
+ out.save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def plain_mark(data: bytes, size: int = MARK_SIZE) -> bytes | None:
+ """做不了品牌处理时的回落:把 favicon 原样缩成 PNG。"""
+ from PIL import Image
+
+ try:
+ image = Image.open(io.BytesIO(data))
+ image.load()
+ except Exception:
+ return None
+ return _encode(image.convert("RGBA").resize((size, size), Image.LANCZOS))
+
+
+def _encode(image) -> bytes:
+ buffer = io.BytesIO()
+ image.save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def cached_path(root: Path, url: str) -> Path | None:
+ key = cache_key(url)
+ return (root / f"{key}.png") if key else None
+
+
+def is_fresh(path: Path, now: float | None = None) -> bool:
+ """缓存还新鲜吗。
+
+ 图标会随站点改版变,但不必每次开页都重取;一个月是「站点改了版早晚会跟上」和
+ 「不要每开一页就打一遍别人的服务器」之间的折中。
+ """
+ try:
+ age = (now if now is not None else time.time()) - path.stat().st_mtime
+ except OSError:
+ return False
+ return 0 <= age < CACHE_TTL
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 04fe2ce50..7722928d7 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -87,6 +87,11 @@ from .catalog_rules import (
from .web_playlists import q_playlist, q_playlists, w_playlist
from .web_review import q_review, w_review_auto_apply, w_review_decision
from .web_settings import q_settings, w_settings
+from .web_links import ( # noqa: E402
+ w_links,
+ w_links_check,
+ w_links_prune,
+)
from .web_resource_sync import (
clean_resource_orphans,
source_is_online,
@@ -198,6 +203,9 @@ class WebContract:
self.resource_scan_lock = threading.Lock()
self.resource_scan_state: dict | None = None
self.resource_scan_thread: threading.Thread | None = None
+ self.link_check_lock = threading.Lock()
+ self.link_check_state: dict | None = None
+ self.link_check_thread: threading.Thread | None = None
self._fts_available: bool | None = None
def cached(self, key, fn):
@@ -1288,7 +1296,7 @@ def q_entity(contract: WebContract, args):
d["canonical_name"], d["aliases"])
links = []
for link in c.execute(
- "SELECT link_kind,label,url,hostname,is_sensitive,metadata_json "
+ "SELECT id AS link_id,link_kind,label,url,hostname,is_sensitive,metadata_json "
"FROM entity_link WHERE entity_id=? ORDER BY link_kind,label", (d["id"],),
):
item = dict(link)
@@ -2150,6 +2158,7 @@ GET_HANDLERS = {
"/api/parts": q_parts,
"/api/editions": q_editions,
"/api/entity": q_entity,
+ "/api/links": w_links,
"/api/photos": q_entity_photos,
"/api/photo-set": q_photo_set,
"/api/index": _get_index,
@@ -2192,6 +2201,8 @@ POST_HANDLERS = {
"/api/taste/source": w_taste_source,
"/api/trash/empty": _post_empty_trash,
"/api/purge-missing": w_purge_missing,
+ "/api/links/check": w_links_check,
+ "/api/links/prune": w_links_prune,
"/api/resource-sync/scan": w_resource_sync_scan,
"/api/resource-sync/apply": w_resource_sync_apply,
"/api/review/auto-apply": w_review_auto_apply,
@@ -2206,6 +2217,7 @@ POST_HANDLERS = {
READ_ONLY_POST_ROUTES = frozenset({
"/api/follow/resolve", "/api/follow/credential",
"/api/taste/refresh", "/api/taste/source", "/api/resource-sync/scan",
+ "/api/links/check",
})
diff --git a/src/peach/web_links.py b/src/peach/web_links.py
new file mode 100644
index 000000000..68f3952cc
--- /dev/null
+++ b/src/peach/web_links.py
@@ -0,0 +1,222 @@
+"""实体链接管理:库里有哪些外链,以及它们现在还打不打得开。
+
+从 `web_contract` 拆出,理由和资源对账一样:这一域自己持有检查线程的状态和网络往返,
+和浏览、复核没有共享逻辑。
+
+为什么资料页需要这么一块管理面:链接是**别人服务器上的东西**,会在我们不知情的时候烂掉。
+2026-09-01 实测 719 条里 152 条打不开,其中 84 条 official 是 404——而它们在资料页上
+和好链接长得一模一样,只有点下去才知道。检查这件事必须能随时重跑,不能是一次性脚本。
+
+`gone` 与 `unclear` 必须分开,这是这块面板最重要的一条:`linktr.ee` 回 403 是挡爬虫、
+`x.com` 回 500 是临时错误,链接本身好好的。按「非 200 就删」会连它们一起删掉。
+"""
+from __future__ import annotations
+
+import re
+import threading
+import time
+import uuid
+from pathlib import Path
+from typing import Protocol
+from urllib.parse import urlsplit
+
+import httpx
+
+USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/128.0 Safari/537.36")
+#: 「这个页面没了」——只有上游明确这么说,才够格作为删除依据。
+GONE_STATUSES = frozenset({404, 410})
+CHECK_TIMEOUT = 12.0
+CHECK_INTERVAL = 0.25
+
+
+class LinkContract(Protocol):
+ """链接管理需要契约提供的能力;比整个 WebContract 小得多。"""
+
+ db_path: Path
+ link_check_lock: threading.Lock
+ link_check_state: dict | None
+ link_check_thread: threading.Thread | None
+
+ def read_connection(self): ...
+
+ def write_connection(self): ...
+
+
+def _probe(url: str, timeout: float = CHECK_TIMEOUT) -> tuple[int, str]:
+ """(status, 说明)。status 为 0 表示连都没连上。
+
+ 每个请求新建 client 并立刻关掉:这批地址分布在上百个互不相同的主机上,其中不少
+ 连不上,而失败的连接会在共享池里漏掉槽位,几十个请求之后一切都变成 PoolTimeout。
+ """
+ try:
+ with httpx.Client(follow_redirects=True, timeout=timeout,
+ limits=httpx.Limits(max_connections=4,
+ max_keepalive_connections=0)) as client:
+ response = client.get(url, headers={"User-Agent": USER_AGENT})
+ except Exception as error:
+ return 0, type(error).__name__
+ return response.status_code, ""
+
+
+def link_verdict(status: int, note: str) -> str:
+ """ok / gone / unclear。
+
+ 取不到不等于没了。实测反例:`linktr.ee` 403(Linktree 挡爬虫,浏览器里能开)、
+ `facebook.com` 400、`x.com` 500(临时错误,账号还在)、连接失败与超时。
+ 把它们并进 gone,删除时就会连好链接一起删。
+ """
+ if status == 200:
+ return "ok"
+ if status in GONE_STATUSES:
+ return "gone"
+ return "unclear"
+
+
+def w_links(contract: LinkContract, args=None):
+ """库里链接的现状。纯读库,随页面一起加载,不联网。"""
+ with contract.read_connection() as connection:
+ rows = [dict(row) for row in connection.execute(
+ "SELECT l.id, l.link_kind, l.label, l.url, l.hostname, e.kind AS entity_kind, "
+ "e.canonical_name AS entity, e.id AS entity_id "
+ "FROM entity_link l JOIN entity e ON e.id=l.entity_id "
+ "ORDER BY e.kind, e.canonical_name, l.link_kind")]
+ by_kind: dict[str, int] = {}
+ by_entity_kind: dict[str, int] = {}
+ hosts: dict[str, int] = {}
+ for row in rows:
+ by_kind[row["link_kind"]] = by_kind.get(row["link_kind"], 0) + 1
+ by_entity_kind[row["entity_kind"]] = by_entity_kind.get(row["entity_kind"], 0) + 1
+ host = row["hostname"] or urlsplit(row["url"]).hostname or ""
+ if host:
+ hosts[host] = hosts.get(host, 0) + 1
+ return {
+ "ok": True,
+ "total": len(rows),
+ "entities": len({row["entity_id"] for row in rows}),
+ "by_kind": by_kind,
+ "by_entity_kind": by_entity_kind,
+ "top_hosts": sorted(hosts.items(), key=lambda item: (-item[1], item[0]))[:12],
+ }
+
+
+def _check_public(state: dict) -> dict:
+ return {
+ "ok": state["status"] != "failed",
+ "status": state["status"],
+ "check_id": state["check_id"],
+ "checked": state["checked"],
+ "total": state["total"],
+ "gone": [dict(item) for item in state["gone"]],
+ "unclear": [dict(item) for item in state["unclear"]],
+ **({"error": state["error"]} if state["status"] == "failed" else {}),
+ }
+
+
+def _run_link_check(contract: LinkContract, check_id: str) -> None:
+ try:
+ 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")]
+ with contract.link_check_lock:
+ state = contract.link_check_state
+ if state is None or state["check_id"] != check_id:
+ return
+ state["total"] = len(rows)
+ for row in rows:
+ status, note = _probe(row["url"])
+ verdict = link_verdict(status, note)
+ with contract.link_check_lock:
+ state = contract.link_check_state
+ if state is None or state["check_id"] != check_id:
+ return # 被新的检查顶掉了,安静收工
+ state["checked"] += 1
+ if verdict != "ok":
+ state["gone" if verdict == "gone" else "unclear"].append({
+ "id": row["id"], "entity": row["entity"],
+ "link_kind": row["link_kind"], "label": row["label"],
+ "url": row["url"],
+ "note": f"HTTP {status}" if status else f"取不到:{note}",
+ })
+ time.sleep(CHECK_INTERVAL)
+ with contract.link_check_lock:
+ state = contract.link_check_state
+ if state is not None and state["check_id"] == check_id:
+ state.update(status="complete", completed_at=time.time())
+ except Exception as error: # 后台失败必须变成可轮询的状态,不能只留在日志里
+ with contract.link_check_lock:
+ state = contract.link_check_state
+ if state is not None and state["check_id"] == check_id:
+ state.update(status="failed", error=f"{type(error).__name__}: {error}",
+ completed_at=time.time())
+
+
+def w_links_check(contract: LinkContract, body=None):
+ """开始(或查询)一次死链检查。
+
+ 七百多条链接逐条联网要好几分钟,同步请求必然超时,所以和资源对账走同一套:
+ 后台线程 + 可轮询状态。
+ """
+ body = body or {}
+ if body.get("status_only") is True:
+ with contract.link_check_lock:
+ state = contract.link_check_state
+ if state is None:
+ return {"ok": True, "status": "idle", "check_id": "", "checked": 0,
+ "total": 0, "gone": [], "unclear": []}
+ return _check_public(state)
+
+ thread = None
+ with contract.link_check_lock:
+ state = contract.link_check_state
+ if state is not None and state["status"] == "running":
+ return _check_public(state)
+ if state is not None and body.get("restart") is not True:
+ return _check_public(state)
+ check_id = uuid.uuid4().hex
+ state = {"check_id": check_id, "status": "running", "checked": 0, "total": 0,
+ "gone": [], "unclear": [], "started_at": time.time(), "error": ""}
+ contract.link_check_state = state
+ thread = threading.Thread(target=_run_link_check, args=(contract, check_id),
+ daemon=True, name="PeachLinkCheckJob")
+ contract.link_check_thread = thread
+ response = _check_public(state)
+ thread.start()
+ return response
+
+
+def w_links_prune(contract: LinkContract, body):
+ """删掉上一次检查判定为 gone 的链接。
+
+ 只接受**刚跑完的那一次**检查的 `check_id`:拿一份放了半天的清单去删,删的可能是
+ 早已改好的链接。删除前逐条重验一次,这几秒钟换的是「不会因为一次网络抖动删掉好链接」。
+ """
+ body = body or {}
+ if body.get("confirm") is not True:
+ return {"ok": False, "error": "需要 confirm"}
+ with contract.link_check_lock:
+ state = contract.link_check_state
+ if state is None or state["status"] != "complete":
+ return {"ok": False, "error": "没有已完成的检查结果"}
+ if body.get("check_id") != state["check_id"]:
+ return {"ok": False, "error": "检查结果已过期,请重新检查"}
+ planned = [dict(item) for item in state["gone"]]
+
+ confirmed, recovered = [], []
+ for item in planned:
+ status, note = _probe(item["url"])
+ (confirmed if link_verdict(status, note) == "gone" else recovered).append(item)
+
+ removed = 0
+ if confirmed:
+ with contract.write_connection() as connection:
+ for item in confirmed:
+ connection.execute("DELETE FROM entity_link WHERE id=?", (item["id"],))
+ removed += connection.execute("SELECT changes()").fetchone()[0]
+ with contract.link_check_lock:
+ state = contract.link_check_state
+ if state is not None and state["check_id"] == body.get("check_id"):
+ state["gone"] = []
+ return {"ok": True, "removed": removed, "recovered": len(recovered),
+ "entities": len({item["entity"] for item in confirmed})}
diff --git a/tests/test_link_marks.py b/tests/test_link_marks.py
new file mode 100644
index 000000000..297d0ed96
--- /dev/null
+++ b/tests/test_link_marks.py
@@ -0,0 +1,109 @@
+"""外链圆标:只在有把握时上色,其余原样放行。"""
+import io
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+
+from PIL import Image
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from peach import link_marks # noqa: E402
+
+
+def ico(pixels, size=32, mode="RGBA"):
+ image = Image.new(mode, (size, size), (0, 0, 0, 0) if mode == "RGBA" else (255, 255, 255))
+ painter = image.load()
+ for (x, y), colour in pixels.items():
+ painter[x, y] = colour
+ buffer = io.BytesIO()
+ image.save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def glyph(colour, size=32, opaque_background=None):
+ """中间一块实心方块当字形;`opaque_background` 不为 None 时整张图不透明。"""
+ pixels = {}
+ if opaque_background is not None:
+ for x in range(size):
+ for y in range(size):
+ pixels[(x, y)] = opaque_background + (255,)
+ for x in range(8, 24):
+ for y in range(8, 24):
+ pixels[(x, y)] = colour + (255,)
+ return ico(pixels, size)
+
+
+class RenderTests(unittest.TestCase):
+ def test_a_single_colour_glyph_with_transparency_is_recoloured(self):
+ """T-POWERS 就是这个形态:48×48、带透明、不透明像素只有一种绿。
+
+ alpha 直接就是遮罩,所以能稳稳做出「品牌色底 + 白色主体」。
+ """
+ made = link_marks.render_mark(glyph((72, 168, 24)))
+ self.assertIsNotNone(made)
+ image = Image.open(io.BytesIO(made)).convert("RGBA")
+ self.assertEqual(image.size, (link_marks.MARK_SIZE, link_marks.MARK_SIZE))
+ centre = image.getpixel((image.width // 2, image.height // 2))
+ self.assertEqual(centre[:3], (255, 255, 255), "主体应当是白的")
+ edge = image.getpixel((image.width // 2, 3))
+ self.assertGreater(edge[1], edge[0], "圆底应当是那个绿")
+
+ def test_an_opaque_favicon_is_left_alone(self):
+ """HEYZO 是白底 + 多色字形。
+
+ 全不透明时只能拿四角猜主体,实测这条路会把白字反转成一团糟——
+ 半吊子的抠图比原图更难看,所以直接不做。
+ """
+ self.assertIsNone(link_marks.render_mark(glyph((240, 0, 96), opaque_background=(240, 240, 240))))
+
+ def test_a_multi_hue_glyph_is_left_alone(self):
+ """多色 logo 没有单一品牌色可取,硬取会挑出其中一块,看起来像认错了牌子。"""
+ pixels = {}
+ for x in range(8, 24):
+ for y in range(8, 24):
+ pixels[(x, y)] = ((240, 0, 0, 255) if x < 12 else
+ (0, 200, 0, 255) if x < 16 else
+ (0, 0, 240, 255) if x < 20 else (240, 200, 0, 255))
+ self.assertIsNone(link_marks.render_mark(ico(pixels)))
+
+ def test_a_broken_image_yields_nothing_instead_of_raising(self):
+ """MOODYZ 的 favicon 根本不是有效图片。
+
+ 端点在页面加载时被调用,抛异常会变成 500;返回 None 让它回落到地球图标。
+ """
+ self.assertIsNone(link_marks.render_mark(b"<html>not an image</html>"))
+ self.assertIsNone(link_marks.plain_mark(b"<html>not an image</html>"))
+
+ def test_the_fallback_still_produces_a_png_at_the_mark_size(self):
+ made = link_marks.plain_mark(glyph((240, 0, 96), opaque_background=(240, 240, 240)))
+ self.assertIsNotNone(made)
+ self.assertEqual(Image.open(io.BytesIO(made)).size,
+ (link_marks.MARK_SIZE, link_marks.MARK_SIZE))
+
+
+class CacheTests(unittest.TestCase):
+ def test_the_cache_key_is_per_host_not_per_link(self):
+ """同一个站的每条链接共用一枚图标;按完整地址缓存会为同一张图存几十份。"""
+ self.assertEqual(link_marks.cache_key("https://www.t-powers.co.jp/talent/a/"),
+ link_marks.cache_key("http://t-powers.co.jp/talent/b/"))
+ self.assertNotEqual(link_marks.cache_key("https://t-powers.co.jp/"),
+ link_marks.cache_key("https://x.com/"))
+
+ def test_a_url_without_a_host_has_no_cache_key(self):
+ self.assertEqual(link_marks.cache_key("not a url"), "")
+ self.assertIsNone(link_marks.cached_path(Path("/tmp"), "not a url"))
+
+ def test_freshness_expires_and_a_missing_file_is_never_fresh(self):
+ tmp = Path(tempfile.mkdtemp()) / "mark.png"
+ self.assertFalse(link_marks.is_fresh(tmp))
+ tmp.write_bytes(b"x")
+ self.assertTrue(link_marks.is_fresh(tmp))
+ self.assertFalse(link_marks.is_fresh(
+ tmp, now=time.time() + link_marks.CACHE_TTL + 1))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_link_rediscovery.py b/tests/test_link_rediscovery.py
new file mode 100644
index 000000000..d2b66be7c
--- /dev/null
+++ b/tests/test_link_rediscovery.py
@@ -0,0 +1,96 @@
+"""死链复查:搬走了和没了要分开,而且「搬走了」必须还在同一个站。"""
+import importlib.util
+import sys
+import unittest
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[1]
+
+
+def load_module():
+ sys.path.insert(0, str(REPO / "scripts"))
+ sys.path.insert(0, str(REPO / "src"))
+ spec = importlib.util.spec_from_file_location(
+ "rediscover_entity_links", REPO / "scripts" / "rediscover_entity_links.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class SameSiteTests(unittest.TestCase):
+ def setUp(self):
+ self.module = load_module()
+
+ def test_a_link_to_another_site_is_not_a_repair(self):
+ """实测:KRONE 的索引页里「上川星空」那一条指向她的 X 账号。
+
+ 人是对的——`天馬ゆい` 就在账本别名里,那确实是她。但那不是事务所页面。
+ 照单收下会留下一条标着「KRONE(クローネ)」、点开却是 Twitter 的 official 链接,
+ 比一条死链更糟:它看起来是对的。修复的定义是「在同一个站点上找到新地址」,
+ 不是「找到关于这个人的另一个链接」。
+ """
+ self.assertFalse(self.module.same_site(
+ "https://x.com/tenma_yui2", "http://krone-web.jp/model/info.php?5493"))
+
+ def test_www_and_scheme_changes_are_still_the_same_site(self):
+ """T-POWERS 的真实修复就是这个形态:http 裸域 → https 带 www,路径换了一层。"""
+ self.assertTrue(self.module.same_site(
+ "https://www.t-powers.co.jp/talent/%e6%b6%bc%e6%a3%ae/",
+ "http://t-powers.co.jp/official/talent/%E6%B6%BC%E6%A3%AE"))
+
+ def test_a_lookalike_domain_is_not_the_same_site(self):
+ """`evil-t-powers.co.jp` 不是 `t-powers.co.jp`。判据要落在点边界上。"""
+ self.assertFalse(self.module.same_site(
+ "https://evil-t-powers.co.jp/x", "http://t-powers.co.jp/y"))
+
+ def test_a_japanese_second_level_suffix_keeps_three_labels(self):
+ """`co.jp` 下取末两段会把所有日本公司判成同一家。"""
+ self.assertEqual(self.module.registrable("www.t-powers.co.jp"), "t-powers.co.jp")
+ self.assertEqual(self.module.registrable("x.com"), "x.com")
+ self.assertFalse(self.module.same_site("https://a.co.jp/", "https://b.co.jp/"))
+
+
+class ConfirmTests(unittest.TestCase):
+ def setUp(self):
+ self.module = load_module()
+
+ def test_a_list_page_does_not_confirm_an_individual(self):
+ """列表页同样回 200。
+
+ 少了标题这一关,`/talent/` 本身会被当成每个人的新地址——四百个人被改写成
+ 同一个列表链接,而且每一条都「能打开」。
+ """
+ self.assertEqual(
+ self.module.confirms("<title>所属タレント一覧</title>", ["涼森れむ"]), "")
+
+ def test_a_title_that_spaces_the_family_name_still_confirms(self):
+ """站点常在姓与名之间加空格或全角空格;逐字比会把真页面判成不匹配。"""
+ self.assertIn("涼森", self.module.confirms(
+ "<title>涼森 れむ|AVプロダクション【ティーパワーズ】公式サイト</title>", ["涼森れむ"]))
+ self.assertIn("天海", self.module.confirms(
+ "<title>天海 つばさ|ティーパワーズ</title>", ["天海つばさ"]))
+
+ def test_an_encoded_name_in_the_href_is_matched(self):
+ """日文站的艺人页地址常常就是 URL 编码后的名字,而锚文本只是一张图。"""
+ html = ('<a href="/talent/%E6%B6%BC%E6%A3%AE%E3%82%8C%E3%82%80/"><img></a>'
+ '<a href="/other">別の人</a>')
+ found = self.module.anchors_naming(html, "https://www.t-powers.co.jp/", ["涼森れむ"])
+ self.assertEqual([url for url, _ in found],
+ ["https://www.t-powers.co.jp/talent/%E6%B6%BC%E6%A3%AE%E3%82%8C%E3%82%80/"])
+
+
+class IndexTests(unittest.TestCase):
+ def setUp(self):
+ self.module = load_module()
+
+ def test_index_pages_walk_up_from_the_dead_url(self):
+ """艺人页几乎总挂在某个列表下面,而改版通常只动其中一层。"""
+ self.assertEqual(
+ self.module.index_candidates("http://www.t-powers.co.jp/official/talent/x"),
+ ["http://www.t-powers.co.jp/official/talent/",
+ "http://www.t-powers.co.jp/official/",
+ "http://www.t-powers.co.jp/"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 6265e7af7..604921a43 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -617,7 +617,7 @@ class WebDataTests(unittest.TestCase):
"/api/search-history", "/api/review", "/api/playlists", "/api/playlist",
"/api/follow", "/api/follow/credentials", "/api/follow/schedule",
"/api/follow/tags",
- "/api/taste", "/api/settings",
+ "/api/taste", "/api/settings", "/api/links",
})
self.assertEqual(set(rm_web.POST_HANDLERS), {
"/api/activity", "/api/play", "/api/feedback", "/api/watch-later",
@@ -625,6 +625,7 @@ class WebDataTests(unittest.TestCase):
"/api/preference", "/api/quality-goal", "/api/item-tag", "/api/batch",
"/api/search-history", "/api/trash/empty", "/api/review/decision",
"/api/purge-missing", "/api/review/auto-apply",
+ "/api/links/check", "/api/links/prune",
"/api/resource-sync/scan", "/api/resource-sync/apply",
"/api/follow/check", "/api/follow/status", "/api/follow/save",
"/api/follow/play", "/api/follow/activity",
diff --git a/tests/test_web_links.py b/tests/test_web_links.py
new file mode 100644
index 000000000..34e026e2b
--- /dev/null
+++ b/tests/test_web_links.py
@@ -0,0 +1,138 @@
+"""链接管理契约:取不到不等于没了,删除前必须重验。"""
+import sqlite3
+import sys
+import tempfile
+import threading
+import unittest
+from contextlib import contextmanager
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from peach import web_links # noqa: E402
+
+SCHEMA = """
+CREATE TABLE entity(id INTEGER PRIMARY KEY, kind TEXT, canonical_name TEXT);
+CREATE TABLE entity_link(
+ id INTEGER PRIMARY KEY, entity_id INTEGER NOT NULL, link_kind TEXT NOT NULL,
+ label TEXT NOT NULL, url TEXT NOT NULL, hostname TEXT);
+"""
+
+
+class FakeContract:
+ def __init__(self, db: Path):
+ self.db_path = db
+ self.link_check_lock = threading.Lock()
+ self.link_check_state = None
+ self.link_check_thread = None
+
+ @contextmanager
+ def _connect(self):
+ connection = sqlite3.connect(self.db_path)
+ connection.row_factory = sqlite3.Row
+ try:
+ yield connection
+ connection.commit()
+ finally:
+ connection.close()
+
+ read_connection = _connect
+ write_connection = _connect
+
+
+class VerdictTests(unittest.TestCase):
+ def test_only_a_gone_status_is_deletable(self):
+ """取不到不等于没了,这两件事只有 404/410 能划清。
+
+ 实测反例:`linktr.ee` 回 403(Linktree 挡爬虫,浏览器里能正常打开)、
+ `facebook.com` 回 400、`x.com` 回 500(临时错误,账号还在)、连接失败与超时。
+ 把它们并进 gone,删除时就会连好链接一起删。
+ """
+ self.assertEqual(web_links.link_verdict(200, ""), "ok")
+ for status in (404, 410):
+ self.assertEqual(web_links.link_verdict(status, ""), "gone", status)
+ for status in (400, 403, 429, 500, 502, 503):
+ self.assertEqual(web_links.link_verdict(status, ""), "unclear", status)
+ self.assertEqual(web_links.link_verdict(0, "ConnectError"), "unclear")
+
+
+class SummaryTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp())
+ db = self.tmp / "ledger.db"
+ connection = sqlite3.connect(db)
+ connection.executescript(SCHEMA)
+ connection.executemany("INSERT INTO entity VALUES(?,?,?)",
+ [(1, "performer", "凉森玲梦"), (2, "studio", "MOODYZ")])
+ connection.executemany(
+ "INSERT INTO entity_link(entity_id,link_kind,label,url,hostname) VALUES(?,?,?,?,?)",
+ [(1, "social", "X @a", "https://x.com/a", "x.com"),
+ (1, "official", "T-POWERS", "https://www.t-powers.co.jp/talent/x/", "www.t-powers.co.jp"),
+ (2, "official", "官方网站", "https://moodyz.com/", "moodyz.com")])
+ connection.commit()
+ connection.close()
+ self.contract = FakeContract(db)
+
+ def test_the_summary_counts_links_entities_and_hosts(self):
+ """面板一打开就要能回答「库里现在有什么」,所以这一条纯读库、不联网。"""
+ info = web_links.w_links(self.contract)
+ self.assertEqual(info["total"], 3)
+ self.assertEqual(info["entities"], 2)
+ self.assertEqual(info["by_kind"], {"social": 1, "official": 2})
+ self.assertEqual(info["by_entity_kind"], {"performer": 2, "studio": 1})
+ self.assertIn(("moodyz.com", 1), info["top_hosts"])
+
+ def test_prune_refuses_without_a_finished_check(self):
+ """没有检查结果就删除,等于凭空删。"""
+ self.assertFalse(web_links.w_links_prune(self.contract, {"confirm": True})["ok"])
+
+ def test_prune_refuses_a_stale_check_id(self):
+ """拿一份放了半天的清单去删,删的可能是早已改好的链接。"""
+ self.contract.link_check_state = {
+ "check_id": "fresh", "status": "complete", "checked": 3, "total": 3,
+ "gone": [{"id": 1, "entity": "凉森玲梦", "link_kind": "social",
+ "label": "X @a", "url": "https://x.com/a", "note": "HTTP 404"}],
+ "unclear": [], "error": "",
+ }
+ out = web_links.w_links_prune(self.contract, {"confirm": True, "check_id": "old"})
+ self.assertFalse(out["ok"])
+ self.assertIn("过期", out["error"])
+ self.assertEqual(
+ sqlite3.connect(self.contract.db_path).execute(
+ "SELECT count(*) FROM entity_link").fetchone()[0], 3)
+
+ def test_prune_reverifies_and_keeps_links_that_came_back(self):
+ """删除前逐条重验,这几秒钟换的是「不会因为一次网络抖动删掉好链接」。
+
+ 第一条重验仍是 404,删;第二条重验回了 200,保留并计入 recovered。
+ """
+ self.contract.link_check_state = {
+ "check_id": "fresh", "status": "complete", "checked": 3, "total": 3,
+ "gone": [
+ {"id": 1, "entity": "凉森玲梦", "link_kind": "social", "label": "X @a",
+ "url": "https://x.com/a", "note": "HTTP 404"},
+ {"id": 3, "entity": "MOODYZ", "link_kind": "official", "label": "官方网站",
+ "url": "https://moodyz.com/", "note": "HTTP 404"},
+ ],
+ "unclear": [], "error": "",
+ }
+ original = web_links._probe
+ web_links._probe = lambda url, timeout=0: (404, "") if "x.com" in url else (200, "")
+ try:
+ out = web_links.w_links_prune(
+ self.contract, {"confirm": True, "check_id": "fresh"})
+ finally:
+ web_links._probe = original
+ self.assertEqual((out["removed"], out["recovered"]), (1, 1))
+ remaining = {row[0] for row in sqlite3.connect(self.contract.db_path).execute(
+ "SELECT url FROM entity_link")}
+ self.assertNotIn("https://x.com/a", remaining)
+ self.assertIn("https://moodyz.com/", remaining)
+
+ def test_prune_requires_confirm(self):
+ """不可逆动作不接受默认参数。"""
+ self.assertFalse(web_links.w_links_prune(self.contract, {})["ok"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index b674397f8..f22beec8f 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -251,20 +251,39 @@ class WebUiSourceTests(unittest.TestCase):
# 资料页就会把 Peach 的页面地址报给 x.com、事务所站等每一个被链接的站点。
# 同页的 taste 行早就是 no-referrer,这里此前漏了;资料页链接从 5 条涨到两百
# 多条之后,漏的这一处才真正开始有代价。
- self.assertPageContains(
- 'class="entityfavicon" src="${esc(faviconUrl(x.url))}"')
+ # 现在更进一步:图标由本机 `/link-mark` 提供,浏览器根本不再向对方站点发请求,
+ # 也就无从泄露。referrerpolicy 仍然留着——它守的是这条约束本身。
+ self.assertPageContains('class="entityfavicon" src="${esc(linkMarkUrl(x))}"')
+ self.assertPageLacks('src="${esc(faviconUrl(x.url))}"',
+ "外链图标不应再直接指向对方站点")
anchor = self.app_js.index('class="entityfavicon"')
self.assertIn('referrerpolicy="no-referrer"',
self.app_js[anchor:anchor + 260],
"资料页外链 favicon 必须带 no-referrer")
+ def test_the_link_mark_endpoint_takes_a_link_id_not_a_url(self):
+ # 让前端把地址递给服务端去取,等于开一个任意地址抓取的口子。和 `/follow-stream`
+ # 同一条规矩:服务端只取账本里已有的地址。
+ self.assertPageContains("const linkMarkUrl=link=>`/link-mark?id=")
+ self.assertPageLacks("/link-mark?url=", "外链图标端点不得接受前端给的地址")
+
def test_social_links_show_only_the_platform_mark_not_the_handle(self):
# handle 是网址的一部分,写出来只是把 URL 抄一遍:`X @remu19971203` 里真正有
# 信息量的只有那个 X。图标本身就说明了去哪,名字留给官网那种「点之前看不出是谁」
# 的链接。纯图标没有可读文字,所以标签必须留给辅助技术,不能整个丢掉。
- self.assertPageContains("x.link_kind==='social'\n ? `<span class=\"sr-only\">${esc(x.label)}</span>`")
+ self.assertPageContains('<a class="iconlink" href="${esc(x.url)}"')
+ self.assertPageContains('<span class="sr-only">${esc(x.label)}</span></a>')
self.assertPageContains('.entitylinks a.iconlink{padding:4px;gap:0;border-radius:50%}')
+ def test_a_studio_official_link_shows_its_url_and_no_icon(self):
+ # 厂牌页的头像就是厂牌 logo,旁边再放一枚同品牌的小图标只是把同一个东西说两遍;
+ # 域名本身就是名字,比图标说得清楚。女优页不一样:那里的头像是人,事务所图标
+ # 不构成重复,标签也是事务所名而非域名。
+ self.assertPageContains("if(kind==='studio')")
+ self.assertPageContains('<a class="urllink" href="${esc(x.url)}"')
+ self.assertPageContains("${esc(linkHost(x.url)||x.label)}")
+ self.assertPageContains(".entitylinks a.urllink{padding:4px 14px")
+
def test_entity_links_have_no_external_arrow(self):
# `target="_blank"` 已经是外链,箭头只是重复;一排链接里它还会挤掉本就不多的
# 横向空间。整条 CSS 一并删掉,别留下没人用的类名。
@@ -2166,9 +2185,12 @@ class WebUiSourceTests(unittest.TestCase):
'<b data-middle-truncate>${esc(javDisplayName(x))}</b>',
'class="t resourcecardtitle" data-middle-truncate',
'class="t junkcardtitle" type="button" data-junk-open data-middle-truncate',
- 'class="t junkcardtitle" data-middle-truncate'):
+ 'class="t junkcardtitle" data-middle-truncate',
+ # 死链表里的地址:`/official/talent/X` 与 `/talent/X` 的差别就在尾部,
+ # 尾部省略会把这张表要回答的东西切掉。
+ 'rel="noreferrer" data-middle-truncate>${esc(item.url)}</a>'):
self.assertPageContains(consumer)
- self.assertEqual(self.app_js.count("data-middle-truncate"), 11)
+ self.assertEqual(self.app_js.count("data-middle-truncate"), 12)
self.assertEqual(self.app_js.count('class="mixitemtext"'), 3)
self.assertEqual(self.app_js.count("data-truncate-end"), 4)
self.assertPageContains("new Intl.Segmenter(undefined,{granularity:'grapheme'})")
diff --git a/web/app.css b/web/app.css
index a0600cae2..bc98eb32b 100644
--- a/web/app.css
+++ b/web/app.css
@@ -366,7 +366,8 @@ body.entity-open .index{overflow-x:visible}
.entityportrait:has(img)>span{display:none}
.entityportrait img{width:100%;height:100%;object-fit:cover;display:block;z-index:1}
.entityhero>div:last-child{min-width:0;max-width:100%}.entityhero h2{font-size:var(--fs-3xl);font-weight:400;
- line-height:1.2;letter-spacing:0;margin:0 0 9px;overflow-wrap:anywhere}.entityhero .alias{color:var(--muted);
+ line-height:1.2;letter-spacing:0;margin:0 0 9px;overflow-wrap:anywhere}.entityhero .alias b{color:var(--ink);font-weight:inherit}
+.entityhero .alias{color:var(--muted);
font-size:var(--fs-md);line-height:1.45;margin-bottom:14px;overflow-wrap:anywhere}
.entitysummary{font-size:var(--fs-lg);line-height:1.6;max-width:820px;color:var(--ink-2)}
.entitylinks{display:flex;flex-wrap:wrap;gap:8px;margin-top:17px;max-width:100%}
@@ -386,8 +387,10 @@ body.entity-open .index{overflow-x:visible}
.entitylinkicon.brand svg{width:15px;height:15px;fill:currentColor;stroke:none}
/* 纯图标的社媒链接:收成圆形,没有文字就不给文字留位置。 */
.entitylinks a.iconlink{padding:4px;gap:0;border-radius:50%}
+/* 只有网址的官网链接:没有图标,左内边距不必再给图标留位置。
+ 默认那条 `4px 12px 4px 4px` 是按「圆图标 + 文字」调的,直接套用会让文字贴左。 */
+.entitylinks a.urllink{padding:4px 14px;letter-spacing:.02em}
.entitylinklabel{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
-.entityterms{margin-top:13px;color:var(--muted);font-size:var(--fs-xs)}.entityterms code{color:var(--ink-2);margin-right:8px}
.entitymeta{display:grid;gap:22px;margin:0 0 6px;min-width:0}.entitymeta section{min-width:0}.entitysection h3{font-size:var(--fs-sm);letter-spacing:.08em;color:var(--muted);margin:0 0 12px}
.entitytagbar{position:sticky;top:var(--topH);z-index:61;display:flex;align-items:center;
height:var(--filterH);margin:0 -16px;padding:9px 16px;background:transparent;
@@ -408,7 +411,7 @@ body.entity-open .index{overflow-x:visible}
padding:0;cursor:pointer;text-align:center}.relatedperson .ring{display:grid;place-items:center;width:64px;height:64px;
margin:0 auto 6px;border-radius:50%;overflow:hidden;background:var(--overlay-5);color:var(--muted);position:relative}
.relatedperson img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.relatedperson .nm{display:block;
- overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:var(--fs-xs)}.relatedperson small{color:var(--muted);font-size:var(--fs-xs)}
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:var(--fs-xs)}
.relatedperson:hover .ring{box-shadow:0 0 0 1px var(--border-15)}
.entitysection{min-width:0;max-width:100%}.entitysection h3{font-size:var(--fs-sm);letter-spacing:.08em;color:var(--muted);margin:0 0 12px}
.entitycollectionhead{position:sticky;top:var(--topH);z-index:60;display:flex;align-items:center;gap:10px;
@@ -1746,7 +1749,6 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
.entityhero .alias{margin-bottom:10px}
.entitysummary{margin-inline:auto}
.entityhero .entitylinks{justify-content:center;margin-top:13px}
- .entityhero .entityterms{text-align:center}
.stats h2{font-size:var(--fs-xl)}.stats .insightcopy h2{font-size:var(--fs-3xl)}
/* 窄屏下标题也得一起缩。`/follow` 渲染在 `#stats` 里,上面那条 `.stats h2`
会只把它打到 23px,而 `#manageTitle` 在 `#stats` 外面,手机上又变成两种大小。 */
@@ -2250,3 +2252,24 @@ details.fcred{display:block}
/* 资源标识统一由 MiddleTruncate 计算可见文本。星号让本规则与「类 + 元素」的末尾省略
选择器同权重,并凭源码顺序覆盖,避免两套省略同时生效。 */
*[data-middle-truncate]{min-width:0;overflow:hidden;white-space:nowrap;text-overflow:clip}
+/* 链接管理沿用资源同步那套盒子,只加这里独有的两块:概览格和结果表。
+ 表格必须自己横向滚动——地址列很长,让它撑破 body 会把整页拖成横向可滚。 */
+.linksummary{margin-top:18px}.linksummary .resourcecache{border:1px solid var(--line-soft);border-radius:10px;border-top:1px solid var(--line-soft)}
+.linksummary .resourcecache b{font-size:var(--fs-lg)}
+.linkgroup{padding:16px;border-top:1px solid var(--line-soft)}.linkgroup:first-child{border-top:0}
+.linkgroup h4{margin:0 0 4px;font-size:var(--fs-md);font-weight:600}
+.linkgroup h4 b{margin-left:6px;color:var(--muted);font-weight:inherit;font-variant-numeric:tabular-nums}
+.linkgroup>p{margin:0 0 12px;color:var(--muted);font-size:var(--fs-xs);line-height:1.5}
+.linktablewrap{overflow-x:auto;scrollbar-width:thin}
+.linktable{width:100%;border-collapse:collapse;font-size:var(--fs-xs);white-space:nowrap}
+.linktable th{padding:6px 10px;border-bottom:1px solid var(--line-soft);color:var(--muted);font-weight:600;text-align:left}
+.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}
+/* 地址用中间截断而不是尾部省略:这张表要回答「哪一条坏了」,而
+ `/official/talent/X` 与 `/talent/X` 的差别就在尾部,切掉尾部等于切掉答案。 */
+.linktable .linkurl{max-width:360px;overflow:hidden}
+/* 只需要 block:overflow 与 nowrap 由全局的 `*[data-middle-truncate]` 管,
+ 但那条规则量不出行内元素的可用宽度。 */
+.linktable .linkurl a{display:block;color:var(--muted);text-decoration:none}
+.linktable .linkurl a:hover{color:var(--ink)}
diff --git a/web/app.js b/web/app.js
index 6af216973..5051ec9b9 100644
--- a/web/app.js
+++ b/web/app.js
@@ -1,4 +1,4 @@
-import {$, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, SITE_FAVICONS, STATE_LABELS, STATE_ROUTES, api, brandIcon, entityPath, esc, faviconFallbackUrl, faviconUrl, fmtClock, fmtDur, fmtSize, foldName, icon, isCatalogPath, pageTitle, realDuration} from './js/core.js';
+import {$, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, SITE_FAVICONS, STATE_LABELS, STATE_ROUTES, api, brandIcon, entityPath, esc, faviconFallbackUrl, faviconUrl, linkHost, linkMarkUrl, fmtClock, fmtDur, fmtSize, foldName, icon, isCatalogPath, pageTitle, realDuration} from './js/core.js';
import { initMiddleTruncate } from './js/middle-truncate.js';
import {
emptyStateHtml, loadingDotsHtml, mediaViewButtonsHtml, noteHtml, progressHtml, scrollerHtml,
@@ -1786,6 +1786,7 @@ async function openStats(push=true,focusResource=false){
<div id="stats-panel-recent" role="tabpanel" data-stats-panel="recent" hidden>${recentTable}</div>
<div id="stats-panel-sources" role="tabpanel" data-stats-panel="sources" hidden>${sourceTable}</div></div>
</section>
+ ${linkManagerMarkup()}
${resourceSyncMarkup()}
</div>`;
const statsRoot=$('#stats');
@@ -1801,6 +1802,7 @@ async function openStats(push=true,focusResource=false){
});
$('#stats').querySelectorAll('[data-k]').forEach(b=>b.onclick=()=>{
closeStats(); toggleTag(b.dataset.k)});
+ await wireLinkManager();
await wireResourceSync();
if(focusResource)$('#resource-sync')?.scrollIntoView({block:'start'});
else window.scrollTo({top:0,behavior:'smooth'});
@@ -1815,6 +1817,78 @@ function showHomeSurfaces(){
}
function closeStats(push=true){if(push)route('/');showHomeSurfaces();load(true)}
+/* 外链是别人服务器上的东西,会在我们不知情的时候烂掉——实测 719 条里 152 条打不开,
+ 而它们在资料页上和好链接长得一模一样,只有点下去才知道。所以检查要能随时重跑,
+ 不是一次性脚本。放在资源同步上面:两块都是「把库里的记录和外部现实对齐」。 */
+function linkManagerMarkup(){
+ return `<section class="resourcesync" id="link-manager" aria-labelledby="linkManagerTitle">
+ <h2 id="linkManagerTitle">链接管理</h2>
+ <div class="resourcesyncbox"><div class="resourcesyncbody"><h3>外链与实体</h3>
+ <p>资料页上的官网、事务所与社媒链接。逐条访问一遍,找出已经打不开的。</p>
+ <div id="linkSummary" class="linksummary"></div></div>
+ <div class="resourcesyncfooter"><p>检查只联网、不改账本;七百多条约需几分钟。</p>
+ <button class="resourceaction" type="button" id="linkCheck">${icon('refresh-cw')}<span>检查死链</span></button></div></div>
+ <div id="linkCheckResult" aria-live="polite"></div></section>`;
+}
+async function wireLinkManager(){
+ const button=$('#linkCheck'),result=$('#linkCheckResult'),summary=$('#linkSummary');
+ if(!button||!result)return;
+ const active=()=>location.pathname==='/stats'&&!$('#stats').hidden&&document.body.contains(result);
+ const KINDS={official:'官网 · 事务所',social:'社媒',catalog:'资料库',source_reference:'来源记录'};
+ try{
+ const info=await api('/api/links');
+ summary.innerHTML=`<div class="resourcecache"><div><span>链接</span><b>${info.total.toLocaleString()}</b><small>分布在 ${info.entities.toLocaleString()} 个实体上</small></div>
+ <div><span>按类型</span><b>${Object.entries(info.by_kind||{}).map(([k,n])=>`${KINDS[k]||k} ${n}`).join(' · ')||'—'}</b>
+ <small>最多的站点:${(info.top_hosts||[]).slice(0,3).map(([h,n])=>`${esc(h)} ${n}`).join(' · ')||'—'}</small></div></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>
+ <td>${esc(item.label||'')}</td><td class="linknote">${esc(item.note)}</td>
+ <td class="linkurl"><a href="${esc(item.url)}" target="_blank" rel="noreferrer" data-middle-truncate>${esc(item.url)}</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 render=payload=>{
+ const running=payload.status==='running';
+ const done=payload.status==='complete';
+ button.innerHTML=`${icon('refresh-cw')}<span>${running?'检查中':done?'重新检查':'检查死链'}</span>`;
+ 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?`<p class="resourcescanning">已检查 ${payload.checked.toLocaleString()} / ${(payload.total||0).toLocaleString()} 条…</p>`:'';
+ /* gone 和 unclear 必须分开摆:`linktr.ee` 回 403 是挡爬虫、`x.com` 回 500 是临时错误,
+ 链接本身好好的。混成一张表会让人顺手把好链接一起删掉。 */
+ const gone=table('已失效',payload.gone||[],'上游明确回 404/410,页面确实没了。');
+ const unclear=table('取不到',payload.unclear||[],'一次访问没成功,但不等于没了:有的站挡爬虫,有的是临时错误。不会被删除,下次检查会重试。');
+ const apply=(done&&(payload.gone||[]).length)?`<div class="resourceapplyrow"><p>删除前会逐条重验一次;此操作不可撤销。</p>
+ <button class="resourceaction resourcedanger" type="button" id="linkPrune">删除 ${payload.gone.length} 条失效链接</button></div>`:'';
+ const clean=(done&&!(payload.gone||[]).length&&!(payload.unclear||[]).length)?'<p class="resourcesyncok">全部链接都能打开。</p>':'';
+ result.innerHTML=`<div class="resourcepanel">${progress}${gone}${unclear}${apply}${clean}</div>`;
+ $('#linkPrune')?.addEventListener('click',async event=>{
+ const control=event.currentTarget;
+ if(!confirm(`删除 ${payload.gone.length} 条已失效链接?删除前会逐条重验,但删除本身不可撤销。`))return;
+ setActionBusy(control);
+ control.innerHTML=`${spinnerHtml('正在重验')}<span>正在重验并删除…</span>`;
+ try{
+ const out=await api('/api/links/prune',{method:'POST',body:JSON.stringify({confirm:true,check_id:payload.check_id})});
+ result.innerHTML=noteHtml(`已删除 ${out.removed} 条;重验时又能打开的 ${out.recovered} 条已保留。`,{label:'完成'});
+ await wireLinkManager();
+ }catch(error){result.insertAdjacentHTML('beforeend',noteHtml(error.message,{variant:'error',label:'删除失败'}))}
+ });
+ };
+
+ const poll=async()=>{
+ if(!active())return;
+ const payload=await api('/api/links/check',{method:'POST',body:JSON.stringify({status_only:true})});
+ render(payload);
+ if(payload.status==='running')setTimeout(poll,2000);
+ };
+ button.onclick=async()=>{
+ render(await api('/api/links/check',{method:'POST',body:JSON.stringify({restart:true})}));
+ setTimeout(poll,1200);
+ };
+ await poll();
+}
function resourceSyncMarkup(){
return `<section class="resourcesync" id="resource-sync" aria-labelledby="resourceSyncTitle">
<h2 id="resourceSyncTitle">资源同步</h2>
@@ -4560,22 +4634,28 @@ async function openEntity(kind,name,push=true,requestedTag){
const links=(d.links||[]).map(x=>{
if(!(x.clickable&&/^https?:\/\//i.test(x.url||'')))
return `<span class="private" title="私人馆藏来源记录,不直接打开下载页"><span class="entitylinkicon">${icon('globe')}</span><span class="entitylinklabel">来源 · ${esc(x.label||x.hostname||'已记录')}</span></span>`;
- const brand=brandIcon(x.url);
- const mark=brand
- ? `<span class="entitylinkicon brand">${icon(brand)}</span>`
- : `<span class="entitylinkicon">${icon('globe')}<img class="entityfavicon" src="${esc(faviconUrl(x.url))}" data-studio="${kind==='studio'?esc(d.canonical_name):''}" alt="" loading="lazy" referrerpolicy="no-referrer"></span>`;
- // 纯图标的链接自己不带可读文字,得把标签留给辅助技术。
- const body=x.link_kind==='social'
- ? `<span class="sr-only">${esc(x.label)}</span>`
- : `<span class="entitylinklabel">${esc(x.label)}</span>`;
- return `<a class="${x.link_kind==='social'?'iconlink':''}" href="${esc(x.url)}" target="_blank" rel="noreferrer" title="${esc(x.label)}">${mark}${body}</a>`;
+ /* 社媒的 handle 是网址的一部分,写出来只是把 URL 抄一遍——图标本身已经说明了去哪。 */
+ if(x.link_kind==='social'){
+ const brand=brandIcon(x.url);
+ const mark=brand?`<span class="entitylinkicon brand">${icon(brand)}</span>`
+ :`<span class="entitylinkicon">${icon('globe')}<img class="entityfavicon" src="${esc(linkMarkUrl(x))}" alt="" loading="lazy" referrerpolicy="no-referrer"></span>`;
+ // 纯图标的链接自己不带可读文字,得把标签留给辅助技术。
+ return `<a class="iconlink" href="${esc(x.url)}" target="_blank" rel="noreferrer" title="${esc(x.label)}">${mark}<span class="sr-only">${esc(x.label)}</span></a>`;
+ }
+ /* 厂牌页的官网链接不放图标,直接给网址。
+
+ 这一页的头像就是厂牌 logo,旁边再放一枚同品牌的小图标只是把同一个东西说两遍;
+ 而域名本身就是名字,比图标说得更清楚。女优页不一样:那里的头像是人,事务所
+ 图标不构成重复,标签也是事务所名而非域名。 */
+ if(kind==='studio')
+ return `<a class="urllink" href="${esc(x.url)}" target="_blank" rel="noreferrer" title="${esc(x.label)}"><span class="entitylinklabel">${esc(linkHost(x.url)||x.label)}</span></a>`;
+ return `<a href="${esc(x.url)}" target="_blank" rel="noreferrer" title="${esc(x.label)}"><span class="entitylinkicon">${icon('globe')}<img class="entityfavicon" src="${esc(linkMarkUrl(x))}" alt="" loading="lazy" referrerpolicy="no-referrer"></span><span class="entitylinklabel">${esc(x.label)}</span></a>`;
}).join('');
- const terms=(d.search_terms||[]).map(x=>`<code>${esc(x.term)}</code>`).join('');
const tags=(d.tags||[]).map(x=>`<button class="pill" data-entity-tag="${esc(x.k)}" aria-pressed="${entityTag===x.k}">${esc(tagLabel(x.k))}<small>${x.n.toLocaleString()}</small></button>`).join('');
const related=(d.related_performers||[]).map(x=>`<button class="relatedperson" data-related-performer="${esc(x.k)}">
<span class="ring"><span>${esc(x.k.slice(0,1))}</span><img src="/entity-image?kind=performer&id=${x.id}" alt="" loading="lazy"
onerror="${x.rep?`if(!this.dataset.f){this.dataset.f='1';this.src='/avatar?id=${x.rep}'}else{this.remove()}`:`this.remove()`}"></span>
- <span class="nm">${esc(x.k)}</span><small>${x.n.toLocaleString()} 部</small></button>`).join('');
+ <span class="nm">${esc(x.k)}</span></button>`).join('');
const photoCount=photos&&!photos.error?(photos.total||0):0;
const mediaSelected=entityMediaView.media==='photos';
const mediaToggle=photoCount?mediaViewButtonsHtml({active:mediaSelected?'photos':'videos',
@@ -4584,10 +4664,9 @@ async function openEntity(kind,name,push=true,requestedTag){
$('#index').dataset.entityKind=kind;$('#index').dataset.entityName=name;
$('#index').innerHTML=`<div class="entityhero"><div class="entityportrait ${kind==='performer'||kind==='creator'?'':'square'}">${image}<span>${esc(name.slice(0,1))}</span></div>
<div><h2>${esc(d.canonical_name)}</h2>
- <div class="alias">${(d.display_aliases||[]).length?'别名 · '+d.display_aliases.map(esc).join(' / '):'暂无别名'} · ${d.asset_count.toLocaleString()} 个视频</div>
+ <div class="alias">${(d.display_aliases||[]).length?`${d.display_aliases.map(esc).join(' / ')} · `:''}<b>${d.asset_count.toLocaleString()}</b> 个视频</div>
${d.summary?`<div class="entitysummary">${esc(d.summary)}</div>`:''}
- ${links?`<div class="entitylinks">${links}</div>`:''}
- ${terms?`<div class="entityterms">馆藏检索词 · ${terms}</div>`:''}</div></div>
+ ${links?`<div class="entitylinks">${links}</div>`:''}</div></div>
${related?`<div class="entitymeta"><section aria-label="同台艺人"><div class="relatedpeople">${related}</div></section></div>`:''}
${(tags||mediaToggle)?`<section class="entitytagbar" aria-label="媒体与标签"><div class="entitytags">${mediaToggle}${tags}</div></section>`:''}
<div class="entitysection"></div>`;
diff --git a/web/js/core.js b/web/js/core.js
index 386f160dd..8ba6b339e 100644
--- a/web/js/core.js
+++ b/web/js/core.js
@@ -42,7 +42,17 @@ const SITE_FAVICONS={
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`;
-/* 有品牌标记的主机不取 favicon。
+/* 域名当名字:厂牌页的官网链接直接显示它,比一枚小图标说得清楚。大写跟着 beeg 的
+ 资料页写法,`www.` 去掉——它不携带信息,只占宽度。 */
+const linkHost=url=>{try{return new URL(url).hostname.replace(/^www\./,'').toUpperCase()}catch{return ''}};
+/* 服务端处理过的链接图标:单色字形的 favicon 会被做成「品牌色底 + 白色主体」,
+ 做不了就把原图按 32 px 转出来。放服务端有三个理由:它要读别人站点的图、要缓存,
+ 而且这样浏览器不再直接向对方站点发请求(也就不泄露正在看谁的资料页)。
+
+ 传的是链接 id 而不是地址。跟 `/follow-stream` 同一条规矩:服务端只取账本里已有的
+ 地址,绝不去取前端递过来的任意 URL——那等于开一个任意地址抓取的口子。 */
+const linkMarkUrl=link=>`/link-mark?id=${encodeURIComponent(link.link_id ?? '')}`;
+/* 有品牌标记的主机连 favicon 都不取。
favicon 是别人服务器上的一张小位图:X 直接挡掉爬取(资料页那个空白白圆就是它),
取到的也多是 16×16,放进 32 px 的圆里必然糊。内联 SVG 没有这两个问题,还省一次
@@ -88,6 +98,8 @@ export {
SITE_FAVICONS,
brandIcon,
faviconUrl,
+ linkHost,
+ linkMarkUrl,
faviconFallbackUrl,
foldName,
fmtDur,