refactor(metadata): share the indexed filename lookup across IGDB, Moby and SS (#5130)

This commit is contained in:
Sam Dornan
2026-10-04 16:01:25 -04:00
committed by GitHub
parent c1c3058499
commit 858fd64f7f
5 changed files with 232 additions and 182 deletions

View File

@@ -2,6 +2,8 @@ import abc
import json
import re
import unicodedata
from collections.abc import Collection
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING, Any, Final, Mapping, NotRequired, TypedDict, cast
@@ -79,6 +81,25 @@ class BaseRom(TypedDict):
url_manual: NotRequired[str]
@dataclass(frozen=True, slots=True)
class IndexedFormatPlatforms:
"""A provider's ids for the platforms whose filenames resolve through a local index."""
ps1: int
ps2: int
psp: int
switch: int
arcade: Collection[int]
scummvm: int | None = None
def _fill_from_switch_entry(fallback_rom: BaseRom, index_entry: dict[str, Any]) -> None:
fallback_rom["name"] = index_entry["name"]
fallback_rom["summary"] = index_entry.get("description", "")
fallback_rom["url_cover"] = index_entry.get("iconUrl", "")
fallback_rom["url_screenshots"] = index_entry.get("screenshots", None) or []
class CoverResource(TypedDict):
"""One piece of artwork the manual cover search offers, in the shape
SteamGridDB grids have, so every provider fills the same picker."""
@@ -237,6 +258,66 @@ class MetadataHandler(abc.ABC):
return None, 0.0
async def _resolve_indexed_title(
self,
rom: "Rom",
fs_name: str,
search_term: str,
platform_id: int,
platforms: IndexedFormatPlatforms,
fallback_rom: BaseRom,
) -> str:
"""Swap a serial, title id or short name in the filename for the title its index holds.
Args:
fallback_rom: Filled with what the index knows, for when the provider finds no match.
Returns:
The term to search the provider for.
"""
match = PS2_OPL_REGEX.match(fs_name)
if platform_id == platforms.ps2 and match:
search_term = await self._ps2_opl_format(match, search_term)
fallback_rom["name"] = search_term
match = SONY_SERIAL_REGEX.search(fs_name)
if platform_id == platforms.ps1 and match:
search_term = await self._ps1_serial_format(match, search_term)
fallback_rom["name"] = search_term
if platform_id == platforms.ps2 and match:
search_term = await self._ps2_serial_format(match, search_term)
fallback_rom["name"] = search_term
if platform_id == platforms.psp and match:
search_term = await self._psp_serial_format(match, search_term)
fallback_rom["name"] = search_term
if platform_id == platforms.switch:
match = SWITCH_TITLEDB_REGEX.search(fs_name)
if match:
search_term, index_entry = await self._switch_titledb_format(
match, search_term
)
if index_entry:
_fill_from_switch_entry(fallback_rom, index_entry)
search_term, index_entry = await self._switch_productid_format(
rom, fs_name, search_term
)
if index_entry:
_fill_from_switch_entry(fallback_rom, index_entry)
if platform_id in platforms.arcade:
search_term = await self._mame_format(search_term)
fallback_rom["name"] = search_term
if platforms.scummvm is not None and platform_id == platforms.scummvm:
search_term = await self._scummvm_format(search_term)
fallback_rom["name"] = search_term
return search_term
async def _ps2_opl_format(self, match: re.Match[str], search_term: str) -> str:
serial_code = match.group(1)
index_entry = await async_cache.hget(PS2_OPL_KEY, serial_code)

View File

@@ -27,10 +27,8 @@ from utils.context import ctx_httpx_client
from utils.platform_slugs import UniversalPlatformSlug as UPS
from .base_handler import (
PS2_OPL_REGEX,
SONY_SERIAL_REGEX,
SWITCH_TITLEDB_REGEX,
BaseRom,
IndexedFormatPlatforms,
MetadataHandler,
)
@@ -43,6 +41,14 @@ ARCADE_IGDB_IDS: Final = [
IGDB_PLATFORM_LIST[UPS.NEOGEOAES]["id"],
IGDB_PLATFORM_LIST[UPS.NEOGEOMVS]["id"],
]
IGDB_INDEXED_FORMAT_PLATFORMS: Final = IndexedFormatPlatforms(
ps1=PS1_IGDB_ID,
ps2=PS2_IGDB_ID,
psp=PSP_IGDB_ID,
switch=SWITCH_IGDB_ID,
arcade=ARCADE_IGDB_IDS,
scummvm=IGDB_PLATFORM_LIST[UPS.SCUMMVM]["id"],
)
# IGDB catalogues a console and its regional twin as two separate platforms.
# A game released in only one region is filed under just one of the pair,
@@ -842,66 +848,14 @@ class IGDBHandler(MetadataHandler):
search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name)
fallback_rom = IGDBRom(igdb_id=None)
# Support for PS2 OPL filename format
match = PS2_OPL_REGEX.match(fs_name)
if platform_igdb_id == PS2_IGDB_ID and match:
search_term = await self._ps2_opl_format(match, search_term)
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
# Support for sony serial filename format (PS, PS2, PSP)
match = SONY_SERIAL_REGEX.search(fs_name)
if platform_igdb_id == PS1_IGDB_ID and match:
search_term = await self._ps1_serial_format(match, search_term)
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
if platform_igdb_id == PS2_IGDB_ID and match:
search_term = await self._ps2_serial_format(match, search_term)
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
if platform_igdb_id == PSP_IGDB_ID and match:
search_term = await self._psp_serial_format(match, search_term)
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
# Support for switch titleID filename format
match = SWITCH_TITLEDB_REGEX.search(fs_name)
if platform_igdb_id == SWITCH_IGDB_ID and match:
search_term, index_entry = await self._switch_titledb_format(
match, search_term
)
if index_entry:
fallback_rom = IGDBRom(
igdb_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for switch productID filename format
if platform_igdb_id == SWITCH_IGDB_ID:
search_term, index_entry = await self._switch_productid_format(
rom, fs_name, search_term
)
if index_entry:
fallback_rom = IGDBRom(
igdb_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for MAME arcade filename format
if platform_igdb_id in ARCADE_IGDB_IDS:
search_term = await self._mame_format(search_term)
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
# Support for ScummVM filename format
scummvm_platform = self.get_platform(UPS.SCUMMVM)
if platform_igdb_id == scummvm_platform.get("igdb_id"):
search_term = await self._scummvm_format(search_term)
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
search_term = await self._resolve_indexed_title(
rom,
fs_name,
search_term,
platform_igdb_id,
IGDB_INDEXED_FORMAT_PLATFORMS,
fallback_rom,
)
search_term = self.normalize_search_term(search_term)

View File

@@ -12,10 +12,8 @@ from models.rom import Rom
from utils.platform_slugs import UniversalPlatformSlug as UPS
from .base_handler import (
PS2_OPL_REGEX,
SONY_SERIAL_REGEX,
SWITCH_TITLEDB_REGEX,
BaseRom,
IndexedFormatPlatforms,
MetadataHandler,
)
@@ -24,6 +22,13 @@ PS2_MOBY_ID: Final = 7
PSP_MOBY_ID: Final = 46
SWITCH_MOBY_ID: Final = 203
ARCADE_MOBY_IDS: Final = [143, 36]
MOBY_INDEXED_FORMAT_PLATFORMS: Final = IndexedFormatPlatforms(
ps1=PS1_MOBY_ID,
ps2=PS2_MOBY_ID,
psp=PSP_MOBY_ID,
switch=SWITCH_MOBY_ID,
arcade=ARCADE_MOBY_IDS,
)
# Regex to detect MobyGames ID tags in filenames like (moby-12345)
MOBYGAMES_TAG_REGEX = re.compile(r"\(moby-(\d+)\)", re.IGNORECASE)
@@ -180,60 +185,14 @@ class MobyGamesHandler(MetadataHandler):
search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name)
fallback_rom = MobyGamesRom(moby_id=None)
# Support for PS2 OPL filename format
match = PS2_OPL_REGEX.match(fs_name)
if platform_moby_id == PS2_MOBY_ID and match:
search_term = await self._ps2_opl_format(match, search_term)
fallback_rom = MobyGamesRom(moby_id=None, name=search_term)
# Support for sony serial filename format (PS, PS3, PS3)
match = SONY_SERIAL_REGEX.search(fs_name)
if platform_moby_id == PS1_MOBY_ID and match:
search_term = await self._ps1_serial_format(match, search_term)
fallback_rom = MobyGamesRom(moby_id=None, name=search_term)
if platform_moby_id == PS2_MOBY_ID and match:
search_term = await self._ps2_serial_format(match, search_term)
fallback_rom = MobyGamesRom(moby_id=None, name=search_term)
if platform_moby_id == PSP_MOBY_ID and match:
search_term = await self._psp_serial_format(match, search_term)
fallback_rom = MobyGamesRom(moby_id=None, name=search_term)
# Support for switch titleID filename format
match = SWITCH_TITLEDB_REGEX.search(fs_name)
if platform_moby_id == SWITCH_MOBY_ID and match:
search_term, index_entry = await self._switch_titledb_format(
match, search_term
)
if index_entry:
fallback_rom = MobyGamesRom(
moby_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for switch productID filename format
if platform_moby_id == SWITCH_MOBY_ID:
search_term, index_entry = await self._switch_productid_format(
rom, fs_name, search_term
)
if index_entry:
fallback_rom = MobyGamesRom(
moby_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for MAME arcade filename format
if platform_moby_id in ARCADE_MOBY_IDS:
search_term = await self._mame_format(search_term)
fallback_rom = MobyGamesRom(moby_id=None, name=search_term)
search_term = await self._resolve_indexed_title(
rom,
fs_name,
search_term,
platform_moby_id,
MOBY_INDEXED_FORMAT_PLATFORMS,
fallback_rom,
)
normalized_search_term = self.normalize_search_term(
search_term, remove_punctuation=False

View File

@@ -45,10 +45,8 @@ from utils.datetime import parse_utc_timestamp
from utils.platform_slugs import UniversalPlatformSlug as UPS
from .base_handler import (
PS2_OPL_REGEX,
SONY_SERIAL_REGEX,
SWITCH_TITLEDB_REGEX,
BaseRom,
IndexedFormatPlatforms,
MetadataHandler,
restore_sensitive_query_params,
strip_sensitive_query_params,
@@ -1067,65 +1065,14 @@ class SSHandler(MetadataHandler):
if not search_term:
return fallback_rom
# Support for PS2 OPL filename format
match = PS2_OPL_REGEX.match(file_name)
if platform_ss_id == PS2_SS_ID and match:
search_term = await self._ps2_opl_format(match, search_term)
fallback_rom = SSRom(ss_id=None, name=search_term)
# Support for sony serial filename format (PS, PS3, PS3)
match = SONY_SERIAL_REGEX.search(file_name)
if platform_ss_id == PS1_SS_ID and match:
search_term = await self._ps1_serial_format(match, search_term)
fallback_rom = SSRom(ss_id=None, name=search_term)
if platform_ss_id == PS2_SS_ID and match:
search_term = await self._ps2_serial_format(match, search_term)
fallback_rom = SSRom(ss_id=None, name=search_term)
if platform_ss_id == PSP_SS_ID and match:
search_term = await self._psp_serial_format(match, search_term)
fallback_rom = SSRom(ss_id=None, name=search_term)
# Support for switch titleID filename format
match = SWITCH_TITLEDB_REGEX.search(file_name)
if platform_ss_id == SWITCH_SS_ID and match:
search_term, index_entry = await self._switch_titledb_format(
match, search_term
)
if index_entry:
fallback_rom = SSRom(
ss_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for switch productID filename format
if platform_ss_id == SWITCH_SS_ID:
search_term, index_entry = await self._switch_productid_format(
rom, file_name, search_term
)
if index_entry:
fallback_rom = SSRom(
ss_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for MAME arcade filename format
if platform_ss_id in ARCADES_SS_IDS:
search_term = await self._mame_format(search_term)
fallback_rom = SSRom(ss_id=None, name=search_term)
# Support for ScummVM filename format
scummvm_platform = self.get_platform(UPS.SCUMMVM)
if platform_ss_id == scummvm_platform.get("ss_id"):
search_term = await self._scummvm_format(search_term)
fallback_rom = SSRom(ss_id=None, name=search_term)
search_term = await self._resolve_indexed_title(
rom,
file_name,
search_term,
platform_ss_id,
SS_INDEXED_FORMAT_PLATFORMS,
fallback_rom,
)
## SS API requires punctuation to match
normalized_search_term = self.normalize_search_term(
@@ -1421,5 +1368,14 @@ SCREENSAVER_PLATFORM_LIST: dict[UPS, SlugToSSId] = {
UPS.ZX81: {"id": 77, "name": "ZX81"},
}
SS_INDEXED_FORMAT_PLATFORMS: Final = IndexedFormatPlatforms(
ps1=PS1_SS_ID,
ps2=PS2_SS_ID,
psp=PSP_SS_ID,
switch=SWITCH_SS_ID,
arcade=ARCADES_SS_IDS,
scummvm=SCREENSAVER_PLATFORM_LIST[UPS.SCUMMVM]["id"],
)
# Reverse lookup
SS_ID_TO_SLUG = {v["id"]: k for k, v in SCREENSAVER_PLATFORM_LIST.items()}

View File

@@ -23,6 +23,7 @@ from handler.metadata.base_handler import (
SWITCH_PRODUCT_ID_REGEX,
SWITCH_TITLEDB_REGEX,
BaseRom,
IndexedFormatPlatforms,
MetadataHandler,
_normalize_search_term,
restore_sensitive_query_params,
@@ -479,6 +480,105 @@ class TestMetadataHandlerMethods:
assert result["api_key"] == "ab***ab" # Shows first 2 and last 2
class TestResolveIndexedTitle:
PLATFORMS = IndexedFormatPlatforms(
ps1=1, ps2=2, psp=3, switch=4, arcade=(5, 6), scummvm=7
)
@pytest.fixture
def handler(self) -> MetadataHandler:
return ExampleMetadataHandler()
async def _resolve(
self,
handler: MetadataHandler,
fs_name: str,
platform_id: int,
platforms: IndexedFormatPlatforms = PLATFORMS,
) -> tuple[str, BaseRom]:
fallback_rom = BaseRom()
term = await handler._resolve_indexed_title(
Rom(fs_name=fs_name),
fs_name,
"original",
platform_id,
platforms,
fallback_rom,
)
return term, fallback_rom
@pytest.mark.parametrize(
("fs_name", "platform_id", "method"),
[
("SLUS_200.62.Grand Theft Auto.iso", 2, "_ps2_opl_format"),
("Crash [SCUS-94900].bin", 1, "_ps1_serial_format"),
("Ridge Racer [SLUS-01234].iso", 2, "_ps2_serial_format"),
("Lumines [ULUS-10046].iso", 3, "_psp_serial_format"),
("pacman.zip", 6, "_mame_format"),
("monkey1.scummvm", 7, "_scummvm_format"),
],
)
@pytest.mark.asyncio
async def test_named_index_sets_term_and_fallback_name(
self, handler: MetadataHandler, fs_name: str, platform_id: int, method: str
):
with patch.object(handler, method, AsyncMock(return_value="Indexed Title")):
term, fallback_rom = await self._resolve(handler, fs_name, platform_id)
assert term == "Indexed Title"
assert fallback_rom == BaseRom(name="Indexed Title")
@pytest.mark.asyncio
async def test_switch_entry_fills_the_fallback(self, handler: MetadataHandler):
entry = {
"name": "Celeste",
"description": "Climb",
"iconUrl": "https://example.com/icon.png",
"screenshots": None,
}
with (
patch.object(
handler,
"_switch_titledb_format",
AsyncMock(return_value=("Celeste", entry)),
),
patch.object(
handler,
"_switch_productid_format",
AsyncMock(return_value=("Celeste", None)),
),
):
term, fallback_rom = await self._resolve(
handler, "Celeste [70010000000025].nsp", 4
)
assert term == "Celeste"
assert fallback_rom == BaseRom(
name="Celeste",
summary="Climb",
url_cover="https://example.com/icon.png",
url_screenshots=[],
)
@pytest.mark.asyncio
async def test_other_platform_is_left_alone(self, handler: MetadataHandler):
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
term, fallback_rom = await self._resolve(handler, "SLUS-12345.bin", 99)
mock_hget.assert_not_called()
assert term == "original"
assert fallback_rom == BaseRom()
@pytest.mark.asyncio
async def test_provider_without_scummvm_skips_it(self, handler: MetadataHandler):
platforms = IndexedFormatPlatforms(ps1=1, ps2=2, psp=3, switch=4, arcade=())
with patch.object(handler, "_scummvm_format", new_callable=AsyncMock) as fmt:
term, _ = await self._resolve(handler, "monkey1", 7, platforms)
fmt.assert_not_called()
assert term == "original"
class TestStripSensitiveQueryParams:
"""Test the strip_sensitive_query_params function."""