Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(follow): fanbox 多媒体清单里的视频格用抽帧画面,不再显示站点图标

longmeidaob35933fe1af3
diff --git a/src/peach/follow_covers.py b/src/peach/follow_covers.py
index d07c9654a..7d0d70353 100644
--- a/src/peach/follow_covers.py
+++ b/src/peach/follow_covers.py
@@ -48,6 +48,20 @@ class FollowCoverUnavailable(RuntimeError):
pass
+def fanbox_video_indexes(item: FollowItemRow) -> list[int]:
+ """fanbox 帖子里站内托管的视频在媒体清单中的序号,能由 FFmpeg 抽帧的就是这些。"""
+ return [index for index, media in enumerate(item.metadata.get("media_items") or [])
+ if isinstance(media, dict) and media.get("media_kind") == "video"
+ and media.get("resource_provider") == "fanbox"]
+
+
+def _cache_slot(name: str, item_id: int) -> str:
+ """缓存文件名里视频那一格:第一个视频是空串,点名的其他视频是 `m<序号>-`。"""
+ rest = name[len(f"{item_id}-"):]
+ head, dash, _ = rest.partition("-")
+ return f"{head}-" if dash and head.startswith("m") else ""
+
+
class FollowCoverService:
"""Create a bounded, cached still without exposing the upstream media URL."""
@@ -63,13 +77,23 @@ class FollowCoverService:
# first screen responsive without turning the source CDN into a batch job.
self._slots = threading.BoundedSemaphore(2)
- def cover(self, item: FollowItemRow) -> Path:
+ def cover(self, item: FollowItemRow, media: int | None = None) -> Path:
+ """条目的视频封面;`media` 点名 fanbox 帖子里的某一个视频,缺省是第一个。
+
+ 卡面要的是第一个视频,详情里的多媒体清单每个视频各要一张。第一个视频不论
+ 是否点名都落在同一份缓存上,卡面和清单里那一格共用一次抽帧。
+ """
media_index = None
+ slot = ""
if item.provider == "fanbox":
- media_index = next((index for index, media in enumerate(
- item.metadata.get("media_items") or []) if isinstance(media, dict)
- and media.get("media_kind") == "video"
- and media.get("resource_provider") == "fanbox"), None)
+ videos = fanbox_video_indexes(item)
+ media_index = videos[0] if videos else None
+ if media is not None and media != media_index:
+ if media not in videos:
+ raise FollowCoverUnavailable("点名的媒体不是这篇帖子里的视频")
+ media_index, slot = media, f"m{media}-"
+ elif media is not None:
+ raise FollowCoverUnavailable("只有 fanbox 帖子能按媒体取视频封面")
if not (item.provider == "fanbox" and media_index is not None) and (
item.provider != "rule34paheal"
or str(item.metadata.get("media_kind") or "") != "video"):
@@ -86,7 +110,9 @@ class FollowCoverService:
fingerprint = hashlib.sha256(
f"{_CACHE_VERSION}\0{target.url}".encode("utf-8")
).hexdigest()[:16]
- destination = self.root / f"{item.id}-{fingerprint}.jpg"
+ # 点名的其他视频在文件名里带 `m<序号>-`;指纹是十六进制,不会以 m 开头,
+ # 所以下面按名字清旧帧时,各个视频只清自己那一格。
+ destination = self.root / f"{item.id}-{slot}{fingerprint}.jpg"
if destination.is_file():
return destination
lock = self._lock_for(destination.name)
@@ -120,9 +146,9 @@ class FollowCoverService:
raise FollowCoverUnavailable("视频封面生成失败") from exc
finally:
temporary.unlink(missing_ok=True)
- # URL 变化时留下旧帧没有价值;只清理同一条目的旧缓存。
+ # URL 变化时留下旧帧没有价值;只清理同一条目、同一个视频的旧缓存。
for stale in self.root.glob(f"{item.id}-*.jpg"):
- if stale != destination:
+ if stale != destination and _cache_slot(stale.name, item.id) == slot:
stale.unlink(missing_ok=True)
return destination
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.py
index 205fa0e1c..4bf99f3fe 100644
--- a/src/peach/routes_media.py
+++ b/src/peach/routes_media.py
@@ -891,15 +891,19 @@ def follow_stream(request: Request, id: int, media: int | None = None,
@router.api_route("/follow-cover", methods=["GET", "HEAD"])
-def follow_cover(request: Request, id: int, args: dict[str, str] = Depends(require_auth)):
- """Return a cached clear still for a follow video; keep its URL server-side."""
+def follow_cover(request: Request, id: int, media: int | None = None,
+ args: dict[str, str] = Depends(require_auth)):
+ """Return a cached clear still for a follow video; keep its URL server-side.
+
+ `media` 与 `/follow-stream` 同义,按原始媒体清单的序号点名帖子里的某个视频。
+ """
state = request.app.state
with state.database.read_connection() as connection:
item = FollowStore(lambda: connection).item(id)
if item is None:
return JSONResponse({"error": "no such follow item"}, status_code=404)
try:
- path = state.follow_cover_service.cover(item)
+ path = state.follow_cover_service.cover(item, media)
except FollowCoverUnavailable:
# 这里不 302 到 `item.thumb_url`:那等于把上游主机和地址交回浏览器,
# 而这个端点存在的全部理由就是不让它外露。FFmpeg 或网络的临时失败一律回
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index 61835a8a4..5309a2ca3 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -21,6 +21,7 @@ from pathlib import Path
from . import avatar_face, follow_assets, follow_providers
from .follow import FollowSourceError
from .follow_check import plan_check, run_check
+from .follow_covers import fanbox_video_indexes
from .web_settings import follow_initial_days
from .follow_discovery import (
MAX_SUGGESTIONS, PROFILE_ALIAS_SKIP_SERVICES, archive_suggestions, discover,
@@ -685,6 +686,7 @@ def _media_projection(item) -> tuple[list[dict], list[dict]]:
hidden = frozenset(item.hidden_media or ())
visible, concealed = [], []
skip_poll_chart = _skips_poll_chart(item)
+ covered = fanbox_video_indexes(item) if item.provider == "fanbox" else []
for index, media in enumerate(_raw_media_items(item)):
if not isinstance(media, dict):
continue
@@ -696,13 +698,19 @@ def _media_projection(item) -> tuple[list[dict], list[dict]]:
if skip_poll_chart and index == 0 and kind == "image":
continue
thumb = str(media.get("thumb_url") or "")
+ thumb = thumb if thumb.startswith("https://") else None
+ if thumb is None and index in covered:
+ # fanbox 站内视频不带缩略图,画面由 /follow-cover 抽帧。第一个视频用卡面那条
+ # 地址,两处共用一次抽帧和同一份浏览器缓存。
+ thumb = (f"/follow-cover?id={item.id}" if index == covered[0]
+ else f"/follow-cover?id={item.id}&media={index}")
projected = {
"index": index,
"name": str(media.get("name") or f"{kind} {index + 1}"),
"media_kind": kind,
"media_type": _video_media_type(media.get("name") or media.get("url"))
if kind == "video" else None,
- "thumb_url": thumb if thumb.startswith("https://") else None,
+ "thumb_url": thumb,
"size": media.get("size"),
# 固有宽高给瀑布流预留比例用:fanbox 的 imageMap 带原尺寸,没有的
# 来源保持 None,前端按无尺寸那套占位。
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index e26b8aad3..bfb5b7fec 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -1825,7 +1825,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
def __init__(self):
self.fail = False
- def cover(self, _item):
+ def cover(self, _item, _media=None):
if self.fail:
from peach.follow_covers import FollowCoverUnavailable
raise FollowCoverUnavailable("test")
diff --git a/tests/test_follow_covers.py b/tests/test_follow_covers.py
index 223445404..ccdcdf1fb 100644
--- a/tests/test_follow_covers.py
+++ b/tests/test_follow_covers.py
@@ -130,6 +130,40 @@ class FollowCoverServiceTests(unittest.TestCase):
resolver.resolve.assert_called_with(item, 1)
self.assertEqual(ffmpeg.call_count, 1)
+ def test_each_fanbox_video_in_a_post_gets_its_own_cached_still(self):
+ """多媒体清单里每个视频各要一格画面;第一个视频点不点名都落在卡面那份缓存上。"""
+ item = self._item("fanbox")
+ item.metadata = {"media_items": [
+ {"media_kind": "video", "resource_provider": "fanbox"},
+ {"media_kind": "image", "resource_provider": "fanbox"},
+ {"media_kind": "video", "resource_provider": "fanbox"},
+ ]}
+ resolver = mock.Mock()
+ resolver.resolve.side_effect = lambda _item, index: ResolvedFollowMedia(
+ f"https://downloads.fanbox.cc/files/video-{index}.mp4", item.url)
+ service = FollowCoverService(_FFmpeg(), resolver, self.root)
+
+ def run(command, **kwargs):
+ Path(command[-1]).write_bytes(b"jpeg")
+ return subprocess.CompletedProcess(command, 0, b"", b"")
+
+ with mock.patch("peach.follow_covers.subprocess.run", side_effect=run) as ffmpeg:
+ card = service.cover(item)
+ self.assertEqual(service.cover(item, 0), card)
+ second = service.cover(item, 2)
+ # 生成第二个视频的画面不能把第一个视频那份当旧帧清掉,反之亦然。
+ self.assertEqual(service.cover(item), card)
+ self.assertNotEqual(second, card)
+ self.assertTrue(card.is_file() and second.is_file())
+ self.assertEqual(ffmpeg.call_count, 2)
+ for media in (1, 5):
+ with self.subTest(media=media), self.assertRaises(FollowCoverUnavailable):
+ service.cover(item, media)
+
+ def test_only_fanbox_posts_accept_a_media_index(self):
+ with self.assertRaises(FollowCoverUnavailable):
+ self.service.cover(self._item(), 0)
+
def test_only_supported_videos_enter_the_generator(self):
for provider, kind in (("rule34xxx", "video"),
("rule34paheal", "image")):
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index fe6a7a526..ea8fe9152 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -715,6 +715,33 @@ class FollowContractTests(unittest.TestCase):
self.assertEqual(items[key]["thumb_url"], f"/follow-cover?id={items[key]['id']}")
self.assertEqual(items["3"]["thumb_url"], image)
+ def test_fanbox_videos_in_the_media_list_show_a_frame_not_nothing(self):
+ """fanbox 站内视频不带缩略图,清单那一格给抽帧地址,不留空让页面退回站点图标。"""
+ cover = "https://pixiv.pximg.net/c/1200x630_90_a2_g5/fanbox/public/images/post/1/cover/a.jpeg"
+ self._seed(candidates=(FollowCandidate(
+ provider="fanbox", external_id="1", title="Clip", thumb_url=cover,
+ url="https://creator.fanbox.cc/posts/1",
+ extra={"media_items": [
+ {"id": "v1", "name": "first", "media_kind": "video", "resource_provider": "fanbox",
+ "url": "https://downloads.fanbox.cc/files/post/1/v1.mp4", "thumb_url": None},
+ {"id": "cover", "name": "封面", "media_kind": "image", "resource_provider": "fanbox",
+ "url": cover, "thumb_url": cover},
+ {"id": "v2", "name": "second", "media_kind": "video", "resource_provider": "fanbox",
+ "url": "https://downloads.fanbox.cc/files/post/1/v2.mp4", "thumb_url": None},
+ {"id": "g", "name": "elsewhere", "media_kind": "video", "resource_provider": "gofile",
+ "url": "https://gofile.io/d/abc", "thumb_url": None},
+ ]},
+ ),), provider="fanbox", ref="creator")
+ item = self._get()["groups"][0]["primary"]
+ thumbs = {media["name"]: media["thumb_url"] for media in item["media_items"]}
+ self.assertEqual(thumbs, {
+ "first": f"/follow-cover?id={item['id']}",
+ "封面": cover,
+ "second": f"/follow-cover?id={item['id']}&media=2",
+ # 抽帧只对 fanbox 站内视频成立;别处托管的视频没有画面就留空,由页面给中性占位。
+ "elsewhere": None,
+ })
+
def test_fanbox_card_thumb_prefers_the_author_cover(self):
chart = "https://downloads.fanbox.cc/images/post/1/w/1200/chart.jpeg"
art = "https://downloads.fanbox.cc/images/post/1/w/1200/art.jpeg"
diff --git a/web/app.js b/web/app.js
index 47bca8740..bbbbe3770 100644
--- a/web/app.js
+++ b/web/app.js
@@ -6087,6 +6087,12 @@ function followCollectionCopy(group,item,mark=''){
return {label,title:group.is_release&&item.author?`${item.author}:${body}`:body};
}
+/* 队列里没有画面的那一格放中性图形,不放站点图标:格子里的图一律按画面铺满,
+ 48px 的 favicon 会被拉成整格,看上去就像这条视频的缩略图。 */
+function followQueueNoThumb(kind){
+ return `<span class="fnothumb">${icon(kind==='image'?'image-off':'play')}</span>`;
+}
+
function followQueueHtml(group,itemId){
const groupedOwner=followGroupedMediaOwner(group);
if(groupedOwner)return followEmbeddedQueueHtml(groupedOwner,null);
@@ -6096,7 +6102,7 @@ function followQueueHtml(group,itemId){
const copy=followCollectionCopy(group,item,group.duplicates.includes(item)?item.provider_label:'');
const thumb=item.thumb_url
?`<img src="${esc(item.thumb_url)}" alt="" loading="lazy" referrerpolicy="no-referrer" data-drop="self">`
- :`<span class="fnothumb">${sourceIcon(item.provider)}</span>`;
+ :followQueueNoThumb('video');
return `<div class="mixrow"><button class="mixitem ${item.id===itemId?'current':''}" data-follow-queue-item="${item.id}" aria-current="${item.id===itemId?'true':'false'}">
<span class="mixitempic">${thumb}${realDuration(item.duration)?`<i class="dur mono">${fmtDur(item.duration)}</i>`:''}</span>
<span class="mixitemtext"><b data-truncate-end>${esc(copy.title)}</b><span data-truncate-end><i class="fvkind ${esc(item.variant_kind||'')}">${esc(copy.label)}</i>${followWhen(item)}</span></span></button></div>`;
@@ -6115,7 +6121,7 @@ function followEmbeddedQueueHtml(item,mediaIndex){
const rows=groups.map(group=>`${group.label?`<h3 class="mixgrouplabel">${esc(group.label)} <span>${group.items.length}</span></h3>`:''}${group.items.map(media=>{
const thumb=media.thumb_url
?`<img src="${esc(media.thumb_url)}" alt="" loading="lazy" referrerpolicy="no-referrer" data-drop="self">`
- :`<span class="fnothumb">${sourceIcon(media.resource_provider||item.provider)}</span>`;
+ :followQueueNoThumb(media.media_kind);
return `<div class="mixrow"><button class="mixitem ${media.index===mediaIndex?'current':''}" data-follow-media-owner="${item.id}" data-follow-media-item="${media.index}" data-media-kind="${media.media_kind}" aria-current="${media.index===mediaIndex?'true':'false'}">
<span class="mixitempic">${thumb}</span><span class="mixitemtext"><b data-middle-truncate>${esc(javDisplayName(media))}</b><span data-truncate-end>${media.media_kind==='image'?'图片':'视频'}</span></span></button></div>`;
}).join('')}`).join('');
diff --git a/web/css/21-online.css b/web/css/21-online.css
index e15542592..bc9602513 100644
--- a/web/css/21-online.css
+++ b/web/css/21-online.css
@@ -93,7 +93,7 @@
悬停得按标签自己那个类型色加深,不能回到中性的 `--hover`。 */
.followdetailtags .tg:hover{border-color:color-mix(in srgb,var(--r34-tag) 68%,transparent);
background:color-mix(in srgb,var(--r34-tag) 18%,transparent);color:var(--ink)}
-.followqueue .mixitempic>.fnothumb{position:static;width:100%;height:100%}
+.followqueue .mixitempic>.fnothumb{position:static;width:100%;height:100%}.followqueue .fnothumb svg{width:22px;height:22px;stroke:currentColor;fill:none;stroke-width:2}
.fnote.followmediaissue{margin:18px 0 8px;color:var(--drop)}.followresources{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 16px}.followresources a{align-items:center;gap:2px;height:34px;padding:0 11px;border:1px solid var(--border-15);border-radius:var(--control-radius);color:var(--ink-2);text-decoration:none}.followresources a:hover{background:var(--hover);color:var(--ink);text-decoration:none}.followresources svg{width:15px;height:15px;stroke:currentColor;fill:none}.followdetailactions{margin-top:2px}
/* 标签沉到侧栏最后:来源站的标签动辄几十个,夹在正文和操作之间就得先滚过整片
标签云才够得着「已看/忽略」。 */