Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix: 合并关注来源并整理近期界面

longmeidaoa014fd02519c
diff --git a/migrations/0020_follow_source_identity.sql b/migrations/0020_follow_source_identity.sql
new file mode 100644
index 000000000..e318458ca
--- /dev/null
+++ b/migrations/0020_follow_source_identity.sql
@@ -0,0 +1,101 @@
+-- rule34.xxx 标签不区分大小写。旧唯一键直接保存用户粘贴的大小写,导致同一作者在
+-- 分两批添加时成为两条来源。本迁移把大小写重复项合回最早的来源,同时保留候选、
+-- 已看/忽略/保存状态与已生成的 online asset 关联。
+
+CREATE TEMP TABLE _follow_source_merge AS
+SELECT source.id AS loser_id, grouped.keep_id
+FROM follow_source AS source
+JOIN (
+ SELECT provider, lower(ref) AS canonical_ref, min(id) AS keep_id
+ FROM follow_source
+ WHERE provider='rule34xxx'
+ GROUP BY provider, lower(ref)
+ HAVING count(*) > 1
+) AS grouped
+ ON grouped.provider=source.provider
+ AND grouped.canonical_ref=lower(source.ref)
+WHERE source.id<>grouped.keep_id;
+
+INSERT INTO follow_item(
+ source_id,external_id,title,url,media_url,thumb_url,published_at,
+ published_precision,version,duration,release_key,variant_kind,variant_label,
+ group_hint,status,asset_id,evidence_path,metadata_json,first_seen_at,last_seen_at
+)
+SELECT
+ merge.keep_id,item.external_id,item.title,item.url,item.media_url,item.thumb_url,
+ item.published_at,item.published_precision,item.version,item.duration,item.release_key,
+ item.variant_kind,item.variant_label,item.group_hint,item.status,item.asset_id,
+ item.evidence_path,item.metadata_json,item.first_seen_at,item.last_seen_at
+FROM _follow_source_merge AS merge
+JOIN follow_item AS item ON item.source_id=merge.loser_id
+WHERE 1
+ON CONFLICT(source_id,external_id) DO UPDATE SET
+ status=CASE
+ WHEN follow_item.status='saved' OR excluded.status='saved' THEN 'saved'
+ WHEN follow_item.status='new' THEN excluded.status
+ ELSE follow_item.status
+ END,
+ asset_id=coalesce(follow_item.asset_id,excluded.asset_id),
+ evidence_path=coalesce(follow_item.evidence_path,excluded.evidence_path),
+ first_seen_at=min(follow_item.first_seen_at,excluded.first_seen_at),
+ last_seen_at=max(follow_item.last_seen_at,excluded.last_seen_at);
+
+UPDATE follow_source AS kept
+SET entity_id=coalesce(kept.entity_id,(
+ SELECT source.entity_id FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ AND source.entity_id IS NOT NULL
+ ORDER BY source.updated_at DESC LIMIT 1
+ )),
+ enabled=(
+ SELECT max(source.enabled) FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ ),
+ backfill_page=(
+ SELECT max(source.backfill_page) FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ ),
+ last_checked_at=(
+ SELECT max(source.last_checked_at) FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ ),
+ etag=(
+ SELECT source.etag FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ ORDER BY coalesce(source.last_checked_at,source.updated_at) DESC LIMIT 1
+ ),
+ last_modified=(
+ SELECT source.last_modified FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ ORDER BY coalesce(source.last_checked_at,source.updated_at) DESC LIMIT 1
+ ),
+ last_status=(
+ SELECT source.last_status FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ ORDER BY coalesce(source.last_checked_at,source.updated_at) DESC LIMIT 1
+ ),
+ last_error=(
+ SELECT source.last_error FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ ORDER BY coalesce(source.last_checked_at,source.updated_at) DESC LIMIT 1
+ ),
+ metadata_json=coalesce((
+ SELECT nullif(source.metadata_json,'{}') FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ ORDER BY source.updated_at DESC LIMIT 1
+ ),kept.metadata_json),
+ updated_at=(
+ SELECT max(source.updated_at) FROM follow_source AS source
+ WHERE source.provider=kept.provider AND lower(source.ref)=lower(kept.ref)
+ )
+WHERE kept.id IN (SELECT keep_id FROM _follow_source_merge);
+
+DELETE FROM follow_source
+WHERE id IN (SELECT loser_id FROM _follow_source_merge);
+
+UPDATE follow_source
+SET ref=lower(ref),
+ updated_at=max(updated_at,created_at)
+WHERE provider='rule34xxx';
+
+DROP TABLE _follow_source_merge;
diff --git a/src/peach/api.py b/src/peach/api.py
index 080d35a11..087d989b7 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -18,6 +18,8 @@ from fastapi.staticfiles import StaticFiles
from . import __version__, web_contract
from .config import LOCATION_ROOT_DECLARATIONS, PROJECT_ROOT, PeachSettings
from .ffmpeg import FFmpegResolver
+from .follow import FollowSourceError
+from .follow_avatar import resolve_official_avatar
from .http import HttpxTransport
from .media import (
FilesystemBackend,
@@ -644,6 +646,20 @@ def create_app(
response.headers["Cache-Control"] = "public, max-age=86400"
return response
+ @app.api_route("/follow-avatar", methods=["GET", "HEAD"])
+ def follow_avatar(request: Request, service: str, id: str):
+ """Resolve an official creator avatar, then let the image CDN serve it."""
+ args = _first_query_values(request)
+ if not _authorized(request, settings.token, args):
+ return JSONResponse({"error": "unauthorized"}, status_code=401)
+ try:
+ target = resolve_official_avatar(service, id)
+ except (OSError, FollowSourceError):
+ return JSONResponse({"error": "unavailable"}, status_code=404)
+ response = RedirectResponse(target, status_code=307)
+ response.headers["Cache-Control"] = "private, max-age=86400"
+ return response
+
@app.api_route("/logo", methods=["GET", "HEAD"])
def logo(request: Request, studio: str = ""):
args = _first_query_values(request)
diff --git a/src/peach/follow_avatar.py b/src/peach/follow_avatar.py
new file mode 100644
index 000000000..c9da4f2ce
--- /dev/null
+++ b/src/peach/follow_avatar.py
@@ -0,0 +1,79 @@
+"""Resolve creator avatars from verified official profile endpoints."""
+from __future__ import annotations
+
+import json
+import re
+import urllib.parse
+
+from bs4 import BeautifulSoup
+
+from .follow import FollowSourceError
+from .http import HttpRequest, HttpTransport, HttpxTransport
+
+
+MAX_PROFILE_BYTES = 1024 * 1024
+_USER_ID_RE = re.compile(r"^\d{1,20}$")
+_CREATOR_ID_RE = re.compile(r"^[a-zA-Z0-9_-]{1,80}$")
+
+
+def resolve_official_avatar(service: str, user_id: str, *,
+ transport: HttpTransport | None = None) -> str:
+ """Return a fixed-host official avatar URL for one supported creator service.
+
+ FANBOX archive sources expose the Pixiv numeric user id. The official creator
+ page maps it to the public creator id; ``creator.get`` then returns the current
+ ``user.iconUrl``. Both requests and the returned image host are fixed here so a
+ client cannot turn this endpoint into an SSRF or open redirect.
+ """
+ if service != "fanbox" or not _USER_ID_RE.fullmatch(str(user_id or "")):
+ raise FollowSourceError("不支持这个官方头像来源")
+ request = transport or HttpxTransport()
+ profile_url = f"https://www.pixiv.net/fanbox/creator/{user_id}"
+ page = request(
+ HttpRequest("GET", profile_url, {
+ "Accept": "text/html", "User-Agent": "Peach/0.2",
+ }),
+ 15.0,
+ MAX_PROFILE_BYTES,
+ )
+ if page.status != 200:
+ raise FollowSourceError(f"FANBOX 官方页面返回 HTTP {page.status}")
+ try:
+ soup = BeautifulSoup(page.body, "html.parser")
+ metadata_node = soup.find("meta", attrs={"name": "metadata"})
+ metadata = json.loads(str(metadata_node.get("content"))) if metadata_node else {}
+ creator_id = str(
+ (((metadata.get("urlContext") or {}).get("host") or {}).get("creatorId"))
+ or ""
+ )
+ except (AttributeError, TypeError, ValueError, json.JSONDecodeError) as error:
+ raise FollowSourceError("FANBOX 官方页面没有可用的创作者资料") from error
+ if not _CREATOR_ID_RE.fullmatch(creator_id):
+ raise FollowSourceError("FANBOX 官方页面没有可用的创作者 id")
+
+ creator_origin = f"https://{creator_id}.fanbox.cc"
+ api_url = "https://api.fanbox.cc/creator.get?" + urllib.parse.urlencode(
+ {"creatorId": creator_id}
+ )
+ response = request(
+ HttpRequest("GET", api_url, {
+ "Accept": "application/json", "Origin": creator_origin,
+ "Referer": creator_origin + "/", "User-Agent": "Peach/0.2",
+ }),
+ 15.0,
+ MAX_PROFILE_BYTES,
+ )
+ if response.status != 200:
+ raise FollowSourceError(f"FANBOX 官方资料返回 HTTP {response.status}")
+ try:
+ body = (json.loads(response.body.decode("utf-8")) or {}).get("body") or {}
+ user = body.get("user") or {}
+ avatar = str(user.get("iconUrl") or "")
+ returned_user_id = str(user.get("userId") or "")
+ except (UnicodeDecodeError, TypeError, ValueError, json.JSONDecodeError) as error:
+ raise FollowSourceError("FANBOX 官方资料格式不符") from error
+ parsed = urllib.parse.urlsplit(avatar)
+ if (returned_user_id != user_id or parsed.scheme != "https"
+ or parsed.hostname != "pixiv.pximg.net"):
+ raise FollowSourceError("FANBOX 官方资料没有可信的头像地址")
+ return avatar
diff --git a/src/peach/follow_discovery.py b/src/peach/follow_discovery.py
index 3ac0d7eb4..893e4394a 100644
--- a/src/peach/follow_discovery.py
+++ b/src/peach/follow_discovery.py
@@ -19,7 +19,7 @@ from .follow import FollowSourceError
from .follow_secrets import Credential, CredentialError, CredentialStore
from .follow_sources import (
DEFAULT_MAX_ITEMS, USER_AGENT, F95ZoneConnector, KemonoConnector,
- Rule34VideoConnector, Rule34XxxConnector, _BaseConnector,
+ Rule34VideoConnector, Rule34XxxConnector, _BaseConnector, canonical_source_ref,
)
#: 创作者索引的缓存有效期。索引是几 MB 的整站清单,不该每次发现都重下一遍。
@@ -152,7 +152,7 @@ def _rule34video_candidates(term: str, transport) -> list[Candidate]:
def _rule34xxx_candidates(term: str, transport, credential: Credential | None) -> list[Candidate]:
if credential is None:
raise CredentialError("rule34xxx 需要 user_id 与 api_key 才能查标签")
- tag = re.sub(r"\s+", "_", term.strip())
+ tag = canonical_source_ref("rule34xxx", re.sub(r"\s+", "_", term.strip()))
connector = Rule34XxxConnector(transport=transport, credential=credential, max_items=1)
result = connector.fetch(tag)
if not result.candidates:
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.py
index 56f048d67..9759b0745 100644
--- a/src/peach/follow_sources.py
+++ b/src/peach/follow_sources.py
@@ -824,6 +824,18 @@ _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})")
+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 == "rule34xxx" else value
+
+
#: 线程 slug 里从这个 token 起就不是作品名了:f95 的惯例是
#: `<作品名>-<发布日期>-<作者手柄>`,日期之后全是元数据。
_SLUG_TAIL_RE = re.compile(r"^(?:19|20)\d{2}$|^v?\d+(?:\.\d+)+[a-z]?$")
@@ -886,7 +898,10 @@ def parse_source_url(raw_url: str) -> ParsedSource:
_slug_label(slug), "work")
if bare in ("rule34.xxx", "api.rule34.xxx"):
- tags = urllib.parse.parse_qs(parsed.query).get("tags", [""])[0].strip()
+ tags = canonical_source_ref(
+ "rule34xxx",
+ urllib.parse.parse_qs(parsed.query).get("tags", [""])[0],
+ )
if not tags:
raise FollowSourceError(
"rule34.xxx 的链接要带标签,形如 "
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index 816231e3a..c34207dc9 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -17,7 +17,7 @@ from datetime import datetime, timezone
from pathlib import Path
from .follow import FollowSourceError, write_immutable
-from .follow_sources import FollowCandidate, SourceFetch
+from .follow_sources import FollowCandidate, SourceFetch, canonical_source_ref
from .follow_variants import classify, group_duplicates
@@ -111,6 +111,7 @@ class FollowStore:
metadata: dict | None = None, moment: datetime | None = None) -> int:
if semantics not in ("work", "release"):
raise FollowSourceError("semantics 只能是 work 或 release")
+ ref = canonical_source_ref(provider, ref)
stamp = _now_text(moment)
payload = json.dumps(metadata or {}, ensure_ascii=False)
connection = self._connect()
@@ -121,7 +122,9 @@ class FollowStore:
" ON CONFLICT(provider,ref) DO UPDATE SET"
" label=excluded.label, url=excluded.url, semantics=excluded.semantics,"
" entity_id=COALESCE(excluded.entity_id, follow_source.entity_id),"
- " metadata_json=excluded.metadata_json, updated_at=excluded.updated_at",
+ " metadata_json=CASE WHEN excluded.metadata_json='{}'"
+ " THEN follow_source.metadata_json ELSE excluded.metadata_json END,"
+ " updated_at=excluded.updated_at",
(entity_id, provider, ref, label, url, semantics, payload, stamp, stamp),
)
row = connection.execute(
diff --git a/src/peach/metadata.py b/src/peach/metadata.py
index 83f362774..08d681d96 100644
--- a/src/peach/metadata.py
+++ b/src/peach/metadata.py
@@ -204,6 +204,16 @@ def normalized_release_date(raw: object) -> tuple[str, list[str]]:
return normalized, warnings
+def japanese_view(payload: dict) -> dict:
+ """Return the Japanese translation bundled in an r18dev payload."""
+ for translation in payload.get("translations") or []:
+ if not isinstance(translation, dict):
+ continue
+ if str(translation.get("language") or "").lower().startswith("ja"):
+ return translation
+ return {}
+
+
def extract_peach_fields(payload: dict, category_map: dict[str, str]) -> dict[str, dict]:
"""Map raw provider data to the Peach truth fields supported by P0."""
out: dict[str, dict] = {}
@@ -214,8 +224,10 @@ def extract_peach_fields(payload: dict, category_map: dict[str, str]) -> dict[st
"display_value": "、".join(item["name"] for item in performers),
"warnings": warnings,
}
+ japanese = japanese_view(payload)
for field in ("studio", "series"):
- raw_name = payload.get("maker" if field == "studio" else field)
+ key = "maker" if field == "studio" else field
+ raw_name = str(japanese.get(key) or "").strip() or payload.get(key)
name, repeated = collapse_repeated_phrase(str(raw_name or ""))
if name:
out[field] = {
diff --git a/src/peach/tray.py b/src/peach/tray.py
index 29a4587fb..1737a6f56 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -50,6 +50,7 @@ TRAY_SOURCES = (
"src/peach/tray.py",
"src/peach/menubar.py",
"src/peach/versioning.py",
+ "src/peach/sync.py",
"src/peach/certs.py",
"src/peach/netwatch.py",
"src/peach/config.py",
@@ -650,6 +651,7 @@ class PeachTray:
def launchd_owns_this_process(
run: Callable[..., subprocess.CompletedProcess] = subprocess.run,
+ *, uid: int | None = None,
) -> bool:
"""本进程是不是 LaunchAgent 拉起的那一个。
@@ -657,8 +659,13 @@ def launchd_owns_this_process(
launchd 名下那一份;托盘要是从终端跑起来的,kickstart 会在旁边**再**起一个,
菜单栏上就出现两个桃子,而旧的那个还占着单实例锁。
"""
+ if uid is None:
+ getuid = getattr(os, "getuid", None)
+ if getuid is None:
+ return False
+ uid = getuid()
result = run(
- ["launchctl", "print", f"gui/{os.getuid()}/{LAUNCH_AGENT_LABEL}"],
+ ["launchctl", "print", f"gui/{uid}/{LAUNCH_AGENT_LABEL}"],
capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
)
if result.returncode != 0:
@@ -669,6 +676,7 @@ def launchd_owns_this_process(
def restart_tray_process(
run: Callable[..., subprocess.CompletedProcess] = subprocess.run,
+ *, uid: int | None = None,
) -> subprocess.CompletedProcess:
"""让 launchd 杀掉并重新拉起托盘。调用方必须先停掉自己拥有的服务。
@@ -676,8 +684,13 @@ def restart_tray_process(
`_owned` 是空的,之后每次「同步 Ledger」都被自己的归属检查挡成
「服务不归本托盘管理」。
"""
+ if uid is None:
+ getuid = getattr(os, "getuid", None)
+ if getuid is None:
+ raise OSError("launchd is unavailable on this platform")
+ uid = getuid()
return run(
- ["launchctl", "kickstart", "-k", f"gui/{os.getuid()}/{LAUNCH_AGENT_LABEL}"],
+ ["launchctl", "kickstart", "-k", f"gui/{uid}/{LAUNCH_AGENT_LABEL}"],
capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
)
@@ -725,7 +738,6 @@ def run_macos_menu_bar(manager: "ServiceManager") -> None:
return
def work() -> None:
- released = False
try:
notify("正在检查更新通道…", "Peach 开发进度")
result = versions.update()
@@ -737,9 +749,13 @@ def run_macos_menu_bar(manager: "ServiceManager") -> None:
if launchd_owns_this_process():
notify(f"{result.message}正在重启菜单栏项…", "Peach 开发进度")
manager.stop_owned()
- action_lock.release() # kickstart 之后本进程就没了
- released = True
- restart_tray_process()
+ restarted = restart_tray_process()
+ if restarted.returncode != 0:
+ # kickstart 失败时旧进程仍在;把刚停掉的服务恢复,不能留下
+ # 一个有菜单图标却没有 HTTP/HTTPS 的半死状态。
+ manager.start_missing()
+ notify("代码已同步,但菜单栏项重启失败;服务已恢复。",
+ "Peach 开发进度")
return
notify(
f"{result.message}服务已重启;菜单栏项本身要手动退出重开才会生效。",
@@ -750,8 +766,7 @@ def run_macos_menu_bar(manager: "ServiceManager") -> None:
manager.restart()
notify(f"{result.message}服务已重启。", "Peach 开发进度")
finally:
- if not released:
- action_lock.release()
+ action_lock.release()
threading.Thread(target=work, name="PeachSourceSync", daemon=True).start()
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index ff5199764..4afd743f4 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -8,13 +8,15 @@ from __future__ import annotations
import json
import os
import re
+import urllib.parse
from datetime import datetime, timezone
from .follow import FollowSourceError
from .follow_discovery import discover
from .follow_secrets import CredentialError, CredentialStore
from .follow_sources import (
- CONNECTORS, KemonoConnector, build_connector, parse_source_url,
+ CONNECTORS, KemonoConnector, build_connector, canonical_source_ref,
+ parse_source_url,
)
from .follow_store import FollowStore, ReleaseGroup
from .taste_history import read_creator_candidates
@@ -32,6 +34,9 @@ PROVIDER_LABELS = {
}
_STATUSES = ("new", "seen", "saved", "ignored")
+_BACKFILL_PROVIDERS = frozenset(
+ {"kemono", "coomer", "pawchive", "rule34video", "rule34xxx"}
+)
def _store(contract, connection) -> FollowStore:
@@ -113,6 +118,25 @@ def _group_payload(group: ReleaseGroup) -> dict:
#: `lazyprocrastinator` 是同一个人,中点后面那截只说明他在哪个平台连载。
_LABEL_SERVICE_RE = re.compile(r"\s*[·|]\s*[A-Za-z0-9_\-]+\s*$")
_AUTHOR_NOISE_RE = re.compile(r"[^0-9a-z一-鿿]+")
+_F95_TITLE_SUFFIX_RE = re.compile(r"\s+collections?\s*$", re.IGNORECASE)
+
+
+def _normalized_author_name(value: str, *, provider: str = "") -> str:
+ stripped = _LABEL_SERVICE_RE.sub("", str(value or "").strip())
+ if provider == "f95zone":
+ # F95 thread titles describe a container, not a different author. The real
+ # data is ``Lazy Procrastinator Collection`` while every author source is
+ # ``LazyProcrastinator``; retaining the generic suffix creates a false group.
+ stripped = _F95_TITLE_SUFFIX_RE.sub("", stripped)
+ return _AUTHOR_NOISE_RE.sub("", stripped.casefold())
+
+
+def _source_metadata(row) -> dict:
+ try:
+ payload = json.loads(row["metadata_json"] or "{}")
+ except (KeyError, TypeError, json.JSONDecodeError):
+ return {}
+ return payload if isinstance(payload, dict) else {}
def author_key(row) -> str:
@@ -131,9 +155,11 @@ def author_key(row) -> str:
entity = row["entity_id"]
if entity:
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 "")
- stripped = _LABEL_SERVICE_RE.sub("", label)
- normalized = _AUTHOR_NOISE_RE.sub("", stripped.casefold())
+ normalized = _normalized_author_name(label, provider=str(row["provider"] or ""))
return f"name:{normalized}" if normalized else f"source:{row['id']}"
@@ -158,6 +184,21 @@ def _avatar_url(provider: str, ref: str) -> str | None:
return f"https://{KemonoConnector.HOSTS[provider]}/icons/{service}/{user}"
+def _official_avatar_url(provider: str, ref: str) -> str | None:
+ """Local resolver for an avatar from the creator's official profile.
+
+ FANBOX archive refs carry the Pixiv user id, which is enough for Peach's fixed-host
+ resolver to locate the public FANBOX profile and its official ``user.iconUrl``.
+ Other services have no verified resolver yet, so they keep the archive fallback.
+ """
+ if provider not in KemonoConnector.HOSTS:
+ return None
+ service, _, user = str(ref or "").partition("/")
+ if service != "fanbox" or not user.isdigit():
+ return None
+ return "/follow-avatar?" + urllib.parse.urlencode({"service": service, "id": user})
+
+
def _source_payload(row) -> dict:
return {
"id": row["id"],
@@ -166,12 +207,14 @@ def _source_payload(row) -> dict:
"ref": row["ref"],
"label": row["label"],
"author_key": author_key(row),
+ "official_avatar_url": _official_avatar_url(row["provider"], row["ref"]),
"avatar_url": _avatar_url(row["provider"], row["ref"]),
"url": row["url"],
"semantics": row["semantics"],
"enabled": bool(row["enabled"]),
"entity_id": row["entity_id"],
"entity_name": row["entity_name"],
+ "can_backfill": row["provider"] in _BACKFILL_PROVIDERS,
# 往回抓到哪一页了(0 起,0 = 只抓过第一页)。界面据此说清进度,
# 否则用户点一次只看到列表变长一点,不知道自己走到第几页。
"backfill_page": row["backfill_page"],
@@ -273,7 +316,8 @@ def w_follow_check(contract, body) -> dict:
results: list[dict] = []
with contract.database.read_connection() as connection:
rows = [dict(row) for row in _store(contract, connection).sources(enabled_only=True)
- if source_id is None or row["id"] == source_id]
+ if (source_id is None or row["id"] == source_id)
+ and (not older or row["provider"] in _BACKFILL_PROVIDERS)]
for row in rows:
moment = datetime.now(timezone.utc)
provider, ref = row["provider"], row["ref"]
@@ -369,10 +413,13 @@ def w_follow_source(contract, body) -> dict:
credential = credentials.load(parsed.provider)
label = str(body.get("label") or "").strip() or _resolve_label(
contract, parsed, credential)
+ author_hint = str(body.get("author") or "").strip()
+ author_hint = _normalized_author_name(author_hint) if author_hint else ""
+ metadata = {"author_key": author_hint} if author_hint else None
with contract.database.write_transaction() as connection:
source_id = _store(contract, connection).register(
provider=parsed.provider, ref=parsed.ref, label=label, url=parsed.url,
- semantics=parsed.semantics)
+ semantics=parsed.semantics, metadata=metadata)
checked = w_follow_check(contract, {"source": source_id})
outcome = next((row for row in checked["results"]
if row["source"] == source_id), None)
@@ -384,10 +431,11 @@ def w_follow_source(contract, body) -> dict:
MAX_RESOLVE_LINES = 40
-def _candidate_payload(candidate) -> dict:
+def _candidate_payload(candidate, *, author: str = "") -> dict:
return {"provider": candidate.provider,
"provider_label": PROVIDER_LABELS.get(candidate.provider, candidate.provider),
- "ref": candidate.ref, "url": candidate.url, "label": candidate.label,
+ "ref": canonical_source_ref(candidate.provider, candidate.ref),
+ "url": candidate.url, "label": candidate.label, "author": author,
"semantics": candidate.semantics, "evidence": candidate.evidence}
@@ -409,7 +457,7 @@ def w_follow_resolve(contract, body) -> dict:
if len(lines) > MAX_RESOLVE_LINES:
raise ValueError(f"一次最多解析 {MAX_RESOLVE_LINES} 行,收到 {len(lines)} 行")
- known = {(row["provider"], row["ref"]) for row in
+ known = {(row["provider"], canonical_source_ref(row["provider"], row["ref"])) for row in
(_source_payload(r) for r in _existing_sources(contract))}
results = []
for line in lines:
@@ -428,15 +476,17 @@ def w_follow_resolve(contract, body) -> dict:
continue
results.append({
"line": line, "kind": "term",
- "candidates": [{**_candidate_payload(c),
- "known": (c.provider, c.ref) in known}
+ "candidates": [{**_candidate_payload(c, author=line),
+ "known": (c.provider, canonical_source_ref(
+ c.provider, c.ref)) in known}
for c in found.candidates],
"failures": found.failures,
})
continue
results.append({"line": line, "kind": "url",
"candidates": [{**_candidate_payload(parsed),
- "known": (parsed.provider, parsed.ref) in known}]})
+ "known": (parsed.provider, canonical_source_ref(
+ parsed.provider, parsed.ref)) in known}]})
return {"ok": True, "results": results}
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 7bf9023c4..df3cbea32 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -238,6 +238,18 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(response.headers["content-type"], "image/png")
self.assertTrue(response.content.startswith(b"\x89PNG\r\n\x1a\n"))
+ async def test_follow_avatar_redirects_only_after_the_official_resolver(self):
+ denied = await self.client.get("/follow-avatar?service=fanbox&id=30917150")
+ self.assertEqual(denied.status_code, 401)
+ with patch("peach.api.resolve_official_avatar",
+ return_value="https://pixiv.pximg.net/icon.jpeg") as resolver:
+ response = await self.client.get(
+ "/follow-avatar?t=secret&service=fanbox&id=30917150")
+ self.assertEqual(response.status_code, 307)
+ self.assertEqual(response.headers["location"],
+ "https://pixiv.pximg.net/icon.jpeg")
+ resolver.assert_called_once_with("fanbox", "30917150")
+
async def test_emptying_the_recycle_bin_is_actually_wired_and_deletes_media(self):
"""接线本身要有测试:此前 dispatch 接上了 `/api/trash/empty`,函数却根本没写。
diff --git a/tests/test_follow_avatar.py b/tests/test_follow_avatar.py
new file mode 100644
index 000000000..e05de9919
--- /dev/null
+++ b/tests/test_follow_avatar.py
@@ -0,0 +1,63 @@
+import json
+import unittest
+
+from peach.follow import FollowSourceError
+from peach.follow_avatar import resolve_official_avatar
+from peach.http import HttpResponse
+
+
+class _Transport:
+ def __init__(self, responses):
+ self.responses = list(responses)
+ self.requests = []
+
+ def __call__(self, request, _timeout, _max_bytes):
+ self.requests.append(request)
+ return self.responses.pop(0)
+
+
+class OfficialAvatarTests(unittest.TestCase):
+ def _responses(self, *, user_id="30917150",
+ icon="https://pixiv.pximg.net/c/160x160/icon.jpeg"):
+ metadata = {"urlContext": {"host": {"creatorId": "lazyprocrast"}}}
+ page = (
+ "<html><meta name='metadata' content='"
+ + json.dumps(metadata).replace("'", "&#39;")
+ + "'></html>"
+ ).encode()
+ api = json.dumps({"body": {"user": {
+ "userId": user_id, "iconUrl": icon,
+ }}}).encode()
+ return [HttpResponse(200, {"content-type": "text/html"}, page),
+ HttpResponse(200, {"content-type": "application/json"}, api)]
+
+ def test_fanbox_avatar_comes_from_the_official_creator_profile(self):
+ transport = _Transport(self._responses())
+ avatar = resolve_official_avatar("fanbox", "30917150", transport=transport)
+ self.assertEqual(avatar, "https://pixiv.pximg.net/c/160x160/icon.jpeg")
+ self.assertEqual(transport.requests[0].url,
+ "https://www.pixiv.net/fanbox/creator/30917150")
+ self.assertIn("creatorId=lazyprocrast", transport.requests[1].url)
+ self.assertEqual(transport.requests[1].headers["Origin"],
+ "https://lazyprocrast.fanbox.cc")
+
+ def test_the_official_api_must_return_the_requested_user(self):
+ with self.assertRaises(FollowSourceError):
+ resolve_official_avatar(
+ "fanbox", "30917150", transport=_Transport(
+ self._responses(user_id="999")))
+
+ def test_the_avatar_cannot_redirect_to_an_untrusted_host(self):
+ with self.assertRaises(FollowSourceError):
+ resolve_official_avatar(
+ "fanbox", "30917150", transport=_Transport(
+ self._responses(icon="https://example.test/avatar.jpg")))
+
+ def test_only_verified_fanbox_numeric_ids_are_accepted(self):
+ for service, user in (("patreon", "30917150"), ("fanbox", "../secret")):
+ with self.assertRaises(FollowSourceError):
+ resolve_official_avatar(service, user, transport=_Transport([]))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.py
index 59b9cbddf..6ba6e2d51 100644
--- a/tests/test_follow_sources.py
+++ b/tests/test_follow_sources.py
@@ -562,6 +562,14 @@ class ParseSourceUrlTests(unittest.TestCase):
self.assertEqual(parsed.ref, "fanbox/30917150")
self.assertEqual(parsed.url, "https://kemono.cr/fanbox/user/30917150")
+ def test_rule34_tags_use_one_case_insensitive_identity(self):
+ upper = parse_source_url(
+ "https://rule34.xxx/index.php?page=post&s=list&tags=LazyProcrastinator")
+ lower = parse_source_url(
+ "https://rule34.xxx/index.php?page=post&s=list&tags=lazyprocrastinator")
+ self.assertEqual(upper.ref, "lazyprocrastinator")
+ self.assertEqual(upper, lower)
+
def test_threads_get_release_semantics_and_others_get_work(self):
self.assertEqual(parse_source_url("https://f95zone.to/threads/x.1/").semantics,
"release")
diff --git a/tests/test_follow_store.py b/tests/test_follow_store.py
index 8e176de76..5827427ec 100644
--- a/tests/test_follow_store.py
+++ b/tests/test_follow_store.py
@@ -69,6 +69,13 @@ class RegistrationTests(_StoreCase):
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0]["label"], "Lazy P")
+ def test_rule34_case_variants_are_the_same_source(self):
+ first = self._source(provider="rule34xxx", ref="LazyProcrastinator")
+ second = self._source(provider="rule34xxx", ref="lazyprocrastinator")
+ self.assertEqual(first, second)
+ self.assertEqual(len(self.store.sources()), 1)
+ self.assertEqual(self.store.sources()[0]["ref"], "lazyprocrastinator")
+
def test_register_keeps_an_existing_entity_when_the_update_omits_it(self):
entity_id = self._entity()
self._source(entity_id=entity_id)
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 76d10cf35..72919706e 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -138,6 +138,17 @@ class FollowContractTests(unittest.TestCase):
# 第一次常规检查 → 0;两次往回抓 → 1、2,游标一次只走一页。
self.assertEqual(pages, [0, 1, 2])
+ def test_paging_back_skips_sources_without_a_history_endpoint(self):
+ self._seed(provider="f95zone", ref="50685", semantics="release")
+ factory = mock.Mock()
+ with mock.patch.object(web_follow, "build_connector", factory):
+ result = self._post("/api/follow/check", {"older": True})
+ self.assertEqual(result["checked"], 0)
+ factory.assert_not_called()
+ source = next(row for row in self._get()["sources"]
+ if row["provider"] == "f95zone")
+ self.assertFalse(source["can_backfill"])
+
def test_feed_groups_variants_under_one_card(self):
self._seed()
payload = self._get()
@@ -527,6 +538,20 @@ class FollowSourceAddTests(FollowContractTests):
self.assertEqual(self._get()["sources"][0]["url"],
"https://rule34video.com/models/lazyprocrastinator/")
+ def test_a_discovery_author_hint_is_persisted_for_cross_site_grouping(self):
+ with mock.patch.object(web_follow, "build_connector") as factory:
+ factory.return_value.fetch.return_value = SourceFetch(
+ provider="rule34video", ref="lazyprocrastinator",
+ request_url="https://rule34video.test/x", semantics="work",
+ not_modified=True)
+ self._post("/api/follow/source", {
+ "action": "add",
+ "url": "https://rule34video.com/models/lazyprocrastinator/",
+ "author": "Lazy Procrastinator",
+ })
+ source = self._get()["sources"][0]
+ self.assertEqual(source["author_key"], "name:lazyprocrastinator")
+
def test_a_thread_link_is_registered_with_release_semantics(self):
self._add("https://f95zone.to/threads/"
"lazy-procrastinator-collection-2026-06-28-lazyprocrast.50685/")
@@ -547,6 +572,16 @@ class FollowSourceAddTests(FollowContractTests):
self._add("https://rule34video.com/models/lazyprocrastinator/")
self.assertEqual(len(self._get()["sources"]), 1)
+ def test_rule34_case_variants_do_not_duplicate_the_source(self):
+ self._add(
+ "https://rule34.xxx/index.php?page=post&s=list&tags=LazyProcrastinator")
+ self._add(
+ "https://rule34.xxx/index.php?page=post&s=list&tags=lazyprocrastinator")
+ sources = [row for row in self._get()["sources"]
+ if row["provider"] == "rule34xxx"]
+ self.assertEqual(len(sources), 1)
+ self.assertEqual(sources[0]["ref"], "lazyprocrastinator")
+
def test_a_failing_first_check_still_leaves_the_source_registered(self):
# rule34.xxx 缺 key 就是这种情况。整个回滚掉反而让人不知道发生了什么。
with mock.patch.object(web_follow, "build_connector") as factory:
@@ -833,6 +868,25 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageContains("row.path")
self.assertPageContains("row.world_readable")
+ def test_credential_explanation_is_collapsed_without_hiding_the_warning(self):
+ summary = self.page.split("存放位置与权限", 1)[1].split("</summary>", 1)[0]
+ self.assertIn("Windows 上不收紧文件权限", summary)
+ self.assertPageContains(".fdetails summary::before")
+
+ def test_follow_source_icons_fail_back_to_plain_text(self):
+ icons = self.page.split("const SOURCE_ICONS={", 1)[1].split("};", 1)[0]
+ self.assertIn("kemono.cr/assets/favicon-", icons)
+ self.assertIn("pawchive.pw/static/favicon.png", icons)
+ self.assertNotIn("kemono.cr/favicon.ico", icons)
+ self.assertPageContains('onerror="this.remove()"')
+
+ def test_follow_watch_filters_use_the_source_identity(self):
+ self.assertPageContains("if(followAuthor&&source.author_key!==followAuthor)return false;")
+ self.assertPageContains("if(followProvider&&source.provider!==followProvider)return false;")
+ self.assertPageContains("const chips=(items,current,attr)=>items.length<2?''")
+ self.assertPageContains("标签 · 只有 ${")
+ self.assertPageContains(".sort((a,b)=>b[1]-a[1]).slice(0,20)")
+
def test_credentials_are_typed_into_the_page_not_into_a_file_by_hand(self):
self.assertPageContains('data-cred-form=')
self.assertPageContains("'/api/follow/credential'")
@@ -926,6 +980,8 @@ class FollowWebSourceTests(unittest.TestCase):
row.setdefault("entity_id", None)
row.setdefault("id", 1)
row.setdefault("ref", "")
+ row.setdefault("provider", "rule34video")
+ row.setdefault("metadata_json", "{}")
return web_follow.author_key(row)
# 「· 服务名」只说明他在哪个平台连载,不是身份的一部分。
@@ -939,6 +995,15 @@ class FollowWebSourceTests(unittest.TestCase):
key(label="LazyProcrastinator", entity_id=7))
# 不同的人不许并。
self.assertNotEqual(key(label="bewyx"), key(label="bewyx2"))
+ self.assertEqual(
+ key(label="Lazy Procrastinator Collection", provider="f95zone"),
+ key(label="lazyprocrastinator"),
+ )
+ self.assertEqual(
+ key(label="unrelated", provider="f95zone",
+ metadata_json='{"author_key":"lazyprocrastinator"}'),
+ "name:lazyprocrastinator",
+ )
# 名字为空时退回来源 id,不能让所有空名字挤成一组。
self.assertNotEqual(key(label="", id=1), key(label="", id=2))
@@ -953,6 +1018,10 @@ class FollowWebSourceTests(unittest.TestCase):
"https://kemono.cr/icons/fanbox/30917150")
self.assertEqual(web_follow._avatar_url("pawchive", "fanbox/30917150"),
"https://pawchive.pw/icons/fanbox/30917150")
+ self.assertEqual(
+ web_follow._official_avatar_url("kemono", "fanbox/30917150"),
+ "/follow-avatar?service=fanbox&id=30917150",
+ )
for provider, ref in (("rule34video", "1290582"),
("rule34xxx", "lazyprocrastinator"),
("f95zone", "50685"),
@@ -1005,6 +1074,12 @@ class FollowWebSourceTests(unittest.TestCase):
avatar = avatar[:avatar.index("function followAuthorBlock")]
self.assertNotIn("charAt", avatar, "不许用首字母冒充头像")
self.assertIn("source.avatar_url", avatar)
+ self.assertIn("source.official_avatar_url", avatar)
+ self.assertIn("data-fallback", avatar)
+
+ def test_discovered_sources_keep_the_search_term_as_the_author_identity(self):
+ self.assertPageContains('data-author="${esc(c.author||\'\')}"')
+ self.assertPageContains("author:input.dataset.author")
def test_credential_dependent_media_is_called_out(self):
self.assertPageContains("媒体需要登录会话才能取,发现本身不需要")
diff --git a/tests/test_metadata.py b/tests/test_metadata.py
index 3eed87d65..2f05ce054 100644
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -82,6 +82,28 @@ class MetadataProviderTests(unittest.TestCase):
self.assertIn("已规范化", fields["release_date"]["warnings"][0])
self.assertEqual(fields["tags"]["value"], ["肛交"])
+ def test_series_and_studio_take_the_japanese_original(self):
+ payload = {
+ "maker": "Prestige",
+ "series": "Prestige 20th Anniversary Special Event",
+ "translations": [
+ {"language": "en", "maker": "Prestige", "series": "Prestige 20th Anniversary Special Event"},
+ {"language": "ja", "maker": "プレステージ", "series": "【プレステージ20周年特別企画】"},
+ ],
+ }
+ fields = extract_peach_fields(payload, {})
+ self.assertEqual(fields["series"]["value"], "【プレステージ20周年特別企画】")
+ self.assertEqual(fields["studio"]["value"], "プレステージ")
+
+ def test_empty_japanese_names_fall_back_to_the_default_view(self):
+ fields = extract_peach_fields({
+ "maker": "FALENO",
+ "series": "FALENO Compilation",
+ "translations": [{"language": "ja", "maker": "", "series": ""}],
+ }, {})
+ self.assertEqual(fields["series"]["value"], "FALENO Compilation")
+ self.assertEqual(fields["studio"]["value"], "FALENO")
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_migrations.py b/tests/test_migrations.py
index 8a2890e42..f2ddcab52 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"])
+ ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020"])
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"])
+ 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(upgrade(self.db, MIGRATIONS), [])
self.assertEqual(plan(self.db, MIGRATIONS)[1], [])
@@ -288,6 +288,54 @@ class MigrationTests(unittest.TestCase):
).fetchall(), [])
connection.close()
+ def test_rule34_source_case_duplicates_merge_without_losing_item_state(self):
+ base_migrations = self.root / "base-migrations"
+ base_migrations.mkdir()
+ for path in sorted(MIGRATIONS.glob("*.sql")):
+ if not path.name.startswith("0020_"):
+ shutil.copyfile(path, base_migrations / path.name)
+ sqlite3.connect(self.db).close()
+ upgrade(self.db, base_migrations)
+ connection = sqlite3.connect(self.db)
+ connection.executescript("""
+ INSERT INTO asset(id,location,path,name,medium)
+ VALUES(1,'online','https://example.test/1','saved','video');
+ INSERT INTO follow_source(
+ id,provider,ref,label,url,semantics,metadata_json,created_at,updated_at
+ ) VALUES
+ (10,'rule34xxx','lazyprocrastinator','lazyprocrastinator',
+ 'https://rule34.xxx/?tags=lazyprocrastinator','work','{}','1','1'),
+ (11,'rule34xxx','LazyProcrastinator','LazyProcrastinator',
+ 'https://rule34.xxx/?tags=LazyProcrastinator','work','{}','2','2');
+ INSERT INTO follow_item(
+ source_id,external_id,title,published_precision,release_key,variant_kind,
+ status,asset_id,metadata_json,first_seen_at,last_seen_at
+ ) VALUES
+ (10,'same','same','exact','same','main','ignored',NULL,'{}','1','2'),
+ (10,'lower-only','lower','exact','lower','main','new',NULL,'{}','1','2'),
+ (11,'same','same','exact','same','main','saved',1,'{}','2','3'),
+ (11,'upper-only','upper','exact','upper','main','seen',NULL,'{}','2','3');
+ """)
+ connection.close()
+
+ upgrade(self.db, MIGRATIONS)
+
+ connection = sqlite3.connect(self.db)
+ sources = connection.execute(
+ "SELECT id,ref,url FROM follow_source WHERE provider='rule34xxx'"
+ ).fetchall()
+ items = connection.execute(
+ "SELECT external_id,status,asset_id FROM follow_item ORDER BY external_id"
+ ).fetchall()
+ connection.close()
+ self.assertEqual(sources, [(10, "lazyprocrastinator",
+ "https://rule34.xxx/?tags=lazyprocrastinator")])
+ self.assertEqual(items, [
+ ("lower-only", "new", None),
+ ("same", "saved", 1),
+ ("upper-only", "seen", None),
+ ])
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_tray.py b/tests/test_tray.py
index acd296ed8..00d9d4718 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -332,13 +332,14 @@ class SourceSyncTests(unittest.TestCase):
def test_launchd_ownership_requires_a_matching_pid_not_just_a_loaded_job(self):
"""只看「作业已加载」会在终端启动的托盘上 kickstart 出第二个菜单栏图标。"""
loaded_elsewhere = Mock(returncode=0, stdout="\tpid = 1\n\tstate = running\n")
- self.assertFalse(launchd_owns_this_process(Mock(return_value=loaded_elsewhere)))
+ self.assertFalse(launchd_owns_this_process(
+ Mock(return_value=loaded_elsewhere), uid=501))
mine = Mock(returncode=0, stdout=f"\tpid = {os.getpid()}\n\tstate = running\n")
- self.assertTrue(launchd_owns_this_process(Mock(return_value=mine)))
+ self.assertTrue(launchd_owns_this_process(Mock(return_value=mine), uid=501))
self.assertFalse(launchd_owns_this_process(
- Mock(return_value=Mock(returncode=113, stdout=""))))
+ Mock(return_value=Mock(returncode=113, stdout="")), uid=501))
def test_the_menu_lists_source_sync_next_to_the_ledger_actions(self):
"""标签和位置是语义契约:菜单只有一条,写错了没有第二处会报错。"""
@@ -356,12 +357,19 @@ class SourceSyncTests(unittest.TestCase):
def test_tray_restart_asks_launchd_to_kill_and_relaunch_this_label(self):
runner = Mock(return_value=Mock(returncode=0, stdout="", stderr=""))
- restart_tray_process(runner)
+ restart_tray_process(runner, uid=501)
self.assertEqual(
runner.call_args.args[0],
- ["launchctl", "kickstart", "-k", f"gui/{os.getuid()}/gg.lmd.peach.tray"],
+ ["launchctl", "kickstart", "-k", "gui/501/gg.lmd.peach.tray"],
)
+ def test_sync_changes_restart_the_tray_and_failed_kickstart_restores_services(self):
+ self.assertTrue(tray_restart_required(("src/peach/sync.py",)))
+ from peach import tray as tray_module
+ source = inspect.getsource(tray_module.run_macos_menu_bar)
+ self.assertIn("if restarted.returncode != 0:", source)
+ self.assertIn("manager.start_missing()", source)
+
@unittest.skipUnless(sys.platform == "darwin", "菜单栏图标与服务规格是 macOS 专属")
class MacMenuBarTests(unittest.TestCase):
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 94f5ad19c..c194d9b61 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -113,13 +113,15 @@ class WebUiSourceTests(unittest.TestCase):
# 少了这条规则,按钮画在页面上但 requestMore 首行就 return,点了没反应。
self.assertPageContains(".indexmore[hidden],.entitymore[hidden]{display:none}")
- def test_co_starred_cards_show_every_performer_not_only_the_first(self):
- # 卡片不能再只取 performers[0]:共演作品要叠头像、列名字并给出总数。
+ def test_co_starred_cards_keep_one_name_and_the_total(self):
+ # 多人合集保留头像提示,但文字只写第一位和总人数,避免名称折成多行。
self.assertPageContains("const coStarred=performers.length>1&&!it.creator")
self.assertPageContains('<div class="mavstack">')
self.assertPageContains("performers.slice(0,3)")
self.assertPageContains("data-entity-kind=\"performer\" data-entity-name=\"${esc(nm)}\"")
+ self.assertPageContains("data-entity-name=\"${esc(performer)}\"")
self.assertPageContains("等 ${performerTotal} 人")
+ self.assertPageLacks("performers.slice(0,2).map")
self.assertPageContains(".mavstack .mav+.mav{margin-left:-14px}")
def test_every_card_avatar_falls_back_through_the_same_helper(self):
@@ -893,6 +895,8 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("opener.dataset.openWired='1'")
self.assertPageContains(".hovertools button{pointer-events:none")
self.assertPageContains(".card.longhover .seektools button,.card:hover .later-tools button{pointer-events:auto}")
+ self.assertPageContains("section.querySelector('h3').textContent=`视频 ·")
+ self.assertPageLacks("的馆藏作品 ·")
def test_remote_hover_previews_do_not_stream_full_media(self):
self.assertPageContains("if(it.location!=='local')")
diff --git a/web/app.css b/web/app.css
index 74f6a79ed..fb49321ef 100644
--- a/web/app.css
+++ b/web/app.css
@@ -1182,6 +1182,22 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
.follow{padding:8px 0 42px}
.follow .reviewtabs .fcheck{margin-left:auto;display:inline-flex;align-items:center;gap:6px;background:var(--tungsten);border-color:var(--tungsten);color:#fff;font-weight:600}
.follow .reviewtabs .fcheck svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:2}
+.fdetails summary{cursor:pointer;list-style:none}
+.fdetails summary::-webkit-details-marker{display:none}
+.fdetails summary::before{content:"› ";display:inline-block;transition:transform .12s}
+.fdetails[open] summary::before{transform:rotate(90deg)}
+.fdetails p{margin:6px 0 0}
+.ficon{width:14px;height:14px;border-radius:3px;object-fit:contain;
+ vertical-align:-2px;margin-right:5px}
+.fauthorhead .ficon{margin-right:2px}
+.ffilter{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 12px}
+.ffilter button{display:inline-flex;align-items:center;border:1px solid var(--border-15);
+ border-radius:var(--pill-radius);background:transparent;color:var(--ink-2);
+ padding:5px 12px;cursor:pointer;font-size:var(--fs-xs)}
+.ffilter button:hover{border-color:var(--tungsten);color:var(--ink)}
+.ffilter button[aria-pressed="true"]{background:var(--tungsten-soft);
+ border-color:var(--tungsten);color:var(--tungsten);font-weight:600}
+.ffilterlabel{align-self:center;margin-right:2px}
.followlist{display:grid;grid-template-columns:repeat(auto-fill,minmax(400px,1fr));gap:14px}
.followitem{display:grid;grid-template-columns:150px minmax(0,1fr);gap:12px;background:var(--surface);border:1px solid var(--line-soft);border-radius:12px;padding:12px;min-width:0}
.followitem[data-status="ignored"],.followitem[data-status="seen"]{opacity:.62}
diff --git a/web/app.js b/web/app.js
index 029333cc3..f8f379ede 100644
--- a/web/app.js
+++ b/web/app.js
@@ -530,8 +530,8 @@ function cardHtml(it,cls){
const who=identity.name,whoKind=identity.kind;
const sizeText=Number(it.size)>0?fmtSize(Number(it.size)):'大小未知';
const tgs=(it.tags||[]).slice(0,3).map(x=>`<span class="tg general" data-tag="${esc(x)}">${esc(tagLabel(x))}</span>`).join('');
- // 共演作品的每一位出镜者都要露出,而不是只留第一位。头像叠放最多 3 个,
- // 名字最多 2 个,剩下的记为「等 N 人」,避免 BEST 合集把整行撑开。
+ // 共演作品用头像提示多人,但文字只保留第一位,再给总人数。两个长名字加元数据
+ // 会在普通卡片里折成三行;「第一位 + 等 N 人」仍能说明身份与规模。
const coStarred=performers.length>1&&!it.creator;
const avatar=coStarred
? `<div class="mavstack">${performers.slice(0,3)
@@ -549,8 +549,8 @@ function cardHtml(it,cls){
: `<span class="mav">${inner}</span>`;
})();
const whoHtml=coStarred
- ? performers.slice(0,2).map(nm=>`<button class="who entitylink" data-entity-kind="performer" data-entity-name="${esc(nm)}">${esc(nm)}</button>`).join('<span class="whosep">、</span>')
- +(performerTotal>2?`<span class="whomore">等 ${performerTotal} 人</span>`:'')
+ ? `<button class="who entitylink" data-entity-kind="performer" data-entity-name="${esc(performer)}">${esc(performer)}</button>`
+ +`<span class="whomore">等 ${performerTotal} 人</span>`
: (whoKind?`<button class="who entitylink" data-entity-kind="${whoKind}" data-entity-name="${esc(who)}">${esc(who)}</button>`:`<span class="who">${esc(who)}</span>`);
const tools=`<button class="previewcounter" data-open title="打开预览" aria-label="打开预览">
<svg viewBox="-18 -18 36 36"><circle r="17"></circle><circle r="17"></circle></svg>${icon('play','ringplay')}</button>
@@ -1314,7 +1314,7 @@ function followCard(group){
<a class="fthumb" href="${esc(item.url||'#')}" target="_blank" rel="noreferrer noopener">${thumb}</a>
<div class="fbody">
<h4><a href="${esc(item.url||'#')}" target="_blank" rel="noreferrer noopener">${esc(item.title)}</a></h4>
- <p class="mono"><span>${esc(item.provider_label)}</span><span>${followWhen(item)}</span>${
+ <p class="mono"><span>${sourceIcon(item.provider)}${esc(item.provider_label)}</span><span>${followWhen(item)}</span>${
item.duration?`<span>${fmtDur(item.duration)}</span>`:''}</p>
<div class="fbadges">${followBadges(group)}</div>
${rows?`<ul class="fvariants">${rows}</ul>`:''}
@@ -1365,23 +1365,64 @@ function followCheckSummary(report){
}
/* ── 看的那一页 ── */
+let followAuthor='',followProvider='',followTag='';
+const TAGGED_PROVIDERS=['rule34xxx'];
function renderFollow(){
const groups=followData.groups||[],counts=followData.counts||{};
const sources=followData.sources||[];
const broken=sources.filter(s=>s.last_status==='error'||s.last_status==='unauthorized');
+ const byId=new Map(sources.map(source=>[source.id,source]));
+ const sourceOf=group=>byId.get(group.primary&&group.primary.source_id);
+ const authorSources=new Map(),providers=new Map(),tagCounts=new Map();
+ groups.forEach(group=>{
+ (group.primary&&group.primary.tags||[]).forEach(tag=>
+ tagCounts.set(tag,(tagCounts.get(tag)||0)+1));
+ const source=sourceOf(group);if(!source)return;
+ if(source.author_key){
+ if(!authorSources.has(source.author_key))authorSources.set(source.author_key,[]);
+ authorSources.get(source.author_key).push(source);
+ }
+ if(!providers.has(source.provider))providers.set(source.provider,source.provider_label);
+ });
+ const authors=new Map([...authorSources].map(([key,list])=>[key,followAuthorName(list)]));
+ const topTags=[...tagCounts].sort((a,b)=>b[1]-a[1]).slice(0,20)
+ .map(([tag,n])=>[tag,`${tag} ${n}`]);
+ if(followAuthor&&!authors.has(followAuthor))followAuthor='';
+ if(followProvider&&!providers.has(followProvider))followProvider='';
+ if(followTag&&!tagCounts.has(followTag))followTag='';
+ const visible=groups.filter(group=>{
+ const source=sourceOf(group);
+ if(!source)return !followAuthor&&!followProvider;
+ if(followAuthor&&source.author_key!==followAuthor)return false;
+ if(followProvider&&source.provider!==followProvider)return false;
+ if(followTag&&!(group.primary&&group.primary.tags||[]).includes(followTag))return false;
+ return true;
+ });
+ const chips=(items,current,attr)=>items.length<2?'':`<div class="ffilter">`+
+ [['','全部'],...items].map(([key,label])=>
+ `<button data-${attr}="${esc(key)}" aria-pressed="${key===current}">${
+ attr==='follow-provider'&&key?sourceIcon(key):''}${esc(label)}</button>`).join('')+`</div>`;
$('#stats').innerHTML=`<div class="follow">
<h2 class="disp pagetitle">关注</h2>
<div class="reviewtabs">${FOLLOW_FILTERS.map(([key,label])=>
`<button data-follow-filter="${key}" aria-pressed="${key===followFilter}">${label}${
key?` <span class="n mono">${counts[key]||0}</span>`:''}</button>`).join('')}
<button class="fcheck" data-follow-manage>${icon('settings')}管理关注</button></div>
+ ${chips([...authors],followAuthor,'follow-author')}
+ ${chips([...providers],followProvider,'follow-provider')}
+ ${topTags.length?`<div class="ffilter"><span class="fmeta ffilterlabel">标签 · 只有 ${
+ TAGGED_PROVIDERS.map(provider=>esc(providers.get(provider)||provider)).join('、')} 提供</span>`+
+ [['','全部'],...topTags].map(([key,label])=>
+ `<button data-follow-tag="${esc(key)}" aria-pressed="${key===followTag}">${esc(label)}</button>`
+ ).join('')+`</div>`:''}
${broken.length?`<p class="fwarn">${broken.length} 个来源上次检查失败,去
<button class="flink" data-follow-manage>管理关注</button>看原因。</p>`:''}
${followCheckReport?followCheckSummary(followCheckReport):''}
- <div class="followlist">${groups.length?groups.map(followCard).join('')
+ <div class="followlist">${visible.length?visible.map(followCard).join('')
+ :groups.length?'<p class="empty">当前筛选下没有更新</p>'
:sources.length?'<p class="empty">没有符合条件的更新</p>'
:`<p class="empty">还没有关注任何来源。<button class="flink" data-follow-manage>去添加</button></p>`}</div>
- ${sources.length?`<div class="folderfoot">
+ ${sources.some(source=>source.can_backfill)?`<div class="folderfoot">
<button class="fbtn" data-follow-older>${icon('refresh-cw')}抓更早的一页</button>
<span class="fmeta">${esc(followBackfillState(sources))}</span></div>`:''}</div>`;
wireFollowItems();
@@ -1390,6 +1431,12 @@ function renderFollow(){
followCheckReport=null;button.closest('.fcheckreport')?.remove()});
$('#stats').querySelectorAll('[data-follow-filter]').forEach(button=>button.onclick=()=>{
followFilter=button.dataset.followFilter;openFollow(false)});
+ $('#stats').querySelectorAll('[data-follow-author]').forEach(button=>button.onclick=()=>{
+ followAuthor=button.dataset.followAuthor;renderFollow()});
+ $('#stats').querySelectorAll('[data-follow-provider]').forEach(button=>button.onclick=()=>{
+ followProvider=button.dataset.followProvider;renderFollow()});
+ $('#stats').querySelectorAll('[data-follow-tag]').forEach(button=>button.onclick=()=>{
+ followTag=button.dataset.followTag;renderFollow()});
$('#stats').querySelectorAll('[data-follow-manage]').forEach(button=>
button.onclick=()=>openFollowManage());
}
@@ -1397,7 +1444,9 @@ function renderFollow(){
/* 往回抓到哪儿了。不说的话,用户点一次只看到列表变长一点,不知道自己走到第几页,
也不知道还要点几次。页码是 0 起的游标(0 = 只抓过第一页),显示成人读的第几页。 */
function followBackfillState(sources){
- const pages=sources.map(source=>(source.backfill_page||0)+1);
+ const pages=sources.filter(source=>source.can_backfill)
+ .map(source=>(source.backfill_page||0)+1);
+ if(!pages.length)return '';
const deepest=Math.max(...pages), shallowest=Math.min(...pages);
if(deepest<=1)return '每个来源都只抓了第 1 页';
return shallowest===deepest
@@ -1460,13 +1509,32 @@ function followAuthorGroups(sources){
return order.map(key=>byKey.get(key));
}
+/* 这些地址来自各站实际声明的图标;内容哈希变更或站点拒绝外链时退回纯文字。 */
+const SOURCE_ICONS={
+ kemono:'https://kemono.cr/assets/favicon-CPB6l7kH.ico',
+ coomer:'https://coomer.st/assets/favicon-CPB6l7kH.ico',
+ pawchive:'https://pawchive.pw/static/favicon.png',
+ rule34video:'https://rule34video.com/favicon-32x32.png',
+ rule34xxx:'https://rule34.xxx/favicon.ico',
+ f95zone:'https://f95zone.to/assets/favicon-32x32.png',
+};
+const sourceIcon=provider=>SOURCE_ICONS[provider]
+ ? `<img class="ficon" src="${esc(SOURCE_ICONS[provider])}" alt="" loading="lazy"
+ referrerpolicy="no-referrer" onerror="this.remove()">`
+ : '';
+
/* 头像只有实测拿得到的来源才有(kemono 系)。取不到就显示站点缩写,
**不用首字母假装成头像**——那会让「没取到」看起来像「取到了」。 */
function followAuthorAvatar(group){
- const withIcon=group.find(source=>source.avatar_url);
- if(withIcon)return `<img class="favatar" src="${esc(withIcon.avatar_url)}" alt=""
- loading="lazy" referrerpolicy="no-referrer" onerror="this.replaceWith(
- Object.assign(document.createElement('span'),{className:'favatar none',textContent:'—'}))">`;
+ const official=group.find(source=>source.official_avatar_url);
+ const mirror=group.find(source=>source.avatar_url);
+ const src=official?.official_avatar_url||mirror?.avatar_url;
+ const fallback=official&&mirror&&mirror.avatar_url!==src?mirror.avatar_url:'';
+ if(src)return `<img class="favatar" src="${esc(src)}" alt=""
+ ${fallback?`data-fallback="${esc(fallback)}"`:''}
+ loading="lazy" referrerpolicy="no-referrer" onerror="if(!this.dataset.f&&this.dataset.fallback){
+ this.dataset.f='1';this.src=this.dataset.fallback}else{this.replaceWith(
+ Object.assign(document.createElement('span'),{className:'favatar none',textContent:'—'}))}">`;
return '<span class="favatar none" title="这些来源没有可取的头像">—</span>';
}
@@ -1491,7 +1559,9 @@ function followAuthorBlock(group){
return `<div class="fauthor${bad?' bad':''}">
<div class="fauthorhead">${followAuthorAvatar(group)}
<b>${esc(name)}</b>
- <span class="fmeta">${group.length>1?`${group.length} 个来源`:esc(group[0].provider_label)}</span>
+ <span class="fmeta">${group.length>1
+ ? group.map(source=>sourceIcon(source.provider)).join('')+`${group.length} 个来源`
+ : sourceIcon(group[0].provider)+esc(group[0].provider_label)}</span>
${bad?`<span class="fmeta warn">${bad} 个失败</span>`:''}
</div>
${group.map(followSourceRow).join('')}</div>`;
@@ -1502,7 +1572,7 @@ function followSourceRow(source){
const bad=state==='error'||state==='unauthorized';
return `<div class="frow fsource${bad?' bad':''}">
<b>${esc(source.label)}</b>
- <span class="fmeta">${esc(source.provider_label)}</span>
+ <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>
@@ -1610,8 +1680,12 @@ function renderFollowManage(credentials){
<div class="fsechead"><h3>凭据</h3>
${needCred.length?`<span class="fmeta warn">${needCred.length} 个待配置</span>`:''}</div>
<div class="frows">${creds.map(followCredentialRow).join('')}</div>
- <p class="fnote">存在<b>运行 Peach 的那台机器</b>上,不进 Git、日志或 ledger。
- Windows 上不收紧文件权限(NTFS 走 ACL)。</p>
+ <details class="fnote fdetails">
+ <summary>存放位置与权限 · Windows 上不收紧文件权限</summary>
+ <p>存在<b>运行 Peach 的那台机器</b>上,不是浏览器所在机器;
+ 不进 Git、URL、日志或 ledger。</p>
+ <p>NTFS 的访问控制走 ACL,<code>chmod</code> 在那里没有效果;POSIX 上建成 0600。</p>
+ </details>
</section>
</aside></div>`;
wireFollowManage();
@@ -1782,6 +1856,7 @@ function renderFollowPicks(results){
const failures=Object.entries(row.failures||{});
const items=(row.candidates||[]).map((c,ci)=>`<label class="fpickitem${c.known?' known':''}">
<input type="checkbox" data-pick="${index}-${ci}" value="${esc(c.url)}"
+ data-author="${esc(c.author||'')}"
data-label="${esc(c.label)}"${c.known?' disabled':' checked'}>
<span><b>${esc(c.provider_label)}</b> ${esc(c.label)}
<i>${esc(c.known?'已经在追':c.evidence)}</i></span></label>`).join('');
@@ -1808,7 +1883,8 @@ function renderFollowPicks(results){
state.textContent=`添加中… ${++done}/${picked.length}`;
try{
await api('/api/follow/source',{method:'POST',body:JSON.stringify(
- {action:'add',url:input.value,label:input.dataset.label})});
+ {action:'add',url:input.value,label:input.dataset.label,
+ author:input.dataset.author})});
}catch(error){
// 一条失败不该把其余的一起丢掉,逐条报。
failures.push(`${input.dataset.label}:${error.message}`);
@@ -1993,7 +2069,7 @@ function renderEntityCollection(kind,name,items,filters,append=false){
const section=$('#index').querySelector('.entitysection');if(!section)return;
if(!append){section.innerHTML=`<h3></h3><div class="grid"></div><button class="entitymore" type="button">载入更多</button>`;
section.dataset.total=String(items.total||0);
- section.querySelector('h3').textContent=`${ENTITY_LABELS[kind]||kind}的馆藏作品 · ${(items.total||0).toLocaleString()}${entityTag?' · '+entityTag:''}`}
+ section.querySelector('h3').textContent=`视频 · ${(items.total||0).toLocaleString()}${entityTag?' · '+entityTag:''}`}
const grid=section.querySelector('.grid');
grid.insertAdjacentHTML('beforeend',items.items.map(it=>cardHtml(it)).join(''));
wireCards(grid,undefined,tag=>updateEntityCollection(