Peach: Local-first video metadata scraper and media manager.
feat(follow): SimpCity 线程凭用户自己的登录 cookie 追更
longmeidao7558b9bf88bc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55bcc90ed..5e2d9c1f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,10 @@ Removed / Fixed / Security。## [未发布]+### 新增++- **关注**:SimpCity 线程可以作为关注来源。站点不让游客读帖,需要把你自己的登录 Cookie 写进凭据文件;Peach 不解任何机器人质询。+## [0.30.0] - 2026-09-08### 新增diff --git a/README.en.md b/README.en.mdindex 9e8f73d19..07974935d 100644--- a/README.en.md+++ b/README.en.md@@ -36,7 +36,7 @@ Peach is a single-user, local-first media system. Search, play and organize mediLocal disks alone work. 115 and PikPak arrive as folders mounted by CloudDrive: sign in and mount them there first, then add the folders to Peach. See [CloudDrive tuning](docs/CLOUDDRIVE.md) for cache and read-length settings.-Follow sources include FANBOX, Patreon, SubscribeStar, Kemono, Pawchive, Coomer, the Rule34 family and F95zone. Availability depends on the site and your access rights. See [source collection](docs/SOURCING.md) for supported workflows and boundaries.+Follow sources include FANBOX, Patreon, SubscribeStar, Kemono, Pawchive, Coomer, the Rule34 family, F95zone and SimpCity (needs your own login cookie). Availability depends on the site and your access rights. See [source collection](docs/SOURCING.md) for supported workflows and boundaries.Interface preferences are saved in the current browser and live under Settings: default sort, official covers or preview images for JAV works, autoplay when details open, and SFW mode, which blurs, desaturates and dims images and video and stops hover previews.diff --git a/README.md b/README.mdindex 9adfbbe77..bcdd79a47 100644--- a/README.md+++ b/README.md@@ -36,7 +36,7 @@ Peach 是单用户、本地优先的个人媒体系统。在自己的电脑上媒体来源可以只用本地磁盘,也可以接 CloudDrive 挂出的 115 与 PikPak:先在 CloudDrive 登录并挂载,再把文件夹交给 Peach 索引。缓存和读取长度怎么填见 [CloudDrive 配置与调优](docs/CLOUDDRIVE.md)。-关注来源包括 FANBOX、Patreon、SubscribeStar,以及 Kemono、Pawchive、Coomer、Rule34 系列与 F95zone。来源可用性受站点和使用者权限限制;采集边界与支持情况见 [来源采集](docs/SOURCING.md)。+关注来源包括 FANBOX、Patreon、SubscribeStar,以及 Kemono、Pawchive、Coomer、Rule34 系列、F95zone 与 SimpCity(需要你自己的登录 cookie)。来源可用性受站点和使用者权限限制;采集边界与支持情况见 [来源采集](docs/SOURCING.md)。界面偏好保存在当前浏览器,在右上角「设置」里改:默认排序、JAV 封面用官方封面还是预览图、打开详情是否自动播放,以及把图像模糊降饱和、关掉悬停预览的「SFW 模式」。diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.mdindex 69434f47d..c4023b99f 100644--- a/docs/PRODUCT_BACKLOG.md+++ b/docs/PRODUCT_BACKLOG.md@@ -23,7 +23,7 @@1. **寻找更好版本**:已经能逐条标记「高清 / 无水印 / 完整版」等目标;后续仍需相似内容匹配、候选去重、来源发现和人工替换确认。2. **现代自适应播放**:Video.js、Range、统计面板和面向 115/PikPak 原生 MP4 的按需 HLS 清单已经上线;自适应码率、多路清单、快速首帧和来源层大块预取优化仍未完成。-3. **在线追更**:`src/peach/follow_providers.py` 登记的十一个来源(FANBOX、SubscribeStar、Patreon、Kemono、Pawchive、Coomer、Rule34Video、Rule34.xxx、Rule34 Paheal、F95zone、SimpCity)、WIP/alt/跨站重复判定、`follow_source`/`follow_item`、看的 `/follow` 与管的 `/follow-manage` 两个页面已上线,writer 用 APScheduler 按设置自动轮询,在线资产可就地播放。仍缺的是下载落地(凭据、流量与磁盘预算未定,见下面「待执行的操作」第 12 条)和 simpcity 的可用入口(DDoS-Guard,未取得)。+3. **在线追更**:`src/peach/follow_providers.py` 登记的十一个来源(FANBOX、SubscribeStar、Patreon、Kemono、Pawchive、Coomer、Rule34Video、Rule34.xxx、Rule34 Paheal、F95zone、SimpCity)、WIP/alt/跨站重复判定、`follow_source`/`follow_item`、看的 `/follow` 与管的 `/follow-manage` 两个页面已上线,writer 用 APScheduler 按设置自动轮询,在线资产可就地播放。仍缺的是下载落地(凭据、流量与磁盘预算未定,见下面「待执行的操作」第 12 条);SimpCity 已能凭用户自己的登录 cookie 发现更新,但帖子里的图站图片与网盘链接只登记不代理,就地查看仍未接。4. **首尾帧出处与不完整候选**:已有受限 FFmpeg 首尾抽帧、Windows 内置 OCR、证据帧缓存、来源/Full version 候选和 `/review`;仍需决定全库批次范围,并把用户批准后的不完整版判断接到更好版本目标。5. **厂牌 Logo 补齐与持续校验**:14 个已确认社交 handle 已有内容缓存、provenance、精确/感知哈希、质量与重复门槛及健康报告;仍有 72 个厂牌没有可信 handle,必须继续从官网/公开来源取证,不能猜账号。6. **口味证据持续刷新**:ledger 已实时记录搜索、播放、高潮、喜欢/理由、不合口味和稍后看;浏览器历史现可用 SQLite 一致性副本增量进入私有源库,并生成不含 URL/标题的 creator/tag candidate 与聚合报告。旧 2026-08-13 原始包已确认不在 Windows 外置盘;仍需在 Mac 开启 iCloud Safari、完成首次导入,并把两端每周刷新装成系统计划任务。AI 结论不得直接改真相字段。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 4d0e794a7..f5ffe1ec9 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -189,7 +189,8 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP| 本机文件夹对话框 | Windows 自带 `powershell.exe` 经 `Add-Type` 调 Shell 的 `IFileOpenDialog`(带地址栏的文件夹选择框);macOS `osascript` 的 `choose folder` | `src/peach/folder_picker.py` 只拼命令、区分取消与失败、一次只开一个;不为一个对话框引入 tkinter 或 GUI 框架 || HTTP | 默认复用全项目共用的 `httpx.Client`/transport;FANBOX 公开 `post.info` 按固定证据复用 `curl_cffi==0.16.2` | 来源策略、DTO、脱敏、站点限定、大小上限;不求解机器人质询 || RSS/Atom | `feedparser` | 有界抓取、快照、复核、导入 |-| 追更来源接口 | FANBOX 公开帖子 API(详情只使用用户自己的可选 Cookie 与 Firefox 传输特征)、kemono 系公开 JSON API(`Accept: text/css`,站点自述的抓取路径)、rule34.xxx 官方 dapi(需账号 API key)与官方 tag 补全(公开)、Paheal 标签/详情页、Gofile contents API(需 Premium 账号 API token)、f95zone `latest_data.php`、站内搜索(需登录 cookie)、线程页与站内 masked XHR | 连接器边界、凭据隔离、多媒体顺序、文件站目标校验、变体与跨站重复判定、候选复核与批准后的 online asset 投影 |+| 追更来源接口 | FANBOX 公开帖子 API(详情只使用用户自己的可选 Cookie 与 Firefox 传输特征)、kemono 系公开 JSON API(`Accept: text/css`,站点自述的抓取路径)、rule34.xxx 官方 dapi(需账号 API key)与官方 tag 补全(公开)、Paheal 标签/详情页、Gofile contents API(需 Premium 账号 API token)、f95zone `latest_data.php`、站内搜索(需登录 cookie)、线程页与站内 masked XHR、simpcity 线程页(需登录 cookie;只请求规范地址,不解 DDoS-Guard 质询) | 连接器边界、凭据隔离、多媒体顺序、文件站目标校验、变体与跨站重复判定、候选复核与批准后的 online asset 投影 |+| XenForo 论坛解析 | gallery-dl `v1.32.11` / `2adf2a8e`(GPL-2.0)的 `extractor/xenforo.py` 只作协议证据:登录先查 cookie 再走账号密码、`article[data-content]` 楼层、`.pageNav` 分页、`data-s9e-mediaembed` 嵌入;cyberdrop-dl `5.6.21`(GPL-3.0,2024-09 起按站方要求下线 SimpCity)只作历史参照。两者都是完整下载器,不引入运行时 | f95zone 与 simpcity 共用一份 `_xenforo_posts` / `_xenforo_thread_title`;Peach 自己负责 cookie 只发回来源站、末页由分页导航自算(HTTPX 跟随重定向会丢显式 Cookie)、纯讨论楼层过滤与 release 语义。gallery-dl 把 simpcity 登录 cookie 名写死为 `ogaddgmetaprof_user`,而站点前缀已轮换为 `yMziCv8BrCZz1o7_`,所以 Peach 不认 cookie 名、只透传整条 Cookie 头 || HTML 适配器 | Beautiful Soup 或 selectolax | 来源专用选择器和来源记录 || 位图 | Pillow | 头像/Logo 质量和来源策略 || SVG 光栅化 | `resvg-py==0.5.0`(resvg,MPL-2.0 绑定) | 只用于把站点自己的矢量图标转成位图再交给 Pillow。2026-09-02 实测 threads 的成品 app 图标只以 SVG 形式提供,不光栅化就只能退回位图 favicon。选它而不是 cairosvg:后者在 Windows 上要另装 cairo 原生库,前者是 abi3 轮子,win_amd64 / macosx_11_0_arm64 / macosx_10_12_x86_64 都有官方预编译,两个平台都不必装系统依赖。候选发现、内容比例判定、缓存与失败回退仍在 Peach。 |diff --git a/docs/adr/0019-site-follow-connectors-and-variant-grouping.md b/docs/adr/0019-site-follow-connectors-and-variant-grouping.mdindex 636bc33fb..8b8cabd66 100644--- a/docs/adr/0019-site-follow-connectors-and-variant-grouping.md+++ b/docs/adr/0019-site-follow-connectors-and-variant-grouping.md@@ -26,8 +26,10 @@ rule34.xxx 上。不区分这三种关系,界面就只是一堆重复条目。- 联网只在显式调用时发生:CLI 的 `peach follow check` 和 Web 的`POST /api/follow/check`。服务启动、健康检查、普通浏览和首页「换一批」都不联网。- **不求解任何机器人质询。** rule34.xxx 网页版挂着 Cloudflare Turnstile,因此只走官方- dapi 并要求账号自己的 API key;simpcity.cr 挂着 DDoS-Guard 浏览器质询,连接器只登记- 不可用并原样报出原因,不做质询求解。FANBOX 公开 `post.info` 是一个有证据的窄例外:+ dapi 并要求账号自己的 API key;simpcity.cr 前面是 DDoS-Guard,2026-09-08 实测它对标准+ 桌面 UA 不出质询,帖子页 403 是站点「游客不可读帖」的规则,所以连接器要求用户自己的+ 登录 cookie,cookie 失效就原样报 403,不换指纹、不解质询。FANBOX 公开 `post.info`+ 是一个有证据的窄例外:普通 HTTPX 与地址栏会返回 403 或 `general_error`,而同一公开请求携带用户自己的可选Cookie 并保留 Firefox TLS/HTTP2 特征可得到原始 JSON。它不执行浏览器脚本、不解质询、不登录,也仍只收 `feeRequired=0`、`isRestricted=false` 的免费帖子。@@ -97,7 +99,7 @@ rule34.xxx 上。不区分这三种关系,界面就只是一堆重复条目。| rule34video.com | `/models/{slug}/` | 无 | KVS 引擎无公开 API;`.time` 是时长、`.added` 是相对提交时间、`[data-preview]` 是预览片 || rule34.xxx | `https://api.rule34.xxx/index.php?page=dapi&s=post&q=index` | user_id + api_key | 网页版挂 Turnstile;无 key 时 API 返回 `Missing authentication`。**2026-08-26 用真实 key 复核**(见下) || f95zone.to | `/threads/{id}/latest` + `latest_alpha/latest_data.php` | 发现不需要,取媒体需要 | 主贴版本号滞后于回复;`index.rss` 返回「无法以该格式呈现」;`h1.p-title-value` 去掉 `.label` 才是线程标题 |-| simpcity.cr | — | — | DDoS-Guard 浏览器质询,**未取得**可用入口 |+| simpcity.cr | `/threads/{id}/` 取分页导航,再读 `page-N` | 必需登录 cookie | 2026-09-08 实测:无 cookie 时首页、版块、登录页 200,帖子页 403「You don't have access to this page」;带 cookie 帖子页 200 且 `data-logged-in="true"`。`/latest` 与纯数字线程地址都会 30x 到带 slug 的规范地址,HTTPX 跟随重定向会丢显式 `Cookie` 头,所以传输层自己跟同源重定向。图片是 `img.bbImage`(`data-url` 原图、`src` 缩略图),分页在 `.pageNav-page a[href]` || fanbox.cc | `api.fanbox.cc/post.listCreator` + `post.info` | 详情可选用户 Cookie | 2026-08-27 实测列表 JSON 给出 `feeRequired`、`isRestricted`、标题、时间和封面;2026-08-28 复核详情需要 Firefox 传输特征,InitialA 的 10 条列表样本均为免费公开 || subscribestar.adult | `/{creator}` | 无 | 2026-08-27 实测公开 HTML 含 `div.post[data-id]`、帖子链接、标题和时间;InitialA 页面明确声明内容公开免费 || patreon.com | `/cw/{creator}` | 无 | 2026-08-27 实测公开页服务端渲染最新帖子卡片;官方 posts API 需 `campaigns.posts` OAuth scope |diff --git a/src/peach/follow_secrets.py b/src/peach/follow_secrets.pyindex 8c9f147c6..20dde21d8 100644--- a/src/peach/follow_secrets.py+++ b/src/peach/follow_secrets.py@@ -212,9 +212,14 @@ CREDENTIAL_GUIDE: dict[str, dict] = {"howto": "登录后从浏览器复制整条 Cookie 请求头,写进凭据文件的 cookie 字段。",},"simpcity": {- "requirement": "blocked",- "why": "站点由 DDoS-Guard 的浏览器质询保护,放行绑客户端 IP 且最短 20 分钟过期,"- "撑不起定时追更。Peach 不绕机器人验证。",+ "requirement": "required",+ "fields": ["cookie"],+ # 登录会话绑浏览器与 DDoS-Guard 的放行记录,同步到另一台大概率直接失效——不同步。+ "syncable": [],+ "why": "站点不让游客读帖,检查更新必须带登录会话;前面的 DDoS-Guard 对标准桌面浏览器"+ "标识不出质询,Peach 也不解任何质询,cookie 失效就原样报错。",+ "where": "https://simpcity.cr/",+ "howto": "登录后从浏览器复制整条 Cookie 请求头,写进凭据文件的 cookie 字段。",},}diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex 8b10cc70f..358a48f2a 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -1559,6 +1559,41 @@ class Rule34PahealConnector(_BaseConnector):return " · ".join(values[:5])+def _xenforo_thread_title(soup) -> str | None:+ """取 XenForo 线程页的 `h1.p-title-value` 并去掉前缀标签。++ `<title>` 会被站点拼上栏目名和站名,og:title 同样带前缀,只有 h1 里的+ `.label` 是可以精确摘掉的结构。f95zone 与 simpcity 都是 XenForo,这段只写一份。+ """+ heading = soup.select_one("h1.p-title-value")+ if heading is None:+ return None+ for label in heading.select(".label, .labelLink"):+ label.extract()+ return plain_text(heading.get_text(" "))+++def _xenforo_posts(soup, limit: int):+ """XenForo 线程页里最后 `limit` 个楼层,逐个给出 `(article, post_id, time, body)`。++ 引用块在这里就剥掉。XenForo 把被引用的楼层原样嵌在正文里,不剥的话摘要会变成+ 「某某 said: … Click to expand…」,而引用里的下载链接还会被算成这条回复自己发的——+ 追更判断因此指向错误的楼层。+ """+ posts = soup.select('article[data-content^="post-"]')+ for article in posts[-limit:]:+ content = str(article.get("data-content") or "")+ post_id = content.removeprefix("post-")+ if not post_id.isdigit():+ continue+ time_node = article.select_one("time")+ body = article.select_one(".bbWrapper")+ if body is not None:+ for quote in body.select("blockquote, .bbCodeBlock, .js-expandWatch"):+ quote.extract()+ yield article, post_id, time_node, body++class F95ZoneConnector(_BaseConnector):"""f95zone.to 的线程追更。@@ -1617,7 +1652,7 @@ class F95ZoneConnector(_BaseConnector):if response is None:return SourceFetch(not_modified=True, **common)soup = BeautifulSoup(response.body, "html.parser")- title = self._thread_title(soup)+ title = _xenforo_thread_title(soup)candidates, parsed, skipped = self._replies(soup, thread, title or f"thread {thread}")if not parsed:@@ -1637,39 +1672,12 @@ class F95ZoneConnector(_BaseConnector):return SourceFetch(candidates=tuple(enriched), skipped=skipped,raw_body=response.body, **common)- @staticmethod- def _thread_title(soup) -> str | None:- """取 `h1.p-title-value` 并去掉前缀标签。-- `<title>` 会被站点拼上栏目名和站名,og:title 同样带前缀,只有 h1 里的- `.label` 是可以精确摘掉的结构。- """- heading = soup.select_one("h1.p-title-value")- if heading is None:- return None- for label in heading.select(".label, .labelLink"):- label.extract()- return plain_text(heading.get_text(" "))-def _replies(self, soup, thread: str, thread_title: str):- posts = soup.select('article[data-content^="post-"]')candidates: list[FollowCandidate] = []parsed = 0skipped = 0- for article in posts[-self.max_items:]:- content = str(article.get("data-content") or "")- post_id = content.removeprefix("post-")- if not post_id.isdigit():- continue+ for article, post_id, time_node, body in _xenforo_posts(soup, self.max_items):parsed += 1- time_node = article.select_one("time")- body = article.select_one(".bbWrapper")- # XenForo 把被引用的楼层原样嵌在正文里。不剥掉的话,摘要会变成- # 「某某 said: … Click to expand…」,而引用里的下载链接还会被算成这条- # 回复自己发的——追更判断因此指向错误的楼层。- if body is not None:- for quote in body.select("blockquote, .bbCodeBlock, .js-expandWatch"):- quote.extract()links = [str(node.get("href")) for node in (body.select("a[href]") if body else [])if str(node.get("href", "")).startswith("http")@@ -1846,7 +1854,7 @@ class F95ZoneConnector(_BaseConnector):if found is None or found.group(1) in seen:continueseen.add(found.group(1))- # 标题前挂着 `Collection`、`Pinup` 这类前缀标签,和 `_thread_title` 一样摘掉。+ # 标题前挂着 `Collection`、`Pinup` 这类前缀标签,和 `_xenforo_thread_title` 一样摘掉。for label in link.select(".label, .labelLink, .label-append"):label.extract()# 命中的词被 `<em class="textHighlight">` 包着,按分隔符取文本会把@@ -2232,25 +2240,193 @@ class PatreonConnector(_BaseConnector):class SimpCityConnector(_BaseConnector):- """simpcity.cr 目前挂着 DDoS-Guard 的浏览器质询。+ """simpcity.cr 的线程追更。++ 站点前面是 DDoS-Guard。2026-09-08 实测它对 Peach 的标准桌面 UA 不出质询:首页、+ 版块列表和登录页在无 cookie 下直接 200。帖子页 403 不是机器人拦截,而是站点+ 「游客不可读帖」的访问规则——所以这里**必须**带用户自己的登录 cookie,而 Peach+ 仍然不解任何质询:cookie 不对就把 403 原样报出来,不重试、不换指纹。++ **只请求不重定向的规范地址。** XenForo 的 `/latest` 会 303 到末页,而 HTTPX 跟随+ 重定向时会丢掉显式的 `Cookie` 头:同一份 cookie 直接请求目标页是 200,经重定向+ 到达就是 403(2026-09-08 实测)。所以末页由自己算——先读第一页的分页导航取末页号,+ 末页不是第一页时再读 `page-N`;一次检查最多两个请求。- Peach 不绕机器人验证,所以这个连接器只登记不可用,并把原因原样报出来。+ cookie 只发回 simpcity.cr。帖子里的图站与网盘链接只记录,不在这里去取。+ `ref` 是线程 id,例如 `21229`。"""provider = "simpcity"- blocked_reason = (- "simpcity.cr 由 DDoS-Guard 的浏览器质询保护;Peach 不绕机器人验证。"- "要接入需要你在浏览器里通过质询后提供会话 cookie,或改用其他来源。")+ HOST = "simpcity.cr"+ _THREAD_RE = re.compile(r"^\d{1,12}$")+ _PAGE_HREF_RE = re.compile(r"/page-(\d+)(?:[?#]|$)")+ _ATTACHMENT_PATH_RE = re.compile(r"^/attachments/[^/?#]+/?$", re.IGNORECASE)@classmethoddef parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,host: str) -> "ParsedSource":- # 整站被质询挡着,登记下来也抓不到;当场说原因比留一条死来源好。- raise FollowSourceError(cls.blocked_reason)+ path = parsed.path or "/"+ matched = _THREAD_PATH_RE.match(path)+ if not matched:+ raise FollowSourceError(+ "simpcity 的链接要指向一个线程,形如 "+ "https://simpcity.cr/threads/xxx.21229/")+ thread = matched.group(1)+ segment = path.split("/threads/", 1)[1].split("/", 1)[0]+ slug = segment.rsplit(".", 1)[0] if "." in segment else ""+ return ParsedSource("simpcity", thread,+ f"https://{cls.HOST}/threads/{thread}/",+ _slug_label(slug) or f"线程 {thread}")++ def _cookie(self) -> str:+ if self.credential is None:+ raise CredentialError(+ "simpcity 需要登录 cookie:站点不让游客读帖。登录后把浏览器里 "+ "simpcity.cr 的整条 Cookie 请求头写进凭据文件的 cookie 字段。")+ return self.credential.require("cookie")[0]++ def _check_status(self, response: HttpResponse) -> None:+ if response.status == 403:+ raise FollowSourceError(+ "simpcity 拒绝访问(HTTP 403):站点不让游客读帖,cookie 可能已过期或"+ "不完整,请重新登录后更新凭据文件")+ super()._check_status(response)def fetch(self, ref: str, *, etag: str | None = None,last_modified: str | None = None, page: int = 0) -> SourceFetch:- raise FollowSourceError(self.blocked_reason)+ thread = (ref or "").strip()+ if not self._THREAD_RE.match(thread):+ raise FollowSourceError(f"simpcity 的 ref 必须是线程 id,收到:{ref!r}")+ headers = {"Accept": "text/html", "Cookie": self._cookie()}+ base = f"https://{self.HOST}/threads/{thread}/"+ # 第一页不带条件请求头:新回复长在末页,第一页没变不代表线程没更新。+ common, response = self._request(base, ref=thread, headers=headers)+ soup = self._page(response)+ target = self._last_page(soup) - int(page or 0)+ if target < 1:+ raise FollowHistoryEnd("没有更多历史内容")+ if target != 1:+ common, response = self._request(+ f"{base}page-{target}", ref=thread, etag=etag,+ last_modified=last_modified, page=page, headers=headers)+ if response is None:+ return SourceFetch(not_modified=True, **common)+ soup = self._page(response)+ title = _xenforo_thread_title(soup) or f"thread {thread}"+ candidates, parsed, skipped = self._posts(soup, thread, title, target)+ if not parsed:+ raise FollowSourceError("simpcity 线程页没有解析出任何楼层:页面结构可能已变")+ return SourceFetch(candidates=tuple(candidates), skipped=skipped,+ raw_body=response.body, **common)++ @staticmethod+ def _page(response: HttpResponse):+ """解析一页并确认站点认出了登录态。++ 游客态的帖子页是 403;能拿到 200 却写着 `data-logged-in="false"` 只会发生在+ cookie 被部分接受时,这时候正文是残缺的,与其解析出一堆「什么都没有」不如+ 直接说 cookie 没被认出。+ """+ soup = BeautifulSoup(response.body, "html.parser")+ root = soup.find("html")+ if root is not None and str(root.get("data-logged-in") or "").lower() == "false":+ raise FollowSourceError(+ "simpcity 没有认出这份 cookie(页面仍是游客态):请重新登录后复制整条 "+ "Cookie 请求头")+ return soup++ @classmethod+ def _last_page(cls, soup) -> int:+ """分页导航里最大的页号;单页线程没有导航,就是第 1 页。"""+ last = 1+ for node in soup.select(".pageNav-page a[href]"):+ matched = cls._PAGE_HREF_RE.search(str(node.get("href") or ""))+ if matched:+ last = max(last, int(matched.group(1)))+ return last++ def _posts(self, soup, thread: str, title: str, page_number: int):+ candidates: list[FollowCandidate] = []+ parsed = 0+ skipped = 0+ for article, post_id, time_node, body in _xenforo_posts(soup, self.max_items):+ parsed += 1+ images = self._images(body)+ file_links: list[str] = []+ for node in (body.select("a[href]") if body else []):+ link = str(node.get("href") or "")+ if _is_resource_url(link) and link not in file_links:+ file_links.append(link)+ attachments = self._attachments(body)+ embeds = len(body.select("[data-s9e-mediaembed], .bbMediaWrapper iframe")) \+ if body else 0+ # 图、网盘、附件、嵌入播放器四样都没有的楼层是纯讨论,不进追更。+ if not (images or file_links or attachments or embeds):+ skipped += 1+ continue+ media_url = file_links[0] if file_links else (images[0][0] if images else None)+ candidates.append(FollowCandidate(+ provider=self.provider,+ external_id=post_id,+ title=title,+ url=f"https://{self.HOST}/threads/{thread}/post-{post_id}",+ media_url=media_url,+ thumb_url=images[0][1] if images else None,+ published_at=_iso_from_text(time_node.get("datetime"))+ if time_node is not None else None,+ author=plain_text(str(article.get("data-author") or "")) or None,+ summary=(plain_text(body.get_text(" ")) or None) if body else None,+ extra={"thread_id": thread, "page": page_number,+ "images": [full for full, _ in images[:40]],+ "image_count": len(images),+ "links": file_links[:8], "link_count": len(file_links),+ "attachments": attachments[:8],+ "attachment_count": len(attachments),+ "embed_count": embeds},+ ))+ return candidates, parsed, skipped++ @classmethod+ def _images(cls, body) -> list[tuple[str, str]]:+ """正文里的图片:`(原图, 缩略图)`。++ 2026-09-08 实测:图片是 `img.bbImage`,`data-url` 指原图、`src` 指缩略图,+ 外面套着图站页面的链接。表情是 `img.smilie`,不带 bbImage,选择器天然排除。+ """+ if body is None:+ return []+ result: list[tuple[str, str]] = []+ seen: set[str] = set()+ for node in body.select("img.bbImage"):+ full = str(node.get("data-url") or node.get("data-src") or node.get("src") or "")+ thumb = str(node.get("src") or full)+ if not full.startswith("https://") or full in seen:+ continue+ host = (urllib.parse.urlsplit(full).hostname or "").casefold()+ if host == cls.HOST or host.endswith("." + cls.HOST):+ continue+ seen.add(full)+ result.append((full, thumb if thumb.startswith("https://") else full))+ return result++ @classmethod+ def _attachments(cls, body) -> list[str]:+ """站内附件链接,统一写成绝对地址;取附件同样需要登录,这里只登记。"""+ if body is None:+ return []+ found: list[str] = []+ for node in body.select("a[href]"):+ value = str(node.get("href") or "").strip()+ if value.startswith("/"):+ value = f"https://{cls.HOST}{value}"+ try:+ parsed = urllib.parse.urlsplit(value)+ except ValueError:+ continue+ if (parsed.scheme == "https" and parsed.hostname == cls.HOST+ and cls._ATTACHMENT_PATH_RE.match(parsed.path) and value not in found):+ found.append(value)+ return founddef parse_source_url(raw_url: str) -> ParsedSource:diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex ca153029f..efc34e31f 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -185,6 +185,62 @@ PATREON_HTML = b"""<html><body><div class="card"><a href="https://www.patreon.com/sample/posts/new-public-work-167576581">duplicate</a></div></body></html>"""+# 属性名与 DOM 形状取自 2026-09-08 对 simpcity.cr 真实线程页的实测:`img.bbImage` 的+# `data-url` 是原图、`src` 是缩略图,分页在 `.pageNav-page a[href]`,表情是 `img.smilie`。+# 内容本身是编的。+SIMPCITY_FIRST_HTML = b"""<html data-logged-in="true" data-cookie-prefix="yMziCv8BrCZz1o7_">+<head><title>Sample Creator | SimpCity Forums</title></head><body>+<h1 class="p-title-value"><span class="label">OnlyFans</span> Sample Creator</h1>+<nav class="pageNav"><ul class="pageNav-main">+<li class="pageNav-page pageNav-page--current"><a href="/threads/sample-creator.4242/">1</a></li>+<li class="pageNav-page"><a href="/threads/sample-creator.4242/page-2">2</a></li>+<li class="pageNav-page pageNav-page--skipEnd"><a href="/threads/sample-creator.4242/page-7">7</a></li>+</ul></nav>+<article data-content="post-100" data-author="opener">+ <time datetime="2026-01-01T10:00:00+0000">Jan 1, 2026</time>+ <div class="bbWrapper">First page post+ <a href="https://imgpage.test/img/first"><img class="bbImage"+ src="https://cdn.imgpage.test/first.md.jpg" data-url="https://cdn.imgpage.test/first.jpg"></a>+ </div>+</article>+</body></html>"""++SIMPCITY_LAST_HTML = b"""<html data-logged-in="true" data-cookie-prefix="yMziCv8BrCZz1o7_">+<head><title>Sample Creator | SimpCity Forums</title></head><body>+<h1 class="p-title-value"><span class="label">OnlyFans</span> Sample Creator</h1>+<nav class="pageNav"><ul class="pageNav-main">+<li class="pageNav-page"><a href="/threads/sample-creator.4242/">1</a></li>+<li class="pageNav-page pageNav-page--current"><a href="/threads/sample-creator.4242/page-7">7</a></li>+</ul></nav>+<article data-content="post-700" data-author="uploader1">+ <time datetime="2026-09-07T10:00:00+0000">Sep 7, 2026</time>+ <div class="bbWrapper">New set+ <a href="https://imgpage.test/img/abc"><img class="bbImage"+ src="https://cdn.imgpage.test/abc.md.jpg" data-url="https://cdn.imgpage.test/abc.jpg"></a>+ <a href="https://imgpage.test/img/def"><img class="bbImage"+ src="https://cdn.imgpage.test/def.md.jpg" data-url="https://cdn.imgpage.test/def.jpg"></a>+ <img class="smilie smilie--emoji" src="https://cdn.jsdelivr.net/emoji.png">+ <a href="https://gofile.io/d/abc123">Gofile</a>+ </div>+</article>+<article data-content="post-701" data-author="replier">+ <time datetime="2026-09-07T11:00:00+0000">Sep 7, 2026</time>+ <div class="bbWrapper"><blockquote class="bbCodeBlock">uploader1 said:+ <a href="https://gofile.io/d/abc123">Gofile</a> Click to expand...</blockquote>+ thanks!</div>+</article>+<article data-content="post-702" data-author="uploader2">+ <time datetime="2026-09-07T12:00:00+0000">Sep 7, 2026</time>+ <div class="bbWrapper">Attachment and player only+ <a href="/attachments/clip-mp4.9001/">clip.mp4</a>+ <div class="bbMediaWrapper"><iframe src="https://player.test/e/xyz"></iframe></div>+ </div>+</article>+</body></html>"""++SIMPCITY_GUEST_HTML = b"""<html data-logged-in="false"><body>+<h1 class="p-title-value">Sample Creator</h1></body></html>"""+class OfficialConnectorTests(unittest.TestCase):def test_fanbox_keeps_only_public_free_posts(self):@@ -1249,10 +1305,113 @@ class Rule34XxxConnectorTests(unittest.TestCase):class SimpCityConnectorTests(unittest.TestCase):- def test_blocked_source_refuses_instead_of_defeating_the_bot_check(self):+ COOKIE = Credential("simpcity", {"cookie": "yMziCv8BrCZz1o7_user=u; yMziCv8BrCZz1o7_session=s"})++ @staticmethod+ def _paged_transport(record, first=SIMPCITY_FIRST_HTML, last=SIMPCITY_LAST_HTML):+ def call(request, timeout, max_bytes):+ record.append(request)+ body = last if "/page-" in request.url else first+ return HttpResponse(200, {"ETag": '"p7"'}, body)+ return call++ def test_thread_links_resolve_to_the_thread_id(self):+ parsed = parse_source_url("https://simpcity.cr/threads/sample-creator.4242/page-3")+ self.assertEqual((parsed.provider, parsed.ref), ("simpcity", "4242"))+ self.assertEqual(parsed.url, "https://simpcity.cr/threads/4242/")+ self.assertEqual(parsed.label, "sample creator")+ self.assertEqual(parsed.semantics, "release")+ with self.assertRaises(FollowSourceError):+ parse_source_url("https://simpcity.cr/forums/onlyfans.12/")++ def test_without_a_cookie_nothing_is_requested(self):+ # 站点不让游客读帖:缺 cookie 就是「未授权」,不该先打一次 403 再说。+ seen = []+ with self.assertRaises(CredentialError) as caught:+ SimpCityConnector(transport=_transport(record=seen)).fetch("4242")+ self.assertIn("cookie", str(caught.exception))+ self.assertEqual(seen, [])++ def test_the_last_page_is_read_after_the_first_page_reveals_it(self):+ seen = []+ result = SimpCityConnector(+ credential=self.COOKIE, transport=self._paged_transport(seen),+ ).fetch("4242", etag='"old"')+ self.assertEqual([r.url for r in seen], [+ "https://simpcity.cr/threads/4242/",+ "https://simpcity.cr/threads/4242/page-7",+ ])+ # 两个请求都带 cookie;条件请求头只在末页上——第一页没变不代表线程没更新。+ self.assertTrue(all(r.headers["Cookie"] == self.COOKIE.values["cookie"] for r in seen))+ self.assertNotIn("If-None-Match", seen[0].headers)+ self.assertEqual(seen[1].headers["If-None-Match"], '"old"')+ self.assertEqual(result.request_url, "https://simpcity.cr/threads/4242/page-7")+ self.assertEqual(result.semantics, "release")+ self.assertEqual(result.etag, '"p7"')+ self.assertEqual([c.external_id for c in result.candidates], ["700", "702"])+ self.assertEqual(result.skipped, 1)++ def test_a_single_page_thread_costs_one_request(self):+ seen = []+ head, rest = SIMPCITY_LAST_HTML.split(b"<nav", 1)+ single = head + rest.split(b"</nav>", 1)[1]+ result = SimpCityConnector(+ credential=self.COOKIE, transport=_transport(body=single, record=seen),+ ).fetch("4242")+ self.assertEqual([r.url for r in seen], ["https://simpcity.cr/threads/4242/"])+ self.assertEqual(len(result.candidates), 2)++ def test_images_links_and_attachments_are_read_from_the_post_body(self):+ result = SimpCityConnector(+ credential=self.COOKIE, transport=self._paged_transport([]),+ ).fetch("4242")+ first, second = result.candidates+ self.assertEqual(first.title, "Sample Creator")+ self.assertEqual(first.url, "https://simpcity.cr/threads/4242/post-700")+ self.assertEqual(first.author, "uploader1")+ self.assertEqual(first.published_at, "2026-09-07T10:00:00Z")+ self.assertEqual(first.media_url, "https://gofile.io/d/abc123")+ self.assertEqual(first.thumb_url, "https://cdn.imgpage.test/abc.md.jpg")+ self.assertEqual(first.extra["images"],+ ["https://cdn.imgpage.test/abc.jpg", "https://cdn.imgpage.test/def.jpg"])+ self.assertEqual((first.extra["image_count"], first.extra["link_count"]), (2, 1))+ self.assertEqual(first.extra["page"], 7)+ # 表情图不是内容;被引用的网盘链接属于被引用的楼层,不算 replier 发的。+ self.assertNotIn("cdn.jsdelivr.net", str(first.extra))+ self.assertEqual(second.external_id, "702")+ self.assertIsNone(second.thumb_url)+ self.assertEqual(second.media_url, None)+ self.assertEqual(second.extra["attachments"],+ ["https://simpcity.cr/attachments/clip-mp4.9001/"])+ self.assertEqual(second.extra["embed_count"], 1)++ def test_history_pages_count_back_from_the_last_page(self):+ seen = []+ connector = SimpCityConnector(credential=self.COOKIE,+ transport=self._paged_transport(seen))+ connector.fetch("4242", page=1, etag='"old"')+ self.assertEqual(seen[1].url, "https://simpcity.cr/threads/4242/page-6")+ self.assertNotIn("If-None-Match", seen[1].headers)+ seen.clear()+ # 翻回到第 1 页时复用刚读过的第一页,不再多打一次。+ result = connector.fetch("4242", page=6)+ self.assertEqual(len(seen), 1)+ self.assertEqual([c.external_id for c in result.candidates], ["100"])+ with self.assertRaises(FollowHistoryEnd):+ connector.fetch("4242", page=7)++ def test_a_forbidden_page_blames_the_cookie_not_a_bot_check(self):+ with self.assertRaises(FollowSourceError) as caught:+ SimpCityConnector(credential=self.COOKIE,+ transport=_transport(status=403, body=b"Forbidden")).fetch("4242")+ self.assertIn("cookie", str(caught.exception))+ self.assertNotIn("机器人", str(caught.exception))++ def test_a_guest_page_means_the_cookie_was_not_recognised(self):with self.assertRaises(FollowSourceError) as caught:- SimpCityConnector().fetch("123")- self.assertIn("DDoS-Guard", str(caught.exception))+ SimpCityConnector(credential=self.COOKIE,+ transport=_transport(body=SIMPCITY_GUEST_HTML)).fetch("4242")+ self.assertIn("游客态", str(caught.exception))class OriginGroupKeyTests(unittest.TestCase):@@ -1405,11 +1564,7 @@ class ParseUrlDelegationTests(unittest.TestCase):self.assertEqual(parsed.path, "/models/abc/")def test_every_registered_connector_can_parse_its_own_links(self):- """漏写 `parse_url` 只会让那个站的链接报「暂不支持」,界面上看不出是漏写。-- simpcity 是有意的例外:整站被质询挡着,它覆盖 `parse_url` 只为把原因原样- 报出来,所以这里断言它也覆盖了,而不是跳过它。- """+ """漏写 `parse_url` 只会让那个站的链接报「暂不支持」,界面上看不出是漏写。"""for provider, factory in follow_sources.CONNECTORS.items():with self.subTest(provider=provider):self.assertIsNot(factory.parse_url.__func__,diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 0724aa629..eccd1ca53 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -938,8 +938,9 @@ class FollowContractTests(unittest.TestCase):self.assertEqual(by_provider["gofile"]["requirement"], "optional")self.assertEqual(by_provider["gofile"]["needs"], ["api_token"])self.assertTrue(by_provider["gofile"]["path"].endswith("gofile.json"))- self.assertEqual(by_provider["simpcity"]["requirement"], "blocked")- self.assertIn("DDoS-Guard", by_provider["simpcity"]["why"])+ self.assertEqual(by_provider["simpcity"]["requirement"], "required")+ self.assertEqual(by_provider["simpcity"]["needs"], ["cookie"])+ self.assertIn("游客", by_provider["simpcity"]["why"])self.assertTrue(by_provider["rule34xxx"]["path"].endswith("rule34xxx.json"))def test_a_configured_credential_reports_nothing_missing(self):@@ -1319,11 +1320,16 @@ class FollowSourceAddTests(FollowContractTests):{"action": "add", "url": "https://example.test/creator"})self.assertIn("kemono.cr", str(caught.exception))- def test_simpcity_is_refused_with_the_bot_check_reason(self):- with self.assertRaises(FollowSourceError) as caught:- self._post("/api/follow/source",- {"action": "add", "url": "https://simpcity.cr/threads/x.1/"})- self.assertIn("DDoS-Guard", str(caught.exception))+ def test_a_simpcity_thread_registers_and_the_first_check_asks_for_the_cookie(self):+ # 没有 cookie 时来源照样登记,首次检查报「未授权」而不是把整次登记回滚。+ result = self._post("/api/follow/source",+ {"action": "add", "url": "https://simpcity.cr/threads/x.4242/"})+ self.assertTrue(result["ok"])+ self.assertFalse(result["checked"]["ok"])+ self.assertEqual(result["checked"]["status"], "unauthorized")+ self.assertIn("cookie", result["checked"]["error"])+ source = self._get()["sources"][0]+ self.assertEqual((source["provider"], source["ref"]), ("simpcity", "4242"))def test_removing_a_source_takes_its_items_with_it(self):self._seed()