Peach: Local-first video metadata scraper and media manager.
refactor(follow): 来源登记表变成唯一真相,链接解析回到各站连接器
longmeidaod84b85192043
diff --git a/src/peach/follow_providers.py b/src/peach/follow_providers.pyindex d6173a980..04822d4a8 100644--- a/src/peach/follow_providers.py+++ b/src/peach/follow_providers.py@@ -38,10 +38,20 @@ class ProviderSpec:official_identity: bool = False#: 用户明确点名要隐藏的既有条目(站内 id)。只影响浏览面,不删 ledger 行。excluded_external_ids: tuple[str, ...] = ()+ #: 粘一条链接时,哪些站点主机认成这个来源。子域也算(`x.fanbox.cc`、+ #: `api.rule34.xxx`),所以这里只写注册域那一截。**不是** `hosts`:那是媒体+ #: 代理的白名单,值可能完全不同(paheal 的站点是 `rule34.paheal.net`,+ #: 媒体在 `paheal-cdn.net`)。+ url_hosts: tuple[str, ...] = ()+ #: 这个来源的每个条目都是一次独立发布,即使标题相同。+ #: F95 的线程标题只是容器名,每个带资源的楼层各自成组。+ release_key_per_post: bool = Falsedef __post_init__(self) -> None:if self.semantics not in ("work", "release"):raise ValueError(f"{self.key} 的 semantics 只能是 work 或 release")+ if self.source_url and not self.url_hosts:+ raise ValueError(f"{self.key} 是追更来源,必须登记至少一个 url_hosts")def _spec(key: str, label: str, **kwargs) -> ProviderSpec:@@ -55,36 +65,44 @@ PROVIDERS: dict[str, ProviderSpec] = {# 官方渠道:只读公开免费发布,身份可信,所以优先做主条目;媒体走各自详情接口,# 不经本地代理,因此没有 hosts。_spec("fanbox", "FANBOX", source_url="https://{ref}.fanbox.cc/",- priority=1, official_identity=True),+ url_hosts=("fanbox.cc",), priority=1, official_identity=True),_spec("subscribestar", "SubscribeStar", source_url="https://{ref}",+ url_hosts=("subscribestar.adult", "subscribestar.com"),priority=2, official_identity=True),_spec("patreon", "Patreon", source_url="https://www.patreon.com/cw/{ref}",- priority=3, official_identity=True),+ url_hosts=("patreon.com",), priority=3, official_identity=True),# 归档站:同一套代码的姊妹站,支持真实历史分页所以可回填。_spec("kemono", "Kemono", source_url="https://kemono.cr/{ref}",- hosts=("kemono.cr",), priority=10, backfill=True),+ hosts=("kemono.cr",), url_hosts=("kemono.cr",),+ priority=10, backfill=True),_spec("pawchive", "Pawchive", source_url="https://pawchive.pw/{ref}",- hosts=("pawchive.pw",), priority=15, backfill=True),+ hosts=("pawchive.pw",), url_hosts=("pawchive.pw",),+ priority=15, backfill=True),_spec("coomer", "Coomer", source_url="https://coomer.st/{ref}",- hosts=("coomer.st",), priority=20, backfill=True),+ hosts=("coomer.st",), url_hosts=("coomer.st",),+ priority=20, backfill=True),# 标签/模特站。# `excluded_external_ids` 是用户明确点名的那个既有超大合集。连接器现在按# 详情页署名作者数拦截同类条目;这一条只让已经入库的旧候选立即从浏览面消失。_spec("rule34video", "Rule34Video",source_url="https://rule34video.com/models/{ref}/",- hosts=("rule34video.com",), priority=30, backfill=True,+ hosts=("rule34video.com",), url_hosts=("rule34video.com",),+ priority=30, backfill=True,excluded_external_ids=("4533145",)),_spec("rule34xxx", "Rule34.xxx",source_url="https://rule34.xxx/index.php?page=post&s=list&tags={ref}",- hosts=("rule34.xxx",), priority=40, backfill=True),+ hosts=("rule34.xxx",), url_hosts=("rule34.xxx",),+ priority=40, backfill=True),_spec("rule34paheal", "Rule34 Paheal",source_url="https://rule34.paheal.net/post/list/{ref}/1",- hosts=("paheal.net", "paheal-cdn.net"), priority=45, backfill=True),+ hosts=("paheal.net", "paheal-cdn.net"),+ url_hosts=("rule34.paheal.net",), priority=45, backfill=True),# 论坛:每个条目是同一作品的一次发布,不是独立作品。_spec("f95zone", "F95zone", source_url="https://f95zone.to/threads/{ref}/",- semantics="release", hosts=("f95zone.to",), priority=50),+ semantics="release", hosts=("f95zone.to",), url_hosts=("f95zone.to",),+ priority=50, release_key_per_post=True),_spec("simpcity", "SimpCity", source_url="https://simpcity.cr/threads/{ref}/",- semantics="release", priority=60),+ semantics="release", url_hosts=("simpcity.cr",), priority=60),# 文件站:不是追更来源,只作为媒体来源出现在界面上,所以没有 source_url。_spec("gofile", "Gofile"),)@@ -131,6 +149,36 @@ def official_identity_providers() -> frozenset[str]:return frozenset(key for key, spec in PROVIDERS.items() if spec.official_identity)+def url_hosts() -> dict[str, str]:+ """站点主机 → 来源键。解析粘进来的链接时用它替代一串 if/elif。++ 键只写注册域那一截;子域由 `provider_for_host` 按后缀匹配,所以+ `creator.fanbox.cc` 和 `api.rule34.xxx` 都不必单独登记。+ """+ return {host: key for key, spec in PROVIDERS.items() for host in spec.url_hosts}+++def provider_for_host(host: str) -> str:+ """这个主机属于哪个来源。认不出来返回空串。++ 先精确匹配,再按最长后缀匹配——后缀更长的登记更具体,必须赢:+ `rule34.paheal.net` 不能被将来某个 `paheal.net` 登记抢走。+ """+ bare = str(host or "").strip().lower().removeprefix("www.")+ table = url_hosts()+ if bare in table:+ return table[bare]+ matched = [registered for registered in table+ if bare.endswith(f".{registered}")]+ return table[max(matched, key=len)] if matched else ""+++def release_key_per_post() -> frozenset[str]:+ """每个条目都是一次独立发布的来源;同名条目不合并。"""+ return frozenset(key for key, spec in PROVIDERS.items()+ if spec.release_key_per_post)++def excluded_external_ids() -> dict[str, frozenset[str]]:"""按来源列出要从浏览面隐藏的既有条目。没有要隐藏的来源不出现在结果里。"""return {key: frozenset(spec.excluded_external_ids)diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex ea0cbd7d7..92e5f2d85 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -310,6 +310,62 @@ def _exc_summary(exc: Exception, limit: int = 140) -> str:return re.sub(r"\s+", " ", text)[:limit]+@dataclass(frozen=True)+class ParsedSource:+ """从一条粘进来的链接认出来的订阅。"""++ provider: str+ ref: str+ url: str+ label: str+ semantics: str++ @property+ def evidence(self) -> str:+ return "链接直接指明"+++#: 每个来源的条目语义:`work` 是每条一个独立作品,`release` 是同一作品的历次发布。+_SEMANTICS = follow_providers.semantics()++#: 站点主机 → 来源键。粘进来的链接靠它认出属于哪个站,不再是一串 if/elif。+_URL_HOSTS = follow_providers.url_hosts()++_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})(?:/|$)")+_FANBOX_AT_RE = re.compile(r"^/@([A-Za-z0-9_-]{1,64})(?:/|$)")+_PAHEAL_LIST_RE = re.compile(r"^/post/list/([^/]+)/\d+$")+++def canonical_source_ref(provider: str, ref: str) -> str:+ """Return the provider's stable source identity.++ Most provider ids are case-sensitive opaque values. rule34.xxx tags are not:+ the API returns the same feed for ``LazyProcrastinator`` and+ ``lazyprocrastinator``. Keeping the pasted spelling in the unique key therefore+ creates duplicate subscriptions when the same author is added in two batches.+ """+ value = str(ref or "").strip()+ return value.casefold() if provider in {"rule34xxx", "rule34paheal"} else value+++#: 线程 slug 里从这个 token 起就不是作品名了:f95 的惯例是+#: `<作品名>-<发布日期>-<作者手柄>`,日期之后全是元数据。+_SLUG_TAIL_RE = re.compile(r"^(?:19|20)\d{2}$|^v?\d+(?:\.\d+)+[a-z]?$")+++def _slug_label(slug: str) -> str:+ words = [word for word in re.split(r"[-_]+", slug) if word]+ kept: list[str] = []+ for word in words:+ if kept and _SLUG_TAIL_RE.match(word):+ break+ kept.append(word)+ return " ".join(kept).strip() or re.sub(r"[-_]+", " ", slug).strip() or slug++class _BaseConnector:provider = ""semantics = "work"@@ -469,6 +525,26 @@ class _BaseConnector:"""return str(item.thumb_url or "") or None+ @classmethod+ def provider_keys(cls) -> tuple[str, ...]:+ """这个连接器负责哪些来源键。默认就是它自己声明的那一个。++ kemono 系三站共用一套代码,所以由类自己说清楚它服务三个键,而不是在+ `CONNECTORS` 里把同一个类写三遍——那份重复要和 `HOSTS` 各改一处。+ """+ return (cls.provider,) if cls.provider else ()++ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ """把一条已经认出属于本站的链接解析成可登记的订阅。++ 主机到来源的分派由 `follow_providers.provider_for_host` 做,`host` 已经+ 小写且去掉了 `www.`;这里只管「这个站的 URL 里哪一截是 ref」。纯解析,+ 不联网;认不出就抛 `FollowSourceError` 并说清楚该长什么样。+ """+ raise FollowSourceError(f"{cls.provider} 暂不支持从链接登记")+@classmethoddef profile_handle(cls, ref: str) -> str:"""这条 ref 里可以当作者别名用的平台手柄,没有就返回空串。@@ -551,6 +627,23 @@ class KemonoConnector(_BaseConnector):#: 列表接口一页的条数,2026-08-27 实测为 50(`?o=50` 拿到的是第 51 条起)。PAGE_SIZE = 50+ @classmethod+ def provider_keys(cls) -> tuple[str, ...]:+ return tuple(cls.HOSTS)++ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ matched = _KEMONO_PATH_RE.match(parsed.path or "/")+ if not matched:+ raise FollowSourceError(+ f"{host} 的链接要指向某个创作者,形如 "+ f"https://{host}/fanbox/user/30917150")+ service, user = matched.group(1), matched.group(2)+ return ParsedSource(provider, f"{service}/{user}",+ f"https://{host}/{service}/user/{user}",+ f"{user} · {service}", "work")+def __init__(self, provider: str = "kemono", *,max_probes: int = DEFAULT_MAX_PROBES, **kwargs):if provider not in self.HOSTS:@@ -807,6 +900,19 @@ class Rule34VideoConnector(_BaseConnector):MAX_COLLECTION_MODELS = 20DEFAULT_MAX_PROBES = 24+ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ matched = _R34V_PATH_RE.match(parsed.path or "/")+ if not matched:+ raise FollowSourceError(+ "rule34video 的链接要指向作者页,形如 "+ "https://rule34video.com/models/lazyprocrastinator/")+ slug = matched.group(1)+ return ParsedSource("rule34video", slug,+ f"https://rule34video.com/models/{slug}/",+ _slug_label(slug), "work")+def __init__(self, *, max_probes: int = DEFAULT_MAX_PROBES,max_collection_models: int = MAX_COLLECTION_MODELS, **kwargs):super().__init__(**kwargs)@@ -994,6 +1100,20 @@ class Rule34XxxConnector(_BaseConnector):r"^https://api-cdn\.rule34\.xxx/thumbnails/(\d+)/thumbnail_"r"([0-9a-f]{32})\.jpg(?:[?#].*)?$", re.IGNORECASE)+ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ tags = canonical_source_ref(+ "rule34xxx", urllib.parse.parse_qs(parsed.query).get("tags", [""])[0])+ if not tags:+ raise FollowSourceError(+ "rule34.xxx 的链接要带标签,形如 "+ "https://rule34.xxx/index.php?page=post&s=list&tags=lazyprocrastinator")+ return ParsedSource("rule34xxx", tags,+ "https://rule34.xxx/index.php?page=post&s=list"+ f"&tags={urllib.parse.quote(tags)}",+ _slug_label(tags), "work")+@classmethoddef display_thumb_url(cls, item) -> str | None:matched = cls._PREVIEW_RE.match(str(item.thumb_url or ""))@@ -1213,6 +1333,24 @@ class Rule34PahealConnector(_BaseConnector):_DURATION_RE = re.compile(r"\b(\d+(?:\.\d+)?)s\b", re.IGNORECASE)_TITLE_STOPWORDS = frozenset({"animated", "blender", "video", "sound", "mp4", "webm"})+ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ # 搜索标签既可能在 fragment 里(帖子详情页),也可能在列表页路径里。+ tag = urllib.parse.parse_qs(parsed.fragment).get("search", [""])[0]+ if not tag:+ matched = _PAHEAL_LIST_RE.match(parsed.path or "/")+ tag = urllib.parse.unquote(matched.group(1)) if matched else ""+ tag = canonical_source_ref("rule34paheal", tag)+ if not tag:+ raise FollowSourceError(+ "rule34.paheal 的链接要带搜索标签,形如 "+ "https://rule34.paheal.net/post/view/7428820#search=InitialA")+ encoded = urllib.parse.quote(tag, safe="()_")+ return ParsedSource("rule34paheal", tag,+ f"https://rule34.paheal.net/post/list/{encoded}/1",+ _slug_label(tag), "work")+def __init__(self, *, max_items: int = 24, **kwargs):super().__init__(max_items=max_items, **kwargs)@@ -1343,6 +1481,21 @@ class F95ZoneConnector(_BaseConnector):_INLINE_IMAGE_RE = re.compile(r"\.(?:avif|bmp|gif|jpe?g|png|webp)(?:$|[?#])", re.IGNORECASE)+ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ path = parsed.path or "/"+ matched = _THREAD_PATH_RE.match(path)+ if not matched:+ raise FollowSourceError(+ "f95zone 的链接要指向一个线程,形如 "+ "https://f95zone.to/threads/xxx.50685/")+ thread = matched.group(1)+ slug = path.split("/threads/", 1)[1].rsplit(".", 1)[0] if "." in path else ""+ return ParsedSource("f95zone", thread,+ f"https://f95zone.to/threads/{thread}/",+ _slug_label(slug) or f"线程 {thread}", "release")+def fetch(self, ref: str, *, etag: str | None = None,last_modified: str | None = None, page: int = 0) -> SourceFetch:thread = (ref or "").strip()@@ -1613,6 +1766,21 @@ class FanboxConnector(_BaseConnector):semantics = "work"_CREATOR_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")+ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ # 作者主页有两种形状:`creator.fanbox.cc` 子域,和 `fanbox.cc/@creator`。+ if host.endswith(".fanbox.cc"):+ creator = host.removesuffix(".fanbox.cc")+ else:+ matched = _FANBOX_AT_RE.match(parsed.path or "/")+ 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")+@classmethoddef profile_handle(cls, ref: str) -> str:return str(ref or "").strip()@@ -1766,6 +1934,22 @@ class SubscribeStarConnector(_BaseConnector):HOSTS = frozenset({"subscribestar.adult", "subscribestar.com"})_SLUG_RE = re.compile(r"^[A-Za-z0-9_-]{1,80}$")+ #: 这些首段路径是站点自己的功能页,不是创作者。+ _RESERVED = frozenset({"posts", "search", "login", "signup"})++ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ matched = _DIRECT_CREATOR_RE.match(parsed.path or "/")+ if not matched or matched.group(1) in cls._RESERVED:+ raise FollowSourceError(+ "SubscribeStar 的链接要指向创作者主页,形如 "+ "https://subscribestar.adult/creator")+ slug = matched.group(1)+ # ref 带上主机名:`.adult` 与 `.com` 是两个站,同名创作者不一定是一个人。+ return ParsedSource("subscribestar", f"{host}/{slug}",+ f"https://{host}/{slug}", slug, "work")+@classmethoddef profile_handle(cls, ref: str) -> str:# ref 带着站点主机名(`subscribestar.adult/initiala`),手柄只是最后那截。@@ -1840,6 +2024,28 @@ class PatreonConnector(_BaseConnector):_VANITY_RE = re.compile(r"^[A-Za-z0-9_-]{1,80}$")_POST_RE = re.compile(r"/posts/(?:[^/?#]*-)?(\d{4,})(?:[/?#]|$)")+ #: 这些首段路径是站点自己的功能页,不是创作者短名。+ _RESERVED = frozenset({"posts", "join", "login", "signup", "home", "explore"})++ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ path = parsed.path or "/"+ 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:]+ if not parts or parts[0].lower() in cls._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")+@classmethoddef profile_handle(cls, ref: str) -> str:value = str(ref or "").strip().strip("/")@@ -1918,68 +2124,23 @@ class SimpCityConnector(_BaseConnector):"simpcity.cr 由 DDoS-Guard 的浏览器质询保护;Peach 不绕机器人验证。""要接入需要你在浏览器里通过质询后提供会话 cookie,或改用其他来源。")+ @classmethod+ def parse_url(cls, provider: str, parsed: urllib.parse.SplitResult,+ host: str) -> "ParsedSource":+ # 整站被质询挡着,登记下来也抓不到;当场说原因比留一条死来源好。+ raise FollowSourceError(cls.blocked_reason)+def fetch(self, ref: str, *, etag: str | None = None,last_modified: str | None = None, page: int = 0) -> SourceFetch:raise FollowSourceError(self.blocked_reason)-@dataclass(frozen=True)-class ParsedSource:- """从一条粘进来的链接认出来的订阅。"""-- provider: str- ref: str- url: str- label: str- semantics: str-- @property- def evidence(self) -> str:- return "链接直接指明"---#: 每个来源的条目语义:`work` 是每条一个独立作品,`release` 是同一作品的历次发布。-_SEMANTICS = follow_providers.semantics()--_KEMONO_HOSTS = {"kemono.cr": "kemono", "coomer.st": "coomer", "pawchive.pw": "pawchive"}-_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:- """Return the provider's stable source identity.-- Most provider ids are case-sensitive opaque values. rule34.xxx tags are not:- the API returns the same feed for ``LazyProcrastinator`` and- ``lazyprocrastinator``. Keeping the pasted spelling in the unique key therefore- creates duplicate subscriptions when the same author is added in two batches.- """- value = str(ref or "").strip()- return value.casefold() if provider in {"rule34xxx", "rule34paheal"} else value---#: 线程 slug 里从这个 token 起就不是作品名了:f95 的惯例是-#: `<作品名>-<发布日期>-<作者手柄>`,日期之后全是元数据。-_SLUG_TAIL_RE = re.compile(r"^(?:19|20)\d{2}$|^v?\d+(?:\.\d+)+[a-z]?$")---def _slug_label(slug: str) -> str:- words = [word for word in re.split(r"[-_]+", slug) if word]- kept: list[str] = []- for word in words:- if kept and _SLUG_TAIL_RE.match(word):- break- kept.append(word)- return " ".join(kept).strip() or re.sub(r"[-_]+", " ", slug).strip() or slug--def parse_source_url(raw_url: str) -> ParsedSource:"""把一条来源链接认成可登记的订阅。- 只做纯解析,不联网。认不出来就抛 `FollowSourceError` 并说清楚支持哪些形状——- 与其静默登记一个永远抓不到东西的来源,不如当场说不认识。+ 只做纯解析,不联网。这里只管链接本身是否合法、以及这个主机属于哪个站;每个站+ 的 URL 形状归它自己的连接器(`parse_url`)。认不出来就抛 `FollowSourceError`+ 并说清楚支持哪些形状——与其静默登记一个永远抓不到东西的来源,不如当场说不认识。"""text = (raw_url or "").strip()if not text:@@ -1994,134 +2155,26 @@ def parse_source_url(raw_url: str) -> ParsedSource:raise FollowSourceError("只接受 http(s) 链接")if parsed.username is not None or parsed.password is not None:raise FollowSourceError("链接里不能带账号密码")- host = parsed.hostname.lower()- bare = host[4:] if host.startswith("www.") else host- path = parsed.path or "/"-- provider = _KEMONO_HOSTS.get(bare)- if provider:- matched = _KEMONO_PATH_RE.match(path)- if not matched:- raise FollowSourceError(- f"{bare} 的链接要指向某个创作者,形如 "- f"https://{bare}/fanbox/user/30917150")- service, user = matched.group(1), matched.group(2)- return ParsedSource(provider, f"{service}/{user}",- 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:- raise FollowSourceError(- "rule34video 的链接要指向作者页,形如 "- "https://rule34video.com/models/lazyprocrastinator/")- slug = matched.group(1)- return ParsedSource("rule34video", slug,- f"https://rule34video.com/models/{slug}/",- _slug_label(slug), "work")-- if bare in ("rule34.xxx", "api.rule34.xxx"):- tags = canonical_source_ref(- "rule34xxx",- urllib.parse.parse_qs(parsed.query).get("tags", [""])[0],- )- if not tags:- raise FollowSourceError(- "rule34.xxx 的链接要带标签,形如 "- "https://rule34.xxx/index.php?page=post&s=list&tags=lazyprocrastinator")- return ParsedSource("rule34xxx", tags,- "https://rule34.xxx/index.php?page=post&s=list"- f"&tags={urllib.parse.quote(tags)}",- _slug_label(tags), "work")+ host = parsed.hostname.lower().removeprefix("www.")- if bare == "rule34.paheal.net":- tag = urllib.parse.parse_qs(parsed.fragment).get("search", [""])[0]- if not tag:- matched = re.match(r"^/post/list/([^/]+)/\d+$", path)- tag = urllib.parse.unquote(matched.group(1)) if matched else ""- tag = canonical_source_ref("rule34paheal", tag)- if not tag:- raise FollowSourceError(- "rule34.paheal 的链接要带搜索标签,形如 "- "https://rule34.paheal.net/post/view/7428820#search=InitialA")- encoded = urllib.parse.quote(tag, safe="()_")- return ParsedSource("rule34paheal", tag,- f"https://rule34.paheal.net/post/list/{encoded}/1",- _slug_label(tag), "work")-- if bare == "f95zone.to":- matched = _THREAD_PATH_RE.match(path)- if not matched:- raise FollowSourceError(- "f95zone 的链接要指向一个线程,形如 "- "https://f95zone.to/threads/xxx.50685/")- thread = matched.group(1)- slug = path.split("/threads/", 1)[1].rsplit(".", 1)[0] if "." in path else ""- return ParsedSource("f95zone", thread,- f"https://f95zone.to/threads/{thread}/",- _slug_label(slug) or f"线程 {thread}", "release")-- if bare == "simpcity.cr":- raise FollowSourceError(SimpCityConnector.blocked_reason)+ provider = follow_providers.provider_for_host(host)+ factory = CONNECTORS.get(provider)+ if factory is None:+ raise FollowSourceError(+ f"不认识 {host}。当前支持 " + "、".join(sorted(_URL_HOSTS)) + "。")+ return factory.parse_url(provider, parsed, host)- raise FollowSourceError(- f"不认识 {bare}。当前支持 FANBOX、Patreon、SubscribeStar,"- "kemono.cr、coomer.st、pawchive.pw 的创作者页,rule34video.com 的作者页,"- "rule34.xxx 与 rule34.paheal.net 的标签页,以及 f95zone.to 的线程。")+#: 全部站点连接器。来源键由每个类自己声明,所以 kemono 系三站不再在映射里把+#: 同一个类写三遍——那份重复和 `KemonoConnector.HOSTS` 是同一件事的两份手写。+_CONNECTOR_CLASSES: tuple[type, ...] = (+ FanboxConnector, PatreonConnector, SubscribeStarConnector, KemonoConnector,+ Rule34VideoConnector, Rule34XxxConnector, Rule34PahealConnector,+ F95ZoneConnector, SimpCityConnector,+)CONNECTORS: dict[str, type] = {- "fanbox": FanboxConnector,- "patreon": PatreonConnector,- "subscribestar": SubscribeStarConnector,- "kemono": KemonoConnector,- "coomer": KemonoConnector,- "pawchive": KemonoConnector,- "rule34video": Rule34VideoConnector,- "rule34xxx": Rule34XxxConnector,- "rule34paheal": Rule34PahealConnector,- "f95zone": F95ZoneConnector,- "simpcity": SimpCityConnector,+ key: factory for factory in _CONNECTOR_CLASSES for key in factory.provider_keys()}@@ -2159,6 +2212,7 @@ def build_connector(provider: str, **kwargs) -> FollowConnector:factory = CONNECTORS.get(provider)if factory is None:raise FollowSourceError(f"未知的追更来源:{provider}")- if factory is KemonoConnector:- return KemonoConnector(provider=provider, **kwargs)+ # 服务多个来源键的连接器(kemono 系)必须知道自己这次代表哪个站。+ if len(factory.provider_keys()) > 1:+ return factory(provider=provider, **kwargs)return factory(**kwargs)diff --git a/src/peach/follow_store.py b/src/peach/follow_store.pyindex f756cb852..c3838e271 100644--- a/src/peach/follow_store.py+++ b/src/peach/follow_store.py@@ -41,6 +41,10 @@ _F95_TITLE_SUFFIX_RE = re.compile(r"\s+collections?\s*$", re.IGNORECASE)#: 作者显示名与头像可信的官方渠道;归档站只作回退。_OFFICIAL_IDENTITY_PROVIDERS = follow_providers.official_identity_providers()+#: 每个条目都是一次独立发布的来源。论坛线程的标题只是容器名,同一线程里每个带+#: 资源的楼层各自成组;这条口径登记在 `follow_providers`,不在这里点名站点。+_RELEASE_KEY_PER_POST = follow_providers.release_key_per_post()+def normalized_author_name(value: str, *, provider: str = "") -> str:"""作者别名表的身份键。@@ -241,8 +245,8 @@ class FollowStore:verdict = classify(candidate.title, creator_aliases=creator_aliases,version=candidate.version, semantics=fetch.semantics)release_key = verdict.release_key- if fetch.provider == "f95zone":- # F95 的线程标题只是容器名;每个带资源的楼层都是一次独立发布。+ if fetch.provider in _RELEASE_KEY_PER_POST:+ # 线程标题只是容器名;每个带资源的楼层都是一次独立发布。# 同一楼层若展开出多个视频,由 media_items 在详情里组成 Mix。release_key = f"{release_key}\u0000{candidate.external_id}"elif not candidate.title_is_name:@@ -456,12 +460,12 @@ class FollowStore:"""# 先按标题判据拆开同站撞车,再按来源自带的关系合并:来源自己声明过的关系# 优先,绝不能被标题判据拆散。- # 兼容已经落库的旧 F95 行:旧版用线程标题作为 release_key,读时也要按+ # 兼容已经落库的旧论坛行:旧版用线程标题作为 release_key,读时也要按# 楼层拆开,部署后无需改写真实 ledger 就会立即显示成独立条目。split_posts = tuple(FollowItemRow(**{**item.__dict__,"release_key": f"{item.release_key}\u0000{item.external_id}"})- if item.provider == "f95zone"+ if item.provider in _RELEASE_KEY_PER_POSTand not item.release_key.endswith(f"\u0000{item.external_id}")else itemfor item in itemsdiff --git a/tests/test_follow_providers.py b/tests/test_follow_providers.pyindex b74678722..5f0e7ab22 100644--- a/tests/test_follow_providers.py+++ b/tests/test_follow_providers.py@@ -12,7 +12,8 @@ from peach.follow_secrets import (SYNCABLE_FIELDS,credential_store_for,)-from peach.follow_store import _OFFICIAL_IDENTITY_PROVIDERS+from peach.follow_store import (_OFFICIAL_IDENTITY_PROVIDERS,+ _RELEASE_KEY_PER_POST)from peach.web_follow import PROVIDER_LABELS, _BACKFILL_PROVIDERS@@ -124,6 +125,76 @@ class ProviderRegistryTests(unittest.TestCase):follow_providers.ProviderSpec(key="x", label="X", semantics="whatever")+class UrlHostTests(unittest.TestCase):+ """粘一条链接时「这个主机属于哪个站」的登记与查表。"""++ def test_every_follow_source_declares_at_least_one_url_host(self):+ """没有 url_hosts 的追更来源永远无法从链接登记,而且不会报错。"""+ for key, spec in follow_providers.PROVIDERS.items():+ if spec.source_url:+ self.assertTrue(spec.url_hosts, f"{key} 缺 url_hosts")++ def test_a_source_url_without_url_hosts_is_refused_at_declaration_time(self):+ with self.assertRaises(ValueError):+ follow_providers.ProviderSpec(key="x", label="X",+ source_url="https://x/{ref}")++ def test_no_host_is_claimed_by_two_sources(self):+ declared = [host for spec in follow_providers.PROVIDERS.values()+ for host in spec.url_hosts]+ self.assertEqual(len(declared), len(set(declared)),+ "同一个主机登记两次,解析结果取决于字典顺序")++ def test_url_hosts_are_not_the_media_proxy_allowlist(self):+ """两张表名字像、含义不同:paheal 的站点主机与媒体主机根本不一样。++ 曾经想「复用 hosts 就行」——不行。`hosts` 是媒体代理白名单,放宽它等于+ 放宽能被代理取回的地址;`url_hosts` 只决定一条链接归谁解析。+ """+ paheal = follow_providers.PROVIDERS["rule34paheal"]+ self.assertEqual(paheal.url_hosts, ("rule34.paheal.net",))+ self.assertIn("paheal-cdn.net", paheal.hosts)+ self.assertNotIn("rule34.paheal.net", paheal.hosts)++ def test_subdomains_and_www_resolve_to_the_registered_source(self):+ for host, expected in (+ ("fanbox.cc", "fanbox"),+ ("www.fanbox.cc", "fanbox"),+ ("ffxivinitiala.fanbox.cc", "fanbox"),+ ("api.rule34.xxx", "rule34xxx"),+ ("kemono.cr", "kemono"),+ ("coomer.st", "coomer"),+ ("SubscribeStar.adult", "subscribestar"),+ ):+ self.assertEqual(follow_providers.provider_for_host(host), expected, host)++ def test_the_longest_registered_suffix_wins(self):+ """`rule34.paheal.net` 比将来可能出现的 `paheal.net` 更具体,必须赢。"""+ self.assertEqual(follow_providers.provider_for_host("rule34.paheal.net"),+ "rule34paheal")+ self.assertEqual(+ follow_providers.provider_for_host("cdn.rule34.paheal.net"),+ "rule34paheal")++ def test_an_unregistered_host_is_empty_not_a_guess(self):+ for host in ("nyaa.si", "", "notfanbox.cc", "fanbox.cc.evil.example"):+ self.assertEqual(follow_providers.provider_for_host(host), "", host)+++class ReleaseKeyPerPostTests(unittest.TestCase):+ def test_the_rule_is_declared_in_the_registry_not_named_in_the_data_layer(self):+ """论坛线程每层各自成组,这是来源语义,不是 `follow_store` 里的站点点名。"""+ self.assertEqual(follow_providers.release_key_per_post(),+ frozenset({"f95zone"}))+ self.assertEqual(_RELEASE_KEY_PER_POST,+ follow_providers.release_key_per_post())++ def test_it_only_applies_to_release_semantics(self):+ """每条各自成组只对「同一作品的历次发布」有意义;work 语义靠标题合并。"""+ for key in follow_providers.release_key_per_post():+ self.assertEqual(follow_providers.PROVIDERS[key].semantics, "release")++class ExcludedItemTests(unittest.TestCase):def test_hidden_items_are_declared_in_the_registry_not_in_the_web_layer(self):"""用户点名要隐藏的既有条目登记在这张表上。diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex a7dc61f7b..ffb703377 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -1270,6 +1270,17 @@ class BuildConnectorTests(unittest.TestCase):for provider in ("kemono", "coomer", "pawchive"):self.assertEqual(build_connector(provider).provider, provider)+ def test_the_registry_is_derived_from_what_each_class_declares(self):+ """`CONNECTORS` 不再手写。以前 kemono 系三站要在映射里把同一个类写三遍,+ 和 `KemonoConnector.HOSTS` 是同一件事的两份手写清单。"""+ self.assertEqual(+ follow_sources.CONNECTORS,+ {key: factory for factory in follow_sources._CONNECTOR_CLASSES+ for key in factory.provider_keys()})+ self.assertEqual(set(KemonoConnector.provider_keys()),+ set(KemonoConnector.HOSTS))+ self.assertEqual(FanboxConnector.provider_keys(), ("fanbox",))+def test_unknown_provider_is_rejected(self):with self.assertRaises(FollowSourceError):build_connector("nyaa")@@ -1281,6 +1292,40 @@ class BuildConnectorTests(unittest.TestCase):self.assertIsInstance(build_connector("rule34paheal"), Rule34PahealConnector)+class ParseUrlDelegationTests(unittest.TestCase):+ """链接解析的分派边界:主机归 `follow_providers`,形状归各自的连接器。"""++ def test_the_dispatcher_hands_off_to_the_connector_that_owns_the_host(self):+ with patch.object(Rule34VideoConnector, "parse_url") as parse:+ parse.return_value = "sentinel"+ self.assertEqual(+ parse_source_url("https://www.rule34video.com/models/abc/"),+ "sentinel")+ provider, parsed, host = parse.call_args.args+ self.assertEqual((provider, host), ("rule34video", "rule34video.com"))+ self.assertEqual(parsed.path, "/models/abc/")++ def test_every_registered_connector_can_parse_its_own_links(self):+ """漏写 `parse_url` 只会让那个站的链接报「暂不支持」,界面上看不出是漏写。++ simpcity 是有意的例外:整站被质询挡着,它覆盖 `parse_url` 只为把原因原样+ 报出来,所以这里断言它也覆盖了,而不是跳过它。+ """+ for provider, factory in follow_sources.CONNECTORS.items():+ with self.subTest(provider=provider):+ self.assertIsNot(factory.parse_url.__func__,+ follow_sources._BaseConnector.parse_url.__func__,+ f"{provider} 没有自己的 parse_url")++ def test_an_unrecognised_host_lists_the_hosts_that_are_registered(self):+ """提示词从登记表来;新增站点不必再回来改这句文案。"""+ with self.assertRaises(FollowSourceError) as caught:+ parse_source_url("https://nyaa.si/view/1")+ message = str(caught.exception)+ for host in follow_sources._URL_HOSTS:+ self.assertIn(host, message)++class RelativeDateTests(unittest.TestCase):def test_units_are_converted_against_an_injected_reference(self):now = datetime(2026, 8, 25, 12, 0, tzinfo=timezone.utc)