Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(follow): 归档站多附件帖进详情轮播,宽高只补图片卡面

longmeidao7bba82ce2694
diff --git a/docs/REUSE.md b/docs/REUSE.md
index f3681e005..cc65ed7ae 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -208,7 +208,8 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP
- 厂牌标识由契约位 `has_logo` 决定出不出图:没装标识的厂牌一个 `<img>` 都不发,改用首字母底板,不靠 404 摘。
- 关注检查分两阶段:列表阶段落 partial 行,详情补全按 provider 额度只补新行和未补齐行。「补齐过」由连接器的 `ENRICHED_MARK` 声明、判据登记在 `follow_store._ENRICHED_PREDICATES`。
- 存量行重抓:连接器新学到一个字段(图片宽高、封面)后,旧行不会自己补上——常规检查只看第一页,补齐过的行也不再打详情页。做法固定为两步:把 `ENRICHED_MARK` 换成新字段落库后才有的键并登记判据,让旧行判为未补齐;再 `POST /api/follow/check` 发 `{"older":true,"backfill_all":true,"rewind":true,"background":true}`(可加 `"sources":[id,…]` 只走部分来源),从第 1 页逐页走到站点说没有更多,进度读 `GET /api/follow/check`。`backfill_all`、`rewind` 离开 `older` 会被拒收,不进界面;ledger 的回填游标只进不退。这是长跑任务,重启前按 `peach-batch-jobs` 先查。
-- 图片的固有宽高只问文件头:`follow_image_dims.probe_image_dims` 发一个 `Range: bytes=0-65535` 请求,`dims_from_header` 认 PNG/GIF/WebP(VP8、VP8L、VP8X)/JPEG(跳过 EXIF 到 SOF);判据 `positive_dims` 只有这一份,连接器、`backfill_follow_image_dims.py` 与界面回写(`/api/follow/image-dims`)落库前都经它归一,`FollowStore.set_image_dims` 只补空缺。条目级那对是卡面那张图的比例:图片条目是图本身,视频条目是它的缩略图或封面帧;原文件主机拦脚本(pawchive 的 `file.` 子域挂 ddos-guard)时仍按缩略图量,详情里原图取不到也退回缩略图显示。
+- 图片的固有宽高只问文件头:`follow_image_dims.probe_image_dims` 发一个 `Range: bytes=0-65535` 请求,`dims_from_header` 认 PNG/GIF/WebP(VP8、VP8L、VP8X)/JPEG(跳过 EXIF 到 SOF);判据 `positive_dims` 只有这一份,连接器、`backfill_follow_image_dims.py` 与界面回写(`/api/follow/image-dims`)落库前都经它归一,`FollowStore.set_image_dims` 只补空缺。只有图片视图摆成瀑布流,宽高只为图片卡面预留比例,回填脚本每个条目只问卡面那一张;原文件主机拦脚本(pawchive 的 `file.` 子域挂 ddos-guard)时按缩略图量,详情与灯箱里原图取不到也退回缩略图显示。
+- 归档站(kemono、coomer、pawchive)的帖子有两张以上图或视频时,`KemonoConnector._media_items` 把它们列进 `media_items`(交付文件排第一、按路径去重),详情轮播与 `/follow-stream?media=N` 按条目自己站点的主机白名单取;存量行按上一条的 `rewind` 重抓补上。
- `/api/related` 用 Tag IDF 加 MMR 排序并缓存;搜索使用 FTS5 trigram,短查询回退 LIKE 并覆盖规范名、别名和检索词,搜索历史在 reader 写入被拒时降级到页面内存。
- 复核页覆盖元数据、创作者标签、Logo、头像、身份、番号目录、FC2 证据和媒体失败;抓取与 AI 结果仍是候选,批准后才写真相字段,元数据候选保留 MetaTube 目录证据且不下载 URL。
- 女优与创作者资料页的头像圆框角上有换头像入口:候选来自图库里同名的其他图和这个人取过的每一张图,另外两条路是本机文件与一个 https 地址。每一张取到的图都按内容哈希进候选缓存,被顶下来的那张留在里面,换回去不重新下载。页面只回递服务端自己列出来的 `ref`,图片地址由服务端按索引拼;手填地址是唯一的例外,它过 `http.public_https_url` 那道公网判据。
diff --git a/scripts/backfill_follow_image_dims.py b/scripts/backfill_follow_image_dims.py
index 919e5fb70..61d19ec41 100644
--- a/scripts/backfill_follow_image_dims.py
+++ b/scripts/backfill_follow_image_dims.py
@@ -1,11 +1,10 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
-r"""给已入库的关注卡面图补上固有宽高。
+r"""给已入库的关注图片补上固有宽高。
图片墙靠 `<img width height>` 在图落地前占好比例;没有这两个数的卡片按 1:1
-占位,图一到就整墙重排。条目级那对是卡面那张图的:图片条目是图本身,视频条目是
-它的缩略图——视频原文件量不出宽高,卡面缩略图的比例才是排版要的。尺寸只有 fanbox
-一家一直在记(imageMap 自带),其余来源的存量行都是空的。这一趟分两路补:
+占位,图一到就整墙重排。只有图片视图摆成瀑布流,所以只补图片卡面那一张。尺寸只有
+fanbox 一家一直在记(imageMap 自带),其余来源的存量行都是空的。这一趟分两路补:
- **归档**:rule34.xxx 的 dapi 响应本来就带 `width`/`height`,每次检查更新的
原始响应都归档在 `sources/follow/rule34xxx/` 下。不用再发一个请求,把归档里
@@ -47,9 +46,9 @@ from peach.review_csv import write_rows
from peach.scripting import (
BACKUP_REQUIRED, HostLimiter, add_ledger_write_args, open_for_write, open_readonly,
)
-# 「这条是不是图片」与「卡面挂的是哪张图」都与界面同一判据:卡片按卡面那张图预留
+# 「这条是不是图片」与「卡面是清单里哪一张」都与界面同一判据:卡片按卡面那张图预留
# 比例,这里就按同一张去问尺寸。
-from peach.web_follow import _media_kind as media_kind_of, _thumb_url as card_thumb_of
+from peach.web_follow import _media_items as visible_media_of, _media_kind as media_kind_of
FIELDS = ("item_id", "provider", "external_id", "media", "mode", "result",
"width", "height", "note")
@@ -106,12 +105,12 @@ def archived_dims(root: Path) -> dict[str, tuple[int, int]]:
def pending_targets(items: tuple[FollowItemRow, ...],
providers: set[str]) -> list[tuple[FollowItemRow, int | None, dict | None]]:
- """待补的(条目,媒体序号,媒体)。序号 None 是条目级那张卡面图。
+ """待补的(条目,媒体序号,媒体)。序号 None 是条目级那张直链图。
- 有媒体清单的条目按清单里每张缺尺寸的图各出一条;F95 的附件清单是读时合成的,
- 不在 metadata 里,尺寸没有地方落,跳过。没有清单的条目:图片条目问图本身;
- 视频等条目只在卡面挂着一张公开缩略图时问它——`/follow-cover` 这类站内抽帧的
- 封面没有可问的外部地址,由界面加载后回写。
+ 瀑布流只按卡面那张占位,一个条目最多出一条:有媒体清单的条目问可见清单里的第一张
+ 图(界面卡面取的就是它,隐藏的不算),其余几张只在详情里翻,不需要比例;F95 的
+ 附件清单是读时合成的,不在 metadata 里,尺寸没有地方落,跳过。没有清单的条目
+ 只问图片,视频不进图片墙。
"""
targets: list[tuple[FollowItemRow, int | None, dict | None]] = []
for item in items:
@@ -119,18 +118,17 @@ def pending_targets(items: tuple[FollowItemRow, ...],
continue
media_items = item.metadata.get("media_items")
if isinstance(media_items, list) and media_items:
- for index, media in enumerate(media_items):
- if not isinstance(media, dict) or media.get("media_kind") != "image":
- continue
- if positive_dims(media.get("width"), media.get("height")) is None:
- targets.append((item, index, media))
+ index = next((media["index"] for media in visible_media_of(item)
+ if media["media_kind"] == "image"), None)
+ if index is not None and positive_dims(
+ media_items[index].get("width"), media_items[index].get("height")) is None:
+ targets.append((item, index, media_items[index]))
continue
if item.provider == "f95zone" and f95_attachment_media_items(item.metadata):
continue
- if positive_dims(item.metadata.get("width"), item.metadata.get("height")) is not None:
+ if media_kind_of(item) != "image":
continue
- if (media_kind_of(item) == "image"
- or str(card_thumb_of(item) or "").startswith("https://")):
+ if positive_dims(item.metadata.get("width"), item.metadata.get("height")) is None:
targets.append((item, None, None))
return targets
@@ -146,12 +144,6 @@ def probe_attempts(resolver: FollowMediaResolver, item: FollowItemRow, index: in
"""
attempts: list[tuple[str, dict, str]] = []
notes: list[str] = []
- if media is None and media_kind_of(item) != "image":
- # 视频的原文件不是图,文件头量不出宽高;只问卡面那张缩略图。
- thumb = str(card_thumb_of(item) or "")
- if thumb.startswith("https://"):
- attempts.append((thumb, {}, "缩略图"))
- return attempts, notes
thumb = str((media or {}).get("thumb_url") or "") if media is not None \
else str(display_thumb_url(item) or "")
if thumb.startswith("https://"):
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.py
index e92ff725f..ad4fa635f 100644
--- a/src/peach/follow_sources.py
+++ b/src/peach/follow_sources.py
@@ -967,9 +967,42 @@ class KemonoConnector(_BaseConnector):
group_hint=f"{service}:{post_id}" if post_id else None,
extra={"service": service, "user": user,
"edited": post.get("edited"),
- "attachment_count": len(attachments)},
+ "attachment_count": len(attachments),
+ **({"media_items": items}
+ if (items := self._media_items([primary, *attachments], media)) else {})},
)
+ #: 媒体清单里认作视频的扩展名;图片沿用 `_THUMBABLE`。压缩包、文本不进清单,
+ #: 仍由 `media_url` 作资源交付。
+ _PLAYABLE = (".mp4", ".webm", ".mov", ".m4v")
+
+ def _media_items(self, entries: list[dict], media: str | None) -> list[dict]:
+ """一帖里能看的图和视频,给详情的多图轮播与媒体队列。
+
+ 交付文件排第一:条目级的媒体类型由清单首项决定,要与 `media_url` 是同一个;
+ 其余按帖子里的顺序。`file` 常在附件里再列一遍,按路径去重。只有一张的帖子
+ 不建清单,条目级字段已经说全了。视频没有缩略图(给了也是 404),`thumb_url`
+ 留空。
+ """
+ host = self.FILE_HOSTS.get(self.provider, self.host)
+ items: list[dict] = []
+ seen: set[str] = set()
+ for entry in sorted(entries, key=lambda entry: entry.get("path") != media):
+ path = str(entry.get("path") or "")
+ lowered = path.lower()
+ kind = ("image" if lowered.endswith(self._THUMBABLE)
+ else "video" if lowered.endswith(self._PLAYABLE) else None)
+ if kind is None or path in seen:
+ continue
+ seen.add(path)
+ items.append({"id": path,
+ "name": str(entry.get("name") or path.rsplit("/", 1)[-1]),
+ "url": f"https://{host}/data{path}",
+ "thumb_url": self._thumb_url(path),
+ "media_kind": kind,
+ "resource_provider": self.provider})
+ return items if len(items) > 1 else []
+
def archive_file_url(provider: str, url: str) -> str:
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index 8dd798308..e6239bc8f 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -713,13 +713,12 @@ class FollowStore:
def set_image_dims(self, item_id: int, width: int, height: int, *,
media_index: int | None = None) -> bool:
- """给一条(或它第 N 张媒体)补上卡面图的宽高,只补空缺。
+ """给一条(或它第 N 张媒体)补上图片宽高,只补空缺。
写了返回 True;条目不存在、那张媒体不在 metadata 的 `media_items` 里,或
- 已经有一对正尺寸时不动,返回 False。尺寸只用来定比例:条目级那对是卡面那张
- 图的,图片条目是图本身,视频条目是它的缩略图或封面帧。来自来源接口、文件头
- 探测或界面加载完的 naturalWidth 都算同一个字段;已有的不覆盖,因为三处给的
- 都是同一张图的比例,没有谁更权威。
+ 已经有一对正尺寸时不动,返回 False。尺寸只用来定比例,来自来源接口、
+ 文件头探测或界面加载完的 naturalWidth 都算同一个字段;已有的不覆盖,
+ 因为三处给的都是同一张图的比例,没有谁更权威。
"""
dims = positive_dims(width, height)
if dims is None:
diff --git a/src/peach/follow_stream.py b/src/peach/follow_stream.py
index 551905873..eb0c657eb 100644
--- a/src/peach/follow_stream.py
+++ b/src/peach/follow_stream.py
@@ -192,6 +192,15 @@ class FollowMediaResolver:
return ResolvedFollowMedia(
url, item.url, {"Cookie": cookie} if cookie else None,
allowed_hosts=("attachments.f95zone.to",))
+ if resource_provider and resource_provider == item.provider \
+ and _PROVIDER_HOSTS.get(item.provider):
+ # 归档站(kemono、coomer、pawchive)帖子的附件清单:媒体就在条目自己的
+ # 站上,按该来源的主机白名单放行,与下面的直链分支同一口径。
+ if not _allowed(item.provider, url):
+ raise FollowMediaUnavailable("来源媒体地址不可用")
+ return ResolvedFollowMedia(
+ url, item.url, allowed_hosts=tuple(_PROVIDER_HOSTS[item.provider]),
+ public_hosts=item.provider in _PUBLIC_MEDIA_PROVIDERS)
raise FollowMediaUnavailable("媒体来源不受支持")
if item.metadata.get("media_needs_credential"):
raise FollowMediaUnavailable("媒体需要来源登录会话")
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index 670bfb366..c11e36ff5 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -897,9 +897,8 @@ def _item_payload(item, credential_providers: frozenset[str] = frozenset()) -> d
"media_error": str(item.metadata.get("media_error") or "") or None,
"has_media": bool(item.media_url) or bool(media_items),
"media_kind": media_kind,
- # 条目卡面那张图的固有宽高,与 media_items 里每张自带的那对同义:图片条目是
- # 图本身,视频条目是它的缩略图或封面帧。图片墙拿它在图落地前占好比例;没有的
- # 来源保持 None,界面加载完会回写。
+ # 条目级直链图片的固有宽高,与 media_items 里每张自带的那对同义:图片墙
+ # 拿它在图落地前占好比例。没有的来源保持 None,界面加载完会回写。
"width": _positive_dim(item.metadata.get("width")),
"height": _positive_dim(item.metadata.get("height")),
"media_type": _video_media_type(item.media_url)
@@ -1748,11 +1747,10 @@ IMAGE_DIMS_BATCH_LIMIT = 200
def w_follow_image_dims(contract, body) -> dict:
- """界面把加载完的卡面图固有宽高回写给还没有尺寸的条目。
+ """界面把加载完的图片固有宽高回写给还没有尺寸的条目。
连接器不给尺寸的来源(归档站、论坛附件)第一次只能按无尺寸占位;浏览器一旦
把图读出来就知道 naturalWidth/naturalHeight,回写之后下一次渲染就能预留比例。
- 视频条目回写的是它卡面缩略图或封面帧的尺寸:瀑布流要的就是卡面的比例。
只补空缺,已有尺寸的条目一律不动;条目不存在、媒体序号不在清单里也只是
不计数,不报错——卡片可能是上一轮渲染留下的。
"""
diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.py
index 16ddc652f..37f612ed0 100644
--- a/tests/test_follow_sources.py
+++ b/tests/test_follow_sources.py
@@ -712,6 +712,41 @@ class KemonoConnectorTests(unittest.TestCase):
self.assertEqual(candidate.thumb_url,
"https://img.kemono.cr/thumbnail/data/cover/release.webp")
+ def test_archive_posts_with_several_media_list_them_for_the_detail_carousel(self):
+ """两张以上图或视频的帖子把它们列进媒体清单,详情里才翻得到第二张。
+
+ 交付文件排第一(条目级媒体类型跟清单首项走),其余按帖子顺序;`file` 在附件里
+ 重复列出的按路径去重;文本、压缩包不进清单。只有一张的帖子不建清单。
+ """
+ posts = [
+ {"id": "multi", "title": "Pack", "published": "2026-08-27T00:00:00Z",
+ "file": {"name": "cover.gif", "path": "/a/cover.gif"},
+ "attachments": [{"name": "cover.gif", "path": "/a/cover.gif"},
+ {"name": "clip.mp4", "path": "/a/clip.mp4"},
+ {"name": "notes.txt", "path": "/a/notes.txt"},
+ {"name": "page2.jpg", "path": "/a/page2.jpg"}]},
+ {"id": "single", "title": "One", "published": "2026-08-26T00:00:00Z",
+ "file": {"name": "only.png", "path": "/b/only.png"},
+ "attachments": [{"name": "only.zip", "path": "/b/only.zip"}]},
+ ]
+ result = KemonoConnector("pawchive", transport=_transport(
+ body=json.dumps(posts).encode())).fetch("patreon/1")
+ multi, single = result.candidates
+ self.assertEqual(multi.media_url, "https://file.pawchive.pw/data/a/clip.mp4")
+ items = multi.extra["media_items"]
+ self.assertEqual([(media["id"], media["media_kind"]) for media in items],
+ [("/a/clip.mp4", "video"), ("/a/cover.gif", "image"),
+ ("/a/page2.jpg", "image")])
+ self.assertEqual(items[1], {
+ "id": "/a/cover.gif", "name": "cover.gif",
+ "url": "https://file.pawchive.pw/data/a/cover.gif",
+ "thumb_url": "https://img.pawchive.pw/thumbnail/data/a/cover.gif",
+ "media_kind": "image", "resource_provider": "pawchive"})
+ self.assertIsNone(items[0]["thumb_url"])
+ # 卡面封面与清单里第一张图是同一张,界面据此沿用条目级量过的比例。
+ self.assertEqual(multi.thumb_url, items[1]["thumb_url"])
+ self.assertNotIn("media_items", single.extra)
+
def test_no_thumbnail_is_offered_for_things_that_have_none(self):
# 视频和压缩包没有缩略图,给了也是 404——那会让卡片显示一张碎图,
# 比一个干净的占位更糟。
diff --git a/tests/test_follow_stream.py b/tests/test_follow_stream.py
index cfb1495e3..89e4a6dee 100644
--- a/tests/test_follow_stream.py
+++ b/tests/test_follow_stream.py
@@ -103,6 +103,25 @@ class FollowMediaResolverTests(unittest.TestCase):
target = FollowMediaResolver(lambda *_args: None).resolve(item, 1)
self.assertEqual(target.url, "https://downloads.fanbox.cc/two.jpg")
+ def test_archive_attachment_list_resolves_only_on_the_items_own_site(self):
+ """归档站帖子的附件清单按条目自己站点的主机白名单取,别的主机、别的来源一律拒收。"""
+ item = SimpleNamespace(
+ id=15, provider="pawchive", url="https://pawchive.pw/patreon/user/1/post/15",
+ media_url="https://file.pawchive.pw/data/a/clip.mp4", metadata={"media_items": [
+ {"url": "https://file.pawchive.pw/data/a/clip.mp4", "resource_provider": "pawchive"},
+ {"url": "https://file.pawchive.pw/data/a/page2.jpg", "resource_provider": "pawchive"},
+ {"url": "https://127.0.0.1/data/a/private.jpg", "resource_provider": "pawchive"},
+ {"url": "https://kemono.cr/data/a/page3.jpg", "resource_provider": "kemono"},
+ ]},
+ )
+ resolver = FollowMediaResolver(lambda *_args: None)
+ target = resolver.resolve(item, 1)
+ self.assertEqual(target.url, "https://file.pawchive.pw/data/a/page2.jpg")
+ self.assertEqual(target.referer, item.url)
+ for index in (2, 3):
+ with self.assertRaises(FollowMediaUnavailable):
+ resolver.resolve(item, index)
+
def test_legacy_f95_attachment_is_resolved_as_an_image(self):
item = SimpleNamespace(
id=13, provider="f95zone", url="https://f95zone.to/threads/1/post-13",
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 0cd75d5dc..5ef046eea 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -323,33 +323,35 @@ class OperationalScriptTests(unittest.TestCase):
url="https://rule34.xxx/index.php?id=11",
media_url="https://api-cdn.rule34.xxx/images/1/a.jpg",
thumb_url="https://api-cdn.rule34.xxx/samples/1/a.jpg"),
- # 卡面没有缩略图的视频无处可问:视频原文件量不出宽高。
+ # 视频不占图片墙,不问——带缩略图也一样。
FollowCandidate(provider="rule34xxx", external_id="12", title="v",
url="https://rule34.xxx/index.php?id=12",
- media_url="https://api-cdn-mp4.rule34.xxx/images/1/v.mp4"),
- # 有缩略图的视频按卡面比例补;dapi 给的视频宽高与同帧样图同比例,从归档取。
- FollowCandidate(provider="rule34xxx", external_id="13", title="w",
- url="https://rule34.xxx/index.php?id=13",
- media_url="https://api-cdn-mp4.rule34.xxx/images/1/w.mp4",
- thumb_url="https://api-cdn.rule34.xxx/samples/1/w.jpg"),
+ media_url="https://api-cdn-mp4.rule34.xxx/images/1/v.mp4",
+ thumb_url="https://api-cdn.rule34.xxx/samples/1/v.jpg"),
])
seed("pawchive", "user", [
FollowCandidate(provider="pawchive", external_id="21", title="b",
url="https://pawchive.pw/post/21",
media_url="https://file.pawchive.pw/data/ab/cd/abcd.png",
thumb_url="https://img.pawchive.pw/thumbnail/data/ab/cd/abcd.png"),
- # 视频条目只问卡面缩略图,不去碰 mp4。
- FollowCandidate(provider="pawchive", external_id="22", title="c",
- url="https://pawchive.pw/post/22",
- media_url="https://file.pawchive.pw/data/ef/gh/efgh.mp4",
- thumb_url="https://img.pawchive.pw/thumbnail/data/ef/gh/efgh.gif"),
+ # 多图帖只问卡面那一张,其余几张只在详情里翻。
+ FollowCandidate(provider="pawchive", external_id="23", title="d",
+ url="https://pawchive.pw/post/23",
+ media_url="https://file.pawchive.pw/data/ij/kl/one.png",
+ thumb_url="https://img.pawchive.pw/thumbnail/data/ij/kl/one.png",
+ extra={"media_items": [
+ {"id": f"/ij/kl/{name}.png", "media_kind": "image",
+ "url": f"https://file.pawchive.pw/data/ij/kl/{name}.png",
+ "thumb_url": f"https://img.pawchive.pw/thumbnail/data/ij/kl/{name}.png",
+ "resource_provider": "pawchive"}
+ for name in ("one", "two")]}),
])
connection.commit()
connection.close()
archive = root / "follow" / "rule34xxx" / "k"
archive.mkdir(parents=True)
(archive / "20260901T000000Z-abc.raw").write_bytes(json.dumps(
- [{"id": 11, "width": 1280, "height": 720}, {"id": 13, "width": 1920, "height": 1080},
+ [{"id": 11, "width": 1280, "height": 720}, {"id": 12, "width": 1920, "height": 1080},
{"id": 99, "width": 1, "height": 1}]
).encode())
(archive / "20260901T000000Z-abc.json").write_bytes(b"{}")
@@ -378,14 +380,14 @@ class OperationalScriptTests(unittest.TestCase):
"SELECT external_id, metadata_json FROM follow_item")}
self.assertEqual((dims["11"]["width"], dims["11"]["height"]), (1280, 720))
self.assertEqual((dims["21"]["width"], dims["21"]["height"]), (800, 600))
- self.assertEqual((dims["13"]["width"], dims["13"]["height"]), (1920, 1080))
- self.assertEqual((dims["22"]["width"], dims["22"]["height"]), (800, 600))
+ first, second = dims["23"]["media_items"]
+ self.assertEqual((first["width"], first["height"]), (800, 600))
+ self.assertNotIn("width", second)
self.assertNotIn("width", dims["12"])
with out.open(encoding="utf-8", newline="") as handle:
rows = list(csv.DictReader(handle))
self.assertEqual({(row["external_id"], row["mode"], row["result"]) for row in rows},
- {("11", "归档", "取得"), ("13", "归档", "取得"),
- ("21", "探测", "取得"), ("22", "探测", "取得")})
+ {("11", "归档", "取得"), ("21", "探测", "取得"), ("23", "探测", "取得")})
self.assertTrue((root / "backup.db").exists())
# 第二遍:全部已有尺寸,没有待补,也不再发请求。
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index c7bcdd2a4..447ff4601 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -4710,6 +4710,9 @@ class WebUiSourceTests(unittest.TestCase):
self.assertCode("if(fallback&&el.getAttribute('src')!==fallback){")
self.assertCode("el.src=fallback;if(thumbFallback)thumbFallback.hidden=false;return}")
self.assertPageContains("data-media-thumb-fallback hidden>原图没取回来,这里先显示缩略图")
+ # 灯箱里翻到的每一张同样退回它自己的缩略图。
+ self.assertCode("box.querySelectorAll('.photomain img').forEach((img,at)=>img.addEventListener('error',()=>{")
+ self.assertCode("if(thumb&&img.getAttribute('src')!==thumb)img.src=thumb},{once:true}));")
def test_follow_detail_gets_the_same_player_stats_overlay(self):
"""作品详情与关注详情共用同一段统计模板,关注详情里的在线视频同样有统计入口。"""
@@ -4725,16 +4728,15 @@ class WebUiSourceTests(unittest.TestCase):
def test_follow_image_cards_reserve_their_ratio_from_either_tier_and_learn_the_rest(self):
"""图片墙按卡片高度分列,图落地前就要知道比例,否则每张加载完整墙重排。
- 比例是卡面那张图的,有两层:卡面用媒体清单里那张(fanbox)就落在那张上,
- 其余落在条目上——视频条目也一样,量的是它的缩略图或封面帧。两层都没有的卡片
- 不硬猜,加载完把 natural 尺寸回写给它的主人,下一次渲染就有了。
+ 只有图片视图摆成瀑布流,视频卡片不占位也不回写。比例是卡面那张图的,有两层:
+ 卡面是媒体清单里那张就落在那张上;卡面就是条目自己的缩略图时落在条目上。两层都
+ 没有的卡片不硬猜,加载完把 natural 尺寸回写给它的主人,下一次渲染就有了。
"""
self.assertCode("const cardMedia=selectedMedia&&selectedMedia.thumb_url===thumbUrl?selectedMedia:null;")
- self.assertCode("const sized=dimsOwner.width>0&&dimsOwner.height>0?dimsOwner:null;")
+ self.assertCode("const itemOwnsCard=!cardMedia||thumbUrl===item.thumb_url;")
+ self.assertCode("const sized=imageView?[cardMedia,itemOwnsCard?item:null].find(owner=>owner?.width>0&&owner.height>0):null;")
self.assertCode('const dims=sized?` width="${sized.width}" height="${sized.height}"`:\'\';')
- self.assertCode('const learn=!sized&&thumbUrl?` data-learn-dims="${item.id}"${cardMedia?` data-learn-media="${cardMedia.index}"`:\'\'}`:\'\';')
- self.assertNotIn("item.media_kind==='image'&&item.width>0", self.page,
- "视频卡片的缩略图同样要按比例占位")
+ self.assertCode('const learn=imageView&&!sized&&thumbUrl?` data-learn-dims="${item.id}"${cardMedia?` data-learn-media="${cardMedia.index}"`:\'\'}`:\'\';')
self.assertPageContains("function wireImageDimsLearning(root)")
self.assertPageContains("wireImageDimsLearning(root);")
self.assertPageContains("root.querySelectorAll('img[data-learn-dims]')")
diff --git a/web/app.js b/web/app.js
index 3b18610a6..75334c543 100644
--- a/web/app.js
+++ b/web/app.js
@@ -5945,16 +5945,16 @@ function followCard(group,authorSources=[]){
const thumbUrl=selectedMedia?.thumb_url||item.thumb_url;
/* width/height 属性让浏览器在图片落地前就按固有比例占位:瀑布流按卡片高度
分列,没有这两个属性时未加载的图高度是零,每一张加载完都把整墙的列重新
- 平衡一遍,卡片就在列间跳。比例取卡面上这张图自己的:卡面用的是媒体清单里那张
- (fanbox)就落在那张媒体上,其余落在条目上——图片条目是图本身,视频条目是它的
- 缩略图或封面帧。来路有 rule34.xxx 的接口、回填脚本问过的文件头、上次加载后
- 回写的;原文件主机拦脚本时缩略图照样量得到。都没有就不硬猜,走无尺寸占位那套,
- 并在这张图加载完后把 natural 尺寸回写给它的主人。 */
+ 平衡一遍,卡片就在列间跳。只有图片视图摆成瀑布流,视频卡片不占位也不回写。
+ 比例取卡面上这张图自己的:卡面是媒体清单里那张就落在那张上;卡面就是条目自己的
+ 缩略图时落在条目上(归档站多附件帖的首图与条目封面是同一张,清单补上之前量过的
+ 仍然算数)。来路有来源接口、回填脚本问过的文件头、上次加载后回写的;都没有就
+ 不硬猜,走无尺寸占位那套,并在这张图加载完后把 natural 尺寸回写给它的主人。 */
const cardMedia=selectedMedia&&selectedMedia.thumb_url===thumbUrl?selectedMedia:null;
- const dimsOwner=cardMedia||item;
- const sized=dimsOwner.width>0&&dimsOwner.height>0?dimsOwner:null;
+ const itemOwnsCard=!cardMedia||thumbUrl===item.thumb_url;
+ const sized=imageView?[cardMedia,itemOwnsCard?item:null].find(owner=>owner?.width>0&&owner.height>0):null;
const dims=sized?` width="${sized.width}" height="${sized.height}"`:'';
- const learn=!sized&&thumbUrl?` data-learn-dims="${item.id}"${cardMedia?` data-learn-media="${cardMedia.index}"`:''}`:'';
+ const learn=imageView&&!sized&&thumbUrl?` data-learn-dims="${item.id}"${cardMedia?` data-learn-media="${cardMedia.index}"`:''}`:'';
const thumb=thumbUrl
? `<img${dims}${learn} src="${esc(thumbUrl)}" alt="" loading="lazy" referrerpolicy="no-referrer" data-drop="self">`
: `<span class="fnothumb">${sourceIcon(item.resource_provider||item.provider)}</span>`;
@@ -8655,6 +8655,11 @@ async function openPhotoLightbox(index,source=null){
const resize=new ResizeObserver(()=>{main.update();strip.update();zoomBar.resize()});
resize.observe(box);
activeLightbox={box,main,strip,resize,zoomBar,detail};
+ // 原图取不到时换上这张的缩略图:归档站的原文件主机会拦下代理(pawchive 的 file.
+ // 子域挂着 ddos-guard),缩略图由浏览器直接读公开主机。
+ box.querySelectorAll('.photomain img').forEach((img,at)=>img.addEventListener('error',()=>{
+ const thumb=items[at].thumb;
+ if(thumb&&img.getAttribute('src')!==thumb)img.src=thumb},{once:true}));
box.querySelector('.photoclose').onclick=closePhotoLightbox;
// 主画布铺满视口后,黑色留白属于 zoom 容器而不是最外层;两者都视为背景。
// 点图片、缩略图条、工具栏和翻页按钮仍不退出。