diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index f80d83eb7..f2dc2c416 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -120,6 +120,7 @@ from handler.metadata.ss_handler import ( from handler.recommendation import similar_roms from handler.rom_conversion import promote_single_file_to_folder from handler.scan_handler import ( + RESCAN_RULES, MetadataSource, ScanType, build_hashless_fs_rom, @@ -1947,34 +1948,53 @@ def _ra_miss(rom: Rom) -> dict[str, Any]: class _MatchRefetch: """How an edit that changes one provider's id pulls that provider's metadata.""" - id_field: str + source: MetadataSource fetch: Callable[[Rom, Any], Awaitable[Mapping[str, object]]] on_miss: Callable[[Rom], dict[str, Any]] = lambda _rom: {} @property - def metadata_field(self) -> str: - return self.id_field.removesuffix("_id") + "_metadata" + def id_field(self) -> str: + return RESCAN_RULES[self.source].id_field + + @property + def metadata_field(self) -> str | None: + return RESCAN_RULES[self.source].metadata_field # Applied in order, so a later provider's name, summary or cover wins. _MATCH_REFETCHES: Final = ( _MatchRefetch( - "flashpoint_id", lambda _rom, i: meta_flashpoint_handler.get_rom_by_id(i) + MetadataSource.FLASHPOINT, + lambda _rom, i: meta_flashpoint_handler.get_rom_by_id(i), ), - _MatchRefetch("launchbox_id", _refetch_launchbox), + _MatchRefetch(MetadataSource.LAUNCHBOX, _refetch_launchbox), _MatchRefetch( - "ra_id", + MetadataSource.RA, lambda rom, i: meta_ra_handler.get_rom_by_id(rom, ra_id=i, ra_hash=rom.ra_hash), on_miss=_ra_miss, ), - _MatchRefetch("moby_id", lambda _rom, i: meta_moby_handler.get_rom_by_id(i)), - _MatchRefetch("ss_id", _refetch_ss), - _MatchRefetch("steam_id", lambda _rom, i: meta_steam_handler.get_rom_by_id(i)), - _MatchRefetch("igdb_id", lambda rom, i: meta_igdb_handler.get_rom_by_id(rom, i)), - _MatchRefetch("demozoo_id", lambda _rom, i: meta_demozoo_handler.get_rom_by_id(i)), - _MatchRefetch("pouet_id", lambda _rom, i: meta_pouet_handler.get_rom_by_id(i)), - _MatchRefetch("csdb_id", lambda _rom, i: meta_csdb_handler.get_rom_by_id(i)), - _MatchRefetch("hltb_id", lambda _rom, i: meta_hltb_handler.get_rom_by_id(i)), + _MatchRefetch( + MetadataSource.MOBY, lambda _rom, i: meta_moby_handler.get_rom_by_id(i) + ), + _MatchRefetch(MetadataSource.SS, _refetch_ss), + _MatchRefetch( + MetadataSource.STEAM, lambda _rom, i: meta_steam_handler.get_rom_by_id(i) + ), + _MatchRefetch( + MetadataSource.IGDB, lambda rom, i: meta_igdb_handler.get_rom_by_id(rom, i) + ), + _MatchRefetch( + MetadataSource.DEMOZOO, lambda _rom, i: meta_demozoo_handler.get_rom_by_id(i) + ), + _MatchRefetch( + MetadataSource.POUET, lambda _rom, i: meta_pouet_handler.get_rom_by_id(i) + ), + _MatchRefetch( + MetadataSource.CSDB, lambda _rom, i: meta_csdb_handler.get_rom_by_id(i) + ), + _MatchRefetch( + MetadataSource.HLTB, lambda _rom, i: meta_hltb_handler.get_rom_by_id(i) + ), ) @@ -1990,7 +2010,9 @@ async def _refetch_changed_matches(rom: Rom, cleaned_data: dict[str, Any]) -> No fetched if fetched.get(refetch.id_field) else refetch.on_miss(rom) ) elif old_id and not new_id: - cleaned_data.update({refetch.id_field: None, refetch.metadata_field: {}}) + cleaned_data[refetch.id_field] = None + if refetch.metadata_field: + cleaned_data[refetch.metadata_field] = {} @protected_route( diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 8b51f5887..aac6b7496 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -71,6 +71,7 @@ from handler.redis_handler import ( ) from handler.rom_files import loaded_rom_files, refresh_rom_files from handler.scan_handler import ( + RESCAN_RULES, MetadataSource, ScanType, build_hashless_fs_rom, @@ -82,6 +83,7 @@ from handler.scan_handler import ( scan_firmware, scan_platform, scan_rom, + should_consult, ) from handler.scan_jobs import ( get_blocking_library_scans, @@ -374,6 +376,7 @@ async def _identify_firmware( def should_scan_rom( scan_type: ScanType, + platform: Platform, rom: Rom | None, roms_ids: list[int], metadata_sources: list[str], @@ -382,6 +385,7 @@ def should_scan_rom( Args: scan_type (ScanType): Type of scan to be performed. + platform (Platform): The platform the rom belongs to. rom (Rom | None): The rom to be scanned. roms_ids (list[int]): List of selected roms to be scanned. metadata_sources (list[str]): List of metadata sources to be used. @@ -401,26 +405,21 @@ def should_scan_rom( or (scan_type == ScanType.COMPLETE) # Hashes rescan should scan all roms to update the hashes or (scan_type == ScanType.HASHES) + # Update and unmatched scans only pick a rom some selected source will refresh or ( rom - and ( - # Update scan should scan ROMs identified by the selected metadata sources - ( - scan_type == ScanType.UPDATE - and rom.is_identified - and any( - getattr(rom, f"{source}_id", None) - for source in metadata_sources - ) - ) - # Unmatched scan should scan ROMs that are not identified by the selected metadata sources - or ( - scan_type == ScanType.UNMATCHED - and any( - not getattr(rom, f"{source}_id", None) - for source in metadata_sources - ) + and scan_type in (ScanType.UPDATE, ScanType.UNMATCHED) + and any( + should_consult( + MetadataSource(source), + scan_type=scan_type, + rom=rom, + platform=platform, + newly_added=False, + metadata_sources=metadata_sources, ) + for source in metadata_sources + if source in RESCAN_RULES ) ) ) @@ -1103,6 +1102,7 @@ async def _identify_platform( restored_roms.append(rom) if should_scan_rom( scan_type=scan_type, + platform=platform, rom=rom, roms_ids=roms_ids, metadata_sources=metadata_sources, diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 2a509304f..c27fd8574 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -1,7 +1,8 @@ import asyncio import enum import functools -from collections.abc import Callable, Mapping +from collections.abc import Callable, Collection, Mapping +from dataclasses import dataclass from typing import Any, Final, NotRequired, TypedDict import socketio @@ -152,6 +153,142 @@ PROVIDER_ALL_TAG_FIELDS = PROVIDER_TAG_FIELDS + PROVIDER_MERGED_TAG_FIELDS DUMP_TAG_KEYS = {field: f"dump_{field}" for field in PROVIDER_ALL_TAG_FIELDS} +def _always(_entity: Any) -> bool: + return True + + +@dataclass(frozen=True) +class RescanRule: + """When a scan consults one metadata source for a rom. + + Args: + id_field: the rom column holding the source's match id. + metadata_field: the column an unmatched scan must find filled, or None + when the id alone counts as a match. + platform_supported: whether the source covers the platform at all. + unmatched_supported: an extra platform check an unmatched scan makes. + on_hashes: whether a hash scan consults the source. + """ + + id_field: str + metadata_field: str | None + platform_supported: Callable[[Platform], Any] = _always + unmatched_supported: Callable[[Platform], Any] = _always + on_hashes: bool = False + + +RESCAN_RULES: Final[Mapping[MetadataSource, RescanRule]] = { + MetadataSource.IGDB: RescanRule( + "igdb_id", + "igdb_metadata", + platform_supported=lambda p: p.igdb_id, + unmatched_supported=lambda p: meta_igdb_handler.get_platform(p.slug)["igdb_id"], + ), + MetadataSource.MOBY: RescanRule( + "moby_id", + "moby_metadata", + platform_supported=lambda p: p.moby_id, + unmatched_supported=lambda p: p.slug in MOBYGAMES_PLATFORM_LIST, + ), + MetadataSource.SS: RescanRule( + "ss_id", + "ss_metadata", + platform_supported=lambda p: p.ss_id, + unmatched_supported=lambda p: p.slug in SCREENSAVER_PLATFORM_LIST, + ), + MetadataSource.RA: RescanRule( + "ra_id", + "ra_metadata", + platform_supported=lambda p: p.ra_id, + unmatched_supported=lambda p: p.slug in RA_PLATFORM_LIST, + on_hashes=True, + ), + MetadataSource.LAUNCHBOX: RescanRule( + "launchbox_id", + "launchbox_metadata", + unmatched_supported=lambda p: p.slug in LAUNCHBOX_PLATFORM_LIST, + ), + MetadataSource.HASHEOUS: RescanRule( + "hasheous_id", + "hasheous_metadata", + platform_supported=lambda p: p.hasheous_id, + unmatched_supported=lambda p: p.slug in HASHEOUS_PLATFORM_LIST, + on_hashes=True, + ), + MetadataSource.SGDB: RescanRule("sgdb_id", None), + MetadataSource.FLASHPOINT: RescanRule( + "flashpoint_id", + "flashpoint_metadata", + platform_supported=lambda p: p.slug in FLASHPOINT_PLATFORM_LIST, + ), + MetadataSource.HLTB: RescanRule( + "hltb_id", + "hltb_metadata", + platform_supported=lambda p: p.slug in HLTB_PLATFORM_LIST, + ), + MetadataSource.DEMOZOO: RescanRule("demozoo_id", "demozoo_metadata"), + MetadataSource.POUET: RescanRule("pouet_id", "pouet_metadata"), + MetadataSource.CSDB: RescanRule("csdb_id", "csdb_metadata"), + MetadataSource.STEAM: RescanRule( + "steam_id", + "steam_metadata", + platform_supported=lambda p: p.slug in STEAM_PLATFORMS, + ), + MetadataSource.GAMELIST: RescanRule("gamelist_id", "gamelist_metadata"), + MetadataSource.LIBRETRO: RescanRule( + "libretro_id", + None, + platform_supported=lambda p: p.slug in LIBRETRO_PLATFORM_LIST, + ), +} + + +def should_consult( + source: MetadataSource, + *, + scan_type: ScanType, + rom: Rom, + platform: Platform, + newly_added: bool, + metadata_sources: Collection[str], +) -> bool: + """Whether a scan asks `source` about `rom`.""" + rule = RESCAN_RULES[source] + if source not in metadata_sources or not rule.platform_supported(platform): + return False + if newly_added or scan_type == ScanType.COMPLETE: + return True + if scan_type == ScanType.HASHES: + return rule.on_hashes + match_id = getattr(rom, rule.id_field) + if scan_type == ScanType.UPDATE: + return bool(match_id) + if scan_type == ScanType.UNMATCHED: + unmatched = not match_id or ( + rule.metadata_field is not None and not getattr(rom, rule.metadata_field) + ) + return bool(unmatched and rule.unmatched_supported(platform)) + return False + + +def stored_match_id(source: MetadataSource, *, scan_type: ScanType, rom: Rom) -> Any: + """The id a refresh refetches `source` by, or None when the scan matches anew.""" + # A stored id is often a manual match, so a refresh never trades it for a guess. + rule = RESCAN_RULES[source] + match_id = getattr(rom, rule.id_field) + if not match_id: + return None + if scan_type == ScanType.UPDATE: + return match_id + if ( + scan_type == ScanType.UNMATCHED + and rule.metadata_field is not None + and not getattr(rom, rule.metadata_field) + ): + return match_id + return None + + def hash_source_tags( fields: dict[str, Any], rom_attrs: dict[str, Any] ) -> tuple[dict[str, list[str]], bool]: @@ -504,18 +641,12 @@ async def resolve_launchbox_rom( remote_enabled: bool, ) -> LaunchboxRom: """Resolve a ROM's LaunchBox match, by ID where one is known, else by filename.""" - # An ID already on the ROM is a decision (often a manual match), so it is - # never traded for a filename guess. - if ( - remote_enabled - and rom.launchbox_id - and ( - scan_type == ScanType.UPDATE - or (scan_type == ScanType.UNMATCHED and not rom.launchbox_metadata) - ) - ): + launchbox_id = stored_match_id( + MetadataSource.LAUNCHBOX, scan_type=scan_type, rom=rom + ) + if remote_enabled and launchbox_id: return await meta_launchbox_handler.get_rom_by_id( - rom.launchbox_id, + launchbox_id, remote_enabled=True, fs_name=fs_name, platform_slug=platform_slug, @@ -557,13 +688,9 @@ async def resolve_steam_rom( scan_type: ScanType, ) -> SteamRom: """Resolve a ROM's Steam match, by app ID where one is known, else by filename.""" - # A stored app ID is often a manual match, so it is never traded for the - # filename search, which can land on any app above the similarity floor. - if rom.steam_id and ( - scan_type == ScanType.UPDATE - or (scan_type == ScanType.UNMATCHED and not rom.steam_metadata) - ): - return await meta_steam_handler.get_rom_by_id(rom.steam_id) + steam_id = stored_match_id(MetadataSource.STEAM, scan_type=scan_type, rom=rom) + if steam_id: + return await meta_steam_handler.get_rom_by_id(steam_id) return await meta_steam_handler.get_rom(fs_name, platform_slug) @@ -694,21 +821,34 @@ async def scan_rom( ) return fallback + # A fetcher that passes the platform's id on repeats that check after this, + # so the id narrows to an int. + def consults(source: MetadataSource) -> bool: + return should_consult( + source, + scan_type=scan_type, + rom=rom, + platform=platform, + newly_added=newly_added, + metadata_sources=metadata_sources, + ) + + def stored_id(source: MetadataSource) -> Any: + return stored_match_id(source, scan_type=scan_type, rom=rom) + @functools.cache def get_match_files() -> list[RomFile]: """Files used for hash-based metadata matching, fetched at most once.""" return fs_rom["files"] or db_rom_handler.rom_files_for_rom_id(rom.id) async def fetch_playmatch_hash_match() -> PlaymatchRomMatch: + # Playmatch's ids only feed other sources, so it runs when one of them will. if ( meta_playmatch_handler.is_enabled() and MetadataSource.PLAYMATCH in metadata_sources - and any(PLAYMATCH_SUPPORTED_SOURCES.intersection(metadata_sources)) - and ( - newly_added - or scan_type == ScanType.COMPLETE - or scan_type == ScanType.UPDATE - or scan_type == ScanType.UNMATCHED + and any( + consults(MetadataSource(source)) + for source in PLAYMATCH_SUPPORTED_SOURCES ) ): return await meta_playmatch_handler.lookup_rom(get_match_files()) @@ -729,21 +869,7 @@ async def scan_rom( ) async def fetch_hasheous_hash_match() -> tuple[HasheousRom, bool]: - if ( - MetadataSource.HASHEOUS in metadata_sources - and platform.hasheous_id - and ( - newly_added - or scan_type == ScanType.COMPLETE - or scan_type == ScanType.HASHES - or (scan_type == ScanType.UPDATE and rom.hasheous_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.hasheous_id or not rom.hasheous_metadata) - and rom.platform_slug in HASHEOUS_PLATFORM_LIST - ) - ) - ): + if consults(MetadataSource.HASHEOUS): match, conclusive = await meta_hasheous_handler.lookup_rom( platform.slug, get_match_files() ) @@ -779,21 +905,12 @@ async def scan_rom( async def fetch_igdb_rom( playmatch_rom: PlaymatchRomMatch, hasheous_rom: HasheousRom ) -> IGDBRom: - if ( - MetadataSource.IGDB in metadata_sources - and platform.igdb_id - and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.igdb_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.igdb_id or not rom.igdb_metadata) - and meta_igdb_handler.get_platform(rom.platform_slug)["igdb_id"] - ) - ) - ): + if consults(MetadataSource.IGDB) and platform.igdb_id: attempted_sources.add(MetadataSource.IGDB) + igdb_id = stored_id(MetadataSource.IGDB) + if igdb_id: + return await meta_igdb_handler.get_rom_by_id(rom, igdb_id) + # Use Hasheous match to get the IGDB ID h_igdb_id = hasheous_rom.get("igdb_id") if h_igdb_id: @@ -816,30 +933,18 @@ async def scan_rom( rom, playmatch_rom["igdb_id"] ) + # If no matches found, use the file name to get the IGDB ID main_platform_igdb_id = get_main_platform_igdb_id(platform) - if scan_type == ScanType.UPDATE and rom.igdb_id: - # Use the ID to refetch the metadata from IGDB - return await meta_igdb_handler.get_rom_by_id(rom, rom.igdb_id) - else: - # If no matches found, use the file name to get the IGDB ID - return await meta_igdb_handler.get_rom( - rom, - rom_attrs["fs_name"], - main_platform_igdb_id or platform.igdb_id, - ) + return await meta_igdb_handler.get_rom( + rom, + rom_attrs["fs_name"], + main_platform_igdb_id or platform.igdb_id, + ) return IGDBRom(igdb_id=None) async def fetch_gamelist_rom() -> GamelistRom: - if MetadataSource.GAMELIST in metadata_sources and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.gamelist_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.gamelist_id or not rom.gamelist_metadata) - ) - ): + if consults(MetadataSource.GAMELIST): attempted_sources.add(MetadataSource.GAMELIST) return await meta_gamelist_handler.get_rom( rom_attrs["fs_name"], platform, rom @@ -848,45 +953,19 @@ async def scan_rom( return GamelistRom(gamelist_id=None) async def fetch_flashpoint_rom() -> FlashpointRom: - if ( - MetadataSource.FLASHPOINT in metadata_sources - and platform.slug in FLASHPOINT_PLATFORM_LIST - and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.flashpoint_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.flashpoint_id or not rom.flashpoint_metadata) - and platform.slug in FLASHPOINT_PLATFORM_LIST - ) - ) - ): + if consults(MetadataSource.FLASHPOINT): attempted_sources.add(MetadataSource.FLASHPOINT) - if (scan_type == ScanType.UPDATE and rom.flashpoint_id) or ( - scan_type == ScanType.UNMATCHED - and rom.flashpoint_id - and not rom.flashpoint_metadata - ): - return await meta_flashpoint_handler.get_rom_by_id(rom.flashpoint_id) - else: - return await meta_flashpoint_handler.get_rom( - rom_attrs["fs_name"], platform.slug - ) + flashpoint_id = stored_id(MetadataSource.FLASHPOINT) + if flashpoint_id: + return await meta_flashpoint_handler.get_rom_by_id(flashpoint_id) + return await meta_flashpoint_handler.get_rom( + rom_attrs["fs_name"], platform.slug + ) return FlashpointRom(flashpoint_id=None) async def fetch_libretro_rom() -> LibretroRom: - if ( - MetadataSource.LIBRETRO in metadata_sources - and platform.slug in LIBRETRO_PLATFORM_LIST - and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.libretro_id) - or (scan_type == ScanType.UNMATCHED and not rom.libretro_id) - ) - ): + if consults(MetadataSource.LIBRETRO): attempted_sources.add(MetadataSource.LIBRETRO) return await meta_libretro_handler.get_rom( rom_attrs["fs_name"], platform.slug @@ -895,58 +974,29 @@ async def scan_rom( return LibretroRom(libretro_id=None) async def fetch_hltb_rom() -> HLTBRom: - if ( - MetadataSource.HLTB in metadata_sources - and platform.slug in HLTB_PLATFORM_LIST - and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.hltb_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.hltb_id or not rom.hltb_metadata) - ) - ) - ): + if consults(MetadataSource.HLTB): attempted_sources.add(MetadataSource.HLTB) - # A refresh keeps the ID already on the ROM, often a manual match, - # rather than trading it for a filename guess. COMPLETE rematches. - if rom.hltb_id and ( - scan_type == ScanType.UPDATE - or (scan_type == ScanType.UNMATCHED and not rom.hltb_metadata) - ): - return await meta_hltb_handler.get_rom_by_id(rom.hltb_id) + hltb_id = stored_id(MetadataSource.HLTB) + if hltb_id: + return await meta_hltb_handler.get_rom_by_id(hltb_id) return await meta_hltb_handler.get_rom(rom_attrs["fs_name"], platform.slug) return HLTBRom(hltb_id=None) async def fetch_demozoo_rom() -> DemozooRom: - if MetadataSource.DEMOZOO in metadata_sources and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.demozoo_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.demozoo_id or not rom.demozoo_metadata) - ) - ): + if consults(MetadataSource.DEMOZOO): attempted_sources.add(MetadataSource.DEMOZOO) + demozoo_id = stored_id(MetadataSource.DEMOZOO) + if demozoo_id: + return await meta_demozoo_handler.get_rom_by_id(demozoo_id) return await meta_demozoo_handler.get_rom( rom_attrs["fs_name"], platform.slug ) return DemozooRom(demozoo_id=None) async def fetch_pouet_rom() -> PouetRom: - if MetadataSource.POUET in metadata_sources and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.pouet_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.pouet_id or not rom.pouet_metadata) - ) - ): + if consults(MetadataSource.POUET): attempted_sources.add(MetadataSource.POUET) if rom.pouet_id: return await meta_pouet_handler.get_rom_by_id(int(rom.pouet_id)) @@ -954,15 +1004,7 @@ async def scan_rom( return PouetRom(pouet_id=None) async def fetch_csdb_rom() -> CsdbRom: - if MetadataSource.CSDB in metadata_sources and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.csdb_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.csdb_id or not rom.csdb_metadata) - ) - ): + if consults(MetadataSource.CSDB): attempted_sources.add(MetadataSource.CSDB) if rom.csdb_id: return await meta_csdb_handler.get_rom_by_id(int(rom.csdb_id)) @@ -970,19 +1012,7 @@ async def scan_rom( return CsdbRom(csdb_id=None) async def fetch_steam_rom() -> SteamRom: - if ( - MetadataSource.STEAM in metadata_sources - and platform.slug in STEAM_PLATFORMS - and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.steam_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.steam_id or not rom.steam_metadata) - ) - ) - ): + if consults(MetadataSource.STEAM): attempted_sources.add(MetadataSource.STEAM) return await resolve_steam_rom( rom=rom, @@ -994,23 +1024,11 @@ async def scan_rom( return SteamRom(steam_id=None) async def fetch_moby_rom(playmatch_rom: PlaymatchRomMatch) -> MobyGamesRom: - if ( - MetadataSource.MOBY in metadata_sources - and platform.moby_id - and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.moby_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.moby_id or not rom.moby_metadata) - and rom.platform_slug in MOBYGAMES_PLATFORM_LIST - ) - ) - ): + if consults(MetadataSource.MOBY) and platform.moby_id: attempted_sources.add(MetadataSource.MOBY) - if scan_type == ScanType.UPDATE and rom.moby_id: - return await meta_moby_handler.get_rom_by_id(rom.moby_id) + moby_id = stored_id(MetadataSource.MOBY) + if moby_id: + return await meta_moby_handler.get_rom_by_id(moby_id) if playmatch_rom["moby_id"] is not None: log.debug( @@ -1027,31 +1045,18 @@ async def scan_rom( return MobyGamesRom(moby_id=None) async def fetch_ss_rom(playmatch_rom: PlaymatchRomMatch) -> SSRom: - if ( - MetadataSource.SS in metadata_sources - and platform.ss_id - and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.ss_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.ss_id or not rom.ss_metadata) - and rom.platform_slug in SCREENSAVER_PLATFORM_LIST - ) - ) - ): + if consults(MetadataSource.SS) and platform.ss_id: attempted_sources.add(MetadataSource.SS) # A breaker answering in ScreenScraper's place rules nothing out for # this rom, whichever of the lookups below it short-circuits. short_circuited = False try: - # Use the ID to refetch metadata - if scan_type == ScanType.UPDATE and rom.ss_id: + ss_id = stored_id(MetadataSource.SS) + if ss_id: # With the files, the refetch still finds our own dump among # the game's, so a rescan keeps the tags the hash earned. return await meta_ss_handler.get_rom_by_id( - rom, rom.ss_id, get_match_files() + rom, ss_id, get_match_files() ) # Use Playmatch's hash-based id when available @@ -1100,16 +1105,7 @@ async def scan_rom( async def fetch_launchbox_rom( platform_slug: str, playmatch_rom: PlaymatchRomMatch ) -> LaunchboxRom: - if MetadataSource.LAUNCHBOX in metadata_sources and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.launchbox_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.launchbox_id or not rom.launchbox_metadata) - and rom.platform_slug in LAUNCHBOX_PLATFORM_LIST - ) - ): + if consults(MetadataSource.LAUNCHBOX): attempted_sources.add(MetadataSource.LAUNCHBOX) launchbox_rom = await resolve_launchbox_rom( rom=rom, @@ -1129,51 +1125,19 @@ async def scan_rom( return LaunchboxRom(launchbox_id=None) async def fetch_ra_rom() -> RAGameRom: - if ( - MetadataSource.RA in metadata_sources - and platform.ra_id - and ( - newly_added - or scan_type == ScanType.COMPLETE - or scan_type == ScanType.HASHES - or (scan_type == ScanType.UPDATE and rom.ra_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.ra_id or not rom.ra_metadata) - and rom.platform_slug in RA_PLATFORM_LIST - ) - ) - ): + if consults(MetadataSource.RA): attempted_sources.add(MetadataSource.RA) - if (scan_type == ScanType.UPDATE and rom.ra_id) or ( - scan_type == ScanType.UNMATCHED and rom.ra_id and not rom.ra_metadata - ): + ra_id = stored_id(MetadataSource.RA) + if ra_id: return await meta_ra_handler.get_rom_by_id( - rom=rom, ra_id=rom.ra_id, ra_hash=rom_attrs["ra_hash"] - ) - else: - return await meta_ra_handler.get_rom( - rom=rom, ra_hash=rom_attrs["ra_hash"] + rom=rom, ra_id=ra_id, ra_hash=rom_attrs["ra_hash"] ) + return await meta_ra_handler.get_rom(rom=rom, ra_hash=rom_attrs["ra_hash"]) return RAGameRom(ra_id=None) async def fetch_hasheous_rom(hasheous_rom: HasheousRom) -> HasheousRom: - if ( - MetadataSource.HASHEOUS in metadata_sources - and platform.hasheous_id - and ( - newly_added - or scan_type == ScanType.COMPLETE - or scan_type == ScanType.HASHES - or (scan_type == ScanType.UPDATE and rom.hasheous_id) - or ( - scan_type == ScanType.UNMATCHED - and (not rom.hasheous_id or not rom.hasheous_metadata) - and rom.platform_slug in HASHEOUS_PLATFORM_LIST - ) - ) - ): + if consults(MetadataSource.HASHEOUS): # The hash lookup is the only thing that identifies a rom here, so one # that never answered leaves a complete rescan nothing to redo. if MetadataSource.HASHEOUS not in inconclusive_sources: @@ -1319,87 +1283,36 @@ async def scan_rom( if merged_csdb: blob["summary"] = merged_csdb + handler_roms: dict[MetadataSource, Any] = { + MetadataSource.IGDB: igdb_handler_rom, + MetadataSource.MOBY: moby_handler_rom, + MetadataSource.SS: ss_handler_rom, + MetadataSource.RA: ra_handler_rom, + MetadataSource.LAUNCHBOX: launchbox_handler_rom, + MetadataSource.HASHEOUS: hasheous_handler_rom, + MetadataSource.FLASHPOINT: flashpoint_handler_rom, + MetadataSource.HLTB: hltb_handler_rom, + MetadataSource.DEMOZOO: demozoo_handler_rom, + MetadataSource.POUET: pouet_handler_rom, + MetadataSource.CSDB: csdb_handler_rom, + MetadataSource.STEAM: steam_handler_rom, + MetadataSource.GAMELIST: gamelist_handler_rom, + MetadataSource.LIBRETRO: libretro_handler_rom, + MetadataSource.SGDB: {}, + } metadata_handlers: dict[MetadataSource, dict[str, Any]] = { - MetadataSource.IGDB: { - "handler": igdb_handler_rom, - "id_field": "igdb_id", - "metadata_field": "igdb_metadata", - }, - MetadataSource.MOBY: { - "handler": moby_handler_rom, - "id_field": "moby_id", - "metadata_field": "moby_metadata", - }, - MetadataSource.SS: { - "handler": ss_handler_rom, - "id_field": "ss_id", - "metadata_field": "ss_metadata", - }, - MetadataSource.RA: { - "handler": ra_handler_rom, - "id_field": "ra_id", - "metadata_field": "ra_metadata", - }, - MetadataSource.LAUNCHBOX: { - "handler": launchbox_handler_rom, - "id_field": "launchbox_id", - "metadata_field": "launchbox_metadata", - }, - MetadataSource.HASHEOUS: { - "handler": hasheous_handler_rom, - "id_field": "hasheous_id", - "metadata_field": "hasheous_metadata", - }, - MetadataSource.FLASHPOINT: { - "handler": flashpoint_handler_rom, - "id_field": "flashpoint_id", - "metadata_field": "flashpoint_metadata", - }, - MetadataSource.HLTB: { - "handler": hltb_handler_rom, - "id_field": "hltb_id", - "metadata_field": "hltb_metadata", - }, - MetadataSource.DEMOZOO: { - "handler": demozoo_handler_rom, - "id_field": "demozoo_id", - "metadata_field": "demozoo_metadata", - }, - MetadataSource.POUET: { - "handler": pouet_handler_rom, - "id_field": "pouet_id", - "metadata_field": "pouet_metadata", - }, - MetadataSource.CSDB: { - "handler": csdb_handler_rom, - "id_field": "csdb_id", - "metadata_field": "csdb_metadata", - }, - MetadataSource.STEAM: { - "handler": steam_handler_rom, - "id_field": "steam_id", - "metadata_field": "steam_metadata", - }, - MetadataSource.GAMELIST: { - "handler": gamelist_handler_rom, - "id_field": "gamelist_id", - "metadata_field": "gamelist_metadata", - }, - MetadataSource.LIBRETRO: { - "handler": libretro_handler_rom, - "id_field": "libretro_id", - "metadata_field": None, - }, - MetadataSource.SGDB: { - "handler": {}, - "id_field": "sgdb_id", - "metadata_field": None, - }, - MetadataSource.TGDB: { - "handler": {}, - "id_field": "tgdb_id", - "metadata_field": None, - }, + source: { + "handler": handler_rom, + "id_field": RESCAN_RULES[source].id_field, + "metadata_field": RESCAN_RULES[source].metadata_field, + } + for source, handler_rom in handler_roms.items() + } + # No scan consults TheGamesDB, so it has no rule, but a rescan still resets it. + metadata_handlers[MetadataSource.TGDB] = { + "handler": {}, + "id_field": "tgdb_id", + "metadata_field": None, } # Reset the id and blob of every source this rescan could rematch: the ones it @@ -1642,12 +1555,7 @@ async def scan_rom( if scene_locked: return SGDBRom(sgdb_id=None) - if MetadataSource.SGDB in metadata_sources and ( - newly_added - or scan_type == ScanType.COMPLETE - or (scan_type == ScanType.UPDATE and rom.sgdb_id) - or (scan_type == ScanType.UNMATCHED and not rom.sgdb_id) - ): + if consults(MetadataSource.SGDB): attempted_sources.add(MetadataSource.SGDB) if scan_type == ScanType.UPDATE and rom.sgdb_id: return await meta_sgdb_handler.get_rom_by_id(rom.sgdb_id) diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index b976d92f7..ca584c25b 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -70,6 +70,9 @@ from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory, RomIdentity from utils.platform_slugs import UniversalPlatformSlug as UPS +# A platform IGDB and MobyGames both cover, so rescans can consult either. +N64 = Platform(slug="n64", igdb_id=4, moby_id=9) + @pytest.fixture def hold_everything_back(mocker): @@ -520,51 +523,58 @@ class TestScreenScraperScanReporting: class TestShouldScanRom: def test_new_platforms_scan_with_no_rom(self): """NEW_PLATFORMS should scan when rom is None""" - result = should_scan_rom(ScanType.NEW_PLATFORMS, None, [], ["igdb"]) + result = should_scan_rom(ScanType.NEW_PLATFORMS, N64, None, [], ["igdb"]) assert result is True def test_new_platforms_scan_with_existing_rom(self, rom: Rom): """NEW_PLATFORMS should not scan when rom exists""" - result = should_scan_rom(ScanType.NEW_PLATFORMS, rom, [], ["igdb"]) + result = should_scan_rom(ScanType.NEW_PLATFORMS, N64, rom, [], ["igdb"]) assert result is False # Test QUICK scan type def test_quick_scan_with_no_rom(self): """QUICK should scan when rom is None""" - result = should_scan_rom(ScanType.QUICK, None, [], ["igdb"]) + result = should_scan_rom(ScanType.QUICK, N64, None, [], ["igdb"]) assert result is True def test_quick_scan_with_existing_rom(self, rom: Rom): """QUICK should scan an existing rom, to reconcile its files""" - result = should_scan_rom(ScanType.QUICK, rom, [], ["igdb"]) + result = should_scan_rom(ScanType.QUICK, N64, rom, [], ["igdb"]) assert result is True # Test COMPLETE scan type def test_complete_scan_always_scans(self, rom: Rom): """COMPLETE should scan everything when unscoped, but respect roms_ids when scoped""" - assert should_scan_rom(ScanType.COMPLETE, None, [], ["igdb"]) is True - assert should_scan_rom(ScanType.COMPLETE, rom, [], ["igdb"]) is True + assert should_scan_rom(ScanType.COMPLETE, N64, None, [], ["igdb"]) is True + assert should_scan_rom(ScanType.COMPLETE, N64, rom, [], ["igdb"]) is True # Scoped scan should not scan/add new filesystem ROMs when rom is None - assert should_scan_rom(ScanType.COMPLETE, None, [rom.id], ["igdb"]) is False + assert ( + should_scan_rom(ScanType.COMPLETE, N64, None, [rom.id], ["igdb"]) is False + ) # Scoped scan: rom not in list → skip even for COMPLETE - assert should_scan_rom(ScanType.COMPLETE, rom, [rom.id + 99], ["igdb"]) is False - assert should_scan_rom(ScanType.COMPLETE, rom, [rom.id], ["igdb"]) is True + assert ( + should_scan_rom(ScanType.COMPLETE, N64, rom, [rom.id + 99], ["igdb"]) + is False + ) + assert should_scan_rom(ScanType.COMPLETE, N64, rom, [rom.id], ["igdb"]) is True # Test HASHES scan type def test_hashes_scan_always_scans(self, rom: Rom): """HASHES should scan everything when unscoped, but respect roms_ids when scoped""" - assert should_scan_rom(ScanType.HASHES, None, [], ["igdb"]) is True - assert should_scan_rom(ScanType.HASHES, rom, [], ["igdb"]) is True + assert should_scan_rom(ScanType.HASHES, N64, None, [], ["igdb"]) is True + assert should_scan_rom(ScanType.HASHES, N64, rom, [], ["igdb"]) is True # Scoped scan should not scan/add new filesystem ROMs when rom is None - assert should_scan_rom(ScanType.HASHES, None, [rom.id], ["igdb"]) is False + assert should_scan_rom(ScanType.HASHES, N64, None, [rom.id], ["igdb"]) is False # Scoped scan: rom not in list → skip even for HASHES - assert should_scan_rom(ScanType.HASHES, rom, [rom.id + 99], ["igdb"]) is False - assert should_scan_rom(ScanType.HASHES, rom, [rom.id], ["igdb"]) is True + assert ( + should_scan_rom(ScanType.HASHES, N64, rom, [rom.id + 99], ["igdb"]) is False + ) + assert should_scan_rom(ScanType.HASHES, N64, rom, [rom.id], ["igdb"]) is True # Test UNMATCHED scan type def test_unmatched_scan_with_no_rom(self): """UNMATCHED should not scan when rom is None""" - result = should_scan_rom(ScanType.UNMATCHED, None, [], ["igdb"]) + result = should_scan_rom(ScanType.UNMATCHED, N64, None, [], ["igdb"]) assert result is False def test_unmatched_scan_with_unmatched_rom(self, rom: Rom): @@ -574,25 +584,25 @@ class TestShouldScanRom: rom.ss_id = None rom.ra_id = None rom.launchbox_id = None - result = should_scan_rom(ScanType.UNMATCHED, rom, [], ["igdb"]) + result = should_scan_rom(ScanType.UNMATCHED, N64, rom, [], ["igdb"]) assert result is True def test_unmatched_scan_with_identified_rom(self, rom: Rom): """UNMATCHED should also scan when rom is identified""" rom.igdb_id = 1 - result = should_scan_rom(ScanType.UNMATCHED, rom, [], ["moby"]) + result = should_scan_rom(ScanType.UNMATCHED, N64, rom, [], ["moby"]) assert result is True # Test UPDATE scan type def test_update_scan_with_no_rom(self): """UPDATE should not scan when rom is None""" - result = should_scan_rom(ScanType.UPDATE, None, [], ["igdb"]) + result = should_scan_rom(ScanType.UPDATE, N64, None, [], ["igdb"]) assert result is False def test_update_scan_with_identified_rom(self, rom: Rom): """UPDATE should scan when rom is identified""" rom.igdb_id = 1 - result = should_scan_rom(ScanType.UPDATE, rom, [], ["igdb"]) + result = should_scan_rom(ScanType.UPDATE, N64, rom, [], ["igdb"]) assert result is True def test_update_scan_with_unmatched_rom(self, rom: Rom): @@ -602,9 +612,37 @@ class TestShouldScanRom: rom.ss_id = None rom.ra_id = None rom.launchbox_id = None - result = should_scan_rom(ScanType.UPDATE, rom, [], ["igdb"]) + result = should_scan_rom(ScanType.UPDATE, N64, rom, [], ["igdb"]) assert result is False + def test_unmatched_scan_retries_an_id_without_metadata(self, rom: Rom): + rom.igdb_id = 1 + rom.igdb_metadata = {} + assert should_scan_rom(ScanType.UNMATCHED, N64, rom, [], ["igdb"]) is True + + rom.igdb_metadata = {"total_rating": "90"} + assert should_scan_rom(ScanType.UNMATCHED, N64, rom, [], ["igdb"]) is False + + def test_unmatched_scan_skips_a_source_the_platform_lacks(self, rom: Rom): + rom.igdb_id = 1 + rom.igdb_metadata = {"total_rating": "90"} + rom.libretro_id = None + sources = ["igdb", "libretro"] + + assert should_scan_rom(ScanType.UNMATCHED, N64, rom, [], sources) is True + not_covered = Platform(slug="not-a-platform", igdb_id=4) + assert ( + should_scan_rom(ScanType.UNMATCHED, not_covered, rom, [], sources) is False + ) + + def test_playmatch_alone_picks_no_rom(self, rom: Rom): + rom.igdb_id = 1 + rom.igdb_metadata = {"total_rating": "90"} + sources = ["igdb", "playmatch"] + + assert should_scan_rom(ScanType.UNMATCHED, N64, rom, [], sources) is False + assert should_scan_rom(ScanType.UPDATE, N64, rom, [], ["playmatch"]) is False + # Test rom_ids parameter def test_scan_when_rom_id_in_list(self, rom: Rom): """Should scan when rom.id is in roms_ids list regardless of scan type""" @@ -617,7 +655,7 @@ class TestShouldScanRom: ScanType.UNMATCHED, ScanType.UPDATE, ]: - result = should_scan_rom(scan_type, rom, roms_ids, ["igdb"]) + result = should_scan_rom(scan_type, N64, rom, roms_ids, ["igdb"]) assert result is True def test_no_scan_when_rom_id_not_in_list(self, rom: Rom): @@ -638,7 +676,7 @@ class TestShouldScanRom: ScanType.COMPLETE, ScanType.HASHES, ]: - assert should_scan_rom(scan_type, rom, roms_ids, ["igdb"]) is False + assert should_scan_rom(scan_type, N64, rom, roms_ids, ["igdb"]) is False # Edge cases def test_empty_roms_ids_list(self, rom: Rom): @@ -646,8 +684,8 @@ class TestShouldScanRom: rom.id = 1 rom.igdb_id = 1 - assert should_scan_rom(ScanType.UPDATE, rom, [], ["igdb"]) is True - assert should_scan_rom(ScanType.NEW_PLATFORMS, rom, [], ["igdb"]) is False + assert should_scan_rom(ScanType.UPDATE, N64, rom, [], ["igdb"]) is True + assert should_scan_rom(ScanType.NEW_PLATFORMS, N64, rom, [], ["igdb"]) is False def test_rom_id_type_conversion(self, rom: Rom): """Test that rom.id (int) is properly compared with roms_ids (list of strings)""" @@ -655,7 +693,7 @@ class TestShouldScanRom: roms_ids = [123, 456] # This should scan because 123 should match "123" - result = should_scan_rom(ScanType.QUICK, rom, roms_ids, ["igdb"]) + result = should_scan_rom(ScanType.QUICK, N64, rom, roms_ids, ["igdb"]) assert result is True @pytest.mark.parametrize( @@ -702,7 +740,7 @@ class TestShouldScanRom: if rom_in_list: roms_ids = [1] - result = should_scan_rom(scan_type, rom, roms_ids, ["igdb"]) + result = should_scan_rom(scan_type, N64, rom, roms_ids, ["igdb"]) assert result is expected @@ -2968,13 +3006,13 @@ def test_scan_stats_reports_file_counters(): class TestQuickScanCoversRomFiles: def test_quick_scan_covers_new_and_existing_roms(self, rom: Rom): - assert should_scan_rom(ScanType.QUICK, None, [], []) is True - assert should_scan_rom(ScanType.QUICK, rom, [], []) is True + assert should_scan_rom(ScanType.QUICK, N64, None, [], []) is True + assert should_scan_rom(ScanType.QUICK, N64, rom, [], []) is True def test_scoped_quick_scan_respects_roms_ids(self, rom: Rom): - assert should_scan_rom(ScanType.QUICK, None, [rom.id], []) is False - assert should_scan_rom(ScanType.QUICK, rom, [rom.id + 99], []) is False - assert should_scan_rom(ScanType.QUICK, rom, [rom.id], []) is True + assert should_scan_rom(ScanType.QUICK, N64, None, [rom.id], []) is False + assert should_scan_rom(ScanType.QUICK, N64, rom, [rom.id + 99], []) is False + assert should_scan_rom(ScanType.QUICK, N64, rom, [rom.id], []) is True class TestShouldHashIncrementally: diff --git a/backend/tests/handler/test_scan_playmatch_gate.py b/backend/tests/handler/test_scan_playmatch_gate.py new file mode 100644 index 000000000..685d075b3 --- /dev/null +++ b/backend/tests/handler/test_scan_playmatch_gate.py @@ -0,0 +1,45 @@ +"""When a scan asks Playmatch, whose ids only feed the other sources.""" + +from typing import Any +from unittest.mock import AsyncMock, patch + +from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan + +from handler.metadata import meta_igdb_handler, meta_playmatch_handler +from handler.metadata.igdb_handler import IGDBRom +from handler.scan_handler import MetadataSource, ScanType + + +async def _update_scan(**rom_fields: Any) -> AsyncMock: + platform = add_n64_platform(igdb_id=4) + rom = add_rom(platform, "Paper Mario (USA).z64", "Paper Mario", **rom_fields) + lookup = AsyncMock(wraps=meta_playmatch_handler.lookup_rom) + + with ( + patch.object(meta_playmatch_handler, "is_enabled", return_value=True), + patch.object(meta_playmatch_handler, "lookup_rom", new=lookup), + patch.object( + meta_igdb_handler, + "get_rom_by_id", + new=AsyncMock(return_value=IGDBRom(igdb_id=None)), + ), + ): + await run_scan( + platform, + rom, + scan_type=ScanType.UPDATE, + metadata_sources=[MetadataSource.PLAYMATCH, MetadataSource.IGDB], + ) + return lookup + + +async def test_an_update_asks_playmatch_for_a_source_it_refreshes(): + lookup = await _update_scan(igdb_id=1) + + lookup.assert_awaited_once() + + +async def test_an_update_skips_playmatch_when_no_source_it_feeds_runs(): + lookup = await _update_scan() + + lookup.assert_not_awaited() diff --git a/backend/tests/handler/test_scan_rescan_rules.py b/backend/tests/handler/test_scan_rescan_rules.py new file mode 100644 index 000000000..605590a8c --- /dev/null +++ b/backend/tests/handler/test_scan_rescan_rules.py @@ -0,0 +1,295 @@ +from typing import Any +from unittest.mock import patch + +import pytest + +from handler.metadata.flashpoint_handler import FLASHPOINT_PLATFORM_LIST +from handler.metadata.hltb_handler import HLTB_PLATFORM_LIST +from handler.metadata.libretro_handler import LIBRETRO_PLATFORM_LIST +from handler.metadata.steam_handler import STEAM_PLATFORMS +from handler.scan_handler import ( + RESCAN_RULES, + MetadataSource, + ScanType, + should_consult, + stored_match_id, +) +from models.platform import Platform +from models.rom import METADATA_SOURCE_COLUMNS, Rom + +# A slug each slug-gated source covers; every other source keys off a platform id. +COVERED_SLUG = { + MetadataSource.FLASHPOINT: next(iter(FLASHPOINT_PLATFORM_LIST)), + MetadataSource.HLTB: next(iter(HLTB_PLATFORM_LIST)), + MetadataSource.LIBRETRO: next(iter(LIBRETRO_PLATFORM_LIST)), + MetadataSource.STEAM: next(iter(STEAM_PLATFORMS)), +} + + +def _platform(source: MetadataSource, slug: str | None = None) -> Platform: + return Platform( + slug=slug or COVERED_SLUG.get(source, "n64"), + igdb_id=4, + moby_id=9, + ss_id=14, + ra_id=2, + hasheous_id=8, + ) + + +def _rom(platform: Platform, **fields: Any) -> Rom: + return Rom(platform=platform, **fields) + + +def _consults( + source: MetadataSource, + scan_type: ScanType, + rom: Rom, + *, + newly_added: bool = False, + enabled: bool = True, +) -> bool: + with patch( + "handler.scan_handler.meta_igdb_handler.get_platform", + return_value={"igdb_id": 4}, + ): + return should_consult( + source, + scan_type=scan_type, + rom=rom, + platform=rom.platform, + newly_added=newly_added, + metadata_sources=[source.value] if enabled else [], + ) + + +ALL_SOURCES = list(RESCAN_RULES) + + +def test_every_scanned_source_has_a_rule(): + """TheGamesDB is read off Hasheous and Playmatch has its own gate.""" + assert set(RESCAN_RULES) == set(MetadataSource) - { + MetadataSource.TGDB, + MetadataSource.PLAYMATCH, + } + + +# Written out rather than derived, so a rule pointing at the wrong column fails. +EXPECTED_COLUMNS: dict[MetadataSource, tuple[str, str | None]] = { + MetadataSource.IGDB: ("igdb_id", "igdb_metadata"), + MetadataSource.MOBY: ("moby_id", "moby_metadata"), + MetadataSource.SS: ("ss_id", "ss_metadata"), + MetadataSource.RA: ("ra_id", "ra_metadata"), + MetadataSource.LAUNCHBOX: ("launchbox_id", "launchbox_metadata"), + MetadataSource.HASHEOUS: ("hasheous_id", "hasheous_metadata"), + MetadataSource.SGDB: ("sgdb_id", None), + MetadataSource.FLASHPOINT: ("flashpoint_id", "flashpoint_metadata"), + MetadataSource.HLTB: ("hltb_id", "hltb_metadata"), + MetadataSource.DEMOZOO: ("demozoo_id", "demozoo_metadata"), + MetadataSource.POUET: ("pouet_id", "pouet_metadata"), + MetadataSource.CSDB: ("csdb_id", "csdb_metadata"), + MetadataSource.STEAM: ("steam_id", "steam_metadata"), + MetadataSource.GAMELIST: ("gamelist_id", "gamelist_metadata"), + MetadataSource.LIBRETRO: ("libretro_id", None), +} + + +@pytest.mark.parametrize("source", ALL_SOURCES) +def test_each_rule_reads_its_own_columns(source: MetadataSource): + rule = RESCAN_RULES[source] + assert (rule.id_field, rule.metadata_field) == EXPECTED_COLUMNS[source] + + +def test_the_identified_columns_match_the_rules(): + assert { + slug: column.key + for slug, column in METADATA_SOURCE_COLUMNS.items() + if slug in RESCAN_RULES + } == { + source.value: RESCAN_RULES[source].id_field + for source in RESCAN_RULES + if source.value in METADATA_SOURCE_COLUMNS + } + + +@pytest.mark.parametrize("source", ALL_SOURCES) +def test_a_disabled_source_is_never_consulted(source: MetadataSource): + rom = _rom(_platform(source)) + assert not _consults(source, ScanType.COMPLETE, rom, enabled=False) + + +@pytest.mark.parametrize("source", ALL_SOURCES) +@pytest.mark.parametrize("scan_type", list(ScanType)) +def test_a_new_rom_consults_every_source(source: MetadataSource, scan_type: ScanType): + rom = _rom(_platform(source)) + assert _consults(source, scan_type, rom, newly_added=True) + + +@pytest.mark.parametrize("source", ALL_SOURCES) +def test_a_complete_rescan_consults_a_matched_source(source: MetadataSource): + rule = RESCAN_RULES[source] + rom = _rom(_platform(source), **{rule.id_field: 1}) + assert _consults(source, ScanType.COMPLETE, rom) + + +@pytest.mark.parametrize("source", ALL_SOURCES) +def test_an_update_refreshes_only_a_matched_source(source: MetadataSource): + rule = RESCAN_RULES[source] + platform = _platform(source) + assert _consults(source, ScanType.UPDATE, _rom(platform, **{rule.id_field: 1})) + assert not _consults(source, ScanType.UPDATE, _rom(platform)) + + +@pytest.mark.parametrize("source", ALL_SOURCES) +def test_an_unmatched_scan_retries_a_missing_match(source: MetadataSource): + assert _consults(source, ScanType.UNMATCHED, _rom(_platform(source))) + + +@pytest.mark.parametrize("source", ALL_SOURCES) +def test_an_unmatched_scan_skips_a_full_match(source: MetadataSource): + rule = RESCAN_RULES[source] + fields: dict[str, Any] = {rule.id_field: 1} + if rule.metadata_field: + fields[rule.metadata_field] = {"name": "Matched"} + assert not _consults(source, ScanType.UNMATCHED, _rom(_platform(source), **fields)) + + +@pytest.mark.parametrize( + "source", + [s for s in ALL_SOURCES if RESCAN_RULES[s].metadata_field is not None], +) +def test_an_unmatched_scan_retries_an_id_without_metadata(source: MetadataSource): + rule = RESCAN_RULES[source] + rom = _rom(_platform(source), **{rule.id_field: 1}) + assert _consults(source, ScanType.UNMATCHED, rom) + + +@pytest.mark.parametrize( + "source", + [ + MetadataSource.MOBY, + MetadataSource.SS, + MetadataSource.RA, + MetadataSource.LAUNCHBOX, + MetadataSource.HASHEOUS, + ], +) +def test_an_unmatched_scan_skips_a_platform_the_source_does_not_list( + source: MetadataSource, +): + rom = _rom(_platform(source, slug="not-a-platform")) + assert not _consults(source, ScanType.UNMATCHED, rom) + # Only the unmatched retry checks the list; a complete rescan still asks. + assert _consults(source, ScanType.COMPLETE, rom) + + +@pytest.mark.parametrize("source", list(COVERED_SLUG)) +def test_a_platform_outside_the_sources_list_is_never_consulted( + source: MetadataSource, +): + rom = _rom(_platform(source, slug="not-a-platform")) + assert not _consults(source, ScanType.COMPLETE, rom, newly_added=True) + + +@pytest.mark.parametrize( + "source", + [ + MetadataSource.IGDB, + MetadataSource.MOBY, + MetadataSource.SS, + MetadataSource.RA, + MetadataSource.HASHEOUS, + ], +) +def test_a_platform_without_the_sources_id_is_never_consulted( + source: MetadataSource, +): + platform = _platform(source) + setattr(platform, f"{source.value}_id", None) + assert not _consults(source, ScanType.COMPLETE, _rom(platform), newly_added=True) + + +@pytest.mark.parametrize( + "source", + [ + MetadataSource.LAUNCHBOX, + MetadataSource.SGDB, + MetadataSource.DEMOZOO, + MetadataSource.POUET, + MetadataSource.CSDB, + MetadataSource.GAMELIST, + ], +) +def test_a_source_without_a_platform_gate_covers_any_platform( + source: MetadataSource, +): + rom = _rom(Platform(slug="not-a-platform")) + assert _consults(source, ScanType.COMPLETE, rom, newly_added=True) + + +@pytest.mark.parametrize("source", ALL_SOURCES) +def test_a_hash_scan_consults_only_the_hash_sources(source: MetadataSource): + rule = RESCAN_RULES[source] + rom = _rom(_platform(source), **{rule.id_field: 1}) + assert _consults(source, ScanType.HASHES, rom) == ( + source in {MetadataSource.RA, MetadataSource.HASHEOUS} + ) + + +@pytest.mark.parametrize("source", ALL_SOURCES) +@pytest.mark.parametrize("scan_type", [ScanType.QUICK, ScanType.NEW_PLATFORMS]) +def test_a_quick_scan_leaves_an_existing_rom_alone( + source: MetadataSource, scan_type: ScanType +): + rule = RESCAN_RULES[source] + rom = _rom(_platform(source), **{rule.id_field: 1}) + assert not _consults(source, scan_type, rom) + + +def test_an_unmatched_scan_skips_a_platform_igdb_does_not_list(): + rom = _rom(_platform(MetadataSource.IGDB)) + with patch( + "handler.scan_handler.meta_igdb_handler.get_platform", + return_value={"igdb_id": None}, + ): + assert not should_consult( + MetadataSource.IGDB, + scan_type=ScanType.UNMATCHED, + rom=rom, + platform=rom.platform, + newly_added=False, + metadata_sources=[MetadataSource.IGDB.value], + ) + + +@pytest.mark.parametrize("source", ALL_SOURCES) +def test_an_update_refetches_the_stored_id(source: MetadataSource): + rule = RESCAN_RULES[source] + rom = _rom(_platform(source), **{rule.id_field: 7}) + assert stored_match_id(source, scan_type=ScanType.UPDATE, rom=rom) == 7 + + +@pytest.mark.parametrize("source", ALL_SOURCES) +@pytest.mark.parametrize("scan_type", [ScanType.COMPLETE, ScanType.HASHES]) +def test_a_rematching_scan_ignores_the_stored_id( + source: MetadataSource, scan_type: ScanType +): + rule = RESCAN_RULES[source] + rom = _rom(_platform(source), **{rule.id_field: 7}) + assert stored_match_id(source, scan_type=scan_type, rom=rom) is None + + +@pytest.mark.parametrize( + "source", + [s for s in ALL_SOURCES if RESCAN_RULES[s].metadata_field is not None], +) +def test_an_unmatched_scan_refetches_an_id_missing_its_metadata( + source: MetadataSource, +): + rule = RESCAN_RULES[source] + assert rule.metadata_field is not None + rom = _rom(_platform(source), **{rule.id_field: 7}) + assert stored_match_id(source, scan_type=ScanType.UNMATCHED, rom=rom) == 7 + + setattr(rom, rule.metadata_field, {"name": "Matched"}) + assert stored_match_id(source, scan_type=ScanType.UNMATCHED, rom=rom) is None diff --git a/backend/tests/handler/test_scan_stored_match.py b/backend/tests/handler/test_scan_stored_match.py new file mode 100644 index 000000000..0dd585664 --- /dev/null +++ b/backend/tests/handler/test_scan_stored_match.py @@ -0,0 +1,100 @@ +"""A refresh scan refetches a rom's stored match rather than matching it anew.""" + +from unittest.mock import AsyncMock, patch + +from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan + +from handler.metadata import ( + meta_demozoo_handler, + meta_igdb_handler, + meta_moby_handler, + meta_playmatch_handler, +) +from handler.metadata.demozoo_handler import DemozooRom +from handler.metadata.igdb_handler import IGDBRom +from handler.metadata.moby_handler import MobyGamesRom +from handler.metadata.playmatch_handler import PlaymatchRomMatch +from handler.scan_handler import MetadataSource, ScanType + + +def _playmatch_answer(igdb_id: int) -> PlaymatchRomMatch: + return PlaymatchRomMatch( + igdb_id=igdb_id, + moby_id=None, + ss_id=None, + launchbox_id=None, + sgdb_id=None, + ra_id=None, + hasheous_id=None, + tgdb_id=None, + flashpoint_id=None, + hltb_id=None, + libretro_id=None, + gamelist_id=None, + ) + + +async def test_an_update_keeps_the_stored_igdb_id_over_playmatch(): + platform = add_n64_platform(igdb_id=4) + rom = add_rom(platform, "Paper Mario (USA).z64", "Paper Mario", igdb_id=1) + by_id = AsyncMock(return_value=IGDBRom(igdb_id=None)) + + with ( + patch.object(meta_playmatch_handler, "is_enabled", return_value=True), + patch.object( + meta_playmatch_handler, + "lookup_rom", + new=AsyncMock(return_value=_playmatch_answer(igdb_id=99)), + ), + patch.object(meta_igdb_handler, "get_rom_by_id", new=by_id), + ): + await run_scan( + platform, + rom, + scan_type=ScanType.UPDATE, + metadata_sources=[MetadataSource.PLAYMATCH, MetadataSource.IGDB], + ) + + by_id.assert_awaited_once_with(rom, 1) + + +async def test_an_unmatched_scan_refetches_an_id_without_metadata(): + platform = add_n64_platform(moby_id=9) + rom = add_rom(platform, "Paper Mario (USA).z64", "Paper Mario", moby_id=123) + by_id = AsyncMock(return_value=MobyGamesRom(moby_id=None)) + by_name = AsyncMock(return_value=MobyGamesRom(moby_id=None)) + + with ( + patch.object(meta_moby_handler, "get_rom_by_id", new=by_id), + patch.object(meta_moby_handler, "get_rom", new=by_name), + ): + await run_scan( + platform, + rom, + scan_type=ScanType.UNMATCHED, + metadata_sources=[MetadataSource.MOBY], + ) + + by_id.assert_awaited_once_with(123) + by_name.assert_not_awaited() + + +async def test_an_update_refetches_the_stored_demozoo_id(): + platform = add_n64_platform() + rom = add_rom(platform, "Desert Dream.adf", "Desert Dream", demozoo_id=1234) + by_id = AsyncMock(return_value=DemozooRom(demozoo_id=None)) + by_name = AsyncMock(return_value=DemozooRom(demozoo_id=None)) + + with ( + patch.object(meta_demozoo_handler, "get_rom_by_id", new=by_id), + patch.object(meta_demozoo_handler, "get_rom", new=by_name), + ): + await run_scan( + platform, + rom, + scan_type=ScanType.UPDATE, + metadata_sources=[MetadataSource.DEMOZOO], + ) + + by_id.assert_awaited_once_with(1234) + by_name.assert_not_awaited()