Peach: Local-first video metadata scraper and media manager.
fix(links): 停放页判为已失效,死链清理可限定到一个站
longmeidao83033ba7b064
diff --git a/scripts/install_entity_links.py b/scripts/install_entity_links.pyindex a2be3b262..0f4778ef8 100644--- a/scripts/install_entity_links.py+++ b/scripts/install_entity_links.py@@ -27,6 +27,11 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from peach.review_csv import read_rows # noqa: E402from peach.social_links import canonical_url # noqa: E402+from peach.studio_sites import ( # noqa: E402+ PARKED_NOTE,+ parked_after_certificate_error,+ response_parked_reason,+)from peach.scripting import ( # noqa: E402BACKUP_REQUIRED,USER_AGENT,@@ -145,20 +150,30 @@ def resolves(url: str, timeout: float = 12.0,(`[SSL: UNEXPECTED_EOF_WHILE_READING]`),一次失败就记「打不开」是把抖动写成结论:eltra.jp 2026-09-05 连着两趟这样被判死,而每次重试一下就 200。404 重试三次还是 404。"""+ def get(target: str) -> httpx.Response:+ with httpx.Client(follow_redirects=True, timeout=timeout,+ limits=httpx.Limits(max_connections=4,+ max_keepalive_connections=0)) as client:+ return client.get(target, headers={"User-Agent": USER_AGENT})+note = "取不到"for attempt in range(tries):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})+ response = get(url)except Exception as exc:+ parked = parked_after_certificate_error(url, exc, get)+ if parked:+ return False, parkednote = f"取不到:{type(exc).__name__}"if attempt + 1 < tries:time.sleep(pause)continueif response.status_code != 200:return False, f"HTTP {response.status_code}"+ # 停放页也回 200,判据见 `studio_sites.PARKING_HOSTS`。+ parked = response_parked_reason(response)+ if parked:+ return False, parkedreturn True, "可打开"return False, note@@ -175,7 +190,11 @@ def is_gone(note: str) -> bool:按「非 200 就删」会连这 26 条一起删掉,其中大部分链接本身是好的。5xx、403 和超时要留着下次复查,不是删除的理由——这和取证失败时写 `未取得` 而不是写结论是同一条。++ 停放页是另一种确证:域名已经换了主人,页面打得开,内容却不再是这个人或这家公司。"""+ if note.startswith(PARKED_NOTE):+ return Truematch = re.match(r"HTTP (\d+)$", note)return bool(match) and int(match.group(1)) in GONE_STATUSES@@ -203,8 +222,16 @@ def check_links(planned: list[dict], interval: float = 0.4, probe=None) -> None:time.sleep(interval)-def dead_links(connection: sqlite3.Connection, interval: float = 0.4, probe=None) -> list[dict]:- """已经在库里、但现在打不开的链接。+def on_host(url: str, host: str) -> bool:+ """`url` 的主机是 `host` 本身或它的子域。"""+ name = (urlsplit(url).hostname or "").lower()+ host = host.lower()+ return name == host or name.endswith("." + host)+++def dead_links(connection: sqlite3.Connection, interval: float = 0.4, probe=None,+ host: str = "") -> list[dict]:+ """已经在库里、但现在打不开的链接;给了 `host` 就只查这个站和它的子域。可达性门槛只挡住新写入;库里那 703 条是在门槛存在之前进去的,得单独清一遍。链接还会随时间烂掉——事务所改版、艺人解约、博客注销——所以这条路要留着复用,@@ -215,6 +242,8 @@ def dead_links(connection: sqlite3.Connection, interval: float = 0.4, probe=Nonefor link_id, entity, kind, label, url in connection.execute("SELECT l.id, 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"):+ if host and not on_host(url, host):+ continueok, note = probe(url)if not ok:out.append({"id": link_id, "entity": entity, "link_kind": kind,@@ -265,6 +294,8 @@ def build_parser() -> argparse.ArgumentParser:help=f"复核表,列:{','.join(FIELDS)}")parser.add_argument("--prune-dead", action="store_true",help="改为清理库里已经打不开的链接,不读 --input")+ parser.add_argument("--host", default="",+ help="配合 --prune-dead:只查这个站和它的子域,例如一家已注销的事务所")parser.add_argument("--no-check", action="store_true",help="跳过「地址能不能打开」的检查。只在离线复核时用——""首批 703 条就是没验直接装的,事后发现 37%% 是死链")@@ -274,7 +305,7 @@ def build_parser() -> argparse.ArgumentParser:def prune(connection: sqlite3.Connection, args) -> int:"""列出并(在 --apply 时)删除库里打不开的链接。"""before = connection.execute("SELECT count(*) FROM entity_link").fetchone()[0]- unreachable = dead_links(connection)+ unreachable = dead_links(connection, host=args.host)gone = [item for item in unreachable if is_gone(item["note"])]unclear = [item for item in unreachable if not is_gone(item["note"])]for item in gone:diff --git a/src/peach/studio_sites.py b/src/peach/studio_sites.pyindex a63ff61fd..af0006823 100644--- a/src/peach/studio_sites.py+++ b/src/peach/studio_sites.py@@ -51,6 +51,15 @@ PARKED = re.compile(r"domain (?:is )?for sale|buy this domain|parked (?:free )?at|このドメイン(?:は|を)"r"|ドメイン(?:の)?販売|sedo\.com|afternic|godaddy\.com/domain|hugedomains",re.I)+# 停放平台自己的主机。停放页不一定自述在出售:`crusegroup.net` 在公司注销后由 ParkLogic+# 停放,2026-09-26 实测 200、5.5 KB、标题 `Redirecting...`,正文只有一段把访客送去+# `router.parklogic.com` 的脚本,上面两条自述词一个都对不上。认得出它的只有平台主机名,+# 出现在最终地址、响应头或正文里都算。后三个是同样形态的停放平台。+PARKING_HOSTS = re.compile(+ r"(?<![\w-])((?:[\w-]+\.)*(?:parklogic\.com|sedoparking\.com|bodis\.com"+ r"|parkingcrew\.net))(?![\w.-]*\w)", re.I)+#: 停放页判词的开头。链接体检按它把停放页归进「确证没了」。+PARKED_NOTE = "停放页"# 空壳页也会 200。真站首页(含年龄门)实测都在 10 KB 以上,取一半做下限。MIN_BODY = 5000# 「标题里有厂牌名」证明不了这是**这个**厂牌的站——同名的无关公司照样通过。实测四例:@@ -199,6 +208,49 @@ def page_title(body: bytes) -> str:return re.sub(r"\s+", " ", text).strip()[:120]+def parked_reason(title: str, text: str, headers: str = "", final_url: str = "") -> str:+ """这一页是停放页或域名出售页的依据,以 `PARKED_NOTE` 开头;不是就返回空串。++ 厂牌官网发现与实体链接体检共用这一份:两边要回答的都是「这个 200 是不是真站」。+ """+ if PARKED_TITLE.search(title):+ return f"{PARKED_NOTE}(标题自述在出售域名:{title[:44]})"+ # 不截窗口。实测停放页把「domain for sale」写在第 81683 字节,任何固定窗口都会漏;+ # 整篇扫一遍在这个量级上不值得省。+ if PARKED.search(text):+ return f"{PARKED_NOTE}或域名出售页"+ for where, blob in (("最终地址", final_url), ("响应头", headers), ("正文", text)):+ match = PARKING_HOSTS.search(blob)+ if match:+ return f"{PARKED_NOTE}({where}指向 {match.group(1).lower()})"+ return ""+++def response_parked_reason(response: "httpx.Response") -> str:+ """一个 `httpx` 响应是不是停放页,判据同 `parked_reason`。"""+ body = response.content or b""+ headers = "\n".join(f"{key}: {value}" for key, value in response.headers.items())+ return parked_reason(page_title(body), decode(body), headers, str(response.url))+++def parked_after_certificate_error(url: str, error: Exception, fetch) -> str:+ """HTTPS 证书校验失败时改走 http 再取一次,看这个域名是不是已被停放。++ 停放平台接手域名后没有原主的证书:`crusegroup.net` 2026-09-26 实测 HTTPS 报+ `CERTIFICATE_VERIFY_FAILED`,同一地址走 http 就是 ParkLogic 的停放页。证书校验失败+ 本身不算证据,证书链不全的真站也这样报;只有 http 那一页是停放页才算。+ `fetch(url)` 返回 `httpx.Response`。+ """+ if urlsplit(url).scheme != "https" or "CERTIFICATE_VERIFY_FAILED" not in str(error):+ return ""+ try:+ response = fetch("http://" + url[len("https://"):])+ except Exception:+ return ""+ reason = response_parked_reason(response) if response.status_code == 200 else ""+ return f"{reason};HTTPS 证书无效" if reason else ""++def site_verdict(name: str, status: int, body: bytes, title: str,url: str = "", derived_hosts: frozenset[str] = frozenset(),confirmed: str = "", aliases: Sequence[str] = ()) -> tuple[str, str]:@@ -226,10 +278,9 @@ def site_verdict(name: str, status: int, body: bytes, title: str,if BROKEN_TITLE.search(title):return "未取得", f"站点自述不可用({title[:44]})"text = decode(body)- # 不再截窗口。实测停放页把「domain for sale」写在第 81683 字节,任何固定窗口都会漏;- # 整篇扫一遍在这个量级上不值得省。- if PARKED.search(text):- return "未取得", "停放页或域名出售页"+ reason = parked_reason("", text, final_url=url)+ if reason:+ return "未取得", reason# 标题不比域名多说任何东西,就等于没有自述身份。实测 `prestige.com` 返回 200、# 不是停放页、标题正好是 `prestige.com`——它因此通过了「标题含厂牌名」,被判成# Prestige 官网,而真站是 `prestige-av.com`,那是另一家公司。停放页规则拦不住它:diff --git a/src/peach/web_links.py b/src/peach/web_links.pyindex 81545ae81..56e616b48 100644--- a/src/peach/web_links.py+++ b/src/peach/web_links.py@@ -20,6 +20,7 @@ from urllib.parse import urlsplitimport httpx+from . import studio_sitesfrom .jobs import BackgroundJobfrom .user_agent import USER_AGENT@@ -42,18 +43,24 @@ class LinkContract(Protocol):def _probe(url: str, timeout: float = CHECK_TIMEOUT) -> tuple[int, str]:- """(status, 说明)。status 为 0 表示连都没连上。+ """(status, 说明)。status 为 0 表示连都没连上;停放页的说明里写停放依据。每个请求新建 client 并立刻关掉:这批地址分布在上百个互不相同的主机上,其中不少连不上,而失败的连接会在共享池里漏掉槽位,几十个请求之后一切都变成 PoolTimeout。"""- try:+ def get(target: str) -> httpx.Response: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})+ return client.get(target, headers={"User-Agent": USER_AGENT})++ try:+ response = get(url)except Exception as error:- return 0, type(error).__name__+ return 0, (studio_sites.parked_after_certificate_error(url, error, get)+ or type(error).__name__)+ if response.status_code == 200:+ return 200, studio_sites.response_parked_reason(response)return response.status_code, ""@@ -63,7 +70,12 @@ def link_verdict(status: int, note: str) -> str:取不到不等于没了。实测反例:`linktr.ee` 403(Linktree 挡爬虫,浏览器里能开)、`facebook.com` 400、`x.com` 500(临时错误,账号还在)、连接失败与超时。把它们并进 gone,删除时就会连好链接一起删。++ 停放页反过来:200 也是没了。域名过期后被停放平台接走,页面照样打得开,内容却已+ 不是这个人或这家公司的。"""+ if note.startswith(studio_sites.PARKED_NOTE):+ return "gone"if status == 200:return "ok"if status in GONE_STATUSES:@@ -71,6 +83,13 @@ def link_verdict(status: int, note: str) -> str:return "unclear"+def _note(status: int, note: str) -> str:+ """面板上那一格说明。停放页只写状态码就看不出为什么判了没了。"""+ if status == 200 or note.startswith(studio_sites.PARKED_NOTE):+ return note+ return f"HTTP {status}" if status else f"取不到:{note}"++def w_links(contract: LinkContract, args=None):"""库里链接的现状。纯读库,随页面一起加载,不联网。"""with contract.read_connection() as connection:@@ -145,7 +164,7 @@ def _run_link_check(contract: LinkContract, check_id: str,"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}",+ "note": _note(status, note),})time.sleep(CHECK_INTERVAL)job.update(check_id, status="complete", completed_at=time.time())diff --git a/tests/test_entity_link_install.py b/tests/test_entity_link_install.pyindex 665199205..1b0a75852 100644--- a/tests/test_entity_link_install.py+++ b/tests/test_entity_link_install.py@@ -7,8 +7,16 @@ import tempfileimport unittestfrom pathlib import Path+import httpx+REPO = Path(__file__).resolve().parents[1]+#: 停放页的最小形态,照 `crusegroup.net` 2026-09-26 实测的结构手写:200、标题+#: `Redirecting...`、正文一段把访客送去停放平台路由的脚本,响应头里带着平台主机名。+PARKED_PAGE = (b'<!doctype html><html><head><title>Redirecting...</title></head><body>'+ b'<script>fetch("https://router.parklogic.com/model/221")</script></body></html>')+PARKED_HEADERS = {"permissions-policy": 'ch-ua=(self "https://*.parklogic.com")'}+def load_module(name: str = "install_entity_links"):sys.path.insert(0, str(REPO / "src"))@@ -258,7 +266,7 @@ class ResolvesTests(unittest.TestCase):"""可达性探测:抖动要重试,状态码是一次成局。"""class Client:- """`httpx.Client` 的替身,按剧本逐次抛错或返回状态码。"""+ """`httpx.Client` 的替身,按剧本逐次抛错、返回状态码或返回整个响应。"""def __init__(self, script):self.script = script@@ -276,7 +284,9 @@ class ResolvesTests(unittest.TestCase):step = self.script.pop(0)if isinstance(step, Exception):raise step- return type("Response", (), {"status_code": step})()+ status, body, response_headers = step if isinstance(step, tuple) else (step, b"", {})+ return httpx.Response(status, content=body, headers=response_headers,+ request=httpx.Request("GET", url))def setUp(self):# `time` 和 `httpx` 是进程共享的真模块,替身必须还回去:这一组用例先跑完,@@ -310,6 +320,56 @@ class ResolvesTests(unittest.TestCase):self.assertIn("ConnectionError", note)self.assertFalse(self.module.is_gone(note), "取不到不等于确证没了")+ def test_a_parked_domain_is_gone_even_though_it_answers_200(self):+ """事务所注销、域名被停放平台接走之后,页面照样 200,内容已不是这家公司。"""+ self.use((200, PARKED_PAGE, PARKED_HEADERS))+ ok, note = self.module.resolves("https://www.crusegroup.net/model/221")+ self.assertFalse(ok)+ self.assertIn("parklogic.com", note)+ self.assertTrue(self.module.is_gone(note))+ self.assertEqual(self.slept, [], "停放页是站点的回答,不是抖动,不必重试")++ def test_a_parked_domain_behind_an_invalid_certificate_is_gone(self):+ """停放平台没有原主的证书,HTTPS 当场失败;同一地址走 http 才看得见停放页。"""+ certificate = ConnectionError("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed")+ self.use(certificate, (200, PARKED_PAGE, PARKED_HEADERS))+ ok, note = self.module.resolves("https://crusegroup.net/model/316")+ self.assertFalse(ok)+ self.assertIn("证书", note)+ self.assertTrue(self.module.is_gone(note))++ def test_an_invalid_certificate_alone_is_not_proof(self):+ """证书链不全的真站也报同一个错;http 那一页不是停放页就只算取不到。"""+ certificate = ConnectionError("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed")+ self.use(*[certificate, (200, b"<title>T-POWERS</title>", {})] * 3)+ ok, note = self.module.resolves("https://www.t-powers.co.jp/")+ self.assertFalse(ok)+ self.assertFalse(self.module.is_gone(note))++ def test_an_ordinary_page_that_links_elsewhere_still_opens(self):+ self.use((200, b"<title>ARM</title><a href='https://x.com/arm_pro'>X</a>", {}))+ self.assertEqual(self.module.resolves("https://arm-p.com/models/"), (True, "可打开"))++ def test_pruning_can_be_limited_to_one_site(self):+ """清一家注销事务所的链接时,库里别的死链不跟着一起删。"""+ connection = sqlite3.connect(":memory:")+ connection.executescript(SCHEMA)+ connection.execute("INSERT INTO entity VALUES(1,'performer','山岸逢花')")+ connection.executemany(+ "INSERT INTO entity_link(entity_id,link_kind,label,url,created_at,updated_at) "+ "VALUES(1,'official',?,?,'2026-01-01','2026-01-01')",+ [("Cruse Group", "https://www.crusegroup.net/model/221"),+ ("Cruse Group", "https://crusegroup.net/"),+ ("别的事务所", "https://other.example/gone"),+ ("存档", "https://web.archive.org/web/2015/http://z-earth2.crusegroup.net/")])+ probed = []+ dead = self.module.dead_links(+ connection, host="crusegroup.net",+ probe=lambda url: probed.append(url) or (False, "HTTP 404"))+ self.assertEqual(probed, ["https://www.crusegroup.net/model/221",+ "https://crusegroup.net/"])+ self.assertEqual(len(dead), 2)+class NormalizeHostsTests(unittest.TestCase):"""twitter.com → x.com 的主机归一:改写要保真,撞上已有的新写法要删而不是炸。diff --git a/tests/test_studio_site_harvest.py b/tests/test_studio_site_harvest.pyindex 2179846a7..f577f6c65 100644--- a/tests/test_studio_site_harvest.py+++ b/tests/test_studio_site_harvest.py@@ -318,6 +318,15 @@ class VerdictTests(unittest.TestCase):"Attackers", 200, page(title), title, "https://attackers.net/")self.assertEqual(verdict, "ok")+ def test_a_page_that_only_hands_off_to_a_parking_platform_is_rejected(self):+ """停放页不一定自述在出售,只把访客交给停放平台的路由脚本。"""+ title = "Cruse Group"+ body = page(title) + b'<script>fetch("https://router.parklogic.com/")</script>'+ verdict, note = self.module.site_verdict(+ "Cruse Group", 200, body, title, "https://crusegroup.net/")+ self.assertEqual(verdict, "未取得")+ self.assertIn("parklogic.com", note)+def test_a_parked_title_is_caught_even_when_the_body_keyword_is_far_down(self):"""实测漏判:`kawaii.com - domain for sale`。diff --git a/tests/test_web_links.py b/tests/test_web_links.pyindex c7efdf7c4..1b0d6652d 100644--- a/tests/test_web_links.py+++ b/tests/test_web_links.py@@ -6,6 +6,8 @@ import unittestfrom contextlib import contextmanagerfrom pathlib import Path+import httpx+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from peach import web_links # noqa: E402@@ -68,6 +70,27 @@ class VerdictTests(unittest.TestCase):self.assertEqual(web_links.link_verdict(status, ""), "unclear", status)self.assertEqual(web_links.link_verdict(0, "ConnectError"), "unclear")+ def test_a_parked_domain_answering_200_is_gone(self):+ """事务所注销、域名被停放平台接走之后,页面照样 200,内容已不是这家公司。"""+ page = (b'<title>Redirecting...</title>'+ b'<script>fetch("https://router.parklogic.com/model/221")</script>')+ client = httpx.Client++ def mocked(**kwargs):+ return client(transport=httpx.MockTransport(+ lambda request: httpx.Response(200, content=page)), **kwargs)++ web_links.httpx.Client = mocked+ try:+ status, note = web_links._probe("https://www.crusegroup.net/model/221")+ finally:+ web_links.httpx.Client = client+ self.assertEqual(status, 200)+ self.assertIn("parklogic.com", note)+ self.assertEqual(web_links.link_verdict(status, note), "gone")+ self.assertIn("parklogic.com", web_links._note(status, note),+ "面板上要看得出为什么 200 也判了没了")+class SummaryTests(unittest.TestCase):def setUp(self):