Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(web): 对齐库外 JAV 身份与标签投影并提供预览入口

longmeidao7e65728fb2b8
diff --git a/docs/REUSE.md b/docs/REUSE.md
index b1f5aa5bb..b6ef1ffd8 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -175,6 +175,7 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/
- 页面、框体、操作条与选中项共用一套灰阶,操作条用 `--overlay-5`。
- javdb 属有码与素人链的社区档,候选保留 community 来源性质,不自动写真相字段。
- [JavDB Web UI 实证](reference-snapshots/javdb-web-ui-poc.md):库外作品详情复用舞台、人物身份、想要、`WantMagnets` 与云下载组件;`javdb_public.PublicAPI` 复用 `HttpxTransport`(httpx 0.28.1,BSD-3-Clause)、`HostLimiter`、Pillow 12.3.0 与标准库 MD5/XOR,独立映射公开协议。匿名详情、两页评论、6 条样本资源、封面与预览图像素已取得;全站完整性和不限流未证明。请求串行、3 秒间隔、6 小时有界缓存,评论最多 8 页,失败保留资料并冷却;只读 `peek_movie` 可用于发现匹配。未新增依赖或写入 ledger。
+- 库外 JAV 身份引用复用 `entity_ref` 的本地头像与取景、厂牌 `has_logo` / `logo_version`;来源演员头像按作品演员 ID 取回并由同一 Pillow 路径解码,未知演员不绑定其他实体。标签投影复用 `genre_decision`、`genre_taxonomy.resolve_genre` 与 `tag_cat`,`tag_refs` 保留来源原词。样本 `MIDA-849` 的两张来源演员头像完整解码成功;HLS 预览清单 GET 200,密钥与媒体 HEAD 200,三者均允许匿名跨域访问,未下载视频分片或验证完整播放。预览仅下发已验证 HTTPS 主机与路径,播放复用既有 Video.js;无需新增代理或依赖。外部候选与版本依据沿用上条只读实证,Peach 保留身份、来源和请求预算策略。
- 候选 `ANDonekey/javapi` revision `9a2a245a659a4008ee75bc148b0af9c7126e7a71` 未归档、最后推送为 2026-05-11,使用 Go 和部署服务,GitHub 未标明许可证,不能作为 Python 依赖或复制其源码。仅以部署公开前端与匿名实测确定协议事实;原始取证脚本及脱敏概要保留在工作树 `build/javdb-public-api/`。`phoenixthrush/javdb-python`(MIT、Python ≥3.11、无运行依赖)解析的是 `javdatabase.com` HTML,站点与协议不匹配;现有 `sources.javdb` 同样只适用于 HTML。Peach 保留番号核对、权限失败、字段投影和缓存策略。
- 编码边界依据 [MDN 视频编码说明](https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Formats/Video_codecs) 与 [ffprobe 文档](https://ffmpeg.org/ffprobe.html),用当前 FFmpeg;Peach 只持有兼容格式判定与缓存策略。
- CloudDrive 引导用现有 `settings_file`、`platform.root_online`、`scan_location` 与 React 配置页,来源为 `local`、`115`、`pikpak`。挂载由用户安装的 CloudDrive 负责([官方帮助](https://www.clouddrive2.com/help.html):Windows 用盘符、macOS 用目录挂载点),Peach 不捆绑其二进制,挂载引导不依赖管理 API,路径处理用 `pathlib`、`os.scandir`、`tomllib`;表单、来源归属与扫描选择归 Peach。云下载经官方 proto 子集(`downloads_clouddrive.proto`,version 1.1.0)走 gRPC,令牌存 CredentialStore,不用非官方 SDK(ADR-0089)。
diff --git a/src/peach/genre_taxonomy.py b/src/peach/genre_taxonomy.py
index 4186b6333..0423ed0dd 100644
--- a/src/peach/genre_taxonomy.py
+++ b/src/peach/genre_taxonomy.py
@@ -412,7 +412,7 @@ CONTENT_GENRES: dict[str, str] = {
# JavDB 中文类别原词。复合的「肛門・肛交」不区分行为,只投到肛门这一层。
"肛門・肛交": "屁眼", "高跟鞋": "高跟", "絲襪": "丝袜", "過膝襪": "丝袜",
"絲襪、過膝襪": "丝袜", "白天出軌": "出轨", "出軌": "出轨",
- "潮吹": "潮吹", "大屁股": "巨臀", "蕩婦": "痴女", "第一人稱攝影": "主观视角",
+ "潮吹": "潮吹", "大屁股": "巨臀", "蕩婦": "痴女", "荡妇": "痴女", "第一人稱攝影": "主观视角",
"多P": "多人", "濫交": "多人", "護士": "护士", "紀錄片": "纪录片",
"角色扮演": "角色扮演", "角色扮演者": "角色扮演", "姐姐": "御姐",
"精選綜合": "合集", "流汗": "汗湿", "美容院": "按摩",
@@ -464,7 +464,7 @@ CONTENT_GENRES: dict[str, str] = {
"薄馬賽克": "薄码", "數位馬賽克": "有码",
# 用户确认的译名;JavDB 中英文类别用同一链接核对身份。
"妓女": "风俗女郎", "雙性人": "扶她", "Futanari": "扶她", "ふたなり": "扶她",
- "戀腿癖": "恋腿", "Leg Fetish": "恋腿", "戀乳癖": "恋乳", "Busty Fetish": "恋乳",
+ "戀腿癖": "恋腿", "恋腿癖": "恋腿", "Leg Fetish": "恋腿", "戀乳癖": "恋乳", "Busty Fetish": "恋乳",
"Female Investigator": "女搜查官",
"蠻橫嬌羞": "傲娇", "Tsundere": "傲娇", "ツンデレ": "傲娇",
"瘦小身型": "娇小", "子宮頸": "宫颈", "Cervix": "宫颈",
diff --git a/src/peach/javdb_public.py b/src/peach/javdb_public.py
index fc659fc6a..09cfc3fac 100644
--- a/src/peach/javdb_public.py
+++ b/src/peach/javdb_public.py
@@ -22,6 +22,30 @@ PAGE_SIZE = 10
MAX_REVIEW_PAGES = 8
+def public_image_url(value: object) -> bool:
+ """公开图片仅取已验证来源主机的 HTTPS 地址。"""
+ try:
+ parts = urlsplit(str(value or ""))
+ return (parts.scheme == "https" and parts.hostname == "tp.spfcas.com"
+ and not parts.username and not parts.password and parts.port in (None, 443))
+ except ValueError:
+ return False
+
+
+def preview_video_url(movie: dict) -> str:
+ """只投影来源作品的公开 HLS 预览入口,不替来源断言播放成功。"""
+ value = str(movie.get("preview_video_url") or "")
+ try:
+ parts = urlsplit(value)
+ allowed = (parts.scheme == "https" and parts.hostname == "jdforrepam.com"
+ and not parts.username and not parts.password and parts.port in (None, 443)
+ and not parts.fragment and not any(char.isspace() for char in value)
+ and re.fullmatch(r"/api/v1/movies/ttm3u8/preview/[A-Za-z0-9/_-]+\.m3u8", parts.path))
+ except ValueError:
+ return ""
+ return value if allowed else ""
+
+
class PublicSourceUnavailable(ValueError):
"""公开来源当前未取得。"""
@@ -159,6 +183,13 @@ class PublicAPI:
movie = self.movie(code)
if index == "cover":
url = movie.get("cover_url") or movie.get("thumb_url")
+ elif index.startswith("actor:"):
+ actor_id = index.removeprefix("actor:")
+ actor = next((actor for actor in movie.get("actors") or []
+ if isinstance(actor, dict) and str(actor.get("id")) == actor_id), None)
+ if not actor:
+ raise ValueError("出演者头像不存在")
+ url = actor.get("avatar_url")
else:
previews = movie.get("preview_images") or []
try:
@@ -167,8 +198,7 @@ class PublicAPI:
raise ValueError("预览图不存在") from None
if isinstance(url, dict):
url = url.get("large_url") or url.get("url")
- parts = urlsplit(str(url or ""))
- if parts.scheme != "https" or parts.hostname != "tp.spfcas.com" or parts.username or parts.password:
+ if not public_image_url(url):
raise PublicSourceUnavailable("图片未取得")
def fetch():
diff --git a/src/peach/web_jav_detail.py b/src/peach/web_jav_detail.py
index ed1b1a74f..099a38133 100644
--- a/src/peach/web_jav_detail.py
+++ b/src/peach/web_jav_detail.py
@@ -4,8 +4,11 @@ from __future__ import annotations
import re
from . import entities, wants, web_catalog
-from .catalog_rules import normalise_code_key
-from .javdb_public import MAX_REVIEW_PAGES, PAGE_SIZE, PUBLIC_API, PublicSourceUnavailable
+from .catalog_rules import normalise_code_key, tag_cat
+from .genre_decisions import load_genre_decisions
+from .genre_taxonomy import resolve_genre
+from .javdb_public import (MAX_REVIEW_PAGES, PAGE_SIZE, PUBLIC_API, PublicSourceUnavailable,
+ preview_video_url, public_image_url)
def detail_code(args) -> str:
@@ -44,19 +47,36 @@ def q_jav_detail(contract, args) -> dict:
payload = {"ok": True, "state": "ready" if source else "partial", "message": message,
"code": code, "title": item.get("title") or code,
"release_date": item.get("release_date"), "studio": item.get("studio")}
- payload.update(_source_fields(source or {}))
+ with contract.database.read_connection() as connection:
+ decisions = load_genre_decisions(connection)
+ payload.update(_source_fields(source or {}, decisions))
payload.update(_artwork_fields(contract, code, item, source or {}))
payload.update(_identity_fields(contract, code, item, source or {}))
return payload
def _identity_fields(contract, code, item, source):
- names = [actor.get("name") for actor in (source or {}).get("actors", []) if isinstance(actor, dict)]
+ actors = [actor for actor in source.get("actors", []) if isinstance(actor, dict) and actor.get("name")]
+ names = [actor.get("name") for actor in actors]
if not names:
names = re.split(r"[、,,]", str(item.get("performers") or ""))
with contract.database.read_connection() as connection:
- performer_refs = _refs(contract, connection, "performer", names)
+ performer_refs = []
+ for name in dict.fromkeys(names):
+ refs = _refs(contract, connection, "performer", [name])
+ if not refs:
+ continue
+ ref = refs[0]
+ actor = next((actor for actor in actors if actor.get("name") == name), {})
+ actor_id = str(actor.get("id") or "")
+ if re.fullmatch(r"[A-Za-z0-9]{1,64}", actor_id):
+ ref["source_actor_id"] = actor_id
+ ref["source_avatar"] = public_image_url(actor.get("avatar_url"))
+ performer_refs.append(ref)
studio_refs = _refs(contract, connection, "studio", [item.get("studio")])
+ for ref in studio_refs:
+ ref["has_logo"] = contract.has_logo(ref["name"])
+ ref["logo_version"] = contract.logo_version(ref["name"])
series_refs = _refs(contract, connection, "series", [(source or {}).get("series_name")])
wanted = code in wants.wanted_keys(connection, [code])
want = connection.execute("SELECT id FROM want_item WHERE code_key=? AND state<>'acquired' LIMIT 1", (code,)).fetchone()
@@ -70,15 +90,25 @@ def _artwork_fields(contract, code, item, source):
"cover_url": item.get("cover_url") or "",
"source_image": bool(source and (source.get("cover_url") or source.get("thumb_url"))),
"preview_count": min(len(source.get("preview_images") or []), 30),
+ "preview_video_url": preview_video_url(source),
"source_url": "https://javdb.com/v/" + str(source["id"]) if source else item.get("link") or ""}
-def _source_fields(source):
+def _source_fields(source, decisions):
tags = [str(tag.get("name") or "") if isinstance(tag, dict) else str(tag)
for tag in source.get("tags", [])]
+ tag_refs = []
+ for raw in tags:
+ label = resolve_genre(raw, decisions)
+ if label is None:
+ continue
+ label = label or raw
+ if label and all(ref["name"] != label for ref in tag_refs):
+ tag_refs.append({"name": label, "category": tag_cat(label), "source_name": raw})
return {"duration": source.get("duration"), "score": source.get("score"),
"summary": source.get("summary") or "", "director": source.get("director_name") or "",
"publisher": source.get("publisher_name") or "", "tags": [tag for tag in tags if tag],
+ "tag_refs": tag_refs,
"comments_count": int(source.get("comments_count") or 0)}
@@ -100,7 +130,8 @@ def q_jav_reviews(contract, args) -> dict:
def q_jav_image(contract, args) -> dict:
code = detail_code(args)
index = str(args.get("image") or "cover")
- if index != "cover" and (not index.isdigit() or not 0 <= int(index) < 30):
+ if (index != "cover" and not re.fullmatch(r"actor:[A-Za-z0-9]{1,64}", index)
+ and (not index.isdigit() or not 0 <= int(index) < 30)):
raise ValueError("预览图不存在")
try:
image = PUBLIC_API.image(code, index)
diff --git a/tests/test_genre_taxonomy.py b/tests/test_genre_taxonomy.py
index c737d3e19..f2b09b5b3 100644
--- a/tests/test_genre_taxonomy.py
+++ b/tests/test_genre_taxonomy.py
@@ -43,6 +43,9 @@ class GenreTaxonomyTests(unittest.TestCase):
def test_cat_ears_share_one_target_across_source_spellings(self):
self.assertEqual(map_genres(["猫耳", "貓耳女"]), (["猫耳"], []))
+ def test_public_javdb_simplified_categories_share_verified_targets(self):
+ self.assertEqual(map_genres(['蕩婦', '荡妇', '戀腿癖', '恋腿癖']), (['痴女', '恋腿'], []))
+
def test_anal_region_is_distinct_from_anal_intercourse(self):
for raw in ("Anal", "Anal Play", "アナル", "アナル責め", "アナルシリーズ", "肛門・肛交"):
with self.subTest(raw=raw):
diff --git a/tests/test_javdb_public.py b/tests/test_javdb_public.py
index 1c1edd167..c247e829a 100644
--- a/tests/test_javdb_public.py
+++ b/tests/test_javdb_public.py
@@ -9,7 +9,7 @@ from unittest.mock import patch
from PIL import Image
from peach.http import HttpResponse
-from peach.javdb_public import PublicAPI, PublicSourceUnavailable, decode_image
+from peach.javdb_public import PublicAPI, PublicSourceUnavailable, decode_image, preview_video_url
from peach.web_jav_detail import q_jav_detail, q_jav_image, q_jav_reviews, q_jav_resources
from peach.web_state import WebContract
from peach.web_router import dispatch_api_get
@@ -112,6 +112,34 @@ class PublicProtocolTests(unittest.TestCase):
with self.assertRaises(PublicSourceUnavailable):
decode_image(b'<html>unavailable</html>')
+ def test_preview_entry_accepts_only_the_public_hls_origin_and_path(self):
+ url = 'https://jdforrepam.com/api/v1/movies/ttm3u8/preview/123/0/720p.m3u8?token=sample'
+ self.assertEqual(preview_video_url({'preview_video_url': url}), url)
+ for value in (url.replace('https:', 'http:'), url.replace('jdforrepam.com', 'jdforrepam.com.evil.example'),
+ url.replace('https://', 'https://user:pass@'), url.replace('/preview/', '/private/'),
+ url.replace('.com/', '.com:8443/'), url + '#fragment', 'javascript:alert(1)',
+ 'https://jdforrepam.com:wrong/preview.m3u8'):
+ with self.subTest(url=value):
+ self.assertEqual(preview_video_url({'preview_video_url': value}), '')
+
+ def test_actor_images_are_bound_to_current_work_and_cached(self):
+ api = self.api()
+ original = io.BytesIO()
+ Image.new('RGB', (40, 60)).save(original, 'PNG')
+ movie = {'id': 'Exact', 'actors': [{'id': 'Person', 'avatar_url': 'https://tp.spfcas.com/avatars/person.jpg'}]}
+ with patch.object(api, 'movie', return_value=movie), \
+ patch.object(api, '_get', return_value=HttpResponse(200, {}, original.getvalue())) as get:
+ first = api.image('EXM-001', 'actor:Person')
+ self.assertTrue(first.startswith('data:image/jpeg;base64,'))
+ self.assertEqual(api.image('EXM-001', 'actor:Person'), first)
+ get.assert_called_once()
+ with self.assertRaises(ValueError):
+ api.image('EXM-001', 'actor:OtherPerson')
+ movie['actors'][0]['avatar_url'] = 'https://private.example/person.jpg'
+ with self.assertRaises(PublicSourceUnavailable):
+ api.image('EXM-001', 'actor:Person')
+ get.assert_called_once()
+
class DetailProjectionTests(unittest.TestCase):
def setUp(self):
@@ -170,6 +198,62 @@ class DetailProjectionTests(unittest.TestCase):
self.assertEqual(result['items'][0]['attributes'], ['中字', '高清'])
self.assertEqual(result['source_url'], 'https://javdb.com/v/Exact')
+ def test_source_avatars_and_studio_logos_preserve_each_identity(self):
+ movie = {'id': 'Exact', 'actors': [
+ {'id': 'Known', 'name': '甲', 'avatar_url': 'https://tp.spfcas.com/a.jpg'},
+ {'id': 'Known', 'name': '甲', 'avatar_url': 'https://tp.spfcas.com/a.jpg'},
+ {'id': 'Unknown', 'name': '乙', 'avatar_url': 'https://tp.spfcas.com/b.jpg'}], 'maker_name': '示例厂牌'}
+ with patch('peach.web_jav_detail.PUBLIC_API.movie', return_value=movie), \
+ patch.object(self.contract, 'has_logo', return_value=True), \
+ patch.object(self.contract, 'logo_version', return_value='logo-version'):
+ result = q_jav_detail(self.contract, {'code': 'EXM-001'})
+ self.assertEqual([(ref['name'], ref['source_actor_id']) for ref in result['performer_refs']],
+ [('甲', 'Known'), ('乙', 'Unknown')])
+ self.assertTrue(all(ref['source_avatar'] and ref['id'] is None for ref in result['performer_refs']))
+ self.assertEqual(result['studio_refs'][0]['has_logo'], True)
+ self.assertEqual(result['studio_refs'][0]['logo_version'], 'logo-version')
+ with patch('peach.web_jav_detail.PUBLIC_API.image', return_value='data:image/jpeg;base64,sample') as image:
+ self.assertTrue(q_jav_image(self.contract, {'code': 'EXM-001', 'image': 'actor:Unknown'})['ok'])
+ image.assert_called_once_with('EXM-001', 'actor:Unknown')
+
+ def test_local_performer_reference_keeps_canonical_identity_and_face_crop(self):
+ movie = {'id': 'Exact', 'actors': [
+ {'id': 'Known', 'name': '来源别名', 'avatar_url': 'https://tp.spfcas.com/a.jpg'},
+ {'id': 'Unknown', 'name': '未登记人物', 'avatar_url': 'https://tp.spfcas.com/b.jpg'}]}
+ def resolve(connection, kind, name):
+ return {'id': 7, 'canonical_name': '规范人物'} if kind == 'performer' and name == '来源别名' else None
+ with patch('peach.web_jav_detail.PUBLIC_API.movie', return_value=movie), \
+ patch('peach.web_jav_detail.entities.resolve_entity', side_effect=resolve), \
+ patch.object(self.contract, 'has_entity_image', return_value=True), \
+ patch.object(self.contract, 'entity_image_version', return_value='face-version'), \
+ patch.object(self.contract, 'avatar_focus', return_value={'axis': 'y', 'pct': 7}):
+ result = q_jav_detail(self.contract, {'code': 'EXM-001'})
+ first, second = result['performer_refs']
+ self.assertEqual((first['id'], first['name'], first['source_actor_id']), (7, '规范人物', 'Known'))
+ self.assertEqual(first['avatar_focus'], {'axis': 'y', 'pct': 7})
+ self.assertEqual(first['image_version'], 'face-version')
+ self.assertIsNone(second['id'])
+ self.assertFalse(second['has_image'])
+ self.assertEqual(second['source_actor_id'], 'Unknown')
+
+ def test_tag_projection_uses_taxonomy_and_user_decisions_without_losing_source(self):
+ movie = {'id': 'Exact', 'tags': [{'name': name} for name in
+ ('荡妇', '戀腿癖', '恋腿癖', '中出', '足交', 'Creampie', '4小時以上作品', '未知类别')]}
+ with patch('peach.web_jav_detail.PUBLIC_API.movie', return_value=movie):
+ result = q_jav_detail(self.contract, {'code': 'EXM-001'})
+ self.assertEqual(result['tag_refs'], [
+ {'name': '痴女', 'category': 'role', 'source_name': '荡妇'},
+ {'name': '恋腿', 'category': 'story', 'source_name': '戀腿癖'},
+ {'name': '中出内射', 'category': 'position', 'source_name': '中出'},
+ {'name': '足交', 'category': 'position', 'source_name': '足交'},
+ {'name': '未知类别', 'category': 'general', 'source_name': '未知类别'}])
+ self.assertEqual(result['tags'], [tag['name'] for tag in movie['tags']])
+ with patch('peach.web_jav_detail.PUBLIC_API.movie', return_value=movie), \
+ patch('peach.web_jav_detail.load_genre_decisions', return_value={'荡妇': None, '未知类别': '护士'}):
+ result = q_jav_detail(self.contract, {'code': 'EXM-001'})
+ self.assertNotIn('痴女', [ref['name'] for ref in result['tag_refs']])
+ self.assertEqual(result['tag_refs'][-1], {'name': '护士', 'category': 'role', 'source_name': '未知类别'})
+
def test_resource_source_failure_is_explicit(self):
with patch('peach.web_jav_detail.PUBLIC_API.movie', side_effect=PublicSourceUnavailable('资料未取得')):
result = q_jav_resources(self.contract, {'code': 'EXM-001'})