Peach: Local-first video metadata scraper and media manager.
refactor(follow): Gofile 展开器出站点基类
longmeidao0b927d78cd86
diff --git a/src/peach/follow_gofile.py b/src/peach/follow_gofile.pynew file mode 100644index 000000000..eb76b0801--- /dev/null+++ b/src/peach/follow_gofile.py@@ -0,0 +1,141 @@+"""展开 Gofile 文件页。++Gofile 是第三方文件站,不是追更来源。F95 和 FANBOX 的帖子里可能贴 Gofile 链接,+但 Gofile 本身跟这两个站没有关系。++这段逻辑原先是 `_BaseConnector` 的一个方法,于是每个连接器——包括根本不碰 Gofile 的+rule34、kemono、paheal——都继承着它。更要紧的是那里发请求必须记得写+`connector_headers=False`:漏掉的话,来源站的 Cookie(F95 的会话、FANBOX 的登录态)+会跟着一起发到 gofile.io。那是个只靠「调用方记得传参」维持的安全约束。++搬出来之后,展开器自己持有 transport,只发自己的 User-Agent 和自己的 Bearer token。+把来源站凭据带到第三方主机这件事,从「参数传对了」变成结构上做不到。++token 只进 Authorization 头,永远不进 URL、不进候选、不进日志。+"""+from __future__ import annotations++import json+import re+import urllib.parse++import httpx++from .follow import DEFAULT_MAX_BYTES, FollowSourceError, plain_text, stable_id+from .follow_secrets import Credential, CredentialError+from .http import HttpRequest, HttpResponse, HttpTransport++#: 请求 Gofile 用的固定 UA。刻意不复用连接器的 `_headers()`——那里面可能有来源站+#: 的 Cookie,而这里是另一个主机。+USER_AGENT = "Peach/0.2 (+local self-hosted follow reader)"++_FOLDER_PATH = re.compile(r"/d/([A-Za-z0-9_-]+)")+++def folder_ids(links: list[str]) -> list[str]:+ """从一堆链接里挑出 Gofile 文件夹 id,保持出现顺序且去重。"""+ found: list[str] = []+ for link in links:+ try:+ parsed = urllib.parse.urlsplit(link)+ except ValueError:+ continue+ host = (parsed.hostname or "").casefold()+ matched = _FOLDER_PATH.fullmatch(parsed.path.rstrip("/"))+ if (host == "gofile.io" or host.endswith(".gofile.io")) and matched:+ found.append(matched.group(1))+ return list(dict.fromkeys(found))+++class GofileExpander:+ """用用户自己的 API token 把 Gofile 文件夹展开成媒体条目。"""++ def __init__(self, transport: HttpTransport, *,+ credential: Credential | None = None,+ timeout: float = 15.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ max_items: int = 100):+ self.transport = transport+ self.credential = credential+ self.timeout = timeout+ self.max_bytes = max_bytes+ self.max_items = max_items++ def expand(self, links: list[str]) -> tuple[dict[str, object], ...]:+ folders = folder_ids(links)+ if not folders or self.credential is None:+ return ()+ token, = self.credential.require("api_token")+ items: list[dict[str, object]] = []+ seen: set[str] = set()+ for folder in folders:+ payload = self._contents(folder, token)+ self._collect(payload, items, seen)+ return tuple(items)++ def _contents(self, folder: str, token: str) -> dict:+ url = f"https://api.gofile.io/contents/{urllib.parse.quote(folder)}"+ response = self._get(url, token)+ payload = None+ try:+ payload = json.loads(response.body.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError):+ # 非 JSON 的 401/403 仍按凭据拒绝处理;其他状态交给下面的通用错误。+ pass+ api_status = payload.get("status") if isinstance(payload, dict) else None+ if api_status == "error-notPremium":+ raise FollowSourceError(+ "Gofile 文件列表 API 需要 Premium 账户;token 有效,"+ "但当前账户套餐不支持此接口")+ if response.status in (401, 403) or api_status == "error-token":+ raise CredentialError("Gofile 拒绝了 API token")+ if response.status != 200:+ raise FollowSourceError(f"Gofile 返回 HTTP {response.status}")+ if not isinstance(payload, dict) or payload.get("status") != "ok":+ raise FollowSourceError("Gofile 文件列表未取得")+ return payload++ def _get(self, url: str, token: str) -> HttpResponse:+ headers = {+ "Accept": "application/json",+ "Authorization": f"Bearer {token}",+ "User-Agent": USER_AGENT,+ }+ try:+ response = self.transport(+ HttpRequest("GET", url, headers), self.timeout, self.max_bytes)+ except (OSError, httpx.HTTPError) as exc:+ raise FollowSourceError("Gofile 请求失败") from exc+ if len(response.body) > self.max_bytes:+ raise FollowSourceError("Gofile 响应超出大小上限")+ return response++ def _collect(self, payload: dict, items: list, seen: set) -> None:+ stack = [payload.get("data")]+ while stack and len(items) < self.max_items:+ node = stack.pop()+ if not isinstance(node, dict):+ continue+ children = node.get("children")+ if isinstance(children, dict):+ stack.extend(reversed(list(children.values())))+ elif isinstance(children, list):+ stack.extend(reversed(children))+ if str(node.get("type") or "").casefold() != "file":+ continue+ media_type = str(node.get("mimetype") or "").casefold()+ kind = ("video" if media_type.startswith("video/") else+ "image" if media_type.startswith("image/") else "")+ link = str(node.get("link") or node.get("downloadLink") or "")+ if not kind or not link.startswith("https://") or link in seen:+ continue+ seen.add(link)+ items.append({+ "id": str(node.get("id") or stable_id(link)),+ "name": plain_text(str(node.get("name") or "")) or f"{kind} {len(items)+1}",+ "url": link,+ "thumb_url": str(node.get("thumbnail") or "") or None,+ "media_kind": kind,+ "size": node.get("size"),+ "resource_provider": "gofile",+ })diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex b6e5aa01b..4ac72975f 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -22,6 +22,7 @@ from .fanbox import FanboxContentError, normalize_fanbox_postfrom . import follow_providersfrom .follow import DEFAULT_MAX_BYTES, FollowSourceError, plain_text, stable_idfrom .follow_secrets import Credential, CredentialError+from .follow_gofile import GofileExpanderfrom .http import CurlCffiTransport, HttpRequest, HttpResponse, HttpTransport, HttpxTransport@@ -394,74 +395,15 @@ class _BaseConnector:return self.parse_json(response)def _gofile_media(self, links: list[str]) -> tuple[dict[str, object], ...]:- """用用户自己的 GoFile API token 展开文件页,token 永不进入 URL/候选。"""- folders = []- for link in links:- try:- parsed = urllib.parse.urlsplit(link)- except ValueError:- continue- host = (parsed.hostname or "").casefold()- matched = re.fullmatch(r"/d/([A-Za-z0-9_-]+)", parsed.path.rstrip("/"))- if (host == "gofile.io" or host.endswith(".gofile.io")) and matched:- folders.append(matched.group(1))- if not folders or self.gofile_credential is None:- return ()- token, = self.gofile_credential.require("api_token")- items: list[dict[str, object]] = []- seen: set[str] = set()- for folder in dict.fromkeys(folders):- url = f"https://api.gofile.io/contents/{urllib.parse.quote(folder)}"- response = self._get(url, headers={- "Accept": "application/json", "Authorization": f"Bearer {token}",- }, connector_headers=False)- payload = None- try:- payload = self.parse_json(response)- except FollowSourceError:- # 非 JSON 的 401/403 仍按凭据拒绝处理;其他状态交给通用错误。- pass- api_status = payload.get("status") if isinstance(payload, dict) else None- if api_status == "error-notPremium":- raise FollowSourceError(- "Gofile 文件列表 API 需要 Premium 账户;token 有效,"- "但当前账户套餐不支持此接口")- if response.status in (401, 403) or api_status == "error-token":- raise CredentialError("Gofile 拒绝了 API token")- self._check_status(response)- if payload is None:- payload = self.parse_json(response)- if not isinstance(payload, dict) or payload.get("status") != "ok":- raise FollowSourceError("Gofile 文件列表未取得")- stack = [payload.get("data")]- while stack and len(items) < self.max_items:- node = stack.pop()- if not isinstance(node, dict):- continue- children = node.get("children")- if isinstance(children, dict):- stack.extend(reversed(list(children.values())))- elif isinstance(children, list):- stack.extend(reversed(children))- if str(node.get("type") or "").casefold() != "file":- continue- media_type = str(node.get("mimetype") or "").casefold()- kind = ("video" if media_type.startswith("video/") else- "image" if media_type.startswith("image/") else "")- link = str(node.get("link") or node.get("downloadLink") or "")- if not kind or not link.startswith("https://") or link in seen:- continue- seen.add(link)- items.append({- "id": str(node.get("id") or stable_id(link)),- "name": plain_text(str(node.get("name") or "")) or f"{kind} {len(items)+1}",- "url": link,- "thumb_url": str(node.get("thumbnail") or "") or None,- "media_kind": kind,- "size": node.get("size"),- "resource_provider": "gofile",- })- return tuple(items)+ """把帖子里的 Gofile 链接展开成媒体条目;实现见 `follow_gofile`。++ 留一个薄委托而不是让连接器直接构造展开器:调用点(f95zone / fanbox)不必知道+ 展开器怎么造,而 Gofile 的 HTTP 细节也不再摊在站点基类里。+ """+ return GofileExpander(+ self.transport, credential=self.gofile_credential,+ timeout=self.timeout, max_bytes=self.max_bytes, max_items=self.max_items,+ ).expand(links)class KemonoConnector(_BaseConnector):diff --git a/tests/test_follow_gofile.py b/tests/test_follow_gofile.pynew file mode 100644index 000000000..f8a5d96ee--- /dev/null+++ b/tests/test_follow_gofile.py@@ -0,0 +1,106 @@+"""Gofile 展开器的隔离测试。++重点是那条安全约束:来源站的会话不能跟着资源链接发到第三方主机。展开器还是+`_BaseConnector` 一个方法的时候,它靠调用方记得写 `connector_headers=False` 维持;+搬出来之后展开器自己持有 transport,约束由结构保证。+"""+import json+import unittest++from peach.follow import FollowSourceError+from peach.follow_gofile import GofileExpander, folder_ids+from peach.follow_secrets import Credential, CredentialError+from peach.http import HttpResponse+++CONTENTS_OK = json.dumps({+ "status": "ok",+ "data": {"children": {+ "a": {"type": "file", "mimetype": "video/mp4", "id": "a",+ "name": "one.mp4", "link": "https://store1.gofile.io/download/one.mp4",+ "thumbnail": "https://store1.gofile.io/one.jpg", "size": 123},+ "b": {"type": "file", "mimetype": "text/plain", "id": "b",+ "name": "readme.txt", "link": "https://store1.gofile.io/download/readme.txt"},+ }},+}).encode("utf-8")+++def _transport(status=200, body=CONTENTS_OK, record=None):+ def call(request, timeout, max_bytes):+ if record is not None:+ record.append(request)+ return HttpResponse(status, {}, body)+ return call+++class FolderIdTests(unittest.TestCase):+ def test_only_gofile_folder_links_are_picked_and_deduplicated(self):+ self.assertEqual(+ folder_ids([+ "https://gofile.io/d/OS2Qz9",+ "https://store1.gofile.io/d/OS2Qz9", # 子域也算+ "https://gofile.io/d/OS2Qz9", # 重复+ "https://example.test/d/NOPE", # 别的站+ "https://gofile.io/about", # 不是文件夹路径+ "not a url at all",+ ]),+ ["OS2Qz9"],+ )+++class CredentialIsolationTests(unittest.TestCase):+ """展开器自己发出的请求带什么。++ 端到端的隔离已经有测试守着,这里不重造:+ `test_follow_sources.test_fanbox_cookie_stays_on_fanbox_requests` 断言 FANBOX 的+ 会话不进 Gofile 请求,`test_cookie_resolves_masked_media_without_leaking_to_the_file_host`+ 对 F95 的 masked 链接做同一件事。本文件补的是展开器自身此前没有的直接覆盖。+ """++ def test_the_request_carries_only_the_gofile_token(self):+ seen = []+ GofileExpander(+ _transport(record=seen),+ credential=Credential("gofile", {"api_token": "secret"}),+ ).expand(["https://gofile.io/d/OS2Qz9"])++ self.assertEqual(len(seen), 1)+ headers = {key.casefold(): value for key, value in seen[0].headers.items()}+ self.assertEqual(headers["authorization"], "Bearer secret")+ self.assertNotIn("cookie", headers, "第三方主机不该收到任何 Cookie")+ self.assertNotIn("secret", seen[0].url, "token 永远不进 URL")+++class ApiErrorTests(unittest.TestCase):+ def _expand(self, status=200, body=CONTENTS_OK):+ return GofileExpander(+ _transport(status=status, body=body),+ credential=Credential("gofile", {"api_token": "t"}),+ ).expand(["https://gofile.io/d/OS2Qz9"])++ def test_no_credential_means_no_request_instead_of_an_error(self):+ seen = []+ expander = GofileExpander(_transport(record=seen), credential=None)+ self.assertEqual(expander.expand(["https://gofile.io/d/OS2Qz9"]), ())+ self.assertEqual(seen, [], "没有 token 就不该发请求")++ def test_a_rejected_token_is_a_credential_error(self):+ with self.assertRaises(CredentialError):+ self._expand(status=401, body=b"denied")+ with self.assertRaises(CredentialError):+ self._expand(body=json.dumps({"status": "error-token"}).encode("utf-8"))++ def test_a_non_premium_account_says_so_instead_of_failing_vaguely(self):+ with self.assertRaisesRegex(FollowSourceError, "Premium"):+ self._expand(body=json.dumps(+ {"status": "error-notPremium"}).encode("utf-8"))++ def test_only_playable_files_survive(self):+ items = self._expand()+ self.assertEqual([item["media_kind"] for item in items], ["video"])+ self.assertEqual(items[0]["resource_provider"], "gofile")+ self.assertEqual(items[0]["url"], "https://store1.gofile.io/download/one.mp4")+++if __name__ == "__main__":+ unittest.main()