Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(follow): 卡片不再堆通用标签;生成物缓存一天改一个月

longmeidao42a936516c8f
diff --git a/src/peach/api.py b/src/peach/api.py
index acb6683f1..30463c83b 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -128,6 +128,13 @@ def _offline_response(exc: MediaOffline) -> JSONResponse:
return response
+#: 生成物与外部头像的缓存时长。这些端点按 asset / follow_item id 取图,内容换了
+#: id 也就换了(封面重生成会写新文件、头像换了会解析到新 URL),所以一天太短——
+#: 用户实测「基本不可能变动」。不加 immutable:那会让浏览器连刷新都不再回源,
+#: 万一真要换图就只能等过期。
+MEDIA_CACHE_SECONDS = 30 * 24 * 3600
+
+
def create_app(
settings: PeachSettings | None = None,
sync: LedgerSync | None = None,
@@ -584,7 +591,7 @@ def create_app(
# 片段现在留在缓存里而不是随响应删除:回放、重连和多设备都会重复请求同一段,
# 每次重跑 FFmpeg 等于让 CloudDrive 再预取一次块。
response = FileResponse(path, media_type="video/mp2t")
- response.headers["Cache-Control"] = "private, max-age=86400"
+ response.headers["Cache-Control"] = f"private, max-age={MEDIA_CACHE_SECONDS}"
response.headers["X-Peach-HLS-Segment"] = "1"
return response
@@ -599,16 +606,15 @@ def create_app(
def thumbnail(request: Request, id: int, args: dict[str, str] = Depends(require_auth)):
path = media_engine.file_for(id, thumbnail=True)
response = FileResponse(path)
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/photo", methods=["GET", "HEAD"])
def photo(request: Request, id: int, args: dict[str, str] = Depends(require_auth)):
- """图片资产原图。灯箱看大图用这条,瀑布流一律走 `/photo-thumb`。"""
"""图片资产原图。灯箱看大图用这条,瀑布流一律走 `/photo-thumb`。"""
path = media_engine.file_for(id)
response = FileResponse(path)
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/photo-thumb", methods=["GET", "HEAD"])
@@ -619,7 +625,7 @@ def create_app(
except PreviewUnavailable:
return JSONResponse({"error": "unavailable"}, status_code=404)
response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/poster", methods=["GET", "HEAD"])
@@ -629,23 +635,21 @@ def create_app(
except PreviewUnavailable:
return JSONResponse({"error": "unavailable"}, status_code=404)
response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/cover", methods=["GET", "HEAD"])
def cover(request: Request, code: str = "", args: dict[str, str] = Depends(require_auth)):
- """官方封套原图。存原图不裁:4:3 与 16:9 两种版式在界面上按比例取景。"""
"""官方封套原图。存原图不裁:4:3 与 16:9 两种版式在界面上按比例取景。"""
path = contract.cover_path(code)
if path is None:
return JSONResponse({"error": "no cover"}, status_code=404)
response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/endcard-frame", methods=["GET", "HEAD"])
def endcard_frame(request: Request, id: int, name: str, args: dict[str, str] = Depends(require_auth)):
- """Serve only generated OCR evidence frames, never a client-provided path."""
"""Serve only generated OCR evidence frames, never a client-provided path."""
if (id <= 0 or not name.endswith(".png") or "/" in name or "\\" in name
or name.startswith(".")):
@@ -655,7 +659,7 @@ def create_app(
if path.parent != root or not path.is_file():
return JSONResponse({"error": "no frame"}, status_code=404)
response = FileResponse(path, media_type="image/png")
- response.headers["Cache-Control"] = "private, max-age=86400"
+ response.headers["Cache-Control"] = f"private, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/avatar", methods=["GET", "HEAD"])
@@ -665,24 +669,22 @@ def create_app(
except PreviewUnavailable:
return JSONResponse({"error": "unavailable"}, status_code=404)
response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/follow-avatar", methods=["GET", "HEAD"])
def follow_avatar(request: Request, service: str, id: str, args: dict[str, str] = Depends(require_auth)):
- """Resolve an official creator avatar, then let the image CDN serve it."""
"""Resolve an official creator avatar, then let the image CDN serve it."""
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"
+ response.headers["Cache-Control"] = f"private, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/follow-stream", methods=["GET", "HEAD"])
def follow_stream(request: Request, id: int, media: int | None = None, args: dict[str, str] = Depends(require_auth)):
- """Play a remote follow candidate through Peach without exposing its upstream URL."""
"""Play a remote follow candidate through Peach without exposing its upstream URL."""
with database.read_connection() as connection:
item = FollowStore(lambda: connection).item(id)
@@ -735,7 +737,6 @@ def create_app(
@app.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."""
"""Return a cached clear still for a follow video; keep its URL server-side."""
with database.read_connection() as connection:
item = FollowStore(lambda: connection).item(id)
@@ -750,7 +751,7 @@ def create_app(
return RedirectResponse(str(item.thumb_url), status_code=307)
return JSONResponse({"error": "follow cover unavailable"}, status_code=404)
response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.api_route("/logo", methods=["GET", "HEAD"])
@@ -807,7 +808,7 @@ def create_app(
except PreviewUnavailable:
return JSONResponse({"error": "unavailable"}, status_code=404)
response = FileResponse(path, media_type=content_type)
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
return response
@app.get("/api/providers")
@@ -816,7 +817,6 @@ def create_app(
@app.get("/api/sources")
def source_health(request: Request, args: dict[str, str] = Depends(require_auth)):
- """无副作用的来源可达性。前端据此把脱盘来源的筛选置灰。"""
"""无副作用的来源可达性。前端据此把脱盘来源的筛选置灰。"""
rows = _source_status()
return {
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 70b21d2d0..8dc0f2580 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -18,6 +18,7 @@ ROOT = Path(__file__).resolve().parents[1]
HAS_DEPS = all(importlib.util.find_spec(name) for name in ("fastapi", "httpx"))
if HAS_DEPS:
import httpx
+ from peach import api as api_module
from peach.api import create_app
from peach.config import PeachSettings
@@ -869,7 +870,8 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(denied.status_code, 401)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b"clear-jpeg")
- self.assertEqual(response.headers["cache-control"], "public, max-age=86400")
+ self.assertEqual(response.headers["cache-control"],
+ f"public, max-age={api_module.MEDIA_CACHE_SECONDS}")
cover.fail = True
fallback = await self.client.get(
"/follow-cover?id=7&t=secret", follow_redirects=False)
@@ -1004,7 +1006,8 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
(b"poster", b"avatar", b"logo", b"snapshot"))
self.assertEqual(logo.headers["content-type"], "image/png")
self.assertEqual(logo.headers["cache-control"], "public, no-cache")
- self.assertEqual(poster.headers["cache-control"], "public, max-age=86400")
+ self.assertEqual(poster.headers["cache-control"],
+ f"public, max-age={api_module.MEDIA_CACHE_SECONDS}")
async def test_endcard_frame_is_authenticated_and_confined_to_evidence_root(self):
denied = await self.client.get(
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 075b1279a..e5dc6202e 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -419,6 +419,37 @@ class FollowContractTests(unittest.TestCase):
self._seed()
self.assertEqual(len(self._get(limit="nope")["groups"]), 1)
+ def test_cards_drop_generic_tags_but_filters_keep_them(self):
+ """卡片只留有身份的标签,general 那类内容描述不上卡片。
+
+ footjob / standing sex / from behind 这种三个一排占满卡片底部,却几乎不用来
+ 找东西。筛选条里仍然保留——主动去筛和被动堆一排不是一回事。
+ """
+ page = (ROOT / "web" / "app.js").read_text(encoding="utf-8")
+ self.assertIn(
+ "const followCardTags=item=>(item.tags||[])"
+ ".filter(tag=>followTagType(item,tag)!=='general');", page)
+ self.assertIn("const tags=followCardTags(item).slice(0,3)", page,
+ "卡片必须走过滤后的标签")
+ self.assertIn("data-follow-tag=\"${esc(key)}\"", page,
+ "筛选条仍要能按标签筛,包括 general")
+
+ def test_generated_media_is_cached_for_a_month_not_a_day(self):
+ """按 id 取的生成物内容不会变,一天太短。
+
+ 换了图 id 也就换了:封面重生成写的是新文件、头像换了会解析到新 URL。
+ 不加 immutable——那会让浏览器连刷新都不回源。
+ """
+ from peach import api
+
+ self.assertEqual(api.MEDIA_CACHE_SECONDS, 30 * 24 * 3600)
+ source = (ROOT / "src" / "peach" / "api.py").read_text(encoding="utf-8")
+ self.assertNotIn('max-age=86400', source,
+ "媒体端点不该再写死一天")
+ self.assertNotIn('immutable"', source.replace(
+ '"public, max-age=31536000, immutable"', ''),
+ "只有 /vendor/ 那条可以 immutable")
+
def test_archive_thumbnails_use_the_img_subdomain(self):
"""归档站静态资源走 img. 子域,主域取不到。
diff --git a/web/app.js b/web/app.js
index 483173969..0fd1bc0ed 100644
--- a/web/app.js
+++ b/web/app.js
@@ -2293,6 +2293,11 @@ function followWhen(item){
}
const followTagType=(item,tag)=>item.tag_types&&item.tag_types[tag]||'general';
+/* 卡片上只留有身份的标签:作者、角色、作品、来源属性。
+ general 是内容描述(footjob、standing sex、from behind 这类),三个一排占满卡片
+ 底部,却几乎不用来找东西——按用户要求不在卡片上展示。筛选条里仍然保留:
+ 那里是主动去筛,和卡片被动堆一排不是一回事。 */
+const followCardTags=item=>(item.tags||[]).filter(tag=>followTagType(item,tag)!=='general');
const followTagChip=(item,tag,kind='span')=>`<${kind} class="tg r34-${
esc(followTagType(item,tag))}" data-follow-tag="${esc(tag)}">${esc(tagLabel(tag))}</${kind}>`;
@@ -2593,7 +2598,7 @@ function followCard(group,authorSources=[]){
:embedded.length&&embedded.some(media=>media.media_kind==='image')?'媒体':'视频';
const mixTarget=embedded.length>1?item.id:videos[0]?.id;
const badges=followBadges(group);
- const tags=(item.tags||[]).slice(0,3).map(tag=>followTagChip(item,tag)).join('');
+ const tags=followCardTags(item).slice(0,3).map(tag=>followTagChip(item,tag)).join('');
const open=`<button class="cardopenhit" data-follow-detail="${item.id}" aria-label="打开 ${esc(item.title)} 详情"></button>`;
return `<article class="card followitem${isMix?' collection':''}${imageView?' imagecard':''}" data-follow-item="${item.id}" data-status="${esc(item.status)}">
<div class="${isMix?'mixstack ':''}followvisual"><div class="pic">