Peach: Local-first video metadata scraper and media manager.
fix(http): 响应文本按站点声明的字符集解码
longmeidao572768c09124
diff --git a/src/peach/http.py b/src/peach/http.pyindex 3a79e5c4f..8226ab35f 100644--- a/src/peach/http.py+++ b/src/peach/http.py@@ -1,7 +1,8 @@-"""共享 HTTP transport:连接池、超时、有界读取与可注入测试边界。"""+"""共享 HTTP transport:连接池、超时、有界读取、字符集解码与可注入测试边界。"""from __future__ import annotationsfrom .user_agent import USER_AGENT+import refrom dataclasses import dataclassfrom typing import Mapping, Protocol@@ -38,6 +39,62 @@ class HttpTransport(Protocol):) -> HttpResponse: ...+#: 从响应开头扫多少字节找 `<meta>` 里的字符集声明。+#: 参考实现(NeoAVDC `src/main/net/httpClient.ts` 的 `bodyToText`)只扫 1 KB;这里取+#: 4 KiB,因为 seesaawiki 的声明落在 1 KB 之后——`metadata_seesaa` 此前自己扫前 3000+#: 字节才认得出 UTF-8 页,扫 1 KB 会把那些页全部按回落编码解。+META_SNIFF_BYTES = 4096++_CHARSET_IN_HEADER = re.compile(r"charset\s*=\s*[\"']?\s*([\w.:-]+)", re.IGNORECASE)+#: `<meta charset="euc-jp">` 与 `<meta http-equiv="Content-Type" content="...; charset=euc-jp">`+#: 两种写法都认。在字节上匹配,免得为了找编码先猜一次编码。+_CHARSET_IN_META = re.compile(rb"""<meta[^>]+charset\s*=\s*["']?\s*([\w.:-]+)""", re.IGNORECASE)+++def _declared_encodings(body: bytes, headers: Mapping[str, str] | None) -> list[str]:+ """站点自己声明的字符集,按可信度排序:响应头在前,页面内的 `<meta>` 在后。"""+ found: list[str] = []+ for key, value in (headers or {}).items():+ if key.lower() != "content-type":+ continue+ matched = _CHARSET_IN_HEADER.search(str(value))+ if matched:+ found.append(matched.group(1))+ matched = _CHARSET_IN_META.search(body[:META_SNIFF_BYTES])+ if matched:+ found.append(matched.group(1).decode("ascii", "ignore"))+ return [name for name in dict.fromkeys(found) if name]+++def body_text(body: bytes, headers: Mapping[str, str] | None = None, *,+ default: str = "utf-8") -> str:+ """按站点自己声明的字符集把响应体解成文本。++ 顺序和浏览器一致:先 `Content-Type` 的 charset,再响应开头的 `<meta>` 声明,+ 都没有才用 `default`。硬写 utf-8 的代价不是报错而是静默损坏——日站里 EUC-JP 与+ Shift_JIS 仍占相当比例,`errors="replace"` 会把整行标题变成 U+FFFD,而「标题里+ 没有这个厂牌名」这条判定会据此误杀掉真官网。++ `default` 留给已知编码的单站:seesaawiki 的页面不声明时就是 EUC-JP。声明的编码+ Python 不认(`x-sjis` 这类站内写法)或者用它解不动,就退到下一个候选;全都不成+ 才用 `default` 加 `errors="replace"` 兜底,宁可留几个替换字符也不抛异常。+ """+ for encoding in (*_declared_encodings(body, headers), default):+ try:+ return body.decode(encoding)+ except (UnicodeDecodeError, LookupError):+ continue+ try:+ return body.decode(default, errors="replace")+ except LookupError:+ return body.decode("utf-8", errors="replace")+++def response_text(response: "HttpResponse", *, default: str = "utf-8") -> str:+ """`body_text` 的响应版:响应头已经在手里,不必让每个调用方自己拆出来。"""+ return body_text(response.body, response.headers, default=default)++#: 跟这些状态的 Location。与 httpx 自己的判据一致。_REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})#: 跨源跳转时丢掉的请求头:凭据只属于发出它的那个站。diff --git a/src/peach/metadata_seesaa.py b/src/peach/metadata_seesaa.pyindex 488551333..04a0a6517 100644--- a/src/peach/metadata_seesaa.py+++ b/src/peach/metadata_seesaa.py@@ -11,7 +11,7 @@ from bs4 import BeautifulSoupimport httpxfrom .catalog_rules import normalise_code_key, same_release_code-from .http import HttpRequest, HttpxTransport+from .http import HttpRequest, HttpxTransport, body_textfrom .metadata import MetadataProviderError, validate_provider_codefrom .scripting import HostLimiter@@ -32,9 +32,9 @@ def page_url(url: str) -> str:def parse_page(body: bytes, url: str) -> list[dict]:"""只从带列名的作品表格取字段;推荐、评论与演员履历不作整片出演证据。"""url = page_url(url)- text = body.decode('utf-8' if b'charset="utf-8"' in body[:3000].lower()- else 'euc_jp', errors='replace')- soup = BeautifulSoup(text, 'html.parser')+ # 这个 Wiki 两种编码的页面并存,声明写在页面自己的 `<meta>` 里;不声明的按+ # EUC-JP 解(站点的历史编码)。判据走共享的 `body_text`,不在这里另写一份。+ soup = BeautifulSoup(body_text(body, default='euc_jp'), 'html.parser')area = soup.select_one('#page-body .user-area')if area is None:return []@@ -182,7 +182,7 @@ class SeesaaProvider:if match:return matchsearch_url = ROOT + 'search?' + urlencode({'keywords': code})- soup = BeautifulSoup(self._fetch(search_url).decode('euc_jp', errors='replace'), 'html.parser')+ soup = BeautifulSoup(body_text(self._fetch(search_url), default='euc_jp'), 'html.parser')links = []for anchor in soup.select('.result-box .body h3 a[href]'):try:@@ -197,7 +197,7 @@ class SeesaaProvider:self.records[url] = parse_page(body, url)if self._match(code):return self._match(code)- person = BeautifulSoup(body.decode('euc_jp', errors='replace'), 'html.parser')+ person = BeautifulSoup(body_text(body, default='euc_jp'), 'html.parser')for anchor in person.select('#page-body .user-area a[href]'):if 'レーベル一覧' not in anchor.get_text():continuediff --git a/src/peach/site_icons.py b/src/peach/site_icons.pyindex 43d9d998f..3f448f12f 100644--- a/src/peach/site_icons.py+++ b/src/peach/site_icons.py@@ -31,6 +31,8 @@ import jsonimport refrom urllib.parse import urljoin, urlsplit+from .http import body_text+#: 声明里没有尺寸时给的保守估计。favicon.ico 历史上就是 16,别按它去赢过 apple-touch-icon。DEFAULT_SIZE = 16#: SVG 没有像素尺寸。给一个高于任何现实位图的分数,让它无条件排在最前。@@ -326,7 +328,9 @@ def discover(url: str, fetch) -> list[Candidate]:candidates = list(overrides_for(url))page = fetch(base)if page is not None:- html = page[0].decode("utf-8", "replace")+ # `fetch` 连内容类型一起给了,声明里的 charset 就在手边:日站首页仍有相当+ # 一部分是 Shift_JIS,按 utf-8 硬解会把 `<title>` 与 `rel` 文本变成替换字符。+ html = body_text(page[0], {"content-type": page[1]})candidates += link_candidates(html, base)manifest = manifest_url(html, base)if manifest:diff --git a/tests/test_http.py b/tests/test_http.pyindex 9b247a47f..c003e4364 100644--- a/tests/test_http.py+++ b/tests/test_http.py@@ -4,7 +4,8 @@ from pathlib import Pathimport httpx-from peach.http import CurlCffiTransport, HttpRequest, HttpxTransport+from peach.http import (CurlCffiTransport, HttpRequest, HttpResponse, HttpxTransport,+ body_text, response_text)from peach.user_agent import USER_AGENT@@ -34,6 +35,53 @@ class UserAgentTests(unittest.TestCase):self.assertEqual(offenders, [])+class BodyTextTests(unittest.TestCase):+ """字节到文本按站点自己的声明解,不按调用方的假设解。"""++ JAPANESE = "架空の作品"++ def test_the_content_type_header_decides_the_encoding(self):+ body = self.JAPANESE.encode("euc_jp")+ self.assertEqual(+ body_text(body, {"Content-Type": "text/html; charset=EUC-JP"}), self.JAPANESE)++ def test_a_meta_declaration_decides_it_when_the_header_is_silent(self):+ for markup in (b'<meta charset="shift_jis">',+ b'<meta http-equiv="Content-Type" content="text/html; charset=shift_jis">'):+ with self.subTest(markup=markup):+ body = b"<html><head>" + markup + self.JAPANESE.encode("shift_jis")+ self.assertIn(self.JAPANESE, body_text(body, {"Content-Type": "text/html"}))++ def test_nothing_declared_falls_back_to_the_caller_default(self):+ body = self.JAPANESE.encode("euc_jp")+ self.assertEqual(body_text(body, default="euc_jp"), self.JAPANESE)+ # 默认值是 utf-8,所以同一份 EUC-JP 字节在没有声明也没有默认值时只能替换字符。+ self.assertNotIn(self.JAPANESE, body_text(body))++ def test_the_header_wins_over_a_contradicting_meta(self):+ body = b'<meta charset="utf-8">' + self.JAPANESE.encode("euc_jp")+ self.assertTrue(+ body_text(body, {"content-type": "text/html;charset=euc-jp"}).endswith(self.JAPANESE))++ def test_an_unusable_declaration_falls_through_instead_of_raising(self):+ """站内写法 Python 不认、或者声明本身就是错的,都要退到下一个候选。"""+ body = self.JAPANESE.encode("euc_jp")+ self.assertEqual(body_text(body, {"Content-Type": "text/html; charset=x-euc-jp"},+ default="euc_jp"), self.JAPANESE)+ self.assertEqual(body_text(body, {"Content-Type": "text/html; charset=utf-8"},+ default="euc_jp"), self.JAPANESE)+ self.assertIn("�", body_text(b"\xff\xfe", default="not-a-codec"))++ def test_the_declaration_is_only_looked_for_near_the_start(self):+ body = b"<!--" + b"x" * 5000 + b'--><meta charset="euc-jp">' + self.JAPANESE.encode("euc_jp")+ self.assertNotIn(self.JAPANESE, body_text(body))++ def test_a_response_carries_its_own_headers_into_the_decoder(self):+ response = HttpResponse(200, {"content-type": "text/html; charset=euc-jp"},+ self.JAPANESE.encode("euc_jp"))+ self.assertEqual(response_text(response), self.JAPANESE)++class _CurlResponse:status_code = 206headers = {"Content-Type": "application/json"}