Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(avatar): 挑头像的封面底图带版本,框按旧封面量的拒收

longmeidao4efd8b89c298
diff --git a/frontend/src/react/avatar-picker/avatar-picker-page.tsx b/frontend/src/react/avatar-picker/avatar-picker-page.tsx
index c9600f495..2f524de1b 100644
--- a/frontend/src/react/avatar-picker/avatar-picker-page.tsx
+++ b/frontend/src/react/avatar-picker/avatar-picker-page.tsx
@@ -30,7 +30,7 @@ import { CropFrame } from '../crop/crop-frame';
import { queryClient } from '../query';
import { busyProps } from '../settings/use-action';
import {
- avatarChoicesKey, baseLabel, choiceDetail, choiceFrame, choiceImageUrl, cropNote,
+ avatarChoicesKey, baseLabel, baseVersion, choiceDetail, choiceFrame, choiceImageUrl, cropNote,
fetchAvatarChoices, fetchCodeCover, framesItself, indexNote, pickerNote, sendAvatarPick, sharedCast,
type AvatarChoice, type AvatarSubmission,
} from './avatar-picker';
@@ -145,7 +145,7 @@ function PickerBody({ kind, entityId, name, onPicked, close }: AvatarPickerProps
{cropping ? (
<CropStep kind={kind} entityId={entityId} choice={cropping} busy={submit.isPending}
back={() => setCropping(null)}
- confirm={(ref, crop) => { if (!submit.isPending) submit.mutate({ ref, crop }) }} />
+ confirm={(ref, crop, version) => { if (!submit.isPending) submit.mutate({ ref, crop, version }) }} />
) : (
<>
{/* 候选网格是这一屏唯一会滚的层:头部和底下那排操作再长也不动。上下各留 16px:
@@ -173,7 +173,8 @@ function PickerBody({ kind, entityId, name, onPicked, close }: AvatarPickerProps
else submit.mutate({ ref: choice.ref });
}}
className="relative flex cursor-pointer flex-col gap-1 overflow-hidden rounded-2lg border border-separator-border bg-background-secondary-default pb-1 text-center text-caption-1-regular text-text-secondary outline-none hover:border-border-button-hover hover:text-text-primary focus-visible:ring-2 focus-visible:ring-border-focus-ring aria-selected:border-border-focus-ring aria-selected:bg-background-tertiary-default aria-selected:text-text-primary aria-disabled:cursor-progress aria-disabled:opacity-60">
- <ChoiceImage src={choiceImageUrl(kind, entityId, choice.ref)} choice={choice} />
+ <ChoiceImage src={choiceImageUrl(kind, entityId, choice.ref, baseVersion(choice, choice.ref))}
+ choice={choice} />
<span className="truncate px-1">{choice.label}</span>
{choice.current
? <span className="absolute top-1 left-1"><Chip variant="caption" color="gray">在用</Chip></span>
@@ -262,13 +263,14 @@ function ChoiceImage({ src, choice }: { src: string; choice: AvatarChoice }) {
* 裁在哪由 CSS 说了算,人在这里框的那一块就不作数了。 */
function CropStep({ kind, entityId, choice, busy, back, confirm }: {
kind: string; entityId: number; choice: AvatarChoice; busy: boolean;
- back(): void; confirm(ref: string, crop: CropBox): void;
+ back(): void; confirm(ref: string, crop: CropBox, version: string): void;
}) {
const bases = choice.bases.length ? choice.bases : [choice.ref];
const [base, setBase] = useState(bases[0]);
const [size, setSize] = useState<CropSize | null>(null);
const [box, setBox] = useState<CropBox | null>(null);
- const src = choiceImageUrl(kind, entityId, base);
+ const version = baseVersion(choice, base);
+ const src = choiceImageUrl(kind, entityId, base, version);
const frame = useOverlayScrollbar<HTMLDivElement>();
/* 换底图就是换一张图,上一张的框一个数都不留:同一组坐标落在另一张图上是一块
错位的区域,而错位在屏幕上和「本来就框在这儿」看不出区别。 */
@@ -317,7 +319,7 @@ function CropStep({ kind, entityId, choice, busy, back, confirm }: {
<div className="flex flex-1 flex-wrap items-center justify-end gap-3">
<Button variant="secondary" onClick={back} {...busyProps(busy)}>回候选</Button>
<Button disabled={!box || !size} {...busyProps(busy)}
- onClick={() => { if (box && !busy) confirm(base, box) }}>用这一块</Button>
+ onClick={() => { if (box && !busy) confirm(base, box, version) }}>用这一块</Button>
</div>
</div>
</>
diff --git a/frontend/src/react/avatar-picker/avatar-picker.ts b/frontend/src/react/avatar-picker/avatar-picker.ts
index 7d692c616..cdd613c7e 100644
--- a/frontend/src/react/avatar-picker/avatar-picker.ts
+++ b/frontend/src/react/avatar-picker/avatar-picker.ts
@@ -32,6 +32,9 @@ export interface AvatarChoice {
/** 这部作品有几位演员;0 是不知道。多于一位时 `focus` 不围着封面上那张脸,
* 那多半是领衔的另一位。 */
cast: number;
+ /** 封面那张底图的版本。封面会原地替换,预览地址带上它才不显示旧图,交框时回递它,
+ * 服务端才认得出框是在哪一张上画的。别的底图不会原地变,是空串。 */
+ version: string;
}
export interface AvatarChoices {
@@ -50,8 +53,13 @@ export const avatarChoicesKey = (kind: string, id: number) => ['avatar-choices',
const query = (kind: string, id: number) => `?kind=${encodeURIComponent(kind)}&id=${id}`;
-export const choiceImageUrl = (kind: string, id: number, ref: string) =>
- `${AVATAR_CHOICE_IMAGE_URL}${query(kind, id)}&ref=${encodeURIComponent(ref)}`;
+export const choiceImageUrl = (kind: string, id: number, ref: string, version = '') =>
+ `${AVATAR_CHOICE_IMAGE_URL}${query(kind, id)}&ref=${encodeURIComponent(ref)}`
+ + (version ? `&v=${encodeURIComponent(version)}` : '');
+
+/** 底图 `ref` 的版本:只有封面那一张有,九宫格那几格是空串。 */
+export const baseVersion = (choice: AvatarChoice, ref: string): string =>
+ ref.startsWith('cover:') || ref.endsWith(':cover') ? choice.version : '';
export const fetchAvatarChoices = (kind: string, id: number, signal?: AbortSignal) =>
apiGet<AvatarChoices>(AVATAR_CHOICES_URL + query(kind, id), signal);
@@ -77,7 +85,7 @@ export interface AvatarCrop { x0: number; y0: number; x1: number; y1: number }
/** 四条路交上去的东西不同,落点是同一个端点。`crop` 是其中三条共用的可选工序。 */
export type AvatarSubmission =
- | { ref: string; crop?: AvatarCrop }
+ | { ref: string; crop?: AvatarCrop; version?: string }
| { url: string; crop?: AvatarCrop }
| { file: File };
diff --git a/frontend/test/react/avatar-picker.test.tsx b/frontend/test/react/avatar-picker.test.tsx
index 4fed95180..ecec37ac3 100644
--- a/frontend/test/react/avatar-picker.test.tsx
+++ b/frontend/test/react/avatar-picker.test.tsx
@@ -30,6 +30,7 @@ const choice = (over: Partial<AvatarChoice> = {}): AvatarChoice => ({
bases: [],
focus: null,
cast: 0,
+ version: '',
...over,
});
@@ -260,11 +261,11 @@ it('封面格子在取景区里取一块 3:4,图库人像照旧铺满', async
});
});
-it('按番号取来的封面直接进框选,默认框就是脸那一块', async () => {
+it('按番号取来的封面直接进框选,默认框就是脸那一块,交框时说明框的是哪一版封面', async () => {
const code = choice({
ref: 'cover:ABW-999', source: 'code', label: 'ABW-999', crop: true,
width: 800, height: 540, bases: ['cover:ABW-999'],
- focus: { x0: 592, y0: 114, x1: 688, y1: 210 },
+ focus: { x0: 592, y0: 114, x1: 688, y1: 210 }, version: '18f3a',
});
const calls: Call[] = [];
vi.stubGlobal('fetch', vi.fn(async (input: string, init?: RequestInit) => {
@@ -284,12 +285,15 @@ it('按番号取来的封面直接进框选,默认框就是脸那一块', asyn
expect(body(calls, 1)).toEqual({ code: 'abw-999' });
expect(dialog()?.textContent).toContain('框出头像那一块');
expect([...document.querySelectorAll('[data-crop-base]')]).toHaveLength(0);
+ // 封面会原地替换:底图地址带着版本,换过的封面是另一个地址,不会复用旧图。
+ expect(document.querySelector('[role="dialog"] img')?.getAttribute('src'))
+ .toBe('/avatar-choice?kind=performer&id=7792&ref=cover%3AABW-999&v=18f3a');
await reportSize(800, 540);
await click(buttonNamed('用这一块'));
await settle();
expect(body(calls, 2)).toEqual({
kind: 'performer', id: 7792, ref: 'cover:ABW-999',
- crop: { x0: 592, y0: 114, x1: 688, y1: 210 },
+ crop: { x0: 592, y0: 114, x1: 688, y1: 210 }, version: '18f3a',
});
});
@@ -334,7 +338,7 @@ it('作品画面先框一块再装,方框是正方形的', async () => {
expect(body(calls, 1)).toEqual({
kind: 'performer', id: 7792, ref: 'asset:11:cover',
// 头像是圆的,框只能是正方形:短边 540 居中。
- crop: { x0: 130, y0: 0, x1: 670, y1: 540 },
+ crop: { x0: 130, y0: 0, x1: 670, y1: 540 }, version: '',
});
expect(picked).toHaveBeenCalledOnce();
});
diff --git a/src/peach/avatar_picker.py b/src/peach/avatar_picker.py
index 20b319e05..2711a883d 100644
--- a/src/peach/avatar_picker.py
+++ b/src/peach/avatar_picker.py
@@ -101,6 +101,10 @@ class Choice:
#: 这部作品有几位演员(`cast_sizes`)。多于一位时封面上那张脸多半是领衔的另一位,
#: `focus` 不围着它取景;0 是不知道(不是她馆藏里的作品)。
cast: int = 0
+ #: 封面那张底图的版本(`cover_version`)。封面会被补高清、重探原地替换,地址不变;
+ #: 预览地址带上它才不会显示旧图,交框时回递它,服务端才认得出框是在哪一张上画的。
+ #: 图库与历史按内容寻址,九宫格从视频抽帧,都不会原地变,是空串。
+ version: str = ""
def as_dict(self) -> dict:
focus = (dict(zip(("x0", "y0", "x1", "y1"), self.focus))
@@ -109,7 +113,24 @@ class Choice:
"width": self.width, "height": self.height,
"detail": self.detail, "found_by": self.found_by,
"current": self.current, "crop": self.crop,
- "bases": list(self.bases), "focus": focus, "cast": self.cast}
+ "bases": list(self.bases), "focus": focus, "cast": self.cast,
+ "version": self.version}
+
+
+def cover_version(cover: Path | None) -> str:
+ """一张封面文件此刻的版本:修改时间的十六进制纳秒。文件不在就是空串。"""
+ if cover is None:
+ return ""
+ try:
+ return f"{cover.stat().st_mtime_ns:x}"
+ except OSError:
+ return ""
+
+
+def _check_version(cover: Path | None, version: str | None) -> None:
+ """框是在 `version` 那一张封面上画的;封面此后被换过,同一组坐标就落在别的地方。"""
+ if version is not None and cover_version(cover) != version:
+ raise PickerError("这张封面刚换过,回候选重新框一次")
def name_chain(connection: sqlite3.Connection, entity_id: int) -> list[str]:
@@ -284,7 +305,7 @@ def asset_artwork(connection: sqlite3.Connection, cover_root: Path,
width=width, height=height,
detail=str(title or ""), crop=True, bases=tuple(bases),
focus=cover_focus(key, cover, _focus_face(read_sidecar(cover), cast), width, height)
- if size else None, cast=cast)))
+ if size else None, cast=cast, version=cover_version(cover) if size else "")))
found.sort(key=lambda item: (-item[0], item[1]))
return [choice for _area, _order, choice in found[:MAX_ASSET_CHOICES]]
@@ -355,7 +376,7 @@ def code_cover(code: str, cover_root: Path | None, providers_root: Path,
focus = cover_focus(key, cover, face, *size)
ref = f"cover:{key}"
return Choice(ref=ref, source="code", label=key, width=size[0], height=size[1],
- crop=True, bases=(ref,), focus=focus)
+ crop=True, bases=(ref,), focus=focus, version=cover_version(cover))
def choices(connection: sqlite3.Connection, providers_root: Path,
@@ -485,7 +506,8 @@ class ArtworkSource:
def _asset_image(ref: str, connection: sqlite3.Connection, entity_id: int,
- artwork: ArtworkSource | None) -> tuple[bytes, dict]:
+ artwork: ArtworkSource | None,
+ version: str | None = None) -> tuple[bytes, dict]:
"""`asset:<id>:cover` / `asset:<id>:cell<n>` → 那张图的字节和来源记录。
作品必须真的挂在这个人身上才给。页面只会递自己刚列出来的那些,但这一层不能
@@ -510,6 +532,7 @@ def _asset_image(ref: str, connection: sqlite3.Connection, entity_id: int,
key = normalise_code_key(row[0])
path = (Path(artwork.cover_root) / f"{key}.jpg") if key else None
label = "封面"
+ _check_version(path, version)
elif what.startswith("cell"):
try:
cell = int(what[len("cell"):])
@@ -535,11 +558,15 @@ def _asset_image(ref: str, connection: sqlite3.Connection, entity_id: int,
def resolve(ref: str, connection: sqlite3.Connection, providers_root: Path,
entity_id: int,
transport: HttpTransport | None,
- artwork: ArtworkSource | None = None) -> tuple[bytes, dict]:
+ artwork: ArtworkSource | None = None,
+ version: str | None = None) -> tuple[bytes, dict]:
"""把页面回递的 `ref` 换成图片字节和一份来源记录。
`ref` 只认这里自己刚枚举出来的那些:图库候选要在索引里真的存在,历史候选要在
缓存里真的有对象。页面递不进任意地址——手填地址是另一条路,它有自己的边界。
+
+ `version` 是交框时页面回递的封面版本(`Choice.version`)。给了就核对,封面在列出
+ 候选之后被换过就拒收;只取预览图时不给。
"""
if ref.startswith("sha256:"):
digest = ref.split(":", 1)[1].strip().lower()
@@ -547,15 +574,16 @@ def resolve(ref: str, connection: sqlite3.Connection, providers_root: Path,
return body, {"source": "avatar picker", "provider": "history",
"external_id": digest[:12]}
if ref.startswith("asset:"):
- return _asset_image(ref, connection, entity_id, artwork)
+ return _asset_image(ref, connection, entity_id, artwork, version)
if ref.startswith("cover:"):
# 只读本机:出网那一步在 `code_cover` 里,由人输入番号时显式触发。来源记录里
# 不写 `upstream_url`——`keep` 拿它当缓存键,写了会让框出来的那一块顶掉整张封面。
key = normalise_code_key(ref.split(":", 1)[1])
- body, _path = _code_cover_bytes(
+ body, path = _code_cover_bytes(
key, artwork.cover_root if artwork else None, providers_root) if key else (None, None)
if body is None:
raise PickerError("这个番号的封面还没有取过")
+ _check_version(path, version)
return body, {"source": "avatar picker", "provider": "code-cover",
"external_id": key, "asset_code": key}
if not ref.startswith("gfriends:"):
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.py
index bbafa2c90..8519299e9 100644
--- a/src/peach/routes_media.py
+++ b/src/peach/routes_media.py
@@ -1161,6 +1161,8 @@ def avatar_choice(request: Request, kind: str = "performer", id: int = 0,
cache.store(str(origin.get("upstream_url") or ""), body, inspected)
result = Response(b"" if request.method == "HEAD" else body,
media_type=inspected.mime_type)
+ # 封面会原地替换,可以缓存这么久是因为它的地址带着 `v`(`Choice.version`):封面一换,
+ # 页面要的就是另一个地址。
result.headers["Cache-Control"] = f"private, max-age={AVATAR_CACHE_SECONDS}"
return result
@@ -1199,12 +1201,14 @@ async def avatar_pick(request: Request, args: dict[str, str] = Depends(require_a
entity_id = current_entity_id(state, entity_id)
kind = _picker_kind(str(payload.get("kind") or "performer"))
ref, url = str(payload.get("ref") or ""), str(payload.get("url") or "")
+ version = payload.get("version")
try:
if ref:
with state.read_connection() as connection:
body, origin = avatar_picker.resolve(
ref, connection, providers_root, entity_id,
- request.app.state.http_transport, _picker_artwork(request))
+ request.app.state.http_transport, _picker_artwork(request),
+ version=version if isinstance(version, str) else None)
elif url:
if not avatar_picker.allowed_source(url):
return JSONResponse(
diff --git a/tests/test_avatar_picker.py b/tests/test_avatar_picker.py
index 5f56815e1..7a23c9f1f 100644
--- a/tests/test_avatar_picker.py
+++ b/tests/test_avatar_picker.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import importlib.util
import io
import json
+import os
import shutil
import sqlite3
import tempfile
@@ -414,6 +415,28 @@ class AssetArtworkTests(PickerFixture):
self.providers, 7792, None, self.artwork)
self.assertEqual(frame, self.cell.read_bytes())
+ def test_a_box_drawn_on_a_cover_that_was_since_replaced_is_refused(self):
+ """补高清会原地换掉封面:旧图上框的那组坐标落在新图上是另一块地方。"""
+ self.add_asset(11, "ABW-232")
+ listed = avatar_picker.choices(self.connection, self.providers, self.avatars,
+ "performer", 7792, cover_root=self.covers)
+ drawn_on = next(one for one in listed["choices"] if one["source"] == "asset")["version"]
+ self.assertTrue(drawn_on, "封面那一格要带版本,预览地址靠它换新")
+ body, _ = avatar_picker.resolve("asset:11:cover", self.connection, self.providers,
+ 7792, None, self.artwork, version=drawn_on)
+ self.assertEqual(body, self.cover.read_bytes())
+
+ self.cover.write_bytes(picture(800, 520, "green"))
+ later = self.cover.stat().st_mtime_ns + 1_000_000_000
+ os.utime(self.cover, ns=(later, later))
+ with self.assertRaisesRegex(avatar_picker.PickerError, "刚换过"):
+ avatar_picker.resolve("asset:11:cover", self.connection, self.providers,
+ 7792, None, self.artwork, version=drawn_on)
+ # 九宫格那几格从视频抽帧,不随封面变,带着旧版本照样取得到。
+ frame, _ = avatar_picker.resolve("asset:11:cell4", self.connection, self.providers,
+ 7792, None, self.artwork, version=drawn_on)
+ self.assertEqual(frame, self.cell.read_bytes())
+
def test_a_work_that_is_not_hers_is_refused_even_though_the_file_is_there(self):
"""`asset:1:cover` 是个人都拼得出来;凭它读到别人作品的封面就是个枚举口子。"""
self.add_asset(13, "ABW-232", entity_id=9001)