feat(platforms): enrich discovery cards and preserve AVIF animations (#5433)

Fetch original launch years and current platform logos during scans, retain curated platform icons, and show launch year and type on responsive discovery cards. Preserve animated AVIF frames during thumbnail and WebP conversion.

Closes rommapp/romm#5432

Authored with Codex assistance, including implementation and tests.
This commit is contained in:
Sam Dornan
2026-11-01 19:23:51 -06:00
committed by GitHub
parent 6f0d910dc5
commit 183ee3b89f
19 changed files with 463 additions and 20 deletions

View File

@@ -10,7 +10,7 @@ from aiohttp.client import ClientTimeout
from fastapi import HTTPException, status
from unidecode import unidecode
from adapters.services.igdb_types import Game
from adapters.services.igdb_types import Game, Platform, PlatformVersion
from adapters.services.provider_http import send_with_retries
from adapters.services.response_validation import parse_response
from config import IGDB_CLIENT_ID
@@ -56,6 +56,11 @@ async def auth_middleware(
return await handler(req)
class PlatformDiscovery(TypedDict):
first_release_year: NotRequired[int]
url_logo: NotRequired[str]
class IGDBService:
"""Service to interact with the IGDB API.
@@ -160,6 +165,58 @@ class IGDBService:
)
return games or []
async def platform_discovery(
self, platform_id: int, *, version: bool = False
) -> PlatformDiscovery:
"""Return current artwork and the earliest regional launch year."""
dates_field = "platform_version_release_dates"
field = f"{dates_field}.y" if version else f"versions.{dates_field}.y"
endpoint = "platform_versions" if version else "platforms"
if version:
versions = (
await self._request(
str(self.url.joinpath(endpoint)),
list[PlatformVersion],
fields=["platform_logo.url", field],
where=f"id={platform_id}",
limit=1,
)
or []
)
logo = versions[0].get("platform_logo") if versions else None
else:
platforms = (
await self._request(
str(self.url.joinpath(endpoint)),
list[Platform],
fields=["platform_logo.url", field],
where=f"id={platform_id}",
limit=1,
)
or []
)
logo = platforms[0].get("platform_logo") if platforms else None
versions = [
v
for p in platforms
for v in p.get("versions", [])
if isinstance(v, dict)
]
years = [
year
for v in versions
for date in v.get("platform_version_release_dates", [])
if isinstance(date, dict)
and (year := date.get("y")) is not None
and 0 < year < 10000
]
result = PlatformDiscovery()
if years:
result["first_release_year"] = min(years)
if isinstance(logo, dict) and (url := logo.get("url")):
result["url_logo"] = url
return result
async def search(
self,
*,

View File

@@ -28,7 +28,6 @@ GameMode = UnimplementedEntity
InvolvedCompany = UnimplementedEntity
Keyword = UnimplementedEntity
LanguageSupport = UnimplementedEntity
PlatformVersionReleaseDate = UnimplementedEntity
PlatformWebsite = UnimplementedEntity
PlayerPerspective = UnimplementedEntity
ReleaseDate = UnimplementedEntity
@@ -468,6 +467,11 @@ class PlatformVersionCompany(IGDBEntity, total=False):
manufacturer: bool
class PlatformVersionReleaseDate(IGDBEntity, total=False):
date: int
y: int
# https://api-docs.igdb.com/#region
class Region(IGDBEntity, total=False):
category: Literal["locale", "continent"]

View File

@@ -0,0 +1,22 @@
"""Store the original platform launch year."""
import sqlalchemy as sa
from alembic import op
from utils.database import column_names
revision = "0158_platform_first_release_year"
down_revision = "0157_rom_custom_sort_key_flag"
branch_labels = None
depends_on = None
def upgrade() -> None:
if "first_release_year" not in column_names(op.get_bind(), "platforms"):
op.add_column(
"platforms", sa.Column("first_release_year", sa.Integer(), nullable=True)
)
def downgrade() -> None:
op.drop_column("platforms", "first_release_year", if_exists=True)

View File

@@ -34,6 +34,7 @@ class PlatformSchema(BaseModel):
flashpoint_id: int | None = None
category: str | None = None
generation: int | None = None
first_release_year: int | None = None
family_name: str | None = None
family_slug: str | None = None
url: str | None = None

View File

@@ -3,7 +3,7 @@ from typing import Any, Final, NotRequired, TypedDict, cast
import httpx2
import pydash
from fastapi import status
from fastapi import HTTPException, status
from adapters.services.igdb import (
IGDB_PLATFORM_FAMILIES,
@@ -11,6 +11,7 @@ from adapters.services.igdb import (
IGDB_PLATFORM_VERSIONS,
IGDB_SIBLING_PLATFORMS,
IGDBService,
PlatformDiscovery,
SlugToIGDB,
)
from adapters.services.igdb_types import (
@@ -779,6 +780,35 @@ class IGDBHandler(MetadataHandler):
platform["family_slug"] = family["family_slug"]
return platform
async def get_platform_discovery(self, slug: str) -> PlatformDiscovery:
"""Look up the exact revision when the folder represents a hardware variant."""
if not self.is_enabled():
return PlatformDiscovery()
version = IGDB_PLATFORM_VERSIONS.get(slug)
platform = (
IGDB_PLATFORM_LIST.get(UPS(slug)) if slug in IGDB_PLATFORM_LIST else None
)
if version is None and platform is None:
return PlatformDiscovery()
platform_id = version["id"] if version else platform["id"] if platform else None
if platform_id is None:
return PlatformDiscovery()
try:
details = await self.igdb_service.platform_discovery(
platform_id, version=version is not None
)
if logo := details.get("url_logo"):
logo = self.normalize_cover_url(logo).replace("/t_thumb/", "/t_720p/")
if logo.startswith("https://images.igdb.com/") and logo.endswith(
".jpg"
):
logo = logo.removesuffix(".jpg") + ".png"
details["url_logo"] = logo
return details
except HTTPException:
log.warning("IGDB platform discovery unavailable for %s", slug)
return PlatformDiscovery()
def _base_platform(self, slug: str) -> IGDBPlatform:
if slug in IGDB_PLATFORM_LIST:
platform = IGDB_PLATFORM_LIST[UPS(slug)]

View File

@@ -216,6 +216,9 @@ async def scan_platform(
}
)
platform_attrs.update(
await meta_igdb_handler.get_platform_discovery(platform_attrs["slug"])
)
platform_attrs["missing_from_fs"] = False
scanned_platform = Platform(**platform_attrs)

View File

@@ -62,6 +62,7 @@ class Platform(BaseModel):
description: Mapped[str | None] = mapped_column(Text, default="")
category: Mapped[str | None] = mapped_column(String(length=100), default="")
generation: Mapped[int | None]
first_release_year: Mapped[int | None] = mapped_column(Integer(), default=None)
family_name: Mapped[str | None] = mapped_column(String(length=1000), default="")
family_slug: Mapped[str | None] = mapped_column(String(length=1000), default="")
url: Mapped[str | None] = mapped_column(String(length=1000), default="")

View File

@@ -149,6 +149,96 @@ class TestAgainstAServer:
class TestRequestsAgainstAServer:
async def test_platform_discovery_returns_current_logo_without_dates(
self, igdb_server
):
fake, service, _ = igdb_server
fake.replies["platforms"] = [
(
200,
[
{
"id": 4,
"platform_logo": {
"id": 2,
"url": "//images.igdb.com/example.png",
},
}
],
)
]
assert await service.platform_discovery(4) == {
"url_logo": "//images.igdb.com/example.png"
}
@pytest.mark.parametrize("version", [False, True])
async def test_platform_launch_uses_earliest_regional_year(
self, igdb_server, version
):
fake, service, _ = igdb_server
endpoint = "platform_versions" if version else "platforms"
dates = {
"id": 1,
"platform_version_release_dates": [
{"id": 1, "y": 1996},
{"id": 2, "y": 1997},
{"id": 3},
],
}
data = (
[dates]
if version
else [
{
"id": 4,
"versions": [
dates,
{
"id": 2,
"platform_version_release_dates": [{"id": 4, "y": 2000}],
},
],
}
]
)
fake.replies[endpoint] = [(200, data)]
assert await service.platform_discovery(4, version=version) == {
"first_release_year": 1996
}
[request] = fake.endpoint(endpoint)
prefix = "" if version else "versions."
assert (
await request.text()
== f"fields platform_logo.url,{prefix}platform_version_release_dates.y; where id=4; limit 1;"
)
@pytest.mark.parametrize(
"data",
[
[],
[{"id": 4}],
[
{
"id": 4,
"versions": [
{
"id": 1,
"platform_version_release_dates": [
{"id": 1, "y": 0},
{"id": 2},
],
},
2,
],
}
],
],
)
async def test_missing_platform_dates_stay_unknown(self, igdb_server, data):
fake, service, _ = igdb_server
fake.replies["platforms"] = [(200, data)]
assert await service.platform_discovery(4) == {}
async def test_sends_an_apicalypse_query_with_credentials(
self, igdb_server: tuple[ScriptedServer, IGDBService, MagicMock]
):

View File

@@ -42,6 +42,7 @@ def test_rescan_preserves_user_authored_fields(platform):
{
"custom_name": "Sega - Genesis/ Mega Drive (Unofficial)",
"description": "Aftermarket only",
"first_release_year": 1996,
},
)
@@ -58,6 +59,7 @@ def test_rescan_preserves_user_authored_fields(platform):
assert merged.custom_name == "Sega - Genesis/ Mega Drive (Unofficial)"
assert merged.description == "Aftermarket only"
assert merged.first_release_year == 1996
def _pegi(rating: str) -> dict[str, list[dict[str, str]]]:

View File

@@ -281,7 +281,7 @@ class TestFSResourcesHandler:
mock_image.resize.assert_called_once_with((expected_width, expected_height))
mock_image.save.assert_called_once_with(save_path)
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "WEBP"])
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "WEBP", "AVIF"])
def test_resize_cover_to_small_keeps_animation(
self, handler: FSResourcesHandler, tmp_path: Path, fmt: str
):
@@ -311,6 +311,7 @@ class TestFSResourcesHandler:
"fmt, source_params",
[
("GIF", {"disposal": 2}),
("AVIF", {}),
("PNG", {"blend": [Blend.OP_OVER, Blend.OP_SOURCE, Blend.OP_SOURCE]}),
],
)

View File

@@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import httpx2
import pytest
import pytest_asyncio
from fastapi import HTTPException
import config
from adapters.services.igdb import (
@@ -52,6 +53,69 @@ from utils.platform_slugs import UniversalPlatformSlug as UPS
GENESIS_IGDB_ID = 29
@pytest.mark.parametrize("slug, version", [("n64", False), ("zx-spectrum", True)])
async def test_platform_launch_year_targets_platform_or_revision(slug, version):
handler = IGDBHandler()
with (
patch.object(handler, "is_enabled", return_value=True),
patch.object(
handler.igdb_service,
"platform_discovery",
new_callable=AsyncMock,
return_value={"first_release_year": 1996},
) as lookup,
):
assert await handler.get_platform_discovery(slug) == {
"first_release_year": 1996
}
assert lookup.await_args is not None
assert lookup.await_args.kwargs == {"version": version}
async def test_platform_launch_year_disabled_does_not_contact_igdb():
handler = IGDBHandler()
with (
patch.object(handler, "is_enabled", return_value=False),
patch.object(
handler.igdb_service, "platform_discovery", new_callable=AsyncMock
) as lookup,
):
assert await handler.get_platform_discovery("n64") == {}
lookup.assert_not_awaited()
async def test_platform_launch_year_failure_does_not_abort_scan():
handler = IGDBHandler()
with (
patch.object(handler, "is_enabled", return_value=True),
patch.object(
handler.igdb_service,
"platform_discovery",
new_callable=AsyncMock,
side_effect=HTTPException(status_code=503),
),
):
assert await handler.get_platform_discovery("n64") == {}
async def test_platform_discovery_preserves_logo_transparency():
handler = IGDBHandler()
with (
patch.object(handler, "is_enabled", return_value=True),
patch.object(
handler.igdb_service,
"platform_discovery",
new_callable=AsyncMock,
return_value={
"url_logo": "//images.igdb.com/igdb/image/upload/t_thumb/example.jpg"
},
),
):
assert await handler.get_platform_discovery("n64") == {
"url_logo": "https://images.igdb.com/igdb/image/upload/t_720p/example.png"
}
def _make_game(
game_id: int,
name: str,

View File

@@ -48,14 +48,21 @@ from utils.context import initialize_context
@pytest.mark.vcr
async def test_scan_platform():
async with initialize_context():
platform = await scan_platform("n64", ["n64"])
with patch.object(
meta_igdb_handler,
"get_platform_discovery",
new_callable=AsyncMock,
return_value={"first_release_year": 1996},
):
async with initialize_context():
platform = await scan_platform("n64", ["n64"])
assert type(platform) is Platform
assert platform.fs_slug == "n64"
assert platform.slug == "n64"
assert platform.name == "Nintendo 64"
assert platform.igdb_id == 4
assert platform.first_release_year == 1996
assert platform.hasheous_id == 64
# Hasheous returns tgdb_id=None and Moby has no tgdb_id for n64, so
# this value must come from the TGDB handler fallback.

View File

@@ -32,7 +32,7 @@ class TestImageConverter:
with Image.open(tmp_path / "big.webp") as img:
assert img.format == "WEBP"
@pytest.mark.parametrize("fmt", ["GIF", "PNG"])
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "AVIF"])
def test_keeps_animation(self, converter: ImageConverter, tmp_path: Path, fmt: str):
source = tmp_path / f"big.{fmt.lower()}"
source.write_bytes(animated_image_bytes(fmt))

View File

@@ -65,7 +65,7 @@ def growing_canvas_gif() -> bytes:
class TestIsAnimated:
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "WEBP"])
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "WEBP", "AVIF"])
def test_multi_frame_image(self, fmt: str):
with Image.open(BytesIO(animated_image_bytes(fmt))) as img:
assert is_animated(img)
@@ -93,7 +93,7 @@ class TestIsAnimated:
class TestFrameDurations:
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "WEBP"])
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "WEBP", "AVIF"])
def test_reads_each_frame(self, fmt: str):
with Image.open(BytesIO(animated_image_bytes(fmt))) as img:
assert frame_durations(img) == DURATIONS

View File

@@ -5,7 +5,7 @@ from PIL import Image, ImageSequence
import utils.jxl # noqa: F401 # registers the size-checked JPEG XL decoder
# Multi-frame formats browsers play as animations (MPO/TIFF pages are not)
ANIMATED_FORMATS = frozenset({"GIF", "PNG", "WEBP"})
ANIMATED_FORMATS = frozenset({"GIF", "PNG", "WEBP", "AVIF"})
# Pixels decoded across all frames past which an animation keeps only its
# first frame, since re-encoding one holds every frame in memory.

View File

@@ -26,6 +26,7 @@ export type PlatformSchema = {
flashpoint_id?: (number | null);
category?: (string | null);
generation?: (number | null);
first_release_year?: (number | null);
family_name?: (string | null);
family_slug?: (string | null);
url?: (string | null);

View File

@@ -1,6 +1,6 @@
import { mount } from "@vue/test-utils";
import { describe, expect, it, vi } from "vitest";
import { defineComponent } from "vue";
import { defineComponent, ref } from "vue";
import PlatformTile from "./PlatformTile.vue";
vi.mock("vue-i18n");
@@ -16,9 +16,9 @@ vi.mock("@/components/shared/PlatformIcon.vue", () => ({
vi.mock("@/composables/usePlatformPlayable", () => ({
usePlatformPlayable: () => ({
emulator: { value: null },
mode: { value: null },
streamLabel: { value: null },
emulator: ref(null),
mode: ref(null),
streamLabel: ref(null),
}),
}));
@@ -28,9 +28,67 @@ describe("PlatformTile", () => {
it("marks its root as a spatial-nav cell", () => {
const wrapper = mount(PlatformTile, {
props: { slug: "snes", displayName: "SNES", id: 1, variant: "grid" },
global: { stubs: { RouterLink: true } },
global: { stubs: { RouterLink: { template: "<a><slot /></a>" } } },
});
expect(wrapper.find(".plat-tile").exists()).toBe(true);
});
it("shows discovery metadata and falls back when artwork fails", async () => {
const wrapper = mount(PlatformTile, {
props: {
slug: "unlisted-platform",
displayName: "SNES",
id: 1,
variant: "grid",
category: "portable_console",
firstReleaseYear: 1990,
artworkUrl: "/hardware.png",
romCount: 42,
},
global: { stubs: { RouterLink: { template: "<a><slot /></a>" } } },
});
expect(wrapper.text()).toContain("1990 · Portable Console");
expect(wrapper.find("img").attributes("src")).toBe("/hardware.png");
await wrapper.find("img").trigger("error");
expect(wrapper.find("img").exists()).toBe(false);
expect(wrapper.find(".plat-tile__icon-inner i").exists()).toBe(true);
});
it("keeps dashboard rows compact and omits unavailable metadata", () => {
const wrapper = mount(PlatformTile, {
props: {
slug: "unlisted-platform",
displayName: "SNES",
artworkUrl: "/hardware.png",
firstReleaseYear: 1990,
category: "console",
},
global: { stubs: { RouterLink: { template: "<a><slot /></a>" } } },
});
expect(wrapper.find("img").exists()).toBe(false);
expect(wrapper.find(".plat-tile__metadata").exists()).toBe(false);
});
it("omits metadata when the platform is unidentified", () => {
const wrapper = mount(PlatformTile, {
props: { slug: "custom", displayName: "My platform", variant: "grid" },
global: { stubs: { RouterLink: { template: "<a><slot /></a>" } } },
});
expect(wrapper.find(".plat-tile__metadata").exists()).toBe(false);
expect(wrapper.text()).toBe("My platform");
});
it("prefers curated platform icons over provider variant logos", () => {
const wrapper = mount(PlatformTile, {
props: {
slug: "n64",
displayName: "Nintendo 64",
variant: "grid",
artworkUrl: "/variant.png",
},
global: { stubs: { RouterLink: { template: "<a><slot /></a>" } } },
});
expect(wrapper.find(".r-image").exists()).toBe(false);
});
});

View File

@@ -5,13 +5,17 @@
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { prettifyPlatformCategory } from "@/components/Platforms/platformListColumns";
import PlatformIcon from "@/components/shared/PlatformIcon.vue";
import Tile from "@/components/shared/Tile.vue";
import { useBreakpoint } from "@/composables/useBreakpoint";
import { usePlatformPlayable } from "@/composables/usePlatformPlayable";
import {
pendingMorphName,
useViewTransition,
} from "@/composables/useViewTransition";
import { RImage } from "@/lib";
import { shippedPlatformIconUrl } from "@/utils/platformIcons";
import PlayModeBadge from "./PlayModeBadge.vue";
defineOptions({ inheritAttrs: false });
@@ -25,6 +29,9 @@ interface Props {
fsSlug?: string | undefined;
displayName: string;
romCount?: number | null;
artworkUrl?: string | null | undefined;
category?: string | null | undefined;
firstReleaseYear?: number | null | undefined;
/** Override destination; otherwise derived from `id`. */
to?: string | object | undefined;
id?: number | string | undefined;
@@ -34,12 +41,33 @@ interface Props {
const props = withDefaults(defineProps<Props>(), {
fsSlug: undefined,
romCount: null,
artworkUrl: null,
category: null,
firstReleaseYear: null,
to: undefined,
id: undefined,
variant: "row",
});
const useProviderArtwork = computed(
() =>
props.variant === "grid" &&
props.artworkUrl &&
!shippedPlatformIconUrl(props.slug) &&
!(props.fsSlug && shippedPlatformIconUrl(props.fsSlug)),
);
const href = computed(() => props.to ?? `/platform/${props.id ?? ""}`);
const { xs } = useBreakpoint();
const artworkSize = computed(() => (xs.value ? 88 : 120));
const discoveryMetadata = computed(() =>
[
props.firstReleaseYear,
props.category && prettifyPlatformCategory(props.category),
]
.filter(Boolean)
.join(" · "),
);
const { t } = useI18n();
@@ -81,17 +109,46 @@ const { emulator, mode, streamLabel } = usePlatformPlayable(() => props.slug);
:to="href"
v-bind="$attrs"
class="plat-tile"
:class="{ 'plat-tile--discovery': variant === 'grid' }"
:row="variant === 'row'"
:focus-key="id != null ? `platform-${id}` : undefined"
@click="onTileClick"
>
<template #icon>
<div ref="iconEl" class="plat-tile__icon-inner" :style="morphStyle">
<RImage
v-if="useProviderArtwork"
:src="artworkUrl ?? undefined"
:alt="displayName"
:width="artworkSize"
:height="artworkSize"
contain
>
<template #loading>
<PlatformIcon
:slug="slug"
:fs-slug="fsSlug"
:alt="displayName"
:size="72"
:show-tooltip="false"
/>
</template>
<template #error>
<PlatformIcon
:slug="slug"
:fs-slug="fsSlug"
:alt="displayName"
:size="72"
:show-tooltip="false"
/>
</template>
</RImage>
<PlatformIcon
v-else
:slug="slug"
:fs-slug="fsSlug"
:alt="displayName"
size="100%"
:size="variant === 'grid' ? artworkSize : '100%'"
:show-tooltip="false"
/>
</div>
@@ -106,16 +163,55 @@ const { emulator, mode, streamLabel } = usePlatformPlayable(() => props.slug);
/>
</template>
{{ displayName }}
<template v-if="romCount != null" #count>
{{ t("collection.games-count", romCount, { named: { n: romCount } }) }}
<template
v-if="romCount != null || (variant === 'grid' && discoveryMetadata)"
#count
>
<span
v-if="variant === 'grid' && discoveryMetadata"
class="plat-tile__metadata"
>{{ discoveryMetadata }}</span
>
<span v-if="romCount != null">{{
t("collection.games-count", romCount, { named: { n: romCount } })
}}</span>
</template>
</Tile>
</template>
<style scoped>
.plat-tile--discovery :deep(.r-tile__icon) {
width: 100%;
height: 120px;
overflow: hidden;
}
.plat-tile--discovery .plat-tile__icon-inner {
height: 120px;
}
.plat-tile--discovery :deep(.r-tile__count) {
display: grid;
gap: var(--r-space-2);
margin-top: auto;
text-align: center;
}
.plat-tile__metadata {
color: var(--r-color-fg-secondary);
}
html[data-bp~="xs"] .plat-tile--discovery :deep(.r-tile__icon),
html[data-bp~="xs"] .plat-tile--discovery .plat-tile__icon-inner {
width: 100%;
height: 88px;
}
.plat-tile__icon-inner {
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
display: grid;
place-items: center;
}

View File

@@ -734,6 +734,9 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
:fs-slug="p.fs_slug"
:display-name="p.display_name"
:rom-count="p.rom_count"
:artwork-url="p.url_logo"
:category="p.category"
:first-release-year="p.first_release_year"
variant="grid"
/>
</div>
@@ -752,6 +755,9 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
:fs-slug="p.fs_slug"
:display-name="p.display_name"
:rom-count="p.rom_count"
:artwork-url="p.url_logo"
:category="p.category"
:first-release-year="p.first_release_year"
variant="grid"
/>
</div>
@@ -768,7 +774,7 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
.r-pidx__grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 16px;
}
@@ -791,7 +797,7 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
}
html[data-bp~="xs"] .r-pidx__grid {
grid-template-columns: repeat(auto-fill, minmax(88px, 1fr));
grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
gap: 10px;
}
</style>