Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor(metadata): 在线头像候选由路由层注入媒体策略

longmeidao6f6de85dbbf3
diff --git a/src/peach/avatar_online.py b/src/peach/avatar_online.py
index 6173700b8..42ce56af7 100644
--- a/src/peach/avatar_online.py
+++ b/src/peach/avatar_online.py
@@ -2,14 +2,26 @@
from __future__ import annotations
import sqlite3
+from collections.abc import Callable
+from dataclasses import dataclass
from urllib.parse import parse_qs, urlsplit
from .avatar_picker import Choice, MAX_ASSET_CHOICES, MAX_IMAGE_BYTES, PickerError, accept_image
from .avatar_provider import inspect_avatar
from .follow_avatar import profile_identities
from .follow_identity import official_avatar_url
-from .follow_store import FollowStore
-from . import images, web_follow
+from .follow_store import FollowItemRow, FollowStore
+from . import images
+
+
+@dataclass(frozen=True)
+class MediaChoices:
+ """调用方确认可见的封面与图片序号;None 序号表示单图原图。"""
+ cover: str | None
+ images: tuple[int | None, ...]
+
+
+MediaProjection = Callable[[FollowItemRow], MediaChoices]
def _profile(url: str) -> dict:
@@ -27,7 +39,7 @@ def _profile(url: str) -> dict:
return {}
-def choices(connection: sqlite3.Connection, entity_id: int) -> list[Choice]:
+def choices(connection: sqlite3.Connection, entity_id: int, *, project: MediaProjection) -> list[Choice]:
"""列举只读本地元数据;图片仅在候选可见或用户进入框选时取。"""
store = FollowStore(lambda: connection)
result: list[Choice] = []
@@ -54,23 +66,22 @@ def choices(connection: sqlite3.Connection, entity_id: int) -> list[Choice]:
item = store.item(item_id)
if item is None:
continue
+ projected = project(item)
bases = []
- if web_follow._thumb_url(item):
+ if projected.cover:
bases.append(f"follow:{item.id}:cover")
- bases += [f"follow:{item.id}:image{media['index']}" for media in web_follow._media_items(item)
- if media["media_kind"] == "image"][:9]
- if (not web_follow._raw_media_items(item) and not item.hidden_media
- and web_follow._media_kind(item) == "image" and item.media_url):
- bases.append(f"follow:{item.id}:image")
+ bases += [f"follow:{item.id}:image{index if index is not None else ''}"
+ for index in projected.images[:9]]
if bases:
result.append(Choice(ref=bases[0], source="online", label=item.title,
crop=True, bases=tuple(bases)))
return result
-def resolve(ref: str, connection: sqlite3.Connection, entity_id: int, *, image, avatar, media) -> tuple[bytes, dict]:
+def resolve(ref: str, connection: sqlite3.Connection, entity_id: int, *, project: MediaProjection,
+ image, avatar, media) -> tuple[bytes, dict]:
"""每次取图重新核对归属与可见媒体,不能借别人的条目或隐藏附件换头像。"""
- listed = choices(connection, entity_id)
+ listed = choices(connection, entity_id, project=project)
allowed = {base for choice in listed for base in (choice.bases or (choice.ref,))}
if ref not in allowed:
raise PickerError("这个候选不在这位创作者名下")
@@ -89,7 +100,7 @@ def resolve(ref: str, connection: sqlite3.Connection, entity_id: int, *, image,
_, item_id, base = ref.split(":")
item = FollowStore(lambda: connection).item(int(item_id))
if base == "cover":
- body = image(item, web_follow._thumb_url(item))
+ body = image(item, project(item).cover)
else:
index = int(base[5:]) if base[5:] else None
body = media(item, index)
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.py
index b4e982a9a..8679f3215 100644
--- a/src/peach/routes_media.py
+++ b/src/peach/routes_media.py
@@ -1136,6 +1136,16 @@ def _remember_library(providers_root: Path, body: bytes, origin: dict,
cache.store(str(origin.get("upstream_url") or ""), body, inspected)
+def _picker_online_projection(item) -> avatar_online.MediaChoices:
+ """候选与关注卡共用可见媒体和封面策略,HTTP 地址由 web 层决定。"""
+ indexes = tuple(media["index"] for media in web_follow._media_items(item)
+ if media["media_kind"] == "image")
+ if (not web_follow._raw_media_items(item) and not item.hidden_media
+ and web_follow._media_kind(item) == "image" and item.media_url):
+ indexes = (None,)
+ return avatar_online.MediaChoices(cover=web_follow._thumb_url(item), images=indexes)
+
+
def _picker_online(request: Request, connection, entity_id: int):
"""复用关注代理的主机、凭据与有界封面判据,按候选缓存原图。"""
state = request.app.state
@@ -1180,6 +1190,7 @@ def _picker_online(request: Request, connection, entity_id: int):
return wrapped
try:
body, origin = avatar_online.resolve(ref, connection, entity_id,
+ project=_picker_online_projection,
image=remembered(image), avatar=remembered(avatar), media=remembered(media))
except (OSError, httpx.HTTPError, FollowMediaUnavailable, FollowProxyError, FollowCoverUnavailable) as error:
raise avatar_picker.PickerError("在线图片未取得") from error
@@ -1200,7 +1211,8 @@ def avatar_choices(request: Request, kind: str = "performer", id: int = 0,
connection, providers_root, avatar_root, _picker_kind(kind), id,
cover_root=state.cover_root)
if kind == "creator":
- listing["choices"] += [choice.as_dict() for choice in avatar_online.choices(connection, id)]
+ listing["choices"] += [choice.as_dict() for choice in avatar_online.choices(
+ connection, id, project=_picker_online_projection)]
return JSONResponse(listing)
@@ -1283,7 +1295,7 @@ async def avatar_frame(request: Request, args: dict[str, str] = Depends(require_
found, origin = avatar_picker.resolve(
ref, connection, providers_root, entity_id, transport,
_picker_artwork(request), online=_picker_online(request, connection, entity_id))
- listed = avatar_online.choices(connection, entity_id) if ref.startswith("follow:") else []
+ listed = avatar_online.choices(connection, entity_id, project=_picker_online_projection) if ref.startswith("follow:") else []
_remember_library(providers_root, found, origin, avatar_picker.accept_image(found))
choice = avatar_picker.framed(ref, found, probe, source="", label="")
if ref.startswith("follow:"):
diff --git a/tests/test_avatar_picker.py b/tests/test_avatar_picker.py
index c0deef0e7..1280dd225 100644
--- a/tests/test_avatar_picker.py
+++ b/tests/test_avatar_picker.py
@@ -14,7 +14,7 @@ from unittest import mock
from PIL import Image, ImageDraw
-from peach import avatar_picker, gfriends, http as peach_http, jav_poster_crop
+from peach import avatar_online, avatar_picker, gfriends, http as peach_http, jav_poster_crop
from peach.avatar_face import sidecar_path
from peach.avatar_provider import AvatarCandidateCache, inspect_avatar, provenance_now
from peach.http import HttpResponse
@@ -881,6 +881,39 @@ class AvatarPickerRouteTests(unittest.TestCase):
self.assertTrue(any(choice['source'] == 'social' for choice in listing['choices']))
self.assertNotIn('https://example.com', json.dumps(listing))
+ def test_online_domain_uses_the_injected_visible_media_and_cover(self):
+ item_id = self._online_creator()
+ project = mock.Mock(return_value=avatar_online.MediaChoices(
+ cover="https://example.com/policy-cover.jpg", images=(0,)))
+ image, avatar, media = mock.Mock(return_value=self.picture), mock.Mock(), mock.Mock()
+ with self.app.state.database.read_connection() as connection:
+ listed = avatar_online.choices(connection, 8892, project=project)
+ online = next(choice for choice in listed if choice.source == "online")
+ self.assertEqual(online.bases, (f"follow:{item_id}:cover", f"follow:{item_id}:image0"))
+ body, origin = avatar_online.resolve(f"follow:{item_id}:cover", connection, 8892,
+ project=project, image=image, avatar=avatar, media=media)
+ self.assertEqual(body, self.picture)
+ self.assertEqual(origin["external_id"], f"follow:{item_id}:cover")
+ self.assertEqual(image.call_args.args[0].id, item_id)
+ self.assertEqual(image.call_args.args[1], "https://example.com/policy-cover.jpg")
+ self.assertTrue(all(call.args[0].id == item_id for call in project.call_args_list))
+ avatar.assert_not_called()
+ media.assert_not_called()
+
+ def test_online_domain_rechecks_visibility_before_fetching_a_listed_candidate(self):
+ item_id = self._online_creator()
+ project = mock.Mock(return_value=avatar_online.MediaChoices(cover=None, images=(0,)))
+ fetch = mock.Mock(return_value=self.picture)
+ with self.app.state.database.read_connection() as connection:
+ online = next(choice for choice in avatar_online.choices(connection, 8892, project=project)
+ if choice.source == "online")
+ self.assertEqual(online.ref, f"follow:{item_id}:image0")
+ project.return_value = avatar_online.MediaChoices(cover=None, images=())
+ with self.assertRaises(avatar_picker.PickerError):
+ avatar_online.resolve(online.ref, connection, 8892,
+ project=project, image=fetch, avatar=fetch, media=fetch)
+ fetch.assert_not_called()
+
def test_single_online_image_lists_its_original_content_alongside_the_cover(self):
item = self._online_creator()
with self.app.state.database.write_transaction() as connection: