Peach: Local-first video metadata scraper and media manager.
feat: expand follow sources and author controls
longmeidao5d828b314c36
diff --git a/.claude/skills/peach-worktree/SKILL.md b/.claude/skills/peach-worktree/SKILL.mdindex 7a84a9be8..690d6abc8 100644--- a/.claude/skills/peach-worktree/SKILL.md+++ b/.claude/skills/peach-worktree/SKILL.md@@ -5,7 +5,7 @@ description: 在用户说并行、开工作树、worktree、暂存、提交、re# 并行 worktree 与提交边界-最后复核:2026-08-26+最后复核:2026-08-27证据来源:`docs/HANDOFF.md`「并行智能体与 Git 工作树」、`README.md`、ADR-0015、ADR-0017。## 何时使用@@ -25,19 +25,21 @@ description: 在用户说并行、开工作树、worktree、暂存、提交、re工作树机制(`.claude/worktrees/`)**:它在分支被集成后会被回收,目录却留在原地。2. 工作者只在自己的工作树内编辑。工作树不复制 `.venv`。-3. 测试在当前工作树根目录运行,每个平台只有一个入口:+3. 测试在当前工作树根目录运行,每个平台只有一个入口。日常开发先跑本功能域:```powershell- & .\scripts\test.ps1 # Windows+ & .\scripts\test.ps1 -Scope follow # Windows 示例``````bash- ./scripts/test.sh # macOS / Linux+ ./scripts/test.sh follow # macOS / Linux 示例```+ 可选域为 `follow`、`catalog`、`media`、`sync`、`metadata`、`tooling`;不传参数是 `full`。两者契约相同:从 Git common directory 定位主项目 venv,强制 `PYTHONPATH=<当前工作树>/src`,核对 `peach.__file__` 后运行标准库 `unittest`。禁止手工拼接 venv 路径或调用 pytest。- 两个入口都要绿——只在一个平台通过的改动不算完成。+ 跨多个域、迁移、共享测试设施、依赖、构建/发布或大面积改动必须跑 `full`;局部功能只跑+ 本域及其公共门槛。两个平台的入口契约都要保持可用。4. 报告 `ready` 前先 rebase 到当前 `master` 并重跑测试;同文件冲突在工作者分支解决。5. 协调者审核后运行 `integrate`。完成顺序不决定覆盖顺序。diff --git a/AGENTS.md b/AGENTS.mdindex 1285444a6..93f2ffa37 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -69,13 +69,13 @@- Never require the user to relay implementation details between agents. Put current facts in `docs/STATUS.md`, durable rules in `docs/HANDOFF.md`/`docs/REUSE.md`, procedures in a skill, and architecture decisions in an ADR.- During concurrent code work, the main `peach-app` checkout is integration-only. Each agent works in an isolated Git worktree created by `scripts/agent_worktree.py create` under `peach-worktrees/`, never anywhere else and never in the main checkout; a worker commits its branch and reports it ready, but never merges itself. Before every commit confirm you are still in that worktree — `git rev-parse --show-toplevel` must not be the main checkout. Details in `peach-worktree`.- Never use `git add .`, `git add -A`, a directory path, or a glob in an agent checkout. Stage only the exact files owned by the task, then inspect `git diff --cached --name-status`. Implementation and its tests must be committed atomically.-- Run the verification commands in `README.md` before committing relevant changes: `scripts/test.ps1` on Windows, `scripts/test.sh` on macOS. Both entry points must stay green; a change that only passes on one platform is not done.+- Run the relevant functional scope from `README.md` before committing: `scripts/test.ps1` on Windows, `scripts/test.sh` on macOS. Cross-domain, migration, shared-harness, dependency, build/release, or broad changes require `full`; both platform entry contracts must stay green.- Reuse existing usage surfaces and protocols. T3 Code/CodexBar cover historical token and API-equivalent cost views; official provider quota endpoints cover live remaining windows. Do not build another session-log cost scanner or depend on T3 Code's private localhost API.## 防止重复错误的硬门槛- PowerShell 变量必须使用任务专属名称;禁止声明 `$HOME`、`$home`、`$CODEX_HOME` 等系统变量的任何大小写变体。`foreach {}` 的结果先存入任务专属数组,再单独接管道格式化,禁止在闭合花括号后直接写管道。-- 测试只在当前隔离 worktree 根目录运行,每个平台只有一个入口:Windows `& .\scripts\test.ps1`,macOS/Linux `./scripts/test.sh`。两者契约相同——自动定位主项目 venv、强制 `PYTHONPATH=<当前 worktree>/src`、核对 `peach.__file__`,再运行 `unittest`;禁止手工拼接 venv 路径或调用 pytest。健康检查只使用 `/healthz`。+- 测试只在当前隔离 worktree 根目录运行,每个平台只有一个入口:Windows `& .\scripts\test.ps1`,macOS/Linux `./scripts/test.sh`。局部改动跑对应功能域;跨域、迁移、共享测试设施、依赖、构建/发布或大面积改动跑默认 `full`。两者自动定位主项目 venv、强制 `PYTHONPATH=<当前 worktree>/src`、核对 `peach.__file__` 后运行 `unittest`;禁止手工拼接 venv 路径或调用 pytest。健康检查只使用 `/healthz`。- HTTPS 结论必须使用项目 CA 做严格校验;Schannel、浏览器或取证入口失败时,立即报告原始错误和未取得的验收面,不能改用 HTTP 成功来声称 HTTPS 已通过。- UI 标签、身份、反馈状态和搜索推荐属于语义契约。修改时必须同时增加数据层测试和页面源测试,不能只改显示文本;推荐词上线前必须对真实 `/api/items` 验证至少一个命中,说明性后缀不得混入搜索词。- 本仓库最常见的缺陷是「只改了自己测试的那条路径」。收尾前按 `peach-surfaces` 逐项说明每个表面适用还是不适用,不要跳过不适用的项。diff --git a/README.md b/README.mdindex 82a2dbd7a..aad2ae38f 100644--- a/README.md+++ b/README.md@@ -66,6 +66,11 @@ python3.14 -m venv .venv每个平台只有一个正式测试入口。脚本会定位主项目的虚拟环境、强制加载当前 worktree 的 `src`,并核对实际导入路径。仓库使用标准库 `unittest`,不使用 pytest。+开发时按功能域运行必要测试,例如 Windows 用 `& .\scripts\test.ps1 -Scope follow`,+macOS/Linux 用 `./scripts/test.sh follow`。可选域为 `follow`、`catalog`、`media`、`sync`、+`metadata`、`tooling`;不传参数仍跑 `full`。跨多个域、修改迁移/共享测试设施/依赖、准备发布或+改动影响面较大时必须跑全量,单一局部功能不再反复跑无关测试。+检查迁移状态并启动本地开发服务:```powershell@@ -97,10 +102,15 @@ python3.14 -m venv .venv## 关注与候选-关注管理支持粘贴链接、名称或 ID。联网只发生在显式查找和检查更新时;服务启动、健康检查和普通浏览不会联网。+关注管理支持粘贴链接、名称或 ID,也可直接登记 FANBOX、Patreon 和 SubscribeStar 的+官方创作者页。每个渠道的复选框决定它是否参与检查更新;联网只发生在显式查找和检查更新时,+服务启动、健康检查和普通浏览不会联网。F95zone 站内索引没有命中名称时,结果区会给出对应的 Google 查询入口;Google 结果只供人核对真实线程链接,不会自动登记来源。-Rule34.xxx 标签身份不区分大小写。跨站来源按规范作者归组,F95 标题中的 `Collection(s)` 不属于作者名。作者头像优先从已验证的官方 FANBOX/Pixiv 页面取得,归档站只作回退。连接器设计与证据见 [`ADR-0019`](docs/adr/0019-site-follow-connectors-and-variant-grouping.md)。+Rule34.xxx 标签身份不区分大小写。跨站来源按规范作者归组,F95 标题中的 `Collection(s)` 不属于作者名。+相似平台名只产生别名建议,用户确认后才合并作者组;别名可随时移除。作者头像优先从已验证的+官方 FANBOX/Pixiv 页面取得,归档站只作回退。连接器设计与证据见+[`ADR-0019`](docs/adr/0019-site-follow-connectors-and-variant-grouping.md)。抓到的更新保持 `new` 或 `seen` 候选状态。只有显式保存或在 `/review` 批准后,数据才进入对应 ledger 真相或在线资产。diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex b4d7be378..c10678221 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -29,7 +29,7 @@## 无摩擦接手- Codex 自动读取项目层级中的 `AGENTS.md`;Claude Code 通过 `CLAUDE.md` 导入同一文件。-- 正式测试入口只有 Windows `& .\scripts\test.ps1` 和 macOS/Linux `./scripts/test.sh`;不要另拼测试命令。+- 正式测试入口只有 Windows `& .\scripts\test.ps1` 和 macOS/Linux `./scripts/test.sh`;不要另拼测试命令。日常用 `-Scope <域>` / `<域>` 只跑当前功能与公共门槛;跨域、迁移、共享测试设施、依赖、构建/发布或大面积改动跑默认 `full`。- 两个智能体使用同一入口、同一必读顺序,不再生成按日期命名的临时交接文档。- 新任务以当前机器真实的 `peach-app` 为工作目录,并说:「接手 Peach,按项目入口文件继续 STATUS 中的下一任务。」不得把 Windows 迁移前的 `R:\peach-app` 当跨平台固定路径。- 改变运行事实的任务同时更新 `docs/STATUS.md`;长期规则更新本文件、`docs/REUSE.md` 或 ADR;可执行流程写成 `.claude/skills/<name>/SKILL.md`。分层判据见 ADR-0015,步骤见 `peach-context-rules`。diff --git a/docs/adr/0019-site-follow-connectors-and-variant-grouping.md b/docs/adr/0019-site-follow-connectors-and-variant-grouping.mdindex cee06e89b..9fc25177e 100644--- a/docs/adr/0019-site-follow-connectors-and-variant-grouping.md+++ b/docs/adr/0019-site-follow-connectors-and-variant-grouping.md@@ -31,6 +31,18 @@ rule34.xxx 上。不区分这三种关系,界面就只是一堆重复条目。- 凭据从 `peach-data/secrets/follow/<provider>.json` 读,只进请求头或查询参数,**绝不进快照、日志、`request_url` 或 ledger**。dapi 只接受查询参数,因此记录下来的是脱敏副本。+- 官方免费渠道是一等来源:FANBOX 走公开 `post.listCreator` 且只收 `feeRequired=0`、+ `isRestricted=false` 的帖子;SubscribeStar 与 Patreon 只读官网公开创作者页,不登录、+ 不穿过付费墙。Patreon 的正式 posts API 需要创作者 OAuth scope,因此不能拿它读取任意+ 外部作者,公开页解析是有意的边界。+- `follow_source.enabled` 由来源行左侧的渠道复选框维护;“检查全部”只读取启用来源。+ 关闭渠道不删除来源或既有条目。++### 作者别名++- 平台账号名只做保守检测,不自动合并。规范化名称存在包含关系时产生建议;用户确认后写入+ `follow_author_alias`,只改变关注页作者归组,不提升为全局 `entity` 真相。+- 用户可删除别名,来源立即恢复为独立作者组。全局实体已经绑定时仍以实体 id 优先。### 变体分组@@ -81,6 +93,9 @@ rule34.xxx 上。不区分这三种关系,界面就只是一堆重复条目。| 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 浏览器质询,**未取得**可用入口 |+| fanbox.cc | `api.fanbox.cc/post.listCreator` | 无 | 2026-08-27 实测公开 JSON 给出 `feeRequired`、`isRestricted`、标题、时间和封面;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 |### rule34.xxx 的真实响应(2026-08-26,用账号 API key 实测)diff --git a/migrations/0021_follow_author_alias.sql b/migrations/0021_follow_author_alias.sqlnew file mode 100644index 000000000..f788a70b8--- /dev/null+++ b/migrations/0021_follow_author_alias.sql@@ -0,0 +1,17 @@+-- 不同平台会给同一位创作者使用不同账号名。这里只保存用户确认的追更别名,+-- 不自动提升为全局 entity 真相;自动检测只产生建议。++CREATE TABLE IF NOT EXISTS follow_author_alias(+ alias_key TEXT PRIMARY KEY,+ alias_name TEXT NOT NULL,+ canonical_key TEXT NOT NULL,+ canonical_name TEXT NOT NULL,+ source TEXT NOT NULL DEFAULT 'manual',+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ CHECK(alias_key<>''),+ CHECK(canonical_key<>'')+);++CREATE INDEX IF NOT EXISTS idx_follow_author_alias_canonical+ON follow_author_alias(canonical_key, alias_name);diff --git a/scripts/test.ps1 b/scripts/test.ps1index b18c89971..07987fd17 100644--- a/scripts/test.ps1+++ b/scripts/test.ps1@@ -1,5 +1,8 @@[CmdletBinding()]-param()+param(+ [ValidateSet('full', 'follow', 'catalog', 'media', 'sync', 'metadata', 'tooling')]+ [string]$Scope = 'full'+)$ErrorActionPreference = 'Stop'$WorktreeRoot = (Resolve-Path -LiteralPath (Split-Path -Parent $PSScriptRoot)).Path@@ -47,7 +50,7 @@ try {}Write-Host "Peach source: $LoadedPath"- & $Python -m unittest discover -s tests -p 'test_*.py' -v+ & $Python scripts\test_runner.py --scope $Scopeexit $LASTEXITCODE} finally {Pop-Locationdiff --git a/scripts/test.sh b/scripts/test.shindex 4468214f7..5aa5c9152 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -4,6 +4,8 @@# 并核对 peach.__file__ 确实来自这个 worktree。worktree 不复制 .venv。set -euo pipefail+SCOPE="${1:-full}"+WORKTREE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"GIT_COMMON_RAW="$(git -C "$WORKTREE_ROOT" rev-parse --git-common-dir)"@@ -36,4 +38,4 @@ if [[ "$LOADED_MODULE" != "$SOURCE_ROOT/"* ]]; thenfiecho "Peach source: $LOADED_MODULE"-exec "$PYTHON" -m unittest discover -s tests -p 'test_*.py' -v+exec "$PYTHON" scripts/test_runner.py --scope "$SCOPE"diff --git a/scripts/test_runner.py b/scripts/test_runner.pynew file mode 100644index 000000000..e138d0a68--- /dev/null+++ b/scripts/test_runner.py@@ -0,0 +1,91 @@+"""Run Peach's unittest suite by a documented product scope."""+from __future__ import annotations++import argparse+import importlib+import sys+import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[1]+TESTS = ROOT / "tests"++COMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py")+SCOPES: dict[str, tuple[str, ...]] = {+ "follow": ("test_follow*.py", "test_http.py", "test_migrations.py"),+ "catalog": ("test_ad_judgement.py", "test_duplicate_identity_merge.py",+ "test_entity_merge.py", "test_fastapi_api.py", "test_migrations.py",+ "test_review_mirror.py", "test_rm_ledger.py", "test_rm_web.py",+ "test_taste_history.py", "test_web_ui.py"),+ "media": ("test_endcard.py", "test_fastapi_api.py", "test_jobs.py",+ "test_media.py", "test_providers.py", "test_segments.py",+ "test_streaming.py", "test_transcodes.py"),+ "sync": ("test_sync*.py", "test_platform.py", "test_tray.py", "test_mdns.py",+ "test_netwatch.py", "test_certs.py", "test_review_mirror.py"),+ "metadata": ("test_metadata*.py", "test_fc2*.py", "test_babepedia_match.py",+ "test_jav*.py", "test_code_creators.py", "test_logo_provider.py",+ "test_avatar_provider.py", "test_performer*.py",+ "test_duplicate_identity_merge.py", "test_entity_merge.py",+ "test_stash_entity_import.py", "test_migrations.py"),+ "tooling": ("test_scripts.py", "test_agent_worktree.py", "test_versioning.py",+ "test_windows_update.py", "test_certs.py", "test_config.py",+ "test_job_status.py", "test_jobs.py", "test_reference_updates.py",+ "test_subprocess_encoding.py"),+}++SCOPE_TEST_IDS: dict[str, tuple[str, ...]] = {+ "follow": (+ "test_rm_web.WebDataTests.test_contract_handler_registries_are_complete_and_unknown_routes_fail",+ "test_rm_web.WebDataTests.test_read_only_post_routes_are_declared_and_all_exist",+ "test_scripts.OperationalScriptTests.test_test_entrypoint_enforces_worktree_source_and_unittest",+ ),+}+++def selected_files(scope: str) -> tuple[Path, ...]:+ if scope == "full":+ return tuple(sorted(TESTS.glob("test_*.py")))+ found: set[Path] = set()+ for pattern in (*COMMON_PATTERNS, *SCOPES[scope]):+ found.update(TESTS.glob(pattern))+ return tuple(sorted(found))+++def unclassified_files() -> tuple[Path, ...]:+ classified = set()+ for scope in SCOPES:+ classified.update(selected_files(scope))+ return tuple(sorted(set(TESTS.glob("test_*.py")) - classified))+++def build_suite(scope: str) -> unittest.TestSuite:+ loader = unittest.defaultTestLoader+ suite = unittest.TestSuite()+ sys.path[:0] = [str(ROOT), str(TESTS)]+ try:+ for path in selected_files(scope):+ suite.addTests(loader.loadTestsFromModule(importlib.import_module(path.stem)))+ for test_id in SCOPE_TEST_IDS.get(scope, ()):+ suite.addTests(loader.loadTestsFromName(test_id))+ finally:+ del sys.path[:2]+ return suite+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--scope", choices=("full", *SCOPES), default="full")+ parser.add_argument("--list-scopes", action="store_true")+ args = parser.parse_args(argv)+ if args.list_scopes:+ print("\n".join(("full", *SCOPES)))+ return 0+ files = selected_files(args.scope)+ print(f"Peach test scope: {args.scope} ({len(files)} files)", flush=True)+ result = unittest.TextTestRunner(verbosity=2).run(build_suite(args.scope))+ return 0 if result.wasSuccessful() else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/peach/follow_cli.py b/src/peach/follow_cli.pyindex 187c1052d..8e2b877e5 100644--- a/src/peach/follow_cli.py+++ b/src/peach/follow_cli.py@@ -19,6 +19,9 @@ from .follow_store import FollowStore#: 登记订阅时按 provider 拼作品页 URL;只用于展示与去重,不参与抓取。_SOURCE_URL = {+ "fanbox": "https://{ref}.fanbox.cc/",+ "patreon": "https://www.patreon.com/cw/{ref}",+ "subscribestar": "https://{ref}","kemono": "https://kemono.cr/{ref}","coomer": "https://coomer.st/{ref}","pawchive": "https://pawchive.pw/{ref}",diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex 4c8264cd2..f7ffc520e 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -908,6 +908,217 @@ class F95ZoneConnector(_BaseConnector):return tuple(row for row in rows if isinstance(row, dict))+class FanboxConnector(_BaseConnector):+ """pixivFANBOX 官方公开帖子列表。++ 只保留 `feeRequired=0` 且没有受限的帖子;付费标题可以被公开接口看见,+ 但这条来源的用途是跟踪作者直接公开分发的内容,不能把付费预告混进来。+ """++ provider = "fanbox"+ semantics = "work"+ _CREATOR_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")++ def _headers(self) -> dict[str, str]:+ headers = super()._headers()+ headers.update({+ "Accept": "application/json",+ "Origin": "https://www.fanbox.cc",+ "Referer": "https://www.fanbox.cc/",+ })+ return headers++ def fetch(self, ref: str, *, etag: str | None = None,+ last_modified: str | None = None, page: int = 0) -> SourceFetch:+ creator = str(ref or "").strip()+ if not self._CREATOR_RE.fullmatch(creator):+ raise FollowSourceError(f"fanbox 的 ref 必须是创作者 id,收到:{ref!r}")+ if page:+ raise FollowSourceError("fanbox 官方来源暂不支持向前翻页")+ # 2026-08-27 实测公开接口单页为 10 条;不要把本地通用上限 100 原样塞给站点。+ query = urllib.parse.urlencode({"creatorId": creator,+ "limit": min(self.max_items, 10)})+ url = f"https://api.fanbox.cc/post.listCreator?{query}"+ response = self._get(url, etag=etag, last_modified=last_modified)+ common = {"provider": self.provider, "ref": creator, "request_url": url,+ "semantics": self.semantics, **self._conditional(response)}+ if response.status == 304:+ return SourceFetch(not_modified=True, **common)+ self._check_status(response)+ payload = self._json(response)+ posts = ((payload or {}).get("body") or {}).get("posts")+ if not isinstance(posts, list):+ raise FollowSourceError("fanbox 返回的帖子列表格式不符")+ candidates, skipped = [], 0+ for post in posts[:self.max_items]:+ if not isinstance(post, dict) or not str(post.get("id") or "").isdigit():+ continue+ if post.get("isRestricted") or int(post.get("feeRequired") or 0) > 0:+ skipped += 1+ continue+ post_id = str(post["id"])+ cover = post.get("cover") if isinstance(post.get("cover"), dict) else {}+ user = post.get("user") if isinstance(post.get("user"), dict) else {}+ candidates.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(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 "")),+ summary=_plain_text(str(post.get("excerpt") or "")),+ group_hint=f"fanbox:{post_id}",+ extra={"fee_required": 0, "official": True},+ ))+ return SourceFetch(candidates=tuple(candidates), skipped=skipped,+ raw_body=response.body, **common)+++def _visible_post_image(node) -> str | None:+ image = node.select_one("img[src]") if node is not None else None+ return str(image.get("src")) if image is not None and image.get("src") else None+++class SubscribeStarConnector(_BaseConnector):+ """SubscribeStar 的公开创作者页;不登录,也不穿过付费墙。"""++ provider = "subscribestar"+ semantics = "work"+ HOSTS = frozenset({"subscribestar.adult", "subscribestar.com"})+ _SLUG_RE = re.compile(r"^[A-Za-z0-9_-]{1,80}$")++ @classmethod+ def _split_ref(cls, ref: str) -> tuple[str, str]:+ host, _, slug = str(ref or "").strip().partition("/")+ if host not in cls.HOSTS or not cls._SLUG_RE.fullmatch(slug):+ raise FollowSourceError(+ "subscribestar 的 ref 必须形如 subscribestar.adult/creator")+ return host, slug++ def fetch(self, ref: str, *, etag: str | None = None,+ last_modified: str | None = None, page: int = 0) -> SourceFetch:+ host, slug = self._split_ref(ref)+ if page:+ raise FollowSourceError("SubscribeStar 官方来源暂不支持向前翻页")+ url = f"https://{host}/{slug}"+ response = self._get(url, headers={"Accept": "text/html"},+ etag=etag, last_modified=last_modified)+ common = {"provider": self.provider, "ref": ref, "request_url": url,+ "semantics": self.semantics, **self._conditional(response)}+ if response.status == 304:+ return SourceFetch(not_modified=True, **common)+ self._check_status(response)+ try:+ soup = BeautifulSoup(response.body.decode("utf-8"), "html.parser")+ except UnicodeDecodeError as exc:+ raise FollowSourceError("subscribestar 返回的页面不是 UTF-8") from exc+ candidates = []+ for post in soup.select("div.post[data-id]")[:self.max_items]:+ post_id = str(post.get("data-id") or "")+ if not post_id.isdigit():+ continue+ title_node = post.select_one(".post-title h2")+ date_node = post.select_one(".post-date a[href]")+ author_node = post.select_one(".post-user")+ title = _plain_text(title_node.get_text(" ") if title_node else "")+ published = _iso_from_text(date_node.get_text(" ") if date_node else "")+ if published is None and date_node is not None:+ try:+ parsed = datetime.strptime(+ date_node.get_text(" ").strip(), "%b %d, %Y %I:%M %p")+ published = _iso_utc(parsed)+ except ValueError:+ pass+ candidates.append(FollowCandidate(+ provider=self.provider,+ external_id=post_id,+ title=title or f"SubscribeStar 帖子 {post_id}",+ url=f"https://{host}/posts/{post_id}",+ thumb_url=_visible_post_image(post.select_one(".post-uploads")),+ published_at=published,+ author=_plain_text(author_node.get_text(" ") if author_node else ""),+ summary=_plain_text(+ post.select_one(".post-content").get_text(" ")+ if post.select_one(".post-content") else ""),+ group_hint=f"subscribestar:{post_id}",+ extra={"official": True, "published_precision": "approximate"},+ ))+ return SourceFetch(candidates=tuple(candidates), raw_body=response.body, **common)+++class PatreonConnector(_BaseConnector):+ """Patreon 公开创作者页。++ Patreon 的正式 posts API 要创作者 OAuth scope,不能用于任意作者;这里仅读取官网+ 已经服务端渲染给公开访客的帖子卡片,不碰登录态或私有 API。+ """++ provider = "patreon"+ semantics = "work"+ _VANITY_RE = re.compile(r"^[A-Za-z0-9_-]{1,80}$")+ _POST_RE = re.compile(r"/posts/(?:[^/?#]*-)?(\d{4,})(?:[/?#]|$)")++ def _url(self, ref: str) -> str:+ value = str(ref or "").strip()+ if value.startswith("user/") and value[5:].isdigit():+ return f"https://www.patreon.com/user?u={value[5:]}"+ if not self._VANITY_RE.fullmatch(value):+ raise FollowSourceError(f"patreon 的 ref 必须是创作者短名,收到:{ref!r}")+ return f"https://www.patreon.com/cw/{value}"++ def fetch(self, ref: str, *, etag: str | None = None,+ last_modified: str | None = None, page: int = 0) -> SourceFetch:+ if page:+ raise FollowSourceError("Patreon 官方来源暂不支持向前翻页")+ url = self._url(ref)+ response = self._get(url, headers={"Accept": "text/html"},+ etag=etag, last_modified=last_modified)+ common = {"provider": self.provider, "ref": ref, "request_url": url,+ "semantics": self.semantics, **self._conditional(response)}+ if response.status == 304:+ return SourceFetch(not_modified=True, **common)+ self._check_status(response)+ try:+ soup = BeautifulSoup(response.body.decode("utf-8"), "html.parser")+ except UnicodeDecodeError as exc:+ raise FollowSourceError("patreon 返回的页面不是 UTF-8") from exc+ candidates, seen = [], set()+ for anchor in soup.select("a[href*='/posts/']"):+ href = str(anchor.get("href") or "")+ matched = self._POST_RE.search(urllib.parse.urlsplit(href).path)+ if not matched or matched.group(1) in seen:+ continue+ post_id = matched.group(1)+ seen.add(post_id)+ node = anchor+ for _ in range(8):+ if node is None or node.select_one("h3") is not None:+ break+ node = node.parent+ title_node = node.select_one("h3") if node is not None else None+ title = _plain_text(title_node.get_text(" ") if title_node else "")+ if not title:+ slug = urllib.parse.urlsplit(href).path.rsplit("/", 1)[-1]+ title = _slug_label(re.sub(rf"-{post_id}$", "", slug))+ text = _plain_text(node.get_text(" ") if node is not None else "") or ""+ relative = _RELATIVE_RE.search(text)+ candidates.append(FollowCandidate(+ provider=self.provider,+ external_id=post_id,+ title=title or f"Patreon 帖子 {post_id}",+ url=urllib.parse.urljoin("https://www.patreon.com", href),+ thumb_url=_visible_post_image(node),+ published_at=_iso_from_relative(relative.group(0)) if relative else None,+ group_hint=f"patreon:{post_id}",+ extra={"official": True, "public_page": True,+ "published_precision": "approximate"},+ ))+ if len(candidates) >= self.max_items:+ break+ return SourceFetch(candidates=tuple(candidates), raw_body=response.body, **common)++class SimpCityConnector(_BaseConnector):"""simpcity.cr 目前挂着 DDoS-Guard 的浏览器质询。@@ -947,6 +1158,7 @@ _KEMONO_HOSTS = {"kemono.cr": "kemono", "coomer.st": "coomer", "pawchive.pw": "p_KEMONO_PATH_RE = re.compile(r"^/([a-z0-9_\-]{1,32})/user/([A-Za-z0-9_\-.]{1,64})")_R34V_PATH_RE = re.compile(r"^/models/([a-z0-9][a-z0-9_\-]{0,80})")_THREAD_PATH_RE = re.compile(r"^/threads/(?:[^/]*?\.)?(\d{1,12})")+_DIRECT_CREATOR_RE = re.compile(r"^/([A-Za-z0-9_-]{1,80})(?:/|$)")def canonical_source_ref(provider: str, ref: str) -> str:@@ -1011,6 +1223,45 @@ def parse_source_url(raw_url: str) -> ParsedSource:f"https://{bare}/{service}/user/{user}",f"{user} · {service}", "work")+ if bare == "fanbox.cc" or bare.endswith(".fanbox.cc"):+ if bare.endswith(".fanbox.cc") and bare != "www.fanbox.cc":+ creator = bare.removesuffix(".fanbox.cc")+ else:+ matched = re.match(r"^/@([A-Za-z0-9_-]{1,64})(?:/|$)", path)+ creator = matched.group(1) if matched else ""+ if not creator:+ raise FollowSourceError(+ "FANBOX 的链接要指向创作者主页,形如 https://creator.fanbox.cc/")+ return ParsedSource("fanbox", creator, f"https://{creator}.fanbox.cc/",+ creator, "work")++ if bare in SubscribeStarConnector.HOSTS:+ matched = _DIRECT_CREATOR_RE.match(path)+ if not matched or matched.group(1) in {"posts", "search", "login", "signup"}:+ raise FollowSourceError(+ "SubscribeStar 的链接要指向创作者主页,形如 "+ "https://subscribestar.adult/creator")+ slug = matched.group(1)+ return ParsedSource("subscribestar", f"{bare}/{slug}",+ f"https://{bare}/{slug}", slug, "work")++ if bare == "patreon.com":+ user_id = urllib.parse.parse_qs(parsed.query).get("u", [""])[0]+ if path.rstrip("/") == "/user" and user_id.isdigit():+ return ParsedSource("patreon", f"user/{user_id}",+ f"https://www.patreon.com/user?u={user_id}",+ f"Patreon {user_id}", "work")+ parts = [part for part in path.split("/") if part]+ if parts and parts[0] == "cw":+ parts = parts[1:]+ reserved = {"posts", "join", "login", "signup", "home", "explore"}+ if not parts or parts[0].lower() in reserved:+ raise FollowSourceError(+ "Patreon 的链接要指向创作者主页,形如 https://patreon.com/cw/creator")+ vanity = parts[0]+ return ParsedSource("patreon", vanity,+ f"https://www.patreon.com/cw/{vanity}", vanity, "work")+if bare == "rule34video.com":matched = _R34V_PATH_RE.match(path)if not matched:@@ -1052,11 +1303,15 @@ def parse_source_url(raw_url: str) -> ParsedSource:raise FollowSourceError(SimpCityConnector.blocked_reason)raise FollowSourceError(- f"不认识 {bare}。当前支持 kemono.cr、coomer.st、pawchive.pw 的创作者页,"- "rule34video.com 的作者页,rule34.xxx 的标签页,以及 f95zone.to 的线程。")+ f"不认识 {bare}。当前支持 FANBOX、Patreon、SubscribeStar,"+ "kemono.cr、coomer.st、pawchive.pw 的创作者页,rule34video.com 的作者页,"+ "rule34.xxx 的标签页,以及 f95zone.to 的线程。")CONNECTORS: dict[str, type] = {+ "fanbox": FanboxConnector,+ "patreon": PatreonConnector,+ "subscribestar": SubscribeStarConnector,"kemono": KemonoConnector,"coomer": KemonoConnector,"pawchive": KemonoConnector,diff --git a/src/peach/follow_variants.py b/src/peach/follow_variants.pyindex 88000a1c8..ef2c12dea 100644--- a/src/peach/follow_variants.py+++ b/src/peach/follow_variants.py@@ -251,6 +251,9 @@ def classify(#: 同一 `release_key` 下选主条目时的来源优先级;越小越优先。未列出的排在最后。PROVIDER_PRIORITY: dict[str, int] = {+ "fanbox": 1,+ "subscribestar": 2,+ "patreon": 3,"kemono": 10,"pawchive": 15,"coomer": 20,diff --git a/src/peach/web_contract.py b/src/peach/web_contract.pyindex 125ca6c39..159e22cb9 100644--- a/src/peach/web_contract.py+++ b/src/peach/web_contract.py@@ -41,7 +41,7 @@ from .platform import (from .repository import LedgerDatabasefrom .web_follow import (q_follow, q_follow_credentials, w_follow_check, w_follow_credential, w_follow_resolve,- w_follow_save, w_follow_source, w_follow_status,+ w_follow_author_alias, w_follow_save, w_follow_source, w_follow_status,)from .web_activity import (DEFAULT_PROFILE_ID,@@ -2612,6 +2612,7 @@ GET_HANDLERS = {POST_HANDLERS = {"/api/follow/check": w_follow_check,"/api/follow/source": w_follow_source,+ "/api/follow/author-alias": w_follow_author_alias,"/api/follow/resolve": w_follow_resolve,"/api/follow/credential": w_follow_credential,"/api/follow/status": w_follow_status,diff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex 00d602720..2d27c374a 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -24,6 +24,9 @@ from .taste_history import read_creator_candidates#: 界面上给每个来源的中文短名。没登记的 provider 直接显示原名。PROVIDER_LABELS = {+ "fanbox": "FANBOX",+ "patreon": "Patreon",+ "subscribestar": "SubscribeStar","kemono": "Kemono","coomer": "Coomer","pawchive": "Pawchive",@@ -195,6 +198,16 @@ def _normalized_author_name(value: str, *, provider: str = "") -> str:return _AUTHOR_NOISE_RE.sub("", stripped.casefold())+def _author_display_name(row) -> str:+ """Return the readable author spelling carried by one follow source."""+ if row["entity_id"] and row["entity_name"]:+ return str(row["entity_name"])+ label = _LABEL_SERVICE_RE.sub("", str(row["label"] or row["ref"] or "").strip())+ if str(row["provider"] or "") == "f95zone":+ label = _F95_TITLE_SUFFIX_RE.sub("", label)+ return label.strip()++def _source_metadata(row) -> dict:try:payload = json.loads(row["metadata_json"] or "{}")@@ -203,7 +216,7 @@ def _source_metadata(row) -> dict:return payload if isinstance(payload, dict) else {}-def author_key(row) -> str:+def author_key(row, aliases: dict[str, str] | None = None) -> str:"""把一条来源归到「哪个作者」。这跟 ADR-0019 的变体分组**不是同一个轴**:那个是同一条发布的多个变体,@@ -221,10 +234,74 @@ def author_key(row) -> str:return f"entity:{entity}"recorded = str(_source_metadata(row).get("author_key") or "").strip()if recorded:- return f"name:{recorded}"- label = str(row["label"] or row["ref"] or "")- normalized = _normalized_author_name(label, provider=str(row["provider"] or ""))- return f"name:{normalized}" if normalized else f"source:{row['id']}"+ normalized = recorded+ else:+ label = str(row["label"] or row["ref"] or "")+ normalized = _normalized_author_name(label, provider=str(row["provider"] or ""))+ if normalized:+ normalized = (aliases or {}).get(normalized, normalized)+ return f"name:{normalized}"+ return f"source:{row['id']}"+++def _follow_alias_state(connection) -> tuple[dict[str, str], list[dict]]:+ rows = connection.execute(+ "SELECT alias_key,alias_name,canonical_key,canonical_name,source "+ "FROM follow_author_alias ORDER BY canonical_name,alias_name"+ ).fetchall()+ mapping = {str(row["alias_key"]): str(row["canonical_key"]) for row in rows}+ groups: dict[str, dict] = {}+ for row in rows:+ canonical_key = str(row["canonical_key"])+ group = groups.setdefault(canonical_key, {+ "canonical_key": canonical_key,+ "canonical_name": str(row["canonical_name"]),+ "aliases": [],+ })+ if str(row["alias_key"]) != canonical_key:+ group["aliases"].append({+ "key": str(row["alias_key"]),+ "name": str(row["alias_name"]),+ "source": str(row["source"]),+ })+ return mapping, [group for group in groups.values() if group["aliases"]]+++def _follow_alias_suggestions(rows, aliases: dict[str, str]) -> list[dict]:+ """Suggest conservative cross-platform aliases; never merge automatically."""+ identities: dict[str, dict] = {}+ for row in rows:+ if row["entity_id"]:+ continue+ raw_key = author_key(row).removeprefix("name:")+ if not raw_key or raw_key.startswith("source:"):+ continue+ identity = identities.setdefault(raw_key, {+ "key": raw_key, "name": _author_display_name(row), "providers": set(),+ })+ identity["providers"].add(str(row["provider"]))+ candidate_name = _author_display_name(row)+ if candidate_name and len(candidate_name) < len(identity["name"]):+ identity["name"] = candidate_name++ suggestions = []+ values = sorted(identities.values(), key=lambda item: item["key"])+ for index, left in enumerate(values):+ for right in values[index + 1:]:+ if aliases.get(left["key"], left["key"]) == aliases.get(+ right["key"], right["key"]):+ continue+ shorter, longer = sorted((left, right), key=lambda item: len(item["key"]))+ if len(shorter["key"]) < 5 or shorter["key"] not in longer["key"]:+ continue+ suggestions.append({+ "canonical": shorter["name"],+ "alias": longer["name"],+ "evidence": "规范化名称存在包含关系,仅供人工确认",+ })+ if len(suggestions) >= 12:+ return suggestions+ return suggestionsdef _avatar_url(provider: str, ref: str) -> str | None:@@ -263,14 +340,14 @@ def _official_avatar_url(provider: str, ref: str) -> str | None:return "/follow-avatar?" + urllib.parse.urlencode({"service": service, "id": user})-def _source_payload(row) -> dict:+def _source_payload(row, aliases: dict[str, str] | None = None) -> dict:return {"id": row["id"],"provider": row["provider"],"provider_label": PROVIDER_LABELS.get(row["provider"], row["provider"]),"ref": row["ref"],"label": row["label"],- "author_key": author_key(row),+ "author_key": author_key(row, aliases),"official_avatar_url": _official_avatar_url(row["provider"], row["ref"]),"avatar_url": _avatar_url(row["provider"], row["ref"]),"url": row["url"],@@ -300,7 +377,10 @@ def q_follow(contract, args) -> dict:source_id = int(source) if str(source or "").isdigit() else Nonewith contract.database.read_connection() as connection:store = _store(contract, connection)- sources = [_source_payload(row) for row in store.sources()]+ source_rows = store.sources()+ alias_map, author_aliases = _follow_alias_state(connection)+ sources = [_source_payload(row, alias_map) for row in source_rows]+ alias_suggestions = _follow_alias_suggestions(source_rows, alias_map)items = tuple(item for item in store.items(statuses=statuses, source_id=source_id, limit=limit)if not _excluded_item(item))@@ -321,6 +401,8 @@ def q_follow(contract, args) -> dict:return {"ok": True,"sources": sources,+ "author_aliases": author_aliases,+ "alias_suggestions": alias_suggestions,"suggestions": suggestions,"groups": groups,"counts": {status: int(counts.get(status, 0)) for status in _STATUSES},@@ -499,6 +581,18 @@ def w_follow_source(contract, body) -> dict:with contract.database.write_transaction() as connection:connection.execute("DELETE FROM follow_source WHERE id=?", (source_id,))return {"ok": True, "removed": source_id}+ if action == "enabled":+ source_id = body.get("id")+ enabled = body.get("enabled")+ if not isinstance(source_id, int) or not isinstance(enabled, bool):+ raise ValueError("id must be an integer and enabled must be a boolean")+ with contract.database.write_transaction() as connection:+ store = _store(contract, connection)+ exists = any(row["id"] == source_id for row in store.sources())+ if not exists:+ raise ValueError("这个关注来源不存在")+ store.set_enabled(source_id, enabled)+ return {"ok": True, "source": source_id, "enabled": enabled}if action != "add":raise ValueError(f"unknown follow source action: {action}")@@ -521,6 +615,73 @@ def w_follow_source(contract, body) -> dict:"ref": parsed.ref, "label": label, "checked": outcome}+def w_follow_author_alias(contract, body) -> dict:+ """Add or remove a user-confirmed cross-platform follow-author alias."""+ action = str(body.get("action") or "add")+ if action == "remove":+ alias_name = str(body.get("alias") or "").strip()+ alias_key = _normalized_author_name(alias_name)+ if not alias_key:+ raise ValueError("别名不能为空")+ with contract.database.write_transaction() as connection:+ row = connection.execute(+ "SELECT canonical_key FROM follow_author_alias WHERE alias_key=?",+ (alias_key,),+ ).fetchone()+ if row is None:+ raise ValueError("这个作者别名不存在")+ if str(row["canonical_key"]) == alias_key:+ raise ValueError("规范名不能作为别名移除")+ connection.execute(+ "DELETE FROM follow_author_alias WHERE alias_key=?", (alias_key,))+ _, groups = _follow_alias_state(connection)+ return {"ok": True, "removed": alias_name, "author_aliases": groups}+ if action != "add":+ raise ValueError(f"unknown follow author alias action: {action}")++ canonical_name = str(body.get("canonical") or "").strip()+ alias_name = str(body.get("alias") or "").strip()+ canonical_key = _normalized_author_name(canonical_name)+ alias_key = _normalized_author_name(alias_name)+ if not canonical_key or not alias_key:+ raise ValueError("规范作者名和平台别名都不能为空")+ if canonical_key == alias_key:+ raise ValueError("这两个名字归一化后相同,不需要维护别名")++ stamp = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ with contract.database.write_transaction() as connection:+ mapping, _ = _follow_alias_state(connection)+ canonical_root = mapping.get(canonical_key, canonical_key)+ alias_root = mapping.get(alias_key, alias_key)+ if canonical_root != alias_root:+ connection.execute(+ "UPDATE follow_author_alias SET canonical_key=?,canonical_name=?,updated_at=? "+ "WHERE canonical_key=?",+ (canonical_root, canonical_name, stamp, alias_root),+ )+ connection.execute(+ "INSERT INTO follow_author_alias(alias_key,alias_name,canonical_key,"+ "canonical_name,source,created_at,updated_at) VALUES(?,?,?,?,?,?,?) "+ "ON CONFLICT(alias_key) DO UPDATE SET canonical_key=excluded.canonical_key,"+ "canonical_name=excluded.canonical_name,alias_name=excluded.alias_name,"+ "source=excluded.source,updated_at=excluded.updated_at",+ (canonical_root, canonical_name, canonical_root, canonical_name,+ "manual", stamp, stamp),+ )+ connection.execute(+ "INSERT INTO follow_author_alias(alias_key,alias_name,canonical_key,"+ "canonical_name,source,created_at,updated_at) VALUES(?,?,?,?,?,?,?) "+ "ON CONFLICT(alias_key) DO UPDATE SET canonical_key=excluded.canonical_key,"+ "canonical_name=excluded.canonical_name,alias_name=excluded.alias_name,"+ "source=excluded.source,updated_at=excluded.updated_at",+ (alias_key, alias_name, canonical_root, canonical_name,+ "manual", stamp, stamp),+ )+ _, groups = _follow_alias_state(connection)+ return {"ok": True, "canonical": canonical_name, "alias": alias_name,+ "author_aliases": groups}++#: 一次最多解析多少行。粘一屏链接是正常的,粘一整个书签导出不是。MAX_RESOLVE_LINES = 40diff --git a/tests/test_follow_cli.py b/tests/test_follow_cli.pyindex dd0f8ff23..a394c7f75 100644--- a/tests/test_follow_cli.py+++ b/tests/test_follow_cli.py@@ -61,6 +61,17 @@ class FollowCliTests(unittest.TestCase):_, output = self._run("add", "--provider", "kemono", "--ref", "fanbox/30917150")self.assertIn("· work ·", output)+ def test_add_derives_official_creator_page_urls(self):+ cases = (+ ("fanbox", "ffxivinitiala", "https://ffxivinitiala.fanbox.cc/"),+ ("patreon", "sample", "https://www.patreon.com/cw/sample"),+ ("subscribestar", "subscribestar.adult/initiala",+ "https://subscribestar.adult/initiala"),+ )+ for provider, ref, expected in cases:+ _, output = self._run("add", "--provider", provider, "--ref", ref)+ self.assertIn(expected, output)+def test_list_says_so_when_nothing_is_registered(self):_, output = self._run("list")self.assertIn("还没有登记", output)diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex a289fd8d9..0bb5d7947 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -15,9 +15,10 @@ from pathlib import Pathfrom peach.follow import FollowSourceErrorfrom peach.follow_secrets import Credential, CredentialError, CredentialStorefrom peach.follow_sources import (- USER_AGENT, F95ZoneConnector, KemonoConnector, Rule34VideoConnector,- Rule34XxxConnector, SimpCityConnector, build_connector, _iso_from_relative,- origin_group_key, parse_source_url,+ USER_AGENT, F95ZoneConnector, FanboxConnector, KemonoConnector,+ PatreonConnector, Rule34VideoConnector, Rule34XxxConnector,+ SimpCityConnector, SubscribeStarConnector, build_connector,+ _iso_from_relative, origin_group_key, parse_source_url,)from peach.http import HttpResponse@@ -94,6 +95,61 @@ Lazy Procrastinator Collection [2026-06-28] [LazyProcrastinator/LazyProcrast]</h</article></body></html>"""+FANBOX_JSON = json.dumps({"body": {"posts": [+ {"id": "12489354", "title": "MobiusFF Sarah Animations", "feeRequired": 0,+ "publishedDatetime": "2026-08-26T23:34:51+09:00", "isRestricted": False,+ "user": {"name": "InitialA"}, "cover": {"url": "https://img.test/cover.jpg"},+ "excerpt": "Public release"},+ {"id": "12400000", "title": "Paid preview", "feeRequired": 500,+ "publishedDatetime": "2026-08-20T00:00:00+09:00", "isRestricted": True},+]}}).encode()++SUBSCRIBESTAR_HTML = b"""<html><body>+<div class="post is-shown" data-id="2650844">+ <a class="post-user" href="/initiala">InitialA</a>+ <div class="post-date"><a href="/posts/2650844">Aug 26, 2026 02:34 pm</a></div>+ <div class="post-title"><h2>MobiusFF Sarah Animations</h2></div>+ <div class="post-uploads"><img src="https://img.test/one.jpg"></div>+ <div class="post-content">Posted for FREE tiers</div>+</div></body></html>"""++PATREON_HTML = b"""<html><body><div class="card">+<a href="https://www.patreon.com/sample/posts/new-public-work-167576581"></a>+<h3>New public work</h3><p>2 days ago</p><img src="https://img.test/patreon.jpg">+<a href="https://www.patreon.com/sample/posts/new-public-work-167576581">duplicate</a>+</div></body></html>"""+++class OfficialConnectorTests(unittest.TestCase):+ def test_fanbox_keeps_only_public_free_posts(self):+ seen = []+ result = FanboxConnector(+ transport=_transport(body=FANBOX_JSON, record=seen)).fetch("ffxivinitiala")+ self.assertIn("creatorId=ffxivinitiala", seen[0].url)+ self.assertEqual(seen[0].headers["Origin"], "https://www.fanbox.cc")+ self.assertEqual(len(result.candidates), 1)+ self.assertEqual(result.skipped, 1)+ self.assertEqual(result.candidates[0].group_hint, "fanbox:12489354")+ self.assertEqual(result.candidates[0].published_at, "2026-08-26T14:34:51Z")++ def test_subscribestar_reads_public_profile_posts_without_login(self):+ result = SubscribeStarConnector(+ transport=_transport(body=SUBSCRIBESTAR_HTML)).fetch(+ "subscribestar.adult/initiala")+ self.assertEqual(len(result.candidates), 1)+ post = result.candidates[0]+ self.assertEqual(post.external_id, "2650844")+ self.assertEqual(post.title, "MobiusFF Sarah Animations")+ self.assertEqual(post.author, "InitialA")+ self.assertEqual(post.url, "https://subscribestar.adult/posts/2650844")++ def test_patreon_uses_server_rendered_public_cards_and_deduplicates_links(self):+ result = PatreonConnector(transport=_transport(body=PATREON_HTML)).fetch("sample")+ self.assertEqual(len(result.candidates), 1)+ self.assertEqual(result.candidates[0].external_id, "167576581")+ self.assertEqual(result.candidates[0].title, "New public work")+ self.assertEqual(result.candidates[0].group_hint, "patreon:167576581")+# 形状取自 2026-08-25 对 api.rule34.xxx 的实测响应:顶层是裸列表,`image` 是 32 位# 十六进制哈希(15/15),`parent_id` 全是 0(15/15),`source` 13/15 有值。RULE34XXX_JSON = json.dumps([@@ -631,6 +687,15 @@ class ParseSourceUrlTests(unittest.TestCase):"https://rule34.xxx/index.php?page=post&s=list&tags=lazyprocrastinator":("rule34xxx", "lazyprocrastinator"),"https://f95zone.to/threads/lazy-collection.50685/": ("f95zone", "50685"),+ "https://ffxivinitiala.fanbox.cc/posts/12489354":+ ("fanbox", "ffxivinitiala"),+ "https://www.fanbox.cc/@ffxivinitiala/posts/12489354":+ ("fanbox", "ffxivinitiala"),+ "https://subscribestar.adult/initiala":+ ("subscribestar", "subscribestar.adult/initiala"),+ "https://www.patreon.com/cw/somnivagrious":+ ("patreon", "somnivagrious"),+ "https://www.patreon.com/user?u=12345": ("patreon", "user/12345"),}for url, expected in cases.items():parsed = parse_source_url(url)@@ -654,6 +719,8 @@ class ParseSourceUrlTests(unittest.TestCase):"release")self.assertEqual(parse_source_url("https://rule34video.com/models/abc/").semantics, "work")+ self.assertEqual(parse_source_url("https://creator.fanbox.cc/").semantics,+ "work")def test_a_bare_host_is_accepted_and_www_is_ignored(self):self.assertEqual(parse_source_url("rule34video.com/models/abc/").provider,@@ -679,6 +746,9 @@ class ParseSourceUrlTests(unittest.TestCase):("https://rule34video.com/latest-updates/", "models"),("https://rule34.xxx/index.php?page=post&s=view&id=1", "tags="),("https://f95zone.to/latest", "threads"),+ ("https://www.fanbox.cc/", "创作者主页"),+ ("https://subscribestar.adult/posts/1", "创作者主页"),+ ("https://www.patreon.com/posts/123", "创作者主页"),):with self.assertRaises(FollowSourceError) as caught:parse_source_url(url)@@ -700,6 +770,11 @@ class BuildConnectorTests(unittest.TestCase):with self.assertRaises(FollowSourceError):build_connector("nyaa")+ def test_official_channel_connectors_are_registered(self):+ self.assertIsInstance(build_connector("fanbox"), FanboxConnector)+ self.assertIsInstance(build_connector("patreon"), PatreonConnector)+ self.assertIsInstance(build_connector("subscribestar"), SubscribeStarConnector)+class RelativeDateTests(unittest.TestCase):def test_units_are_converted_against_an_injected_reference(self):diff --git a/tests/test_follow_variants.py b/tests/test_follow_variants.pyindex 92ff9d459..4adff9644 100644--- a/tests/test_follow_variants.py+++ b/tests/test_follow_variants.py@@ -141,6 +141,7 @@ class GroupDuplicatesTests(unittest.TestCase):self.assertEqual(group_duplicates([wip, main]), (main, main))def test_provider_priority_breaks_ties_between_equal_variants(self):+ self.assertLess(PROVIDER_PRIORITY["fanbox"], PROVIDER_PRIORITY["kemono"])self.assertLess(PROVIDER_PRIORITY["kemono"], PROVIDER_PRIORITY["rule34video"])low = _Item("1", "rule34video", "k", "main", "2026-08-01")high = _Item("2", "kemono", "k", "main", "2026-08-01")diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 4c96cc314..2d4d13f54 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -695,6 +695,62 @@ class FollowSourceAddTests(FollowContractTests):with self.assertRaises(ValueError):self._post("/api/follow/source", {"action": "explode"})+ def test_a_source_can_be_excluded_from_update_checks(self):+ source_id = self._seed()+ result = self._post("/api/follow/source", {+ "action": "enabled", "id": source_id, "enabled": False})+ self.assertFalse(result["enabled"])+ self.assertFalse(self._get()["sources"][0]["enabled"])+ with mock.patch.object(web_follow, "build_connector") as factory:+ checked = self._post("/api/follow/check", {})+ self.assertEqual(checked["checked"], 0)+ factory.assert_not_called()++ def test_source_enabled_requires_typed_values_and_an_existing_source(self):+ for body in ({"action": "enabled", "id": "1", "enabled": False},+ {"action": "enabled", "id": 1, "enabled": 0},+ {"action": "enabled", "id": 999, "enabled": True}):+ with self.assertRaises(ValueError):+ self._post("/api/follow/source", body)+ def _source(self, provider, ref, label):+ with self.contract.database.write_transaction() as connection:+ return FollowStore(lambda: connection).register(+ provider=provider, ref=ref, label=label,+ url=f"https://{provider}.test/{ref}", moment=MOMENT)++ def test_similar_cross_platform_names_are_suggested_but_not_auto_merged(self):+ self._source("fanbox", "initiala", "InitialA")+ self._source("rule34video", "ffxivinitiala", "FFXIVInitialA")+ payload = self._get()+ self.assertEqual(len({row["author_key"] for row in payload["sources"]}), 2)+ self.assertEqual(payload["alias_suggestions"], [{+ "canonical": "InitialA", "alias": "FFXIVInitialA",+ "evidence": "规范化名称存在包含关系,仅供人工确认",+ }])++ def test_confirmed_alias_merges_sources_and_can_be_removed(self):+ self._source("fanbox", "initiala", "InitialA")+ self._source("rule34video", "ffxivinitiala", "FFXIVInitialA")+ added = self._post("/api/follow/author-alias", {+ "action": "add", "canonical": "InitialA", "alias": "FFXIVInitialA"})+ self.assertTrue(added["ok"])+ payload = self._get()+ self.assertEqual({row["author_key"] for row in payload["sources"]},+ {"name:initiala"})+ self.assertEqual(payload["author_aliases"][0]["canonical_name"], "InitialA")+ self.assertEqual(payload["author_aliases"][0]["aliases"][0]["name"],+ "FFXIVInitialA")+ removed = self._post("/api/follow/author-alias", {+ "action": "remove", "alias": "FFXIVInitialA"})+ self.assertTrue(removed["ok"])+ self.assertEqual(len({row["author_key"] for row in self._get()["sources"]}), 2)++ def test_alias_names_must_be_distinct_and_nonempty(self):+ for body in ({"canonical": "InitialA", "alias": "initial-a"},+ {"canonical": "", "alias": "FFXIVInitialA"}):+ with self.assertRaises(ValueError):+ self._post("/api/follow/author-alias", body)+class FollowWebSourceTests(unittest.TestCase):@classmethod@@ -801,6 +857,36 @@ class FollowWebSourceTests(unittest.TestCase):self.assertPageContains('class="fsourcelink" href="${esc(source.url)}"')self.assertPageContains('title="打开原来源"')self.assertPageContains('rel="noreferrer noopener"')+ author = self.page[self.page.index(".fauthor{"):]+ self.assertIn("border-top:0", author[:author.index("}")],+ "每一栏首个作者上方都不应出现横线")++ def test_source_actions_are_icon_only_and_stay_on_one_row(self):+ row = self.page[self.page.index("function followSourceRow(source)"):]+ row = row[:row.index("function followAliasManager")]+ self.assertIn("data-follow-check", row)+ self.assertIn("data-follow-remove", row)+ self.assertIn("${icon('refresh-cw')}", row)+ self.assertIn("${icon('trash')}", row)+ self.assertNotIn(">检查</button>", row)+ self.assertNotIn(">移除</button>", row)+ rule = self.page[self.page.index(".fauthor .fsource.frow{"):]+ self.assertIn("flex-wrap:nowrap", rule[:rule.index("}")])++ def test_each_channel_has_a_styled_update_checkbox(self):+ self.assertPageContains('class="fchannelcheck"')+ self.assertPageContains('type="checkbox" data-follow-enabled=')+ self.assertPageContains("{action:'enabled',id:Number(control.dataset.followEnabled),enabled}")+ self.assertPageContains(".fchannelcheck input{position:absolute;width:1px;height:1px;opacity:0")+ self.assertPageContains(".fchannelcheck input:checked+span{")+ self.assertPageContains("${icon('check')}")++ def test_official_channel_icons_and_alias_manager_are_visible(self):+ icons = self.page.split("const SOURCE_ICONS={", 1)[1].split("};", 1)[0]+ for provider in ("fanbox", "patreon", "subscribestar"):+ self.assertIn(provider, icons)+ self.assertPageContains("followAliasManager(followData.author_aliases,followData.alias_suggestions)")+ self.assertPageContains("'/api/follow/author-alias'")def test_already_followed_candidates_are_shown_but_not_selectable(self):# 灰掉但仍显示,免得人以为没查到。diff --git a/tests/test_migrations.py b/tests/test_migrations.pyindex f2ddcab52..4fd1a006d 100644--- a/tests/test_migrations.py+++ b/tests/test_migrations.py@@ -24,7 +24,7 @@ class MigrationTests(unittest.TestCase):backup = self.root / "before.db"done = upgrade(self.db, MIGRATIONS, backup)self.assertEqual([m.version for m in done],- ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020"])+ ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021"])self.assertTrue(backup.exists())con = sqlite3.connect(self.db)tables = {row[0] for row in con.execute(@@ -41,7 +41,7 @@ class MigrationTests(unittest.TestCase):"playlist", "playlist_item","asset_tag_preference", "asset_search","schema_migration"} <= tables)- self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020"])+ self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021"])self.assertEqual(upgrade(self.db, MIGRATIONS), [])self.assertEqual(plan(self.db, MIGRATIONS)[1], [])@@ -292,7 +292,7 @@ class MigrationTests(unittest.TestCase):base_migrations = self.root / "base-migrations"base_migrations.mkdir()for path in sorted(MIGRATIONS.glob("*.sql")):- if not path.name.startswith("0020_"):+ if not path.name.startswith(("0020_", "0021_")):shutil.copyfile(path, base_migrations / path.name)sqlite3.connect(self.db).close()upgrade(self.db, base_migrations)diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 26fa0ed79..e6e36c5c5 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -471,6 +471,7 @@ class WebDataTests(unittest.TestCase):"/api/purge-missing", "/api/review/auto-apply","/api/follow/check", "/api/follow/status", "/api/follow/save","/api/follow/source", "/api/follow/resolve", "/api/follow/credential",+ "/api/follow/author-alias",})with self.assertRaises(rm_web.ContractRouteNotFound):rm_web.dispatch_api_get(self.contract, "/api/typo", {})diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 4d00195ab..cf8980cd3 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -56,14 +56,16 @@ class OperationalScriptTests(unittest.TestCase):self.assertIn("rev-parse --git-common-dir", windows)self.assertIn("$env:PYTHONPATH = $SourceRoot", windows)self.assertIn("peach.__file__", windows)- self.assertIn("-m unittest discover", windows)+ self.assertIn("scripts\\test_runner.py --scope $Scope", windows)+ self.assertIn("ValidateSet('full', 'follow'", windows)self.assertNotIn("pytest", windows.lower())# 两个平台各有一个入口,契约必须相同——否则「两边都要绿」只是句口号。posix = (ROOT / "scripts" / "test.sh").read_text(encoding="utf-8")self.assertIn("rev-parse --git-common-dir", posix)self.assertIn('export PYTHONPATH="$SOURCE_ROOT"', posix)self.assertIn("peach.__file__", posix)- self.assertIn("-m unittest discover", posix)+ self.assertIn('scripts/test_runner.py --scope "$SCOPE"', posix)+ self.assertIn('SCOPE="${1:-full}"', posix)self.assertNotIn("pytest", posix.lower())# 文档里可以「提到」裸命令来说明它为什么不可信,但绝不能让它单独出现成为一条可照抄的指令。# 判据因此不是黑名单,而是:凡出现该命令的行,必须在同一行指向某个正式入口。@@ -79,6 +81,22 @@ class OperationalScriptTests(unittest.TestCase):f"{relative}:{number} 单独出现了裸命令,读者会照抄;必须同时点明正式入口",)+ def test_functional_test_scopes_are_explicit_and_full_remains_the_default(self):+ runner = load_script("test_runner")+ follow = {path.name for path in runner.selected_files("follow")}+ full = {path.name for path in runner.selected_files("full")}+ self.assertIn("test_follow_web.py", follow)+ self.assertIn("test_migrations.py", follow)+ self.assertNotIn("test_media.py", follow)+ self.assertGreater(len(full), len(follow))+ self.assertEqual(runner.unclassified_files(), (),+ "每个测试文件都应属于至少一个功能域")++ def test_the_full_runner_can_import_repository_scripts(self):+ runner = load_script("test_runner")+ suite = runner.build_suite("tooling")+ self.assertGreater(suite.countTestCases(), 0)+def test_structural_creator_and_mainstream_release_guards(self):self.assertTrue(is_structural_creator("asce"))self.assertTrue(is_structural_creator("门槛"))diff --git a/web/app.css b/web/app.cssindex 9eeab957b..12a98294c 100644--- a/web/app.css+++ b/web/app.css@@ -1365,14 +1365,33 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位这段必须排在 `.frow` 之后:测试用 `index('.frow{')` 取那条规则的正文,放前面的话选择器里的同名片段会被先匹配到,取回来的是这里的规则。 */-.fauthor{border-top:1px solid var(--line-soft)}-.fauthor:first-child{border-top:0}+.fauthor{border-top:0}.fauthorhead{display:flex;align-items:center;gap:9px;padding:10px 0 6px}.fauthorhead b{font-size:var(--fs-md);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fauthorhead .fmeta{margin-left:auto;flex:none}.fauthorhead .fmeta.warn{margin-left:0}-.fauthor .fsource.frow{padding-left:37px}+.fauthor .fsource.frow{padding-left:37px;display:grid;+ grid-template-columns:22px minmax(0,1fr) auto auto auto auto;gap:10px;flex-wrap:nowrap}+.fauthor .fsource.frow>b{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.fsource.disabled{opacity:.62}+.fchannelcheck{position:relative;width:20px;height:20px;display:grid;place-items:center;align-self:center;cursor:pointer}+.fchannelcheck input{position:absolute;width:1px;height:1px;opacity:0;pointer-events:none}+.fchannelcheck span{width:18px;height:18px;border:1px solid var(--border-15);border-radius:5px;+ display:grid;place-items:center;background:var(--ground);color:transparent;transition:.14s ease}+.fchannelcheck span svg{width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:2.5}+.fchannelcheck input:checked+span{background:var(--tungsten);border-color:var(--tungsten);color:var(--ground)}+.fchannelcheck input:focus-visible+span{outline:2px solid var(--tungsten);outline-offset:2px}+.fchannelcheck input:disabled+span{cursor:not-allowed;opacity:.55}+.fsourceactions{display:flex;gap:4px;white-space:nowrap}+.frowicon{width:32px;height:32px;padding:0;display:grid;place-items:center;flex:none;+ border:1px solid var(--border-15);border-radius:6px;background:transparent;color:var(--muted);cursor:pointer}+.frowicon:hover{color:var(--ink);border-color:var(--tungsten)}+.frowicon:disabled{cursor:not-allowed;opacity:.42;color:var(--muted);border-color:var(--border-15)}+.frowicon.danger:hover{color:var(--drop);border-color:var(--drop)}+.frowicon svg{width:16px;height:16px;stroke:currentColor;fill:none}+.frowicon.busy svg{animation:spin .8s linear infinite}+.fsource.frow>.frowerr{grid-column:1/-1}.favatar{width:28px;height:28px;flex:none;border-radius:var(--pill-radius);object-fit:cover;background:var(--overlay-5);outline:1px solid oklch(1 0 0 / 0.1);outline-offset:-1px}/* 取不到头像时是一个明确的空位,不是首字母——首字母会让「未取得」看着像取到了。 */@@ -1390,6 +1409,21 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位.fchip:hover{border-color:var(--tungsten);color:var(--ink)}.fchip:active{scale:.96}.flink:hover{text-decoration:underline}+.faliasmanager{margin-top:12px;border-top:1px solid var(--line-soft);padding-top:10px}+.faliasmanager>summary{cursor:pointer;color:var(--ink-2);font-weight:600;list-style-position:inside}+.faliassuggestions,.faliasrows{display:grid;gap:6px;margin-top:10px}+.faliassuggest,.faliasrow{display:flex;align-items:center;gap:10px;min-width:0}+.faliassuggest>span,.faliasrow>span{display:flex;align-items:center;gap:7px;min-width:0;flex:1;flex-wrap:wrap}+.faliassuggest i{font-style:normal;color:var(--muted)}+.faliassuggest small{color:var(--muted)}+.faliasform{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:7px;margin-top:10px}+.faliasform input{min-width:0;height:34px;padding:0 10px;border:1px solid var(--border-15);+ border-radius:6px;background:var(--ground);color:var(--ink);font:inherit}+.faliaschip{display:inline-flex;align-items:center;gap:3px;color:var(--ink-2)}+.faliaschip button{width:24px;height:24px;padding:0;border:0;background:transparent;color:var(--muted);+ display:grid;place-items:center;cursor:pointer}+.faliaschip button:hover{color:var(--drop)}+.faliaschip svg{width:14px;height:14px;stroke:currentColor;fill:none}/* summary 是 .frow 的 flex 子项,默认 flex:0 1 auto 不撑满整行——于是有折叠体的那几行状态贴在名字后面,没折叠体的却靠右,同一列两种对齐。让它占满,状态就统一在右边。 */@@ -1432,6 +1466,8 @@ details.fcred{display:block}.frow{gap:8px}.fsources{grid-template-columns:1fr}.frow .fmeta:nth-of-type(2){display:none}+ .faliasform{grid-template-columns:1fr}+ .faliasform .fbtn{width:100%}}/* 查找结果属于「添加关注」这一个动作,留在同一容器里;发丝线只分阶段,不再另套卡片。 */diff --git a/web/app.js b/web/app.jsindex 5bb7db477..ca0cb318b 100644--- a/web/app.js+++ b/web/app.js@@ -1612,6 +1612,9 @@ function followAuthorGroups(sources){/* 这些地址来自各站实际声明的图标;内容哈希变更或站点拒绝外链时退回纯文字。 */const SOURCE_ICONS={+ fanbox:'https://www.fanbox.cc/favicon.ico',+ patreon:'https://www.patreon.com/favicon.ico',+ subscribestar:'https://subscribestar.adult/favicon.ico',kemono:'https://kemono.cr/assets/favicon-CPB6l7kH.ico',coomer:'https://coomer.st/assets/favicon-CPB6l7kH.ico',pawchive:'https://pawchive.pw/static/favicon.png',@@ -1647,6 +1650,9 @@ function followAuthorAvatar(group){function followAuthorName(group){const entity=group.find(source=>source.entity_name);if(entity)return entity.entity_name;+ const aliasGroup=(followData.author_aliases||[]).find(+ item=>`name:${item.canonical_key}`===group[0]?.author_key);+ if(aliasGroup)return aliasGroup.canonical_name;// 官方主页来源不只优先提供头像,也优先提供作者写法;否则 F95 的线程标题// `Lazy Procrastinator Collection` 会因为大写字母更多而抢成分组标题。const official=group.find(source=>source.official_avatar_url);@@ -1679,17 +1685,52 @@ function followAuthorBlock(group){function followSourceRow(source){const state=source.last_status||'未检查';const bad=state==='error'||state==='unauthorized';- return `<div class="frow fsource${bad?' bad':''}">+ return `<div class="frow fsource${bad?' bad':''}${source.enabled?'':' disabled'}">+ <label class="fchannelcheck" title="${source.enabled?'参与检查更新':'暂停检查更新'}">+ <input type="checkbox" data-follow-enabled="${source.id}" ${source.enabled?'checked':''}+ aria-label="${source.enabled?'暂停':'启用'} ${esc(source.label)} 的更新检查">+ <span aria-hidden="true">${icon('check')}</span>+ </label><b><a class="fsourcelink" href="${esc(source.url)}" target="_blank"rel="noreferrer noopener" title="打开原来源">${esc(source.label)}</a></b>- <span class="fmeta">${sourceIcon(source.provider)}${esc(source.provider_label)}</span>- <span class="fmeta">${esc(source.last_checked_at?localTime(source.last_checked_at):'未检查')}</span>- <span class="fmeta${bad?' warn':''}">${esc(state)}</span>- <button class="fbtn small" data-follow-check="${source.id}">检查</button>- <button class="fbtn small fquiet" data-follow-remove="${source.id}">移除</button>+ <span class="fmeta fprovider">${sourceIcon(source.provider)}${esc(source.provider_label)}</span>+ <span class="fmeta fchecked">${esc(source.last_checked_at?localTime(source.last_checked_at):'未检查')}</span>+ <span class="fmeta fstatus${bad?' warn':''}">${esc(state)}</span>+ <span class="fsourceactions">+ <button class="frowicon" data-follow-check="${source.id}" title="检查更新"+ ${source.enabled?'':'disabled'}+ aria-label="检查 ${esc(source.label)} 的更新">${icon('refresh-cw')}</button>+ <button class="frowicon danger" data-follow-remove="${source.id}" title="移除来源"+ aria-label="移除 ${esc(source.label)}">${icon('trash')}</button>+ </span>${source.last_error?`<p class="frowerr">${esc(source.last_error)}</p>`:''}</div>`;}+function followAliasManager(groups,suggestions){+ groups=groups||[];suggestions=suggestions||[];+ const detected=suggestions.map(item=>`<div class="faliassuggest">+ <span><b>${esc(item.canonical)}</b><i>+</i><b>${esc(item.alias)}</b>+ <small>${esc(item.evidence)}</small></span>+ <button class="fbtn small" data-follow-alias-add+ data-canonical="${esc(item.canonical)}" data-alias="${esc(item.alias)}">合并</button>+ </div>`).join('');+ const saved=groups.map(group=>`<div class="faliasrow"><b>${esc(group.canonical_name)}</b>+ <span>${group.aliases.map(alias=>`<span class="faliaschip">${esc(alias.name)}+ <button type="button" data-follow-alias-remove="${esc(alias.name)}"+ title="移除别名" aria-label="移除别名 ${esc(alias.name)}">${icon('x')}</button></span>`).join('')}</span>+ </div>`).join('');+ return `<details class="faliasmanager"${suggestions.length?' open':''}>+ <summary>作者别名${suggestions.length?` · 检测到 ${suggestions.length} 组可能重复`:groups.length?` · ${groups.length} 组`:''}</summary>+ ${detected?`<div class="faliassuggestions">${detected}</div>`:''}+ <form class="faliasform" id="followAliasAdd">+ <input name="canonical" required placeholder="规范作者名" aria-label="规范作者名">+ <input name="alias" required placeholder="平台别名" aria-label="平台别名">+ <button class="fbtn" type="submit">保存别名</button>+ </form>+ ${saved?`<div class="faliasrows">${saved}</div>`:'<p class="fnote">还没有保存作者别名。</p>'}+ </details>`;+}+/* 四种状态四种颜色:待办(缺凭据)和完成(已配置)不能同色,那正是要一眼分开的两件事。 */const CRED_STATE={required:['需要','req'],optional:['可选','opt'],none:['不需要','none'],blocked:['接不进来','blocked']};@@ -1765,6 +1806,7 @@ function renderFollowManage(credentials){${(followData.suggestions||[]).length?`<div class="fguess"><span class="fmeta">猜你喜欢</span>${followSuggestionChips(followData.suggestions)}</div>`:''}+ ${followAliasManager(followData.author_aliases,followData.alias_suggestions)}<div id="followPicks"></div></section><section class="fsec">@@ -1801,7 +1843,9 @@ function renderFollowManage(credentials){wireFollowManage();if(locked)$('#stats').querySelectorAll('#followAdd textarea,#followAdd button,[data-follow-remove],[data-follow-check],'+- '[data-follow-bulk],[data-follow-guess],[data-cred-form] input,'++ '[data-follow-enabled],'++ '[data-follow-bulk],[data-follow-guess],[data-follow-alias-add],'++ '[data-follow-alias-remove],#followAliasAdd input,#followAliasAdd button,[data-cred-form] input,'+'[data-cred-form] button,[data-cred-clear]').forEach(control=>{control.disabled=true});}@@ -1895,10 +1939,20 @@ function wireFollowManage(){await openFollowManage(false);}catch(error){button.disabled=false;alert(error.message)}});+ root.querySelectorAll('[data-follow-enabled]').forEach(control=>control.onchange=async()=>{+ const enabled=control.checked;control.disabled=true;+ try{+ await api('/api/follow/source',{method:'POST',body:JSON.stringify(+ {action:'enabled',id:Number(control.dataset.followEnabled),enabled})});+ await openFollowManage(false);+ }catch(error){control.checked=!enabled;control.disabled=false;alert(error.message)}+ });root.querySelectorAll('[data-follow-check]').forEach(button=>button.onclick=async()=>{if(followBusy)return;- followBusy=true;const label=button.innerHTML;button.disabled=true;- button.textContent='检查中…';+ followBusy=true;const label=button.innerHTML,oldTitle=button.title;+ const oldAria=button.getAttribute('aria-label');+ button.disabled=true;button.classList.add('busy');button.title='检查中…';+ button.setAttribute('aria-label','检查中…');try{const id=button.dataset.followCheck;const result=await api('/api/follow/check',{method:'POST',@@ -1916,7 +1970,35 @@ function wireFollowManage(){if(box)box.outerHTML=followCheckSummary(followCheckReport);else await openFollowManage(false);}- finally{followBusy=false;button.disabled=false}+ finally{followBusy=false;button.disabled=false;button.classList.remove('busy');+ button.title=oldTitle;if(oldAria===null)button.removeAttribute('aria-label');+ else button.setAttribute('aria-label',oldAria)}+ });+ const saveAuthorAlias=async(canonical,alias,button)=>{+ button.disabled=true;+ try{+ await api('/api/follow/author-alias',{method:'POST',body:JSON.stringify(+ {action:'add',canonical,alias})});+ await openFollowManage(false);+ }catch(error){button.disabled=false;alert(error.message)}+ };+ root.querySelectorAll('[data-follow-alias-add]').forEach(button=>button.onclick=()=>+ saveAuthorAlias(button.dataset.canonical,button.dataset.alias,button));+ const aliasForm=root.querySelector('#followAliasAdd');+ if(aliasForm)aliasForm.onsubmit=event=>{+ event.preventDefault();const data=new FormData(aliasForm),button=aliasForm.querySelector('button');+ saveAuthorAlias(String(data.get('canonical')||'').trim(),+ String(data.get('alias')||'').trim(),button);+ };+ root.querySelectorAll('[data-follow-alias-remove]').forEach(button=>button.onclick=async()=>{+ const alias=button.dataset.followAliasRemove;+ if(!confirm(`移除作者别名「${alias}」?对应来源会恢复成独立作者组。`))return;+ button.disabled=true;+ try{+ await api('/api/follow/author-alias',{method:'POST',body:JSON.stringify(+ {action:'remove',alias})});+ await openFollowManage(false);+ }catch(error){button.disabled=false;alert(error.message)}});root.querySelectorAll('[data-follow-guess]').forEach(chip=>chip.onclick=()=>{if(!form)return;