Peach: Local-first video metadata scraper and media manager.
feat(follow): normalize FANBOX post bodies
longmeidaod154873d32a8
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 0078dbd65..99f4b35c7 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -79,6 +79,9 @@ FANBOX 多图、Gofile Bearer API、Paheal 标签页与跨站出处键见`follow-fanbox-gofile-paheal`。FANBOX Cookie 是本机可选凭据,只发给 FANBOX API;FANBOX `post.info` 的 Firefox 传输边界与复用依据见 `fanbox-browser-transport`;只允许公开JSON,不解机器人质询、不执行网页脚本、不读取付费帖子。+FANBOX 正文统一先经过 `peach.fanbox.normalize_fanbox_post`:数据模型固定参考 PixivUtil2+`v20251112` / `e537e96`,覆盖 image/text/file/article/video/entry 及各类 map;只有图片和视频+进入可切换媒体,压缩包等文件只保留为资源链接,重复 URL 按正文首次出现顺序去重。Gofile token 是另一份本机可选凭据,只进 Gofile 请求头,不进 URL、证据、ledger 的公开投影或浏览器 JSON。Gofile 当前把 contents API 限给 Premium;`error-notPremium` 要按套餐限制报告,不能误报成 token 无效。未取得文件列表时保留分享页,不得声称已经取得视频。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 804992934..986ad72f2 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -92,7 +92,7 @@| `taste_history.py` 自写 Chrome/Firefox/Zen/Safari 发现、快照与 SQLite 解析 | **优先替换为 `browserexport==0.4.4`** | Python 3.14 依赖解析通过;在本机 7 个 Chrome/Firefox/Zen profile 上与 Peach 逐库计数完全一致。Peach 保留 Takeout、隐私存储、域名分析和 candidate 生成。 || `jobs.PidFileLock` | **优先替换为 `portalocker==4.3.0` 的 `PidFileLock`** | Python 3.14 解析通过,现成覆盖 PID 写入、锁持有者、原子替换、陈旧文件与释放清理。Peach 只保留任务归属和错误文案映射。 || Rule34Video 媒体页解析 | **部分替换为 `yt-dlp==2026.8.19`** | 对真实视频 4533145 无写入提取成功,取得 4 个格式、31 个标签、缩略图与时间。Peach 仍负责作者分页、合集/超多 model 排除、来源分组和跨站去重。 |-| FANBOX 正文解析 | **按 PixivUtil2 FANBOX 模型重做规范化层** | 当前 Peach 只读取 article 的 `blocks` 与 `imageMap`;成熟实现还覆盖 image/file/article/video、`fileMap`、`embedMap`、`urlEmbedMap` 和旧正文。未找到兼具窄依赖、活跃维护与当前传输可用性的 Python wheel;实现时固定 PixivUtil2 revision,只复用公开数据模型,不引入整套下载器。传输继续用 `curl_cffi==0.16.2`。 |+| FANBOX 正文解析 | **已采用 PixivUtil2 `v20251112` / `e537e96` 的公开正文模型** | Peach 的独立规范化 DTO 已覆盖 image/text/file/article/video/entry、`fileMap`、`embedMap`、`urlEmbedMap` 和旧 HTML 正文,并保留正文顺序、稳定去重、可播放媒体与文件页边界;BSD-2-Clause 依据写在实现头部。PixivUtil2 是完整下载器而非可嵌入解析库,因此不引入整套依赖;传输继续固定 `curl_cffi==0.16.2`。真实公开帖 12228983 只读 POC 得到 article、6 图和 Gofile `OS2Qz9`。 || `mp4index.py` 有界 MP4 关键帧索引 | **保留自研** | PyAV 需要 demux,`pymp4` 依赖旧 Construct,Bento4 是额外二进制;都不能证明在云盘文件上保留“只读 moov/stss/stts、避免整片流量”的约束。 || `certs.py` 固定项目 CA 与短期叶证书 | **保留自研 policy,继续调用 OpenSSL** | mkcert 会接管本机 CA 安装/私钥,不能保持跨设备固定项目 CA;cryptography 只替换证书编码且增加原生依赖,不能删除 Peach 的 Apple 398 天与 CA 生命周期策略。 || `migrations.py` SQLite 迁移 | **保留自研** | Alembic 会引入 SQLAlchemy/Mako/greenlet;现有范围只需顺序 SQL、校验和、备份与 PyInstaller 资源定位,没有 ORM 消费者。 |diff --git a/docs/STATUS.md b/docs/STATUS.mdindex eadb17113..18897004f 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -67,11 +67,12 @@- `b0730af` 已经由 `a0a8ccc` 合入 `master`:0.7.2 将 FANBOX `post.info` 收窄到固定版本 `curl_cffi` 的 Firefox 传输;列表及其他来源仍走共用 HTTPX,不执行网页脚本、不求解机器人质询、不读取付费帖子。用管理页已保存的 Cookie 对 LazyProcrastinator 帖子 12228983 做只读复核,已取得 6 图、正文和 Gofile `OS2Qz9` 资源页,证明 Cookie 没填错,先前的 403/`general_error` 来自传输指纹。关注域 386 项、正式 Windows 全量 1114 项通过,分别有 1/13 项按平台跳过。- 0.7.2 正式 EXE 已替换为 SHA-256 `F5F78CDACD9F466A6B8A423151F510F16D40A47BB052B984971D0F59D3EC51E6`,上版备份为 `dist/Peach/Peach.pre-0.7.2-20260828-142052.exe`;80/443 已恢复,打包迁移为 22 个、0 待处理,项目 CA 严格 HTTPS `/healthz` 返回 200、0.7.2、writer。生产凭据 API 显示 FANBOX Cookie 已配置、Gofile token 当前未配置;本轮没有触发检查更新,部署前后 ledger SHA-256 均为 `C2C6F09522305F682636379F43E74A4E60D9475C39FBE0FBC3505A7879CB963C`。本改动没有页面、CSS 或交互变化,桌面/手机视觉验收不适用。- 2026-08-28 已完成全仓自研实现复用审计:浏览器历史、批处理 PID 锁、Rule34Video 媒体页和 FANBOX 正文模型有成熟替代或参考实现,进入替换队列;MP4 有界索引、固定项目 CA、SQLite 迁移、Gofile、系统网络监听、流媒体会话、单 writer 同步与 Windows 更新因已验证的 Peach 约束继续保留。详细候选、版本、真实 POC 与拒绝理由写入 `docs/REUSE.md`;本轮只改规则与文档,没有新增运行时依赖、部署、生产或 ledger 写入。+- 0.7.3 首项复用替换已完成:FANBOX 正文规范化固定参考 PixivUtil2 `v20251112` / `e537e96`,覆盖 image/text/file/article/video/entry、正文 blocks、四类 map 与旧 HTML;图片和视频进入现有多媒体切换,其他文件保留资源链接,URL 稳定去重。已保存 Cookie 对公开帖 12228983 的只读实测为 article、6 图、Gofile `OS2Qz9`;follow 391 项、正式 Windows 全量 1119 项通过,分别有 1/13 项按平台跳过。本轮尚未触发生产检查更新或写 ledger。## 下一批工作1. 另行授权后先备份 ledger,再把 `follow_item` 181、184、185 从 `seen` 恢复为 `new`,复核状态计数、完整性与新哈希。-2. 先按复用审计重做 FANBOX 正文规范化层,再依次替换浏览器历史、PID 锁和 Rule34Video 媒体页;每项固定版本/revision、首个消费者和隔离测试同批落地。+2. 继续按复用审计依次替换浏览器历史、PID 锁和 Rule34Video 媒体页;每项固定版本/revision、首个消费者和隔离测试同批落地。3. 分类剩余 44 个无预览变体,区分确无图片与来源解析遗漏。4. 另行确认后在生产关注页检查 LazyProcrastinator FANBOX,把已验证的 6 图、正文与 Gofile `OS2Qz9` 资源页写入关注候选;Gofile token 当前未配置,且此前验证的账户不是 Premium,21 个视频仍未取得。5. 在 `/review` 人工处理本批 JAV 日文系列名、官方标签及现有创作者标签、FC2、Javinizer、Logo、头像和媒体失败候选;未经批准不写真相字段。diff --git a/src/peach/__init__.py b/src/peach/__init__.pyindex 362ef934d..e71f756e9 100644--- a/src/peach/__init__.py+++ b/src/peach/__init__.py@@ -1,3 +1,3 @@"""Peach application package."""-__version__ = "0.7.2"+__version__ = "0.7.3"diff --git a/src/peach/fanbox.py b/src/peach/fanbox.pynew file mode 100644index 000000000..44e4b4747--- /dev/null+++ b/src/peach/fanbox.py@@ -0,0 +1,242 @@+"""Normalize public pixivFANBOX post bodies into Peach media and links.++The supported body shapes follow PixivUtil2 v20251112 (commit ``e537e96``),+BSD-2-Clause. Peach keeps its own small DTO because the upstream project is a+complete downloader rather than an embeddable parser library.+"""+from __future__ import annotations++import re+import urllib.parse+from dataclasses import dataclass+from pathlib import PurePosixPath+from typing import Mapping++from bs4 import BeautifulSoup+++class FanboxContentError(ValueError):+ """A public post used an invalid or unsupported FANBOX body shape."""+++@dataclass(frozen=True)+class FanboxContent:+ post_type: str+ summary: str+ links: tuple[str, ...]+ media_items: tuple[dict[str, object], ...]+ image_count: int+ video_count: int+ file_count: int+++_SUPPORTED_TYPES = frozenset({"image", "text", "file", "article", "video", "entry"})+_URL_RE = re.compile(r"https?://[^\s\"'<>)\]]+", re.IGNORECASE)+_IMAGE_SUFFIXES = frozenset({".avif", ".bmp", ".gif", ".jpeg", ".jpg", ".png", ".webp"})+_VIDEO_SUFFIXES = frozenset({".m4v", ".mkv", ".mov", ".mp4", ".webm"})+++def _https_url(value: object) -> str | None:+ if not isinstance(value, str):+ return None+ text = value.strip()+ try:+ parsed = urllib.parse.urlsplit(text)+ except ValueError:+ return None+ if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:+ return None+ return text+++def _kind(node: Mapping[str, object], url: str) -> str | None:+ mime = str(node.get("mimeType") or node.get("mimetype") or "").casefold()+ if mime.startswith("image/"):+ return "image"+ if mime.startswith("video/"):+ return "video"+ suffix = PurePosixPath(urllib.parse.urlsplit(url).path).suffix.casefold()+ if suffix in _IMAGE_SUFFIXES:+ return "image"+ if suffix in _VIDEO_SUFFIXES:+ return "video"+ return None+++def _nested_urls(value: object) -> tuple[str, ...]:+ found: list[str] = []++ def add(candidate: object) -> None:+ if isinstance(candidate, Mapping):+ for child in candidate.values():+ add(child)+ return+ if isinstance(candidate, (list, tuple)):+ for child in candidate:+ add(child)+ return+ if not isinstance(candidate, str):+ return+ for matched in _URL_RE.findall(candidate):+ url = _https_url(matched.rstrip(".,;"))+ if url and url not in found:+ found.append(url)++ add(value)+ return tuple(found)+++def _embed_url(node: Mapping[str, object]) -> str | None:+ provider = str(node.get("serviceProvider") or "").casefold()+ content_id = str(+ node.get("videoId") or node.get("contentId") or node.get("video_id") or ""+ ).strip()+ if not content_id:+ return None+ if provider == "youtube":+ return f"https://www.youtube.com/watch?v={urllib.parse.quote(content_id)}"+ if provider == "vimeo" and content_id.isdigit():+ return f"https://vimeo.com/{content_id}"+ return None+++def normalize_fanbox_post(post: Mapping[str, object]) -> FanboxContent:+ """Return ordered text, links and playable media from one public post."""+ post_type = str(post.get("type") or "image").casefold()+ if post_type not in _SUPPORTED_TYPES:+ raise FanboxContentError(f"FANBOX 正文类型不受支持:{post_type or '空'}")+ body = post.get("body")+ if not isinstance(body, Mapping):+ raise FanboxContentError("FANBOX 公开正文缺少 body")++ text_parts: list[str] = []+ links: list[str] = []+ media: list[dict[str, object]] = []+ media_urls: set[str] = set()+ referenced_images: set[str] = set()+ referenced_files: set[str] = set()+ file_count = 0++ def add_link(value: object) -> None:+ for url in _nested_urls(value):+ if url not in links:+ links.append(url)++ def add_text(value: object) -> None:+ if isinstance(value, str) and value.strip():+ text_parts.append(value.strip())+ add_link(value)++ def add_media(node: object, *, item_id: str, fallback_name: str,+ force_kind: str | None = None) -> None:+ if not isinstance(node, Mapping):+ return+ url = _https_url(node.get("originalUrl") or node.get("url"))+ if not url or url in media_urls:+ return+ kind = force_kind or _kind(node, url)+ if kind not in {"image", "video"}:+ return+ thumb = _https_url(node.get("thumbnailUrl") or node.get("thumbnail"))+ media_urls.add(url)+ media.append({+ "id": str(node.get("id") or item_id or url),+ "name": str(node.get("name") or fallback_name),+ "url": url,+ "thumb_url": (thumb or url) if kind == "image" else thumb,+ "media_kind": kind,+ "size": node.get("size"),+ "resource_provider": "fanbox",+ })++ raw_text = body.get("text")+ if isinstance(raw_text, str):+ add_text(raw_text)+ raw_html = body.get("html")+ if isinstance(raw_html, str) and raw_html.strip():+ parsed = BeautifulSoup(raw_html, "html.parser")+ add_text(parsed.get_text("\n", strip=True))+ for anchor in parsed.select("a[href]"):+ add_link(anchor.get("href"))+ for index, image in enumerate(parsed.select("img"), start=1):+ source = image.get("data-src-original") or image.get("src")+ add_media({"originalUrl": source}, item_id=f"html-{index}",+ fallback_name=f"图片 {len(media) + 1}", force_kind="image")++ image_map = body.get("imageMap") if isinstance(body.get("imageMap"), Mapping) else {}+ file_map = body.get("fileMap") if isinstance(body.get("fileMap"), Mapping) else {}+ embed_map = body.get("embedMap") if isinstance(body.get("embedMap"), Mapping) else {}+ url_embed_map = (+ body.get("urlEmbedMap") if isinstance(body.get("urlEmbedMap"), Mapping) else {}+ )+ blocks = body.get("blocks") if isinstance(body.get("blocks"), list) else []+ for block in blocks:+ if not isinstance(block, Mapping):+ continue+ block_type = str(block.get("type") or "")+ if block_type in {"p", "header"}:+ add_text(block.get("text"))+ add_link(block.get("links"))+ elif block_type == "image":+ image_id = str(block.get("imageId") or "")+ referenced_images.add(image_id)+ add_media(image_map.get(image_id), item_id=image_id,+ fallback_name=f"图片 {len(media) + 1}", force_kind="image")+ elif block_type == "file":+ file_id = str(block.get("fileId") or "")+ referenced_files.add(file_id)+ node = file_map.get(file_id)+ if isinstance(node, Mapping):+ file_count += 1+ add_link(node.get("url"))+ add_media(node, item_id=file_id,+ fallback_name=f"文件 {file_count}")+ elif block_type == "embed":+ node = embed_map.get(str(block.get("embedId") or ""))+ add_link(node)+ if isinstance(node, Mapping):+ add_link(_embed_url(node))+ elif block_type == "url_embed":+ add_link(url_embed_map.get(str(block.get("urlEmbedId") or "")))++ for image_id, node in image_map.items():+ if str(image_id) not in referenced_images:+ add_media(node, item_id=str(image_id),+ fallback_name=f"图片 {len(media) + 1}", force_kind="image")+ for file_id, node in file_map.items():+ if str(file_id) in referenced_files or not isinstance(node, Mapping):+ continue+ file_count += 1+ add_link(node.get("url"))+ add_media(node, item_id=str(file_id), fallback_name=f"文件 {file_count}")++ body_images = body.get("images") if isinstance(body.get("images"), list) else []+ for index, node in enumerate(body_images, start=1):+ add_media(node, item_id=f"image-{index}",+ fallback_name=f"图片 {len(media) + 1}", force_kind="image")+ body_files = body.get("files") if isinstance(body.get("files"), list) else []+ for index, node in enumerate(body_files, start=1):+ if not isinstance(node, Mapping):+ continue+ file_count += 1+ add_link(node.get("url"))+ add_media(node, item_id=f"file-{index}", fallback_name=f"文件 {file_count}")++ video = body.get("video")+ add_link(video)+ if isinstance(video, Mapping):+ add_link(_embed_url(video))+ add_link(embed_map)+ add_link(url_embed_map)++ image_count = sum(item["media_kind"] == "image" for item in media)+ video_count = sum(item["media_kind"] == "video" for item in media)+ return FanboxContent(+ post_type=post_type,+ summary="\n".join(text_parts),+ links=tuple(links),+ media_items=tuple(media),+ image_count=image_count,+ video_count=video_count,+ file_count=file_count,+ )diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex d9392f057..9ca857166 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -18,6 +18,7 @@ from typing import Mapping, Protocolimport httpxfrom bs4 import BeautifulSoup+from .fanbox import FanboxContentError, normalize_fanbox_postfrom .follow import DEFAULT_MAX_BYTES, FollowSourceError, _plain_text, _stable_idfrom .follow_secrets import Credential, CredentialErrorfrom .http import CurlCffiTransport, HttpRequest, HttpResponse, HttpTransport, HttpxTransport@@ -36,6 +37,7 @@ DEFAULT_MAX_ITEMS = 100#: 这张表注定不全,作者换网盘就得往里加。加的时候只加**分发文件**的域名:#: 判据是点进去拿到的是文件,不是一个页面。_FILE_HOST_DOMAINS = frozenset({+ "downloads.fanbox.cc","gofile.io", "mega.nz", "mega.io", "mediafire.com", "pixeldrain.com","workupload.com", "catbox.moe", "1fichier.com", "dropbox.com","drive.google.com", "docs.google.com", "1drv.ms", "onedrive.live.com",@@ -61,7 +63,7 @@ def resource_links(text: str | None) -> list[str]:"""found = []for link in _LINK_RE.findall(text or ""):- if _is_resource_url(link):+ if _is_resource_url(link) and link not in found:found.append(link)return found@@ -1295,20 +1297,23 @@ class FanboxConnector(_BaseConnector):# FANBOX 会把单篇 post.info 临时换成 Cloudflare 验证页。# 列表本身仍是可信的公开更新;保留卡片并明确标记媒体未取得,# 不能让一篇详情失败拖垮整个作者来源。- detail = {"summary": "", "links": [], "images": (),+ detail = {"summary": "", "links": [], "media_items": (),+ "post_type": None, "image_count": 0,+ "video_count": 0, "file_count": 0,"error": str(error)}probed += 1links = detail["links"]- images = detail["images"]+ direct_media = detail["media_items"]gofile_media = self._gofile_media(links)- media_items = tuple(images) + gofile_media+ media_items = tuple(direct_media) + gofile_mediacandidates.append(FollowCandidate(provider=self.provider,external_id=post_id,title=_plain_text(str(post.get("title") or "")) or f"FANBOX 帖子 {post_id}",url=f"https://{creator}.fanbox.cc/posts/{post_id}",- thumb_url=(str(images[0].get("thumb_url") or images[0].get("url"))- if images else+ thumb_url=(str(direct_media[0].get("thumb_url")+ or direct_media[0].get("url"))+ if direct_media elsestr(cover.get("url")) if cover.get("url") else None),published_at=_iso_from_text(post.get("publishedDatetime")),author=_plain_text(str(user.get("name") or "")),@@ -1317,7 +1322,10 @@ class FanboxConnector(_BaseConnector):extra={"fee_required": 0, "official": True, "links": links,"media_items": media_items,"media_error": detail.get("error"),- "image_count": len(images),+ "post_type": detail.get("post_type"),+ "image_count": detail.get("image_count", 0),+ "video_count": detail.get("video_count", 0),+ "file_count": detail.get("file_count", 0),"gofile_video_count": sum(item.get("media_kind") == "video" for item in gofile_media)},))@@ -1344,34 +1352,22 @@ class FanboxConnector(_BaseConnector):post = body.get("post") if isinstance(body, dict) else Noneif not isinstance(post, dict):raise FollowSourceError("fanbox 帖子详情格式不符")- article = post.get("body") if isinstance(post.get("body"), dict) else {}- blocks = article.get("blocks") if isinstance(article.get("blocks"), list) else []- image_map = article.get("imageMap") if isinstance(article.get("imageMap"), dict) else {}- text_parts: list[str] = []- image_ids: list[str] = []- for block in blocks:- if not isinstance(block, dict):- continue- if block.get("type") == "p" and block.get("text"):- text_parts.append(str(block["text"]))- if block.get("type") == "image" and block.get("imageId"):- image_ids.append(str(block["imageId"]))- images = []- for image_id in image_ids or list(image_map):- image = image_map.get(image_id)- if not isinstance(image, dict) or not image.get("originalUrl"):- continue- images.append({- "id": image_id,- "name": f"图片 {len(images)+1}",- "url": str(image["originalUrl"]),- "thumb_url": str(image.get("thumbnailUrl") or image["originalUrl"]),- "media_kind": "image",- "resource_provider": "fanbox",- })- text = "\n".join(text_parts)- return {"summary": _plain_text(text), "links": resource_links(text),- "images": tuple(images)}+ if post.get("isRestricted") or int(post.get("feeRequired") or 0) > 0:+ raise FollowSourceError("fanbox 帖子详情不是公开免费正文")+ try:+ content = normalize_fanbox_post(post)+ except FanboxContentError as exc:+ raise FollowSourceError(str(exc)) from exc+ links = resource_links("\n".join((content.summary, *content.links)))+ return {+ "summary": _plain_text(content.summary),+ "links": links,+ "media_items": content.media_items,+ "post_type": content.post_type,+ "image_count": content.image_count,+ "video_count": content.video_count,+ "file_count": content.file_count,+ }def _visible_post_image(node) -> str | None:diff --git a/tests/test_follow_fanbox.py b/tests/test_follow_fanbox.pynew file mode 100644index 000000000..b93af7c36--- /dev/null+++ b/tests/test_follow_fanbox.py@@ -0,0 +1,108 @@+"""FANBOX public post body normalization tests."""+import unittest++from peach.fanbox import FanboxContentError, normalize_fanbox_post+from peach.follow_sources import resource_links+++class FanboxNormalizerTests(unittest.TestCase):+ def test_article_keeps_block_order_and_collects_all_maps(self):+ post = {"type": "article", "body": {+ "blocks": [+ {"type": "header", "text": "Release"},+ {"type": "p", "text": "Gofile", "links": [+ {"offset": 0, "length": 6, "url": "https://gofile.io/d/abc"},+ ]},+ {"type": "image", "imageId": "one"},+ {"type": "file", "fileId": "movie"},+ {"type": "embed", "embedId": "youtube"},+ {"type": "url_embed", "urlEmbedId": "card"},+ ],+ "imageMap": {+ "one": {"originalUrl": "https://downloads.fanbox.cc/one.jpg",+ "thumbnailUrl": "https://downloads.fanbox.cc/one-thumb.jpg"},+ "unused": {"originalUrl": "https://downloads.fanbox.cc/unused.png"},+ },+ "fileMap": {+ "movie": {"name": "movie.mp4", "url":+ "https://downloads.fanbox.cc/movie.mp4", "mimeType": "video/mp4"},+ "archive": {"name": "source.zip", "url":+ "https://downloads.fanbox.cc/source.zip",+ "mimeType": "application/zip"},+ },+ "embedMap": {"youtube": {"serviceProvider": "youtube",+ "videoId": "video-id"}},+ "urlEmbedMap": {"card": {"type": "html.card", "html":+ '<a href="https://pixeldrain.com/u/card">card</a>'}},+ }}++ content = normalize_fanbox_post(post)++ self.assertEqual(content.post_type, "article")+ self.assertEqual(content.summary, "Release\nGofile")+ self.assertEqual(+ [item["url"] for item in content.media_items],+ ["https://downloads.fanbox.cc/one.jpg",+ "https://downloads.fanbox.cc/movie.mp4",+ "https://downloads.fanbox.cc/unused.png"],+ )+ self.assertEqual((content.image_count, content.video_count, content.file_count),+ (2, 1, 2))+ self.assertIn("https://www.youtube.com/watch?v=video-id", content.links)+ self.assertEqual(resource_links("\n".join(content.links)), [+ "https://gofile.io/d/abc",+ "https://downloads.fanbox.cc/movie.mp4",+ "https://pixeldrain.com/u/card",+ "https://downloads.fanbox.cc/source.zip",+ ])++ def test_image_post_exposes_a_switchable_gallery(self):+ content = normalize_fanbox_post({"type": "image", "body": {"images": [+ {"id": "one", "originalUrl": "https://downloads.fanbox.cc/one.jpg",+ "thumbnailUrl": "https://downloads.fanbox.cc/one-thumb.jpg"},+ {"id": "two", "originalUrl": "https://downloads.fanbox.cc/two.png"},+ ]}})++ self.assertEqual(content.image_count, 2)+ self.assertEqual([item["id"] for item in content.media_items], ["one", "two"])+ self.assertTrue(all(item["media_kind"] == "image"+ for item in content.media_items))++ def test_file_post_keeps_playable_files_and_links_the_archive(self):+ content = normalize_fanbox_post({"type": "file", "body": {"files": [+ {"id": "video", "name": "clip.webm", "url":+ "https://downloads.fanbox.cc/clip.webm", "mimeType": "video/webm"},+ {"id": "image", "name": "cover", "url":+ "https://downloads.fanbox.cc/cover", "mimeType": "image/png"},+ {"id": "zip", "name": "source.zip", "url":+ "https://downloads.fanbox.cc/source.zip", "mimeType": "application/zip"},+ ]}})++ self.assertEqual((content.image_count, content.video_count, content.file_count),+ (1, 1, 3))+ self.assertEqual([item["media_kind"] for item in content.media_items],+ ["video", "image"])+ self.assertEqual(resource_links("\n".join(content.links)), [+ "https://downloads.fanbox.cc/clip.webm",+ "https://downloads.fanbox.cc/cover",+ "https://downloads.fanbox.cc/source.zip",+ ])++ def test_legacy_html_collects_text_links_and_images(self):+ content = normalize_fanbox_post({"type": "entry", "body": {"html": """+ <h2>Old post</h2>+ <a href="https://gofile.io/d/old">files</a>+ <img data-src-original="https://downloads.fanbox.cc/old.jpg">+ """}})++ self.assertIn("Old post", content.summary)+ self.assertIn("https://gofile.io/d/old", content.links)+ self.assertEqual(content.image_count, 1)++ def test_unknown_type_fails_loudly(self):+ with self.assertRaisesRegex(FanboxContentError, "类型不受支持"):+ normalize_fanbox_post({"type": "future-shape", "body": {}})+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex cbede9e5d..1545da04e 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -114,7 +114,7 @@ FANBOX_JSON = json.dumps({"body": {"posts": ["publishedDatetime": "2026-08-20T00:00:00+09:00", "isRestricted": True},]}}).encode()-FANBOX_DETAIL_JSON = json.dumps({"body": {"post": {"body": {+FANBOX_DETAIL_JSON = json.dumps({"body": {"post": {"type": "article", "body": {"blocks": [{"type": "p", "text": "gofile - https://gofile.io/d/OS2Qz9"},{"type": "image", "imageId": "one"},@@ -173,6 +173,10 @@ class OfficialConnectorTests(unittest.TestCase):self.assertEqual(len(result.candidates[0].extra["media_items"]), 2)self.assertEqual(result.candidates[0].extra["links"],["https://gofile.io/d/OS2Qz9"])+ self.assertEqual(result.candidates[0].extra["post_type"], "article")+ self.assertEqual(result.candidates[0].extra["image_count"], 2)+ self.assertEqual(result.candidates[0].extra["video_count"], 0)+ self.assertEqual(result.candidates[0].extra["file_count"], 0)self.assertEqual(result.probed, 1)def test_fanbox_routes_only_post_info_through_the_browser_transport(self):