Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

refactor(follow): 凭据仓库只从一个工厂构造,命令行也看得到共享副本

longmeidao32dc5b5d4bae
diff --git a/src/peach/follow_cli.py b/src/peach/follow_cli.py
index aec033c29..fd7b6cd02 100644
--- a/src/peach/follow_cli.py
+++ b/src/peach/follow_cli.py
@@ -10,10 +10,10 @@ import sqlite3
from datetime import datetime, timezone
from pathlib import Path
-from .config import DATABASE_PATH, SECRETS_DIR, SOURCES_DIR
+from .config import DATABASE_PATH, SECRETS_DIR, SHARED_DATA_ROOT, SOURCES_DIR
from . import follow_providers
from .follow import FollowSourceError
-from .follow_secrets import CredentialError, CredentialStore
+from .follow_secrets import CredentialError, credential_store_for
from .follow_sources import CONNECTORS, build_connector
from .follow_store import FollowStore
@@ -78,7 +78,7 @@ def _list(args) -> int:
def _check(args) -> int:
store, connection = _store(args)
- credentials = CredentialStore(args.secrets_root)
+ credentials = credential_store_for(args.secrets_root, shared_root=args.shared_root)
failures = 0
try:
rows = [row for row in store.sources(enabled_only=True)
@@ -193,7 +193,7 @@ def _save(args) -> int:
def _creds(args) -> int:
- store = CredentialStore(args.secrets_root)
+ store = credential_store_for(args.secrets_root, shared_root=args.shared_root)
for provider in sorted(CONNECTORS):
described = store.describe(provider)
state = "已配置" if described["present"] else "未配置"
@@ -211,6 +211,9 @@ def register(commands) -> None:
follow.add_argument("--db", type=Path, default=DATABASE_PATH)
follow.add_argument("--sources-root", type=Path, default=SOURCES_DIR)
follow.add_argument("--secrets-root", type=Path, default=SECRETS_DIR)
+ # 共享根让另一台机器上配好的可同步字段(现在只有 rule34.xxx 的 user_id/api_key)
+ # 在命令行这边也能回填。默认和 Web 一致,测试用它指向临时目录。
+ follow.add_argument("--shared-root", type=Path, default=SHARED_DATA_ROOT)
actions = follow.add_subparsers(dest="follow_command", required=True)
add = actions.add_parser("add", help="登记一个追更来源")
diff --git a/src/peach/follow_discovery.py b/src/peach/follow_discovery.py
index b78de7aa4..c9ae4fab5 100644
--- a/src/peach/follow_discovery.py
+++ b/src/peach/follow_discovery.py
@@ -17,7 +17,7 @@ from pathlib import Path
from .follow import FollowSourceError
from .follow_avatar import resolve_official_profile
-from .follow_secrets import Credential, CredentialError, CredentialStore
+from .follow_secrets import Credential, CredentialError, credential_store_for
from .follow_sources import (
DEFAULT_MAX_ITEMS, USER_AGENT, F95ZoneConnector, KemonoConnector,
Rule34VideoConnector, Rule34XxxConnector, _BaseConnector, canonical_source_ref,
@@ -341,7 +341,8 @@ def _f95_candidates(term: str, transport,
def discover(term: str, *, secrets_root: Path, state_root: Path,
- transport=None, providers: tuple[str, ...] | None = None) -> Discovery:
+ shared_root: Path | None = None, transport=None,
+ providers: tuple[str, ...] | None = None) -> Discovery:
"""把一个裸 id 或名字拿去各来源问一遍。
只回**查到的**结果,每个都带上「为什么认为它命中」。查不到就是查不到,
@@ -355,7 +356,7 @@ def discover(term: str, *, secrets_root: Path, state_root: Path,
if _TERM_FORBIDDEN_RE.search(text):
raise FollowSourceError("名字或 id 里不能包含 / \\ ? # & < > 引号或控制字符")
- credentials = CredentialStore(secrets_root)
+ credentials = credential_store_for(secrets_root, shared_root=shared_root)
index = CreatorIndex(state_root, transport=transport)
wanted = providers or ("kemono", "coomer", "pawchive", "fanbox", "rule34video",
"rule34xxx", "f95zone")
diff --git a/src/peach/follow_providers.py b/src/peach/follow_providers.py
index b72500209..31362eef7 100644
--- a/src/peach/follow_providers.py
+++ b/src/peach/follow_providers.py
@@ -11,7 +11,7 @@
所以这里只登记一次,各模块从这张表派生自己那份投影,形状保持不变。
-**不包含凭据。**哪些字段可以跨机同步由 `web_follow.CREDENTIAL_GUIDE` 逐字段声明,
+**不包含凭据。**哪些字段可以跨机同步由 `follow_secrets.CREDENTIAL_GUIDE` 逐字段声明,
`SYNCABLE_FIELDS` 已经是它的派生视图。那是安全语义,收进这张通用表只会让它更容易
被顺手改错——新增来源时作者必须在凭据表里单独表态,这个摩擦是故意的。
"""
diff --git a/src/peach/follow_secrets.py b/src/peach/follow_secrets.py
index f1fa1c5d6..15349031a 100644
--- a/src/peach/follow_secrets.py
+++ b/src/peach/follow_secrets.py
@@ -166,3 +166,75 @@ class CredentialStore:
return None
mode = stat.S_IMODE(os.stat(path).st_mode)
return bool(mode & (stat.S_IRGRP | stat.S_IROTH))
+
+
+#: 每个来源要不要凭据、要哪些字段、去哪里拿。这张表和上面的读取实现放在一起:
+#: 「哪些字段可以跨机同步」是凭据自己的安全语义,散在 Web 层就会出现命令行与
+#: 网页各建一个仓库、同一份凭据在一边在、在另一边显示「未配置」。
+CREDENTIAL_GUIDE: dict[str, dict] = {
+ "fanbox": {
+ "requirement": "optional",
+ "fields": ["cookie"],
+ # FANBOX Cookie 绑定浏览器会话与风控环境,不跨机同步。
+ "syncable": [],
+ "why": "公开列表不需要登录;帖子详情被 FANBOX 验证页拦住时,可用浏览器会话取得正文、多图和外部资源链接。",
+ "where": "https://www.fanbox.cc/",
+ "howto": "登录 FANBOX 后,从一次成功的 api.fanbox.cc/post.info 请求复制整条 Cookie 请求头。",
+ },
+ "gofile": {
+ "requirement": "optional",
+ "fields": ["api_token"],
+ "syncable": [],
+ "why": "用于展开 Gofile 文件页,取得其中的图片和视频列表;Gofile 当前要求 Premium 才能读取 contents API,不配置仍会保留文件页链接。",
+ "where": "https://gofile.io/myprofile",
+ "howto": "登录 Premium Gofile 账户后,在个人资料页复制 API token。",
+ },
+ "kemono": {"requirement": "none"},
+ "coomer": {"requirement": "none"},
+ "pawchive": {"requirement": "none"},
+ "rule34video": {"requirement": "none"},
+ "rule34xxx": {
+ "requirement": "required",
+ "fields": ["user_id", "api_key"],
+ # 账号级、与机器无关,用户明确要求跨机同步。
+ "syncable": ["user_id", "api_key"],
+ "why": "网页版挂了 Cloudflare 验证码,Peach 不绕验证码,只能走官方 API。",
+ "where": "https://rule34.xxx/index.php?page=account&s=options",
+ "howto": "登录后在账号设置页生成 API key,把 user_id 和 api_key 写进凭据文件。",
+ },
+ "f95zone": {
+ "requirement": "optional",
+ "fields": ["cookie"],
+ # cookie 绑会话与客户端 IP,同步到另一台大概率直接失效——不同步。
+ "syncable": [],
+ "why": "发现更新不需要登录;只有取附件和 masked 下载链接才需要会话。",
+ "where": "https://f95zone.to/",
+ "howto": "登录后从浏览器复制整条 Cookie 请求头,写进凭据文件的 cookie 字段。",
+ },
+ "simpcity": {
+ "requirement": "blocked",
+ "why": "站点由 DDoS-Guard 的浏览器质询保护,放行绑客户端 IP 且最短 20 分钟过期,"
+ "撑不起定时追更。Peach 不绕机器人验证。",
+ },
+}
+
+
+#: 哪些字段可以跨机同步,逐 provider 逐字段声明。绝不按字段名猜——今天 `api_key`
+#: 能同步、`cookie` 不能,明天新增一个 `session_token` 就会落到错误的一侧。
+SYNCABLE_FIELDS: dict[str, tuple[str, ...]] = {
+ provider: tuple(guide.get("syncable", ()))
+ for provider, guide in CREDENTIAL_GUIDE.items()
+}
+
+
+def credential_store_for(secrets_root: Path, *,
+ shared_root: Path | None = None) -> CredentialStore:
+ """构造凭据仓库的唯一入口。
+
+ `shared_root` 与 `syncable_fields` 必须处处一致。以前 Web、发现与 CLI 各自
+ `CredentialStore(...)`,只有 Web 那份带上了共享根和可同步字段声明——表现是
+ 在另一台机器上配好的 rule34.xxx key 网页里能用、`peach follow check` 却报
+ 缺凭据。哪一层都不该自己决定这件事,所以只留这一个构造函数。
+ """
+ return CredentialStore(secrets_root, shared_root=shared_root,
+ syncable_fields=SYNCABLE_FIELDS)
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index bf51e95df..e59b21f6b 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -16,7 +16,9 @@ from datetime import datetime, timezone
from . import follow_providers
from .follow import FollowHistoryEnd, FollowSourceError
from .follow_discovery import discover
-from .follow_secrets import CredentialError, CredentialStore
+from .follow_secrets import (
+ CREDENTIAL_GUIDE, CredentialError, CredentialStore, credential_store_for,
+)
from .follow_sources import (
CONNECTORS, KemonoConnector, build_connector, canonical_source_ref,
f95_attachment_media_items, parse_source_url, resource_links,
@@ -1267,6 +1269,7 @@ def w_follow_resolve(contract, body) -> dict:
continue
try:
found = discover(line, secrets_root=contract.follow_secrets_root,
+ shared_root=contract.follow_shared_root,
state_root=contract.follow_state_root)
except (FollowSourceError, CredentialError) as term_error:
results.append({"line": line, "kind": "error", "error": str(term_error)})
@@ -1294,56 +1297,6 @@ def _existing_sources(contract):
return _store(contract, connection).sources()
-#: 每个来源要不要凭据、要哪些字段、去哪里拿。写在这里而不是模板里,因为知道
-#: 「rule34.xxx 缺 key 就抓不到」的是连接器边界,不是界面。
-CREDENTIAL_GUIDE: dict[str, dict] = {
- "fanbox": {
- "requirement": "optional",
- "fields": ["cookie"],
- # FANBOX Cookie 绑定浏览器会话与风控环境,不跨机同步。
- "syncable": [],
- "why": "公开列表不需要登录;帖子详情被 FANBOX 验证页拦住时,可用浏览器会话取得正文、多图和外部资源链接。",
- "where": "https://www.fanbox.cc/",
- "howto": "登录 FANBOX 后,从一次成功的 api.fanbox.cc/post.info 请求复制整条 Cookie 请求头。",
- },
- "gofile": {
- "requirement": "optional",
- "fields": ["api_token"],
- "syncable": [],
- "why": "用于展开 Gofile 文件页,取得其中的图片和视频列表;Gofile 当前要求 Premium 才能读取 contents API,不配置仍会保留文件页链接。",
- "where": "https://gofile.io/myprofile",
- "howto": "登录 Premium Gofile 账户后,在个人资料页复制 API token。",
- },
- "kemono": {"requirement": "none"},
- "coomer": {"requirement": "none"},
- "pawchive": {"requirement": "none"},
- "rule34video": {"requirement": "none"},
- "rule34xxx": {
- "requirement": "required",
- "fields": ["user_id", "api_key"],
- # 账号级、与机器无关,用户明确要求跨机同步。
- "syncable": ["user_id", "api_key"],
- "why": "网页版挂了 Cloudflare 验证码,Peach 不绕验证码,只能走官方 API。",
- "where": "https://rule34.xxx/index.php?page=account&s=options",
- "howto": "登录后在账号设置页生成 API key,把 user_id 和 api_key 写进凭据文件。",
- },
- "f95zone": {
- "requirement": "optional",
- "fields": ["cookie"],
- # cookie 绑会话与客户端 IP,同步到另一台大概率直接失效——不同步。
- "syncable": [],
- "why": "发现更新不需要登录;只有取附件和 masked 下载链接才需要会话。",
- "where": "https://f95zone.to/",
- "howto": "登录后从浏览器复制整条 Cookie 请求头,写进凭据文件的 cookie 字段。",
- },
- "simpcity": {
- "requirement": "blocked",
- "why": "站点由 DDoS-Guard 的浏览器质询保护,放行绑客户端 IP 且最短 20 分钟过期,"
- "撑不起定时追更。Peach 不绕机器人验证。",
- },
-}
-
-
def w_follow_credential(contract, body) -> dict:
"""保存一个来源的凭据,写到**运行 Peach 的那台机器**的 secrets 目录。
@@ -1431,18 +1384,9 @@ def _write_shared(store, provider: str, values: dict) -> bool:
return True
-#: 哪些字段可以跨机同步,逐 provider 逐字段声明。绝不按字段名猜——今天 `api_key`
-#: 能同步、`cookie` 不能,明天新增一个 `session_token` 就会落到错误的一侧。
-SYNCABLE_FIELDS: dict[str, tuple[str, ...]] = {
- provider: tuple(guide.get("syncable", ()))
- for provider, guide in CREDENTIAL_GUIDE.items()
-}
-
-
def _credential_store(contract) -> CredentialStore:
- return CredentialStore(contract.follow_secrets_root,
- shared_root=contract.follow_shared_root,
- syncable_fields=SYNCABLE_FIELDS)
+ return credential_store_for(contract.follow_secrets_root,
+ shared_root=contract.follow_shared_root)
def q_follow_credentials(contract, _args) -> dict:
diff --git a/tests/test_follow_cli.py b/tests/test_follow_cli.py
index a394c7f75..ece0cb213 100644
--- a/tests/test_follow_cli.py
+++ b/tests/test_follow_cli.py
@@ -43,12 +43,41 @@ class FollowCliTests(unittest.TestCase):
args = self.parser.parse_args([
"follow", "--db", str(self.db),
"--sources-root", str(self.root / "sources"),
- "--secrets-root", str(self.root / "secrets"), *argv])
+ "--secrets-root", str(self.root / "secrets"),
+ "--shared-root", str(self.root / "shared"), *argv])
buffer = io.StringIO()
with contextlib.redirect_stdout(buffer):
code = args.handler(args)
return code, buffer.getvalue()
+ def test_creds_sees_the_shared_copy_like_the_web_surface_does(self):
+ """另一台机器上配好的可同步字段,命令行这边也必须算「已配置」。
+
+ 以前只有 Web 那份仓库带上了共享根和可同步字段声明,CLI 直接
+ `CredentialStore(secrets_root)`——同一份 rule34.xxx key 网页里能用、
+ `peach follow check` 却报缺凭据,而错误里根本看不出是这个原因。
+ """
+ shared = self.root / "shared" / "secrets" / "follow"
+ shared.mkdir(parents=True)
+ (shared / "rule34xxx.json").write_text(
+ '{"user_id": "42", "api_key": "sekret"}', encoding="utf-8")
+ code, output = self._run("creds")
+ self.assertEqual(code, 0)
+ line = next(row for row in output.splitlines()
+ if row.startswith("rule34xxx"))
+ self.assertIn("已配置", line)
+ self.assertIn("api_key", line)
+ self.assertNotIn("sekret", output, "凭据值不进任何输出")
+
+ def test_creds_does_not_take_a_non_syncable_field_from_the_shared_copy(self):
+ """f95zone 的 cookie 绑会话与客户端 IP,声明为不可同步;共享副本里有也不算。"""
+ shared = self.root / "shared" / "secrets" / "follow"
+ shared.mkdir(parents=True)
+ (shared / "f95zone.json").write_text('{"cookie": "xf=1"}', encoding="utf-8")
+ _, output = self._run("creds")
+ line = next(row for row in output.splitlines() if row.startswith("f95zone"))
+ self.assertIn("未配置", line)
+
def test_add_derives_the_url_and_semantics_per_provider(self):
code, output = self._run("add", "--provider", "f95zone", "--ref", "50685")
self.assertEqual(code, 0)
diff --git a/tests/test_follow_providers.py b/tests/test_follow_providers.py
index 51433acfe..8a076fc95 100644
--- a/tests/test_follow_providers.py
+++ b/tests/test_follow_providers.py
@@ -1,14 +1,19 @@
+import inspect
import unittest
+from pathlib import Path
-from peach import follow_providers
+from peach import follow_cli, follow_discovery, follow_providers, web_follow
from peach.follow_cli import _RELEASE_PROVIDERS, _SOURCE_URL
from peach.follow_sources import CONNECTORS, _SEMANTICS
from peach.follow_stream import _PROVIDER_HOSTS
from peach.follow_variants import PROVIDER_PRIORITY
-from peach.web_follow import (
+from peach.follow_secrets import (
CREDENTIAL_GUIDE,
- PROVIDER_LABELS,
SYNCABLE_FIELDS,
+ credential_store_for,
+)
+from peach.web_follow import (
+ PROVIDER_LABELS,
_BACKFILL_PROVIDERS,
_OFFICIAL_IDENTITY_PROVIDERS,
)
@@ -91,6 +96,32 @@ class ProviderRegistryTests(unittest.TestCase):
"SYNCABLE_FIELDS 只能从 CREDENTIAL_GUIDE 派生",
)
+ def test_every_layer_builds_its_credential_store_through_one_factory(self):
+ """Web、发现与 CLI 必须拿到同一套共享根与可同步字段声明。
+
+ 分头 `CredentialStore(...)` 时只有 Web 那份带上了共享回填,同一份凭据
+ 在网页里在、在命令行里「未配置」。这里挡住往回退化。
+ """
+ sources = {
+ name: (Path(inspect.getsourcefile(module)).read_text(encoding="utf-8"))
+ for name, module in (("web_follow", web_follow),
+ ("follow_discovery", follow_discovery),
+ ("follow_cli", follow_cli))
+ }
+ for name, text in sources.items():
+ with self.subTest(module=name):
+ self.assertNotIn("CredentialStore(", text.replace(
+ "-> CredentialStore", ""),
+ f"{name} 必须走 credential_store_for,不要自己构造")
+ self.assertIn("credential_store_for(", text)
+
+ def test_the_factory_carries_the_syncable_declaration(self):
+ store = credential_store_for(Path("secrets"), shared_root=Path("shared"))
+ self.assertEqual(store.syncable_fields, SYNCABLE_FIELDS)
+ self.assertEqual(store.syncable("rule34xxx"), ("user_id", "api_key"))
+ self.assertEqual(store.syncable("f95zone"), ())
+ self.assertEqual(store.shared_root, Path("shared") / "secrets" / "follow")
+
def test_semantics_rejects_unknown_values(self):
with self.assertRaises(ValueError):
follow_providers.ProviderSpec(key="x", label="X", semantics="whatever")