mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 02:22:44 +01:00
refactor(v2): simplify pinned media
Build each media source once per resolve, gate isPinned on scope inside the composable, sync cached ROM copies on pin writes, require pinKey on screenshot items, and share the order-preserving dedupe validator. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -27,7 +27,7 @@ from fastapi import (
|
||||
status,
|
||||
)
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field, StringConstraints, field_validator
|
||||
from pydantic import AfterValidator, BaseModel, Field, StringConstraints
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from starlette.responses import FileResponse
|
||||
|
||||
@@ -141,7 +141,11 @@ from utils.m3u import generate_m3u_content, playlist_files
|
||||
from utils.nginx import FileRedirectResponse, ZipContentLine, ZipResponse
|
||||
from utils.router import APIRouter, as_query_dependency
|
||||
from utils.screenshots import continue_playing_screenshot
|
||||
from utils.validation import ValidationError, parse_comma_separated_ids
|
||||
from utils.validation import (
|
||||
ValidationError,
|
||||
dedupe_in_order,
|
||||
parse_comma_separated_ids,
|
||||
)
|
||||
from utils.zip_cache import (
|
||||
BULK_CACHE_MAX_ROMS,
|
||||
ZipFileEntry,
|
||||
@@ -335,6 +339,14 @@ def _record_rom_update(request: Request, before: Rom, after: Rom) -> None:
|
||||
)
|
||||
|
||||
|
||||
PinnedMediaKey = Annotated[
|
||||
str,
|
||||
StringConstraints(
|
||||
max_length=PINNED_MEDIA_KEY_MAX_LENGTH, pattern=PINNED_MEDIA_KEY_PATTERN
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
class RomUserData(BaseModel):
|
||||
is_main_sibling: bool | None = Field(
|
||||
default=None, description="Whether this rom is the main sibling."
|
||||
@@ -364,29 +376,14 @@ class RomUserData(BaseModel):
|
||||
status: RomUserStatus | None = Field(
|
||||
default=None, description="User play status for this rom."
|
||||
)
|
||||
pinned_media: (
|
||||
list[
|
||||
Annotated[
|
||||
str,
|
||||
StringConstraints(
|
||||
max_length=PINNED_MEDIA_KEY_MAX_LENGTH,
|
||||
pattern=PINNED_MEDIA_KEY_PATTERN,
|
||||
),
|
||||
]
|
||||
]
|
||||
| None
|
||||
) = Field(
|
||||
pinned_media: Annotated[
|
||||
list[PinnedMediaKey] | None, AfterValidator(dedupe_in_order)
|
||||
] = Field(
|
||||
default=None,
|
||||
description="Ordered media keys shown on the overview; null restores the default selection.",
|
||||
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,
|
||||
|
||||
@@ -25,8 +25,8 @@ EMAIL_PATTERN = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
|
||||
MAX_ROM_IDS_PER_QUERY: Final = 500
|
||||
|
||||
|
||||
def _dedupe_rom_ids(rom_ids: list[int] | None) -> list[int] | None:
|
||||
return None if rom_ids is None else list(dict.fromkeys(rom_ids))
|
||||
def dedupe_in_order[T](items: list[T] | None) -> list[T] | None:
|
||||
return None if items is None else list(dict.fromkeys(items))
|
||||
|
||||
|
||||
# Shared by every route that scopes a query to a set of ROMs, so the cap and
|
||||
@@ -34,7 +34,7 @@ def _dedupe_rom_ids(rom_ids: list[int] | None) -> list[int] | None:
|
||||
RomIdScope = Annotated[
|
||||
list[Annotated[int, Field(gt=0)]] | None,
|
||||
Field(max_length=MAX_ROM_IDS_PER_QUERY),
|
||||
AfterValidator(_dedupe_rom_ids),
|
||||
AfterValidator(dedupe_in_order),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import { resolveRomArtwork } from "@/v2/utils/romArtwork";
|
||||
const props = defineProps<{ rom: DetailedRom }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const { canPin, isPinned, togglePin } = usePinnedMedia(() => props.rom);
|
||||
const { 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="canPin ? isPinned : undefined"
|
||||
:is-pinned="isPinned"
|
||||
@toggle-pin="togglePin"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -38,7 +38,7 @@ vi.mock("@/v2/utils/pinnedMedia", () => ({
|
||||
vi.mock("@/v2/composables/usePinnedMedia", () => ({
|
||||
usePinnedMedia: () => ({
|
||||
canPin: ref(true),
|
||||
isPinned: () => true,
|
||||
isPinned: ref(() => true),
|
||||
isCustomized,
|
||||
togglePin: vi.fn(),
|
||||
resetPins,
|
||||
|
||||
@@ -284,7 +284,7 @@ const coverSource = computed(() => {
|
||||
:items="pinnedMedia"
|
||||
compact
|
||||
pin-on-hover
|
||||
:is-pinned="canPin ? isPinned : undefined"
|
||||
:is-pinned="isPinned"
|
||||
@toggle-pin="togglePin"
|
||||
/>
|
||||
<p v-else class="overview-tab__empty">
|
||||
|
||||
@@ -58,7 +58,7 @@ const { user } = storeToRefs(authStore);
|
||||
// section writes per-user assets and stays available to everyone.
|
||||
const canEditRom = useCan("rom.edit");
|
||||
|
||||
const { canPin, isPinned, togglePin } = usePinnedMedia(() => props.rom);
|
||||
const { 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="canPin ? isPinned : undefined"
|
||||
:is-pinned="isPinned"
|
||||
@toggle-pin="togglePin"
|
||||
/>
|
||||
</section>
|
||||
@@ -293,7 +293,7 @@ async function submitEdit(isPublic: boolean) {
|
||||
<ScreenshotsTab
|
||||
:screenshots="romScreenshots"
|
||||
:deletable="canEditRom"
|
||||
:is-pinned="canPin ? isPinned : undefined"
|
||||
:is-pinned="isPinned"
|
||||
@delete="deleteRomScreenshot"
|
||||
@toggle-pin="togglePin"
|
||||
/>
|
||||
@@ -343,7 +343,7 @@ async function submitEdit(isPublic: boolean) {
|
||||
:screenshots="myScreenshots"
|
||||
deletable
|
||||
editable
|
||||
:is-pinned="canPin ? isPinned : undefined"
|
||||
:is-pinned="isPinned"
|
||||
@edit="editTarget = $event"
|
||||
@delete="deleteMyScreenshot"
|
||||
@toggle-pin="togglePin"
|
||||
@@ -362,7 +362,7 @@ async function submitEdit(isPublic: boolean) {
|
||||
</header>
|
||||
<ScreenshotsTab
|
||||
:screenshots="communityScreenshots"
|
||||
:is-pinned="canPin ? isPinned : undefined"
|
||||
:is-pinned="isPinned"
|
||||
@toggle-pin="togglePin"
|
||||
/>
|
||||
</section>
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
// MediaTab, performs the actions):
|
||||
// * edit: when `editable` and owned, opens its visibility (top-right)
|
||||
// * delete: when `deletable` and the item is owned (top-right, hover)
|
||||
// * pin: when `isPinned` is given and the item has a `pinKey`
|
||||
// (bottom-right, always shown while pinned)
|
||||
// * pin: when `isPinned` is given (bottom-right, always shown while
|
||||
// pinned)
|
||||
// * username: community items (others' public shots) show an owner chip
|
||||
import { RAvatar, RBtn, RCarousel } from "@v2/lib";
|
||||
import { computed, ref } from "vue";
|
||||
@@ -24,7 +24,7 @@ defineOptions({ inheritAttrs: false });
|
||||
// `isOwn`/`isPublic`/`username` only matter for the per-user community grids.
|
||||
export type ScreenshotItem = {
|
||||
url: string;
|
||||
pinKey?: string;
|
||||
pinKey: string;
|
||||
id?: number;
|
||||
isOwn?: boolean;
|
||||
isPublic?: boolean;
|
||||
@@ -75,7 +75,7 @@ function canEdit(shot: ScreenshotItem): boolean {
|
||||
<section class="r-v2-det-shots">
|
||||
<div
|
||||
v-for="(shot, i) in screenshots"
|
||||
:key="shot.pinKey ?? shot.url"
|
||||
:key="shot.pinKey"
|
||||
class="r-v2-det-shots__cell r-v2-asset-fade"
|
||||
:style="{ '--asset-fade-i': i }"
|
||||
>
|
||||
@@ -136,7 +136,7 @@ function canEdit(shot: ScreenshotItem): boolean {
|
||||
</div>
|
||||
|
||||
<MediaPinBtn
|
||||
v-if="isPinned && shot.pinKey"
|
||||
v-if="isPinned"
|
||||
class="r-v2-det-shots__pin"
|
||||
:class="{ 'r-v2-det-shots__pin--shown': isPinned(shot.pinKey) }"
|
||||
:pinned="isPinned(shot.pinKey)"
|
||||
|
||||
@@ -13,11 +13,15 @@ vi.mock("@/services/api/rom", () => ({
|
||||
default: { updateUserRomProps: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/auth", () => ({
|
||||
default: () => ({ scopes: ["roms.user.write"] }),
|
||||
}));
|
||||
const auth = vi.hoisted(() => ({ scopes: ["roms.user.write"] }));
|
||||
vi.mock("@/stores/auth", () => ({ default: () => auth }));
|
||||
|
||||
const snackbarError = vi.fn();
|
||||
const syncCachedRom = vi.fn();
|
||||
vi.mock("@/v2/composables/useRomSync", () => ({
|
||||
useRomSync: () => ({ syncCachedRom }),
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/useSnackbar", () => ({
|
||||
useSnackbar: () => ({ error: snackbarError }),
|
||||
}));
|
||||
@@ -56,7 +60,7 @@ describe("usePinnedMedia", () => {
|
||||
const rom = makeRom(null);
|
||||
const { isPinned, isCustomized, togglePin } = usePinnedMedia(rom);
|
||||
|
||||
expect(isPinned("file:1")).toBe(true);
|
||||
expect(isPinned.value?.("file:1")).toBe(true);
|
||||
expect(isCustomized.value).toBe(false);
|
||||
|
||||
togglePin("file:2");
|
||||
@@ -163,6 +167,14 @@ describe("usePinnedMedia", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("hides pin controls without the roms.user.write scope", () => {
|
||||
auth.scopes = [];
|
||||
const { isPinned } = usePinnedMedia(makeRom(["file:1"]));
|
||||
|
||||
expect(isPinned.value).toBeUndefined();
|
||||
auth.scopes = ["roms.user.write"];
|
||||
});
|
||||
|
||||
it("resets to the default selection", async () => {
|
||||
update.mockResolvedValue({} as never);
|
||||
const rom = makeRom(["file:9"]);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useI18n } from "vue-i18n";
|
||||
import romApi from "@/services/api/rom";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import { useRomSync } from "@/v2/composables/useRomSync";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import {
|
||||
PINNED_MEDIA_MAX_ITEMS,
|
||||
@@ -27,10 +28,16 @@ export function usePinnedMedia(rom: MaybeRefOrGetter<DetailedRom>) {
|
||||
const { t } = useI18n();
|
||||
const snackbar = useSnackbar();
|
||||
const auth = storeAuth();
|
||||
const { syncCachedRom } = useRomSync();
|
||||
|
||||
// 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 keys = computed(() => pinnedMediaKeys(toValue(rom)));
|
||||
const pinned = computed(() => new Set(keys.value));
|
||||
// Undefined without the scope, which hides every pin control.
|
||||
const isPinned = computed(() =>
|
||||
canPin.value ? (key: string) => pinned.value.has(key) : undefined,
|
||||
);
|
||||
const isCustomized = computed(
|
||||
() => toValue(rom).rom_user?.pinned_media != null,
|
||||
);
|
||||
@@ -40,23 +47,21 @@ export function usePinnedMedia(rom: MaybeRefOrGetter<DetailedRom>) {
|
||||
const romUser = target.rom_user;
|
||||
if (!romUser) return;
|
||||
|
||||
let writes = romWrites.get(target.id);
|
||||
if (!writes) {
|
||||
writes = {
|
||||
queue: Promise.resolve(),
|
||||
pending: 0,
|
||||
confirmed: romUser.pinned_media,
|
||||
};
|
||||
romWrites.set(target.id, writes);
|
||||
}
|
||||
const state = writes;
|
||||
const state = romWrites.get(target.id) ?? {
|
||||
queue: Promise.resolve(),
|
||||
pending: 0,
|
||||
confirmed: romUser.pinned_media,
|
||||
};
|
||||
romWrites.set(target.id, state);
|
||||
// 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;
|
||||
const current = live.id === target.id ? live : target;
|
||||
current.rom_user.pinned_media = value;
|
||||
syncCachedRom(current);
|
||||
};
|
||||
romUser.pinned_media = next;
|
||||
syncCachedRom(target);
|
||||
state.pending++;
|
||||
state.queue = state.queue.then(async () => {
|
||||
try {
|
||||
@@ -78,12 +83,8 @@ export function usePinnedMedia(rom: MaybeRefOrGetter<DetailedRom>) {
|
||||
});
|
||||
}
|
||||
|
||||
function isPinned(key: string): boolean {
|
||||
return pinned.value.has(key);
|
||||
}
|
||||
|
||||
function togglePin(key: string) {
|
||||
const next = togglePinnedMediaKey(pinnedMediaKeys(toValue(rom)), key);
|
||||
const next = togglePinnedMediaKey(keys.value, key);
|
||||
if (next.length > PINNED_MEDIA_MAX_ITEMS) {
|
||||
snackbar.error(
|
||||
t("rom.pinned-media-limit", { n: PINNED_MEDIA_MAX_ITEMS }),
|
||||
|
||||
@@ -35,45 +35,55 @@ export function romFolderScreenshots(rom: DetailedRom): RomFileSchema[] {
|
||||
});
|
||||
}
|
||||
|
||||
function screenshotLabel(n: number): string {
|
||||
return i18n.global.t("rom.screenshot-num", { n });
|
||||
}
|
||||
|
||||
function scrapedScreenshots(rom: DetailedRom): MediaShelfItem[] {
|
||||
return (rom.merged_screenshots ?? []).map((url, i) => ({
|
||||
key: mediaKey.scraped(url),
|
||||
label: screenshotLabel(i + 1),
|
||||
url,
|
||||
function screenshotItems<T>(
|
||||
list: T[],
|
||||
keyOf: (entry: T) => string,
|
||||
urlOf: (entry: T) => string,
|
||||
): MediaShelfItem[] {
|
||||
return list.map((entry, i) => ({
|
||||
key: keyOf(entry),
|
||||
label: i18n.global.t("rom.screenshot-num", { n: i + 1 }),
|
||||
url: urlOf(entry),
|
||||
}));
|
||||
}
|
||||
|
||||
function folderScreenshots(rom: DetailedRom): MediaShelfItem[] {
|
||||
return romFolderScreenshots(rom).map((file, i) => ({
|
||||
key: mediaKey.file(file.id),
|
||||
label: screenshotLabel(i + 1),
|
||||
url: versionedRomFileUrl(file),
|
||||
}));
|
||||
}
|
||||
|
||||
function userScreenshots(rom: DetailedRom): MediaShelfItem[] {
|
||||
return (rom.all_user_screenshots ?? []).map((shot, i) => ({
|
||||
key: mediaKey.screenshot(shot.id),
|
||||
label: screenshotLabel(i + 1),
|
||||
url: shot.download_path,
|
||||
}));
|
||||
function mediaSources(rom: DetailedRom) {
|
||||
return {
|
||||
screenshots: [
|
||||
...screenshotItems(
|
||||
rom.merged_screenshots ?? [],
|
||||
mediaKey.scraped,
|
||||
(url) => url,
|
||||
),
|
||||
...screenshotItems(
|
||||
romFolderScreenshots(rom),
|
||||
(file) => mediaKey.file(file.id),
|
||||
versionedRomFileUrl,
|
||||
),
|
||||
],
|
||||
userScreenshots: screenshotItems(
|
||||
rom.all_user_screenshots ?? [],
|
||||
(shot) => mediaKey.screenshot(shot.id),
|
||||
(shot) => shot.download_path,
|
||||
),
|
||||
artwork: resolveRomArtwork(rom),
|
||||
};
|
||||
}
|
||||
|
||||
// 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),
|
||||
]
|
||||
function defaultKeys({
|
||||
screenshots,
|
||||
artwork,
|
||||
}: ReturnType<typeof mediaSources>): string[] {
|
||||
return [...screenshots, ...artwork.filter((entry) => entry.isVideo)]
|
||||
.map((item) => item.key)
|
||||
.slice(0, PINNED_MEDIA_MAX_ITEMS);
|
||||
}
|
||||
|
||||
export function defaultPinnedMediaKeys(rom: DetailedRom): string[] {
|
||||
return defaultKeys(mediaSources(rom));
|
||||
}
|
||||
|
||||
export function pinnedMediaKeys(rom: DetailedRom): string[] {
|
||||
return rom.rom_user?.pinned_media ?? defaultPinnedMediaKeys(rom);
|
||||
}
|
||||
@@ -81,15 +91,16 @@ export function pinnedMediaKeys(rom: DetailedRom): string[] {
|
||||
// Keys whose media is gone (a rescrape, a deleted file, a screenshot made
|
||||
// private) are skipped rather than pruned, so they return with the media.
|
||||
export function resolvePinnedMedia(rom: DetailedRom): MediaShelfItem[] {
|
||||
const sources = mediaSources(rom);
|
||||
const byKey = new Map(
|
||||
[
|
||||
...scrapedScreenshots(rom),
|
||||
...folderScreenshots(rom),
|
||||
...userScreenshots(rom),
|
||||
...resolveRomArtwork(rom),
|
||||
...sources.screenshots,
|
||||
...sources.userScreenshots,
|
||||
...sources.artwork,
|
||||
].map((item) => [item.key, item]),
|
||||
);
|
||||
return pinnedMediaKeys(rom).flatMap((key) => byKey.get(key) ?? []);
|
||||
const keys = rom.rom_user?.pinned_media ?? defaultKeys(sources);
|
||||
return keys.flatMap((key) => byKey.get(key) ?? []);
|
||||
}
|
||||
|
||||
export function togglePinnedMediaKey(keys: string[], key: string): string[] {
|
||||
|
||||
Reference in New Issue
Block a user