fix(v2): apply code-review fixes to pinned media

Cap the default selection at the pin limit, settle writes on the live
rom_user, gate pin controls on roms.user.write, dedupe keys server-side,
store resets as SQL NULL, and reuse MediaShelfItem for artwork entries.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-26 10:45:41 -04:00
parent a852d774c2
commit 4f31df90f0
14 changed files with 90 additions and 34 deletions

View File

@@ -27,7 +27,7 @@ from fastapi import (
status,
)
from fastapi.responses import Response
from pydantic import BaseModel, Field, StringConstraints
from pydantic import BaseModel, Field, StringConstraints, field_validator
from sqlalchemy.exc import IntegrityError
from starlette.responses import FileResponse
@@ -381,6 +381,12 @@ class RomUserData(BaseModel):
max_length=PINNED_MEDIA_MAX_ITEMS,
)
@field_validator("pinned_media")
@classmethod
def dedupe_pinned_media(cls, keys: list[str] | None) -> list[str] | None:
"""Drop repeated keys, keeping each at its first position."""
return None if keys is None else list(dict.fromkeys(keys))
async def parse_rom_update_form(
request: Request,

View File

@@ -2395,9 +2395,8 @@ class DBRomsHandler(DBBaseHandler):
if not rom_user:
return None
# Any other RomUser column can back a sort (hidden already bumps the
# global version, pinned_media sorts nothing), and main-sibling picks
# move grouped sets.
# Other RomUser columns can back a sort (hidden bumps the global version,
# pinned_media sorts nothing); main-sibling picks move grouped sets.
_queue_user_cache_bumps(
session,
rom_user.user_id,

View File

@@ -1398,7 +1398,7 @@ class RomUser(BaseModel):
)
# NULL means the default selection; an empty list pins nothing.
pinned_media: Mapped[list[str] | None] = mapped_column(
CustomJSON(), default=None, nullable=True
CustomJSON(none_as_null=True), default=None, nullable=True
)
rom_id: Mapped[int] = mapped_column(ForeignKey("roms.id", ondelete="CASCADE"))

View File

@@ -1523,6 +1523,19 @@ def test_update_rom_user_props_pinned_media(
assert reset.json()["pinned_media"] is None
def test_update_rom_user_props_dedupes_pinned_media(
client: TestClient, access_token: str, rom: Rom
):
response = client.put(
f"/api/roms/{rom.id}/props",
headers={"Authorization": f"Bearer {access_token}"},
json={"pinned_media": ["file:2", "file:1", "file:2"]},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["pinned_media"] == ["file:2", "file:1"]
@pytest.mark.parametrize(
"pinned_media",
[

View File

@@ -16,7 +16,7 @@ import { resolveRomArtwork } from "@/v2/utils/romArtwork";
const props = defineProps<{ rom: DetailedRom }>();
const { t } = useI18n();
const { isPinned, togglePin } = usePinnedMedia(() => props.rom);
const { canPin, isPinned, togglePin } = usePinnedMedia(() => props.rom);
const artwork = computed(() => resolveRomArtwork(props.rom));
</script>
@@ -33,7 +33,7 @@ const artwork = computed(() => resolveRomArtwork(props.rom));
v-else
:items="artwork"
captions
:is-pinned="isPinned"
:is-pinned="canPin ? isPinned : undefined"
@toggle-pin="togglePin"
/>
</div>

View File

@@ -3,8 +3,6 @@ import { RBtn } from "@v2/lib";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
defineOptions({ inheritAttrs: false });
const props = defineProps<{ pinned: boolean }>();
const emit = defineEmits<{ toggle: [] }>();
@@ -17,7 +15,6 @@ const label = computed(() =>
<template>
<RBtn
v-bind="$attrs"
:icon="pinned ? 'mdi-pin' : 'mdi-pin-outline'"
size="small"
variant="flat"

View File

@@ -37,6 +37,7 @@ vi.mock("@/v2/utils/pinnedMedia", () => ({
vi.mock("@/v2/composables/usePinnedMedia", () => ({
usePinnedMedia: () => ({
canPin: ref(true),
isPinned: () => true,
isCustomized,
togglePin: vi.fn(),

View File

@@ -103,7 +103,7 @@ const collectionsStore = storeCollections();
const { supportsWebp, toWebp } = useWebpSupport();
const pinnedMedia = computed(() => resolvePinnedMedia(props.rom));
const { isPinned, isCustomized, togglePin, resetPins } = usePinnedMedia(
const { canPin, isPinned, isCustomized, togglePin, resetPins } = usePinnedMedia(
() => props.rom,
);
@@ -270,7 +270,7 @@ const coverSource = computed(() => {
{{ t("rom.media") }}
</h4>
<RBtn
v-if="isCustomized"
v-if="isCustomized && canPin"
variant="text"
size="x-small"
prepend-icon="mdi-restore"
@@ -284,7 +284,7 @@ const coverSource = computed(() => {
:items="pinnedMedia"
compact
pin-on-hover
:is-pinned="isPinned"
:is-pinned="canPin ? isPinned : undefined"
@toggle-pin="togglePin"
/>
<p v-else class="overview-tab__empty">

View File

@@ -58,7 +58,7 @@ const { user } = storeToRefs(authStore);
// section writes per-user assets and stays available to everyone.
const canEditRom = useCan("rom.edit");
const { isPinned, togglePin } = usePinnedMedia(() => props.rom);
const { canPin, isPinned, togglePin } = usePinnedMedia(() => props.rom);
const scrapedScreenshots = computed<ScreenshotItem[]>(() =>
(props.rom.merged_screenshots ?? []).map((url) => ({
@@ -237,7 +237,7 @@ async function submitEdit(isPublic: boolean) {
</header>
<ScreenshotsTab
:screenshots="scrapedScreenshots"
:is-pinned="isPinned"
:is-pinned="canPin ? isPinned : undefined"
@toggle-pin="togglePin"
/>
</section>
@@ -293,7 +293,7 @@ async function submitEdit(isPublic: boolean) {
<ScreenshotsTab
:screenshots="romScreenshots"
:deletable="canEditRom"
:is-pinned="isPinned"
:is-pinned="canPin ? isPinned : undefined"
@delete="deleteRomScreenshot"
@toggle-pin="togglePin"
/>
@@ -343,7 +343,7 @@ async function submitEdit(isPublic: boolean) {
:screenshots="myScreenshots"
deletable
editable
:is-pinned="isPinned"
:is-pinned="canPin ? isPinned : undefined"
@edit="editTarget = $event"
@delete="deleteMyScreenshot"
@toggle-pin="togglePin"
@@ -362,7 +362,7 @@ async function submitEdit(isPublic: boolean) {
</header>
<ScreenshotsTab
:screenshots="communityScreenshots"
:is-pinned="isPinned"
:is-pinned="canPin ? isPinned : undefined"
@toggle-pin="togglePin"
/>
</section>

View File

@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { reactive } from "vue";
import { reactive, shallowRef } from "vue";
import type { RomUserSchema } from "@/__generated__";
import romApi from "@/services/api/rom";
import type { DetailedRom } from "@/stores/roms";
@@ -13,6 +13,10 @@ vi.mock("@/services/api/rom", () => ({
default: { updateUserRomProps: vi.fn() },
}));
vi.mock("@/stores/auth", () => ({
default: () => ({ scopes: ["roms.user.write"] }),
}));
const snackbarError = vi.fn();
vi.mock("@/v2/composables/useSnackbar", () => ({
useSnackbar: () => ({ error: snackbarError }),
@@ -129,6 +133,22 @@ describe("usePinnedMedia", () => {
expect(rom.rom_user.pinned_media).toEqual(["file:9"]);
});
it("settles on the ROM a refetch swapped in mid-write", async () => {
update.mockResolvedValue({} as never);
const loaded = makeRom([]);
const current = shallowRef(loaded);
const { togglePin } = usePinnedMedia(() => current.value);
togglePin("file:1");
const refetched = reactive({
id: loaded.id,
rom_user: { pinned_media: [] as string[] } as RomUserSchema,
}) as DetailedRom;
current.value = refetched;
await settle();
expect(refetched.rom_user.pinned_media).toEqual(["file:1"]);
});
it("refuses a pin past the limit without writing", async () => {
const rom = makeRom(["file:1", "file:2", "file:3"]);
const { togglePin } = usePinnedMedia(rom);

View File

@@ -4,6 +4,7 @@
import { computed, toValue, type MaybeRefOrGetter } from "vue";
import { useI18n } from "vue-i18n";
import romApi from "@/services/api/rom";
import storeAuth from "@/stores/auth";
import type { DetailedRom } from "@/stores/roms";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import {
@@ -25,7 +26,10 @@ const romWrites = new Map<number, RomWrites>();
export function usePinnedMedia(rom: MaybeRefOrGetter<DetailedRom>) {
const { t } = useI18n();
const snackbar = useSnackbar();
const auth = storeAuth();
// The props endpoint refuses sessions without this scope.
const canPin = computed(() => auth.scopes.includes("roms.user.write"));
const pinned = computed(() => new Set(pinnedMediaKeys(toValue(rom))));
const isCustomized = computed(
() => toValue(rom).rom_user?.pinned_media != null,
@@ -46,6 +50,12 @@ export function usePinnedMedia(rom: MaybeRefOrGetter<DetailedRom>) {
romWrites.set(target.id, writes);
}
const state = writes;
// A refetch mid-write swaps in a new rom_user, so settle on the live one.
const settle = (value: string[] | null) => {
const live = toValue(rom);
const current = live.id === target.id ? live.rom_user : romUser;
current.pinned_media = value;
};
romUser.pinned_media = next;
state.pending++;
state.queue = state.queue.then(async () => {
@@ -55,9 +65,10 @@ export function usePinnedMedia(rom: MaybeRefOrGetter<DetailedRom>) {
data: { pinned_media: next },
});
state.confirmed = next;
if (state.pending === 1) settle(next);
} catch {
// A newer queued write already carries the state the user wants.
if (state.pending === 1) romUser.pinned_media = state.confirmed;
if (state.pending === 1) settle(state.confirmed);
snackbar.error(t("rom.pinned-media-update-failed"), {
icon: "mdi-alert-circle-outline",
});
@@ -87,5 +98,5 @@ export function usePinnedMedia(rom: MaybeRefOrGetter<DetailedRom>) {
write(null);
}
return { isPinned, isCustomized, togglePin, resetPins };
return { canPin, isPinned, isCustomized, togglePin, resetPins };
}

View File

@@ -6,6 +6,7 @@ import type {
} from "@/__generated__";
import type { DetailedRom } from "@/stores/roms";
import {
PINNED_MEDIA_MAX_ITEMS,
defaultPinnedMediaKeys,
resolvePinnedMedia,
romFolderScreenshots,
@@ -87,6 +88,17 @@ describe("defaultPinnedMediaKeys", () => {
"file:6",
]);
});
it("caps the selection at the pin limit", () => {
const rom = makeRom(null, {
merged_screenshots: Array.from(
{ length: PINNED_MEDIA_MAX_ITEMS + 5 },
(_, i) => `/shots/${i}.jpg`,
),
});
expect(defaultPinnedMediaKeys(rom)).toHaveLength(PINNED_MEDIA_MAX_ITEMS);
});
});
describe("resolvePinnedMedia", () => {

View File

@@ -63,12 +63,15 @@ function userScreenshots(rom: DetailedRom): MediaShelfItem[] {
}));
}
// Capped so the first toggle can always save the defaults it starts from.
export function defaultPinnedMediaKeys(rom: DetailedRom): string[] {
return [
...scrapedScreenshots(rom),
...folderScreenshots(rom),
...resolveRomArtwork(rom).filter((entry) => entry.isVideo),
].map((item) => item.key);
]
.map((item) => item.key)
.slice(0, PINNED_MEDIA_MAX_ITEMS);
}
export function pinnedMediaKeys(rom: DetailedRom): string[] {

View File

@@ -1,6 +1,6 @@
// Resolves the art assets attached to a ROM into a flat, display-ready list.
// Shared by the Media tab's Artwork subtab (full gallery) and the Overview tab
// (videos only) so both stay in sync.
// Shared by the Media tab's Artwork subtab (full gallery) and the Overview
// tab's pinned media (utils/pinnedMedia) so both stay in sync.
//
// Two sources feed the list:
// 1. Scraped resources — ScreenScraper is the richest and wins; gamelist
@@ -18,16 +18,10 @@
import i18n from "@/locales";
import type { DetailedRom } from "@/stores/roms";
import { FRONTEND_RESOURCES_PATH } from "@/utils";
import type { MediaShelfItem } from "@/v2/components/GameDetails/MediaShelf.vue";
import { mediaKey } from "@/v2/utils/mediaKeys";
import { versionedRomFileUrl } from "@/v2/utils/romFiles";
export type RomArtworkEntry = {
key: string;
label: string;
url: string;
isVideo?: boolean;
};
// Library file extensions the browser can render inline. Kept in sync with the
// backend download endpoint (utils/media_types.py), which serves these inline.
const LIBRARY_IMAGE_EXTENSIONS = new Set([
@@ -49,17 +43,17 @@ const SURFACED_ELSEWHERE = new Set(["screenshot", "soundtrack", "manual"]);
// A candidate asset before its URL is resolved. `isAbsolute` marks a URL that
// is already browser-ready rather than a path under the resources root.
type ArtworkDef = Omit<RomArtworkEntry, "url"> & {
type ArtworkDef = Omit<MediaShelfItem, "url"> & {
url: string | null;
isAbsolute?: boolean;
};
export function resolveRomArtwork(rom: DetailedRom): RomArtworkEntry[] {
export function resolveRomArtwork(rom: DetailedRom): MediaShelfItem[] {
const ss = rom.ss_metadata;
const gl = rom.gamelist_metadata;
const cacheBust = encodeURIComponent(rom.updated_at);
const seen = new Set<string>();
const out: RomArtworkEntry[] = [];
const out: MediaShelfItem[] = [];
const artworkDefs: ArtworkDef[] = [
{