diff --git a/backend/adapters/services/screenscraper_types.py b/backend/adapters/services/screenscraper_types.py index c971ffd89..f8f96e992 100644 --- a/backend/adapters/services/screenscraper_types.py +++ b/backend/adapters/services/screenscraper_types.py @@ -80,6 +80,38 @@ class SSGameMedia(TypedDict): format: str +class SSRomRegions(TypedDict): + """Parallel arrays, one entry per region, keyed by name language.""" + + regions_shortname: NotRequired[list[str]] + regions_en: NotRequired[list[str]] + + +class SSRomLanguages(TypedDict): + """Parallel arrays, one entry per language, keyed by name language.""" + + langues_shortname: NotRequired[list[str]] + langues_en: NotRequired[list[str]] + + +class SSGameRom(TypedDict): + """One dump of a game, as `jeu.roms` lists every dump ScreenScraper knows.""" + + id: NotRequired[int] + romfilename: NotRequired[str] + romcrc: NotRequired[str] + rommd5: NotRequired[str] + romsha1: NotRequired[str] + regions: NotRequired[SSRomRegions] + langues: NotRequired[SSRomLanguages] + beta: NotRequired[int] + demo: NotRequired[int] + proto: NotRequired[int] + trad: NotRequired[int] + hack: NotRequired[int] + unl: NotRequired[int] + + # https://api.screenscraper.fr/webapi2.php#jeuInfos class SSGame(TypedDict): id: int @@ -101,3 +133,4 @@ class SSGame(TypedDict): modes: list[SSGameMode] familles: list[SSGameFranchise] medias: list[SSGameMedia] + roms: NotRequired[list[SSGameRom]] diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index e97e026b8..54c1155cc 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -4,13 +4,13 @@ import os import re import shutil import tempfile -from collections.abc import Sequence +from collections.abc import Callable, Iterable, Sequence from contextlib import asynccontextmanager from enum import Enum from io import BytesIO from pathlib import Path from tempfile import SpooledTemporaryFile -from typing import BinaryIO +from typing import BinaryIO, Final from anyio import Path as AnyioPath from anyio import open_file @@ -133,6 +133,25 @@ REGION_NAME_TO_PROVIDER_SHORTCODE: dict[str, str] = { "Taiwan": "tw", "USA": "us", "World": "wor", + # ScreenScraper regions with no filename shortcode of their own. Providers + # send these codes bare, so without a name here they land in a facet as + # "pl" beside the "Poland" a filename or Hasheous produces. + "Americas": "ame", + "Bulgaria": "bg", + "Chile": "cl", + "Czech Republic": "cz", + "Denmark": "dk", + "Hungary": "hu", + "Israel": "il", + "Kuwait": "kw", + "Middle East": "mor", + "New Zealand": "nz", + "Oceania": "oce", + "Peru": "pe", + "Poland": "pl", + "Portugal": "pt", + "Slovakia": "sk", + "Turkey": "tr", } _REGION_NAME_TO_PROVIDER_SHORTCODE_CI = { @@ -182,6 +201,21 @@ def region_ranks_for_priority(shortcodes: Sequence[str]) -> dict[str, int]: return ranks +# Provider spellings kept out of the filename aliases, where several of these +# codes ("de", "fr", "nl", "ru") read as a language tag instead (issue #3026). +_REGION_BY_PROVIDER_ALIAS = { + **{name.lower(): name for name in REGION_NAME_TO_PROVIDER_SHORTCODE}, + **{code: names[0] for code, names in _REGION_NAMES_BY_PROVIDER_SHORTCODE.items()}, +} + + +def provider_region_name(value: str) -> str | None: + """Resolve a metadata provider's region spelling to its canonical name.""" + return normalize_region(value) or _REGION_BY_PROVIDER_ALIAS.get( + value.strip().lower() + ) + + LANGUAGES_BY_SHORTCODE = {lang[0]: lang[1] for lang in LANGUAGES} # Every accepted language spelling, lowercased, mapped to its canonical name. @@ -200,6 +234,87 @@ def normalize_language(tag: str) -> str | None: return _LANGUAGE_BY_ALIAS.get(tag.strip().lower()) +# ISO-639-1 languages with no filename shortcode of their own. Provider-only, +# because a filename tag reads by dumper convention instead: "(Tr)" marks a +# translation, not Turkish. +PROVIDER_LANGUAGES: Final = ( + ("af", "Afrikaans"), + ("be", "Belarusian"), + ("bg", "Bulgarian"), + ("ca", "Catalan"), + ("cs", "Czech"), + ("et", "Estonian"), + ("he", "Hebrew"), + ("hi", "Hindi"), + ("hr", "Croatian"), + ("hu", "Hungarian"), + ("hy", "Armenian"), + ("id", "Indonesian"), + ("is", "Icelandic"), + ("la", "Latin"), + ("lt", "Lithuanian"), + ("lv", "Latvian"), + ("mk", "Macedonian"), + ("ro", "Romanian"), + ("sk", "Slovak"), + ("sl", "Slovenian"), + ("sq", "Albanian"), + ("th", "Thai"), + ("tr", "Turkish"), + ("uk", "Ukrainian"), + ("vi", "Vietnamese"), +) + +_LANGUAGE_BY_PROVIDER_ALIAS = { + **{name.lower(): name for _, name in PROVIDER_LANGUAGES}, + **{code: name for code, name in PROVIDER_LANGUAGES}, +} + +# Region shortcodes a filename can also carry, as TOSEC and similar sets write +# them ("(US)", "(JP)"). Added once both language vocabularies are known, and +# only for a code neither claims: "(De)" is German, and "(Tr)" marks a +# translation rather than Turkey (issue #3026). +_REGION_BY_ALIAS.update( + { + code: names[0] + for code, names in _REGION_NAMES_BY_PROVIDER_SHORTCODE.items() + if code not in _LANGUAGE_BY_ALIAS and code not in _LANGUAGE_BY_PROVIDER_ALIAS + } +) + + +def provider_language_name(value: str) -> str | None: + """Resolve a metadata provider's language spelling to its canonical name.""" + return normalize_language(value) or _LANGUAGE_BY_PROVIDER_ALIAS.get( + value.strip().lower() + ) + + +def normalize_provider_values( + values: Iterable[str], resolve: Callable[[str], str | None] +) -> list[str]: + """Canonicalize provider spellings, dropping blanks and duplicates. + + An unrecognized value is kept as given, the way filename parsing keeps a + tag it does not know rather than dropping it. + """ + return list( + dict.fromkeys( + resolve(value) or value.strip() + for value in values + if value and value.strip() + ) + ) + + +def normalize_provider_regions(values: Iterable[str]) -> list[str]: + return normalize_provider_values(values, provider_region_name) + + +def normalize_provider_languages(values: Iterable[str]) -> list[str]: + return normalize_provider_values(values, provider_language_name) + + class CoverSize(Enum): SMALL = "small" BIG = "big" diff --git a/backend/handler/metadata/gamelist_handler.py b/backend/handler/metadata/gamelist_handler.py index 4f6664b71..8b88ffe7d 100644 --- a/backend/handler/metadata/gamelist_handler.py +++ b/backend/handler/metadata/gamelist_handler.py @@ -13,6 +13,10 @@ from defusedxml import ElementTree as ET from config.config_manager import PLATFORM_MEDIA_DIRS, MetadataMediaType from config.config_manager import config_manager as cm from handler.filesystem import fs_platform_handler, fs_resource_handler +from handler.filesystem.base_handler import ( + normalize_provider_languages, + normalize_provider_regions, +) from logger.logger import log from models.platform import Platform from models.rom import Rom, compute_name_sort_key @@ -460,15 +464,15 @@ class GamelistHandler(MetadataHandler): summary = ( desc_elem.text if desc_elem is not None and desc_elem.text else "" ) - regions = ( - _split_comma_separated_values(region_elem.text) - if region_elem is not None - else [] + regions = normalize_provider_regions( + _split_comma_separated_values( + region_elem.text if region_elem is not None else None + ) ) - languages = ( - _split_comma_separated_values(lang_elem.text) - if lang_elem is not None - else [] + languages = normalize_provider_languages( + _split_comma_separated_values( + lang_elem.text if lang_elem is not None else None + ) ) # Build ROM data diff --git a/backend/handler/metadata/hasheous_handler.py b/backend/handler/metadata/hasheous_handler.py index b46a5d318..0390cdf08 100644 --- a/backend/handler/metadata/hasheous_handler.py +++ b/backend/handler/metadata/hasheous_handler.py @@ -1,6 +1,7 @@ import json +from collections.abc import Callable from datetime import datetime -from typing import Any, NotRequired, TypedDict +from typing import Any, Final, NotRequired, TypedDict import httpx import pydash @@ -8,6 +9,11 @@ import yarl from fastapi import status from config import DEV_MODE, HASHEOUS_API_ENABLED, HASHEOUS_API_URL +from handler.filesystem.base_handler import ( + normalize_provider_values, + provider_language_name, + provider_region_name, +) from logger.logger import log from models.rom import RomFile from utils import get_version @@ -47,6 +53,8 @@ class HasheousPlatform(TypedDict): class HasheousRom(BaseRom): hasheous_id: int | None + regions: NotRequired[list[str]] + languages: NotRequired[list[str]] igdb_id: NotRequired[int | None] slug: NotRequired[str] igdb_metadata: NotRequired[IGDBMetadata] @@ -58,6 +66,62 @@ class HasheousRom(BaseRom): ACCEPTABLE_FILE_EXTENSIONS_BY_PLATFORM_SLUG = {UPS.DC: ["bin", "chd", "cue"]} +# Signature sources whose region data is preferred, as Hasheous spells them. +# The curated per-region dumps describe one release; the rest lump variants +# together or, for ScreenScraper, carry the game's whole release spread. +PREFERRED_SIGNATURE_SOURCES: Final = ("NoIntros", "Redump") + +# Codes Hasheous prints as ISO-3166 that a filename shortcode claims for +# somewhere else: CH is Switzerland here and China in a No-Intro name, AS is +# American Samoa and Asia. The name printed beside them decides instead. +_AMBIGUOUS_COUNTRY_CODES: Final = frozenset({"ch", "as"}) + + +def _country_name(code: str) -> str | None: + if code.strip().lower() in _AMBIGUOUS_COUNTRY_CODES: + return None + return provider_region_name(code) + + +def _tags_from_signatures( + signatures: dict[str, Any], + field: str, + resolve: Callable[[str], str | None], +) -> list[str]: + """Read one dump's countries or languages out of the matched signatures. + + Only `rom` is read, never the `game` beside it, which spans every release + of the title. A resolved code wins over the name Hasheous printed. + """ + if not isinstance(signatures, dict): + return [] + + ordered_sources = [ + source for source in PREFERRED_SIGNATURE_SOURCES if source in signatures + ] + [source for source in signatures if source not in PREFERRED_SIGNATURE_SOURCES] + + # Every field below comes straight off the wire, so none of its shapes are + # assumed: a raise here would abort the scan of the rom. + for source in ordered_sources: + entries = signatures.get(source) + for entry in entries if isinstance(entries, list) else []: + tags = pydash.get(entry, ["rom", field]) + if not isinstance(tags, dict): + continue + + values = normalize_provider_values( + ( + resolve(code) or (name if isinstance(name, str) else "") + for code, name in tags.items() + if isinstance(code, str) + ), + resolve, + ) + if values: + return values + + return [] + def _involved_company_names(rom: dict[str, Any], role: str) -> list[str]: """Company names for an IGDB involvement role. @@ -328,7 +392,7 @@ class HasheousHandler(MetadataHandler): metadata = hasheous_game.get("metadata", []) attributes = hasheous_game.get("attributes", []) - signatures = hasheous_game.get("signatures", {}).keys() + signatures = hasheous_game.get("signatures", {}) igdb_id = None tgdb_id = None @@ -359,6 +423,10 @@ class HasheousHandler(MetadataHandler): HasheousRom( hasheous_id=hasheous_game["id"], name=hasheous_game.get("name", ""), + regions=_tags_from_signatures(signatures, "country", _country_name), + languages=_tags_from_signatures( + signatures, "language", provider_language_name + ), igdb_id=int(igdb_id) if igdb_id else None, tgdb_id=int(tgdb_id) if tgdb_id else None, ra_id=int(ra_id) if ra_id else None, diff --git a/backend/handler/metadata/ss_handler.py b/backend/handler/metadata/ss_handler.py index 269d11c01..3b9bc1939 100644 --- a/backend/handler/metadata/ss_handler.py +++ b/backend/handler/metadata/ss_handler.py @@ -17,7 +17,7 @@ from adapters.services.screenscraper import ( prime_account_limits, reset_scan_state, ) -from adapters.services.screenscraper_types import SSGame, SSGameDate +from adapters.services.screenscraper_types import SSGame, SSGameDate, SSGameRom from config import ( SCREENSCRAPER_DEV_ID, SCREENSCRAPER_DEV_PASSWORD, @@ -27,10 +27,14 @@ from config import ( from config.config_manager import MetadataMediaType from config.config_manager import config_manager as cm from handler.filesystem import fs_resource_handler -from handler.filesystem.base_handler import region_name_to_provider_shortcode +from handler.filesystem.base_handler import ( + normalize_provider_languages, + normalize_provider_regions, + region_name_to_provider_shortcode, +) from logger.formatter import highlight as hl from logger.logger import log -from models.rom import Rom, RomFile +from models.rom import LookupHashes, Rom, RomFile from utils.platform_slugs import UniversalPlatformSlug as UPS from .base_handler import ( @@ -228,6 +232,10 @@ ARCADES_SS_IDS: Final = [ARCADE_SS_ID, CPS1_SS_ID, CPS2_SS_ID, CPS3_SS_ID] # Regex to detect ScreenScraper ID tags in filenames like (ssfr-12345) SS_TAG_REGEX = re.compile(r"\(ssfr-(\d+)\)", re.IGNORECASE) + +# ScreenScraper buckets that name no place, so they must not become facet values. +_SS_PSEUDO_REGIONS: Final = frozenset({"ss", "cus"}) + NOTGAME_NAME_PREFIX: Final = "ZZZ(NOTGAME)" _ISO_EXTENSIONS: Final = frozenset({"iso", "cue", "chd", "gdi", "cdi", "bin"}) @@ -333,6 +341,8 @@ class SSMetadata(SSMetadataMedia): class SSRom(BaseRom): ss_id: int | None + regions: NotRequired[list[str]] + languages: NotRequired[list[str]] ss_metadata: NotRequired[SSMetadata] @@ -662,6 +672,52 @@ def extract_metadata_from_ss_rom(rom: Rom, game: SSGame) -> SSMetadata: ) +def find_ss_dump(game: SSGame, hashes: LookupHashes) -> SSGameRom | None: + """The entry in `jeu.roms` our own file is, by hash, or None. + + `jeu.romid` names a dump of the game that is not necessarily the one asked + about, so the hashes decide instead. Nothing else in the response is + specific to the copy on disk. + """ + wanted = { + key: value.lower() + for key, value in ( + ("rommd5", hashes.md5), + ("romsha1", hashes.sha1), + ("romcrc", hashes.crc), + ) + if value + } + if not wanted: + return None + + for dump in game.get("roms") or []: + if not isinstance(dump, dict): + continue + if any( + str(dump.get(key, "")).lower() == value for key, value in wanted.items() + ): + return dump + + return None + + +def extract_regions_from_ss_dump(dump: SSGameRom) -> list[str]: + """Regions of one dump. Its buckets name no place, so they are dropped.""" + codes = (dump.get("regions") or {}).get("regions_shortname") or [] + return normalize_provider_regions( + code + for code in codes + if isinstance(code, str) and code.strip().lower() not in _SS_PSEUDO_REGIONS + ) + + +def extract_languages_from_ss_dump(dump: SSGameRom) -> list[str]: + """Languages of one dump, which a translation carries its target in.""" + codes = (dump.get("langues") or {}).get("langues_shortname") or [] + return normalize_provider_languages(code for code in codes if isinstance(code, str)) + + def build_ss_game(rom: Rom, game: SSGame) -> SSRom: ss_metadata = extract_metadata_from_ss_rom(rom, game) preferred_media_types = get_preferred_media_types() @@ -893,7 +949,18 @@ class SSHandler(MetadataHandler): ) return SSRom(ss_id=None), True - return build_ss_game(rom, res), False + # Tags describe the dump, so they are read only off the entry our own + # hash matched: jeuInfos also answers a bare romnom, which identifies a + # title the way the name search does. + game_rom = build_ss_game(rom, res) + dump = find_ss_dump( + res, LookupHashes(crc=crc_hash, md5=md5_hash, sha1=sha1_hash) + ) + if dump is not None: + game_rom["regions"] = extract_regions_from_ss_dump(dump) + game_rom["languages"] = extract_languages_from_ss_dump(dump) + + return game_rom, False async def get_rom(self, rom: Rom, file_name: str, platform_ss_id: int) -> SSRom: from handler.filesystem import fs_rom_handler diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 72f77ad71..544f9b446 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -130,6 +130,12 @@ SCENE_METADATA_SOURCES = frozenset( {MetadataSource.DEMOZOO, MetadataSource.POUET, MetadataSource.CSDB} ) +# Sources that report the dump a hash matched rather than the title. Their tags +# fill an empty slot only: a filename and a gamelist.xml are curated with the +# library, so they own these fields and the locale pickers read them back. +HASH_MATCHED_TAG_SOURCES = frozenset({MetadataSource.SS, MetadataSource.HASHEOUS}) +PROVIDER_TAG_FIELDS = ("regions", "languages") + def scene_apply_sources( available_sources: list[MetadataSource], @@ -1409,9 +1415,33 @@ async def scan_rom( handler_data = metadata_handlers[source_name]["handler"] # Only update fields that have valid values for key, field_value in handler_data.items(): + if key in PROVIDER_TAG_FIELDS and source_name in HASH_MATCHED_TAG_SOURCES: + continue if field_value: rom_attrs[key] = field_value + # Re-read rather than taken off the row, which cannot say whether its value + # is a tag the user wrote or what a provider left there on an earlier scan. + filename_tags = fs_rom_handler.parse_tags(rom_attrs["fs_name"]) + local_tags = { + "regions": filename_tags.regions, + "languages": filename_tags.languages, + } + for field in PROVIDER_TAG_FIELDS: + if local_tags[field] or any( + metadata_handlers[source_name]["handler"].get(field) + for source_name in priority_ordered + if source_name not in HASH_MATCHED_TAG_SOURCES + ): + continue + for source_name in priority_ordered: + if source_name not in HASH_MATCHED_TAG_SOURCES: + continue + field_value = metadata_handlers[source_name]["handler"].get(field) + if field_value: + rom_attrs[field] = field_value + break + # Artwork sources are prioritized separately, and each field can carry its # own override on top of the shared artwork priority. for field in ["url_cover", "url_screenshots", "url_manual"]: diff --git a/backend/handler/streaming/languages.py b/backend/handler/streaming/languages.py index ec77f9b76..b9cf3ef54 100644 --- a/backend/handler/streaming/languages.py +++ b/backend/handler/streaming/languages.py @@ -2,16 +2,18 @@ from typing import Any -from handler.filesystem.base_handler import LANGUAGES +from handler.filesystem.base_handler import LANGUAGES, PROVIDER_LANGUAGES from models.rom import Rom from models.user import User -# ISO-639-1 codes for the languages RomM recognizes. rom.languages stores names -# ("French") from filename parsing and shortcodes ("fr") from metadata -# providers, so both spellings reduce to the same code here; ui_settings.locale -# stores locale codes ("pt_BR"). A broker maps what it gets to its own dialect. +# ISO-639-1 codes for the languages RomM recognizes, from both vocabularies so +# a provider-only language ("Czech") reduces like a filename tag does. +# rom.languages stores names, ui_settings.locale stores locale codes ("pt_BR"), +# and a broker maps what it gets to its own dialect. _LANGUAGE_NAME_TO_ISO = { - name.lower(): code.lower() for code, name in LANGUAGES if code.lower() != "nolang" + name.lower(): code.lower() + for code, name in (*LANGUAGES, *PROVIDER_LANGUAGES) + if code.lower() != "nolang" } _ISO_CODES = set(_LANGUAGE_NAME_TO_ISO.values()) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 8042a0349..227b5dd14 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -5874,6 +5874,14 @@ def test_the_rom_language_is_reduced_to_an_iso_code(client, access_token, rom: R assert _activate_body(client, access_token, rom)["rom"]["language"] == "fr" +def test_a_provider_only_language_is_reduced_too(client, access_token, rom: Rom): + """The languages only a provider reports ("Czech") have no filename + shortcode, so the broker would otherwise get nothing for them.""" + db_rom_handler.update_rom(rom.id, {"languages": ["Czech"]}) + + assert _activate_body(client, access_token, rom)["rom"]["language"] == "cs" + + def test_an_unknown_rom_language_is_sent_as_none(client, access_token, rom: Rom): """A value RomM cannot reduce leaves the broker on its own default rather than failing the launch.""" diff --git a/backend/tests/handler/filesystem/test_base_handler.py b/backend/tests/handler/filesystem/test_base_handler.py index ac212638a..56c5b25f3 100644 --- a/backend/tests/handler/filesystem/test_base_handler.py +++ b/backend/tests/handler/filesystem/test_base_handler.py @@ -10,7 +10,15 @@ import pytest from fastapi import UploadFile from config.config_manager import DEFAULT_EXCLUDED_FILES -from handler.filesystem.base_handler import FSHandler, region_ranks_for_priority +from handler.filesystem.base_handler import ( + FSHandler, + normalize_language, + normalize_provider_languages, + normalize_provider_regions, + provider_language_name, + provider_region_name, + region_ranks_for_priority, +) from models.base import FILE_NAME_MAX_LENGTH @@ -637,3 +645,147 @@ class TestRegionRanksForPriority: def test_empty_priority_yields_no_ranks(self): assert region_ranks_for_priority([]) == {} + + +class TestNormalizeProviderRegions: + """Provider shortcodes collapse onto the names filename parsing produces.""" + + def test_provider_shortcodes_resolve_to_canonical_names(self): + assert normalize_provider_regions(["us", "eu", "wor", "asi"]) == [ + "USA", + "Europe", + "World", + "Asia", + ] + + def test_filename_spellings_are_accepted_too(self): + assert normalize_provider_regions(["usa", "J", "EUROPE"]) == [ + "USA", + "Japan", + "Europe", + ] + + def test_shortcode_shared_with_a_language_stays_a_region(self): + # "de" and "fr" also spell a language tag, but a provider reporting + # them under a region field means Germany and France. + assert normalize_provider_regions(["de", "fr"]) == ["Germany", "France"] + + def test_duplicate_spellings_collapse_to_one_value(self): + assert normalize_provider_regions(["us", "USA", "U"]) == ["USA"] + + def test_unknown_value_is_kept_as_given(self): + assert normalize_provider_regions([" Neptune "]) == ["Neptune"] + + def test_blank_values_are_dropped(self): + assert normalize_provider_regions(["", " ", "us"]) == ["USA"] + + +class TestNormalizeProviderLanguages: + """ISO-639-1 codes collapse onto the names filename parsing produces.""" + + def test_iso_codes_resolve_to_canonical_names(self): + assert normalize_provider_languages(["en", "fr", "ja"]) == [ + "English", + "French", + "Japanese", + ] + + def test_duplicate_spellings_collapse_to_one_value(self): + assert normalize_provider_languages(["en", "English", "EN"]) == ["English"] + + def test_unknown_value_is_kept_as_given(self): + assert normalize_provider_languages([" Klingon "]) == ["Klingon"] + + def test_blank_values_are_dropped(self): + assert normalize_provider_languages(["", " ", "en"]) == ["English"] + + +# Every region ScreenScraper can report, from its published list. Providers +# send these bare, so one that resolves to nothing becomes a facet value. +SCREENSCRAPER_REGION_CODES = ( + "de", + "asi", + "au", + "br", + "bg", + "ca", + "cl", + "cn", + "ame", + "kr", + "dk", + "sp", + "eu", + "fi", + "fr", + "gr", + "hu", + "il", + "it", + "jp", + "kw", + "wor", + "mor", + "no", + "nz", + "oce", + "nl", + "pe", + "pl", + "pt", + "cz", + "uk", + "ru", + "sk", + "se", + "tw", + "tr", + "us", +) + +# The buckets that name no place. Both readers drop these rather than store them. +SCREENSCRAPER_PSEUDO_REGIONS = ("ss", "cus") + + +class TestProviderVocabularyCoverage: + """A code a provider can send has to resolve, or it lands in a facet raw.""" + + @pytest.mark.parametrize("code", SCREENSCRAPER_REGION_CODES) + def test_every_screenscraper_region_resolves(self, code: str): + assert provider_region_name(code) is not None + + @pytest.mark.parametrize("code", SCREENSCRAPER_PSEUDO_REGIONS) + def test_the_screenscraper_buckets_resolve_to_nothing(self, code: str): + assert provider_region_name(code) is None + + @pytest.mark.parametrize( + "code,expected", + [ + ("pl", "Poland"), + ("cz", "Czech Republic"), + ("tr", "Turkey"), + ("wor", "World"), + ], + ) + def test_a_region_with_no_filename_shortcode_still_canonicalizes( + self, code: str, expected: str + ): + assert normalize_provider_regions([code]) == [expected] + + @pytest.mark.parametrize( + "code,expected", + [("cs", "Czech"), ("tr", "Turkish"), ("he", "Hebrew"), ("uk", "Ukrainian")], + ) + def test_an_iso_language_with_no_filename_shortcode_canonicalizes( + self, code: str, expected: str + ): + assert normalize_provider_languages([code]) == [expected] + + def test_the_provider_languages_stay_out_of_filename_parsing(self): + """A filename "(Tr)" marks a translation, not Turkish.""" + assert normalize_language("tr") is None + assert provider_language_name("tr") == "Turkish" + + def test_a_provider_name_resolves_to_the_same_value_as_its_code(self): + assert provider_region_name("Poland") == provider_region_name("pl") + assert provider_language_name("czech") == provider_language_name("cs") diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 682328a2c..65cd52b36 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -303,6 +303,34 @@ class TestFSRomsHandler: assert handler.parse_tags("Game (nl).rom").regions == ["Netherlands"] assert handler.parse_tags("Game (no).rom").regions == ["Norway"] + def test_parse_tags_reads_two_letter_region_codes(self, handler: FSRomsHandler): + """TOSEC and similar sets write the provider shortcode, not the GoodTools + one, so "(US)" has to read as a region rather than land in tags.""" + assert handler.parse_tags("Game (US).rom").regions == ["USA"] + assert handler.parse_tags("Game (JP).rom").regions == ["Japan"] + assert handler.parse_tags("Game (EU).rom").regions == ["Europe"] + assert handler.parse_tags("Game (BR).rom").regions == ["Brazil"] + assert handler.parse_tags("Game (CZ).rom").regions == ["Czech Republic"] + + parsed = handler.parse_tags("Game (1994)(Konami)(JP).tap") + assert parsed.regions == ["Japan"] + assert "JP" not in parsed.other_tags + + def test_parse_tags_leaves_the_ambiguous_codes_to_their_own_tables( + self, handler: FSRomsHandler + ): + """A two-letter code a language table claims keeps its old meaning, which + is what issue #3026 turned on.""" + assert handler.parse_tags("Game (De).rom").languages == ["German"] + assert handler.parse_tags("Game (Fr).rom").languages == ["French"] + assert handler.parse_tags("Game (Pt).rom").languages == ["Portuguese"] + assert handler.parse_tags("Game (De).rom").regions == [] + + # "(Tr)" marks a translation by dumper convention, never Turkey. + parsed = handler.parse_tags("Game (Japan) (Tr).rom") + assert parsed.regions == ["Japan"] + assert parsed.other_tags == ["Tr"] + def test_parse_tags_language_casing_is_normalized(self, handler: FSRomsHandler): """Language names collapse to one canonical spelling regardless of casing.""" for fs_name in ( diff --git a/backend/tests/handler/metadata/test_gamelist_handler.py b/backend/tests/handler/metadata/test_gamelist_handler.py index 1639251b4..bd8558cc4 100644 --- a/backend/tests/handler/metadata/test_gamelist_handler.py +++ b/backend/tests/handler/metadata/test_gamelist_handler.py @@ -67,8 +67,8 @@ def test_parse_gamelist_xml_includes_folder_entries(tmp_path: Path, platform: Pl folder_entry = roms_data["Subfolder"] assert folder_entry.get("name") == "Folder Entry" assert folder_entry.get("summary") == "Folder summary" - assert folder_entry.get("languages") == ["en", "fr"] - assert folder_entry.get("regions") == ["us", "eu"] + assert folder_entry.get("languages") == ["English", "French"] + assert folder_entry.get("regions") == ["USA", "Europe"] def test_parse_gamelist_xml_keeps_game_entries(tmp_path: Path, platform: Platform): diff --git a/backend/tests/handler/metadata/test_hasheous_handler.py b/backend/tests/handler/metadata/test_hasheous_handler.py index b49dd7699..4146e950b 100644 --- a/backend/tests/handler/metadata/test_hasheous_handler.py +++ b/backend/tests/handler/metadata/test_hasheous_handler.py @@ -1,11 +1,15 @@ +from typing import Any from unittest.mock import AsyncMock, patch import httpx import pytest from fastapi import HTTPException +from handler.filesystem.base_handler import provider_language_name from handler.metadata.hasheous_handler import ( HasheousHandler, + _country_name, + _tags_from_signatures, extract_metadata_from_igdb_rom, ) @@ -75,3 +79,105 @@ async def test_request_propagates_an_unreachable_hasheous(failure: Exception): ): ctx.get.return_value = client await handler._request("https://hasheous.org/api") + + +# Shaped after a real /Lookup/ByHash answer: every signature source reports the +# matched dump under `rom`, with the game it belongs to beside it. +SIGNATURES = { + "TOSEC": [ + { + "game": {"country": {"EU": "Europe", "US": "United States"}}, + "rom": {"country": {"EU": "Europe"}, "language": {}}, + } + ], + "NoIntros": [ + { + "game": {"country": {"EU": "Europe", "JP": "Japan", "US": "United States"}}, + "rom": { + "country": {"US": "United States"}, + "language": {"en": "English"}, + }, + } + ], +} + + +def _regions(signatures: dict[str, Any]) -> list[str]: + return _tags_from_signatures(signatures, "country", _country_name) + + +def _languages(signatures: dict[str, Any]) -> list[str]: + return _tags_from_signatures(signatures, "language", provider_language_name) + + +class TestTagsFromSignatures: + """Region and language data for the dump a hash matched.""" + + def test_prefers_the_curated_dump_over_the_other_sources(self): + # TOSEC says Europe for the same hash; No-Intro wins. + assert _regions(SIGNATURES) == ["USA"] + + def test_reads_the_language_of_the_matched_dump(self): + assert _languages(SIGNATURES) == ["English"] + + def test_falls_through_to_a_source_that_has_the_field(self): + signatures = {"TOSEC": SIGNATURES["TOSEC"], "NoIntros": [{"rom": {}}]} + + assert _regions(signatures) == ["Europe"] + + def test_resolves_a_code_romm_knows_rather_than_its_printed_name(self): + signatures = {"NoIntros": [{"rom": {"country": {"wor": "", "JP": "Japan"}}}]} + + assert _regions(signatures) == ["World", "Japan"] + + def test_a_code_that_means_another_place_to_romm_uses_the_printed_name(self): + # "CH" is Switzerland to Hasheous and China to a No-Intro filename. + assert _regions( + {"NoIntros": [{"rom": {"country": {"CH": "Switzerland"}}}]} + ) == ["Switzerland"] + + def test_keeps_the_printed_name_of_a_code_romm_does_not_know(self): + signatures = {"NoIntros": [{"rom": {"country": {"PL": "Poland"}}}]} + + assert _regions(signatures) == ["Poland"] + + def test_canonicalizes_the_printed_name_it_falls_back_to(self): + signatures = {"NoIntros": [{"rom": {"country": {"XX": "japan"}}}]} + + assert _regions(signatures) == ["Japan"] + + def test_drops_a_bucket_that_names_no_region(self): + # "ss" is a ScreenScraper bucket, and it comes with no display name. + signatures = { + "NoIntros": [{"rom": {"country": {"ss": "", "US": "United States"}}}] + } + + assert _regions(signatures) == ["USA"] + + def test_a_game_only_match_reports_nothing(self): + signatures = {"NoIntros": [{"game": {"country": {"US": "United States"}}}]} + + assert _regions(signatures) == [] + + def test_no_signatures_report_nothing(self): + assert _regions({}) == [] + + @pytest.mark.parametrize( + "signatures", + [ + pytest.param({"NoIntros": {}}, id="source-is-not-a-list"), + pytest.param({"NoIntros": ["TOSEC"]}, id="entry-is-not-an-object"), + pytest.param({"NoIntros": [{"rom": []}]}, id="rom-is-an-empty-collection"), + pytest.param( + {"NoIntros": [{"rom": {"country": []}}]}, id="field-is-a-list" + ), + pytest.param( + {"NoIntros": [{"rom": {"country": {"ZZ": None}}}]}, id="null-name" + ), + ], + ) + def test_a_shape_hasheous_did_not_promise_reports_nothing( + self, signatures: dict[str, Any] + ): + # A raise here would abort the scan of the rom, not just its tags. + assert _regions(signatures) == [] diff --git a/backend/tests/handler/metadata/test_ss_handler.py b/backend/tests/handler/metadata/test_ss_handler.py index e1aec435f..5254bb1a8 100644 --- a/backend/tests/handler/metadata/test_ss_handler.py +++ b/backend/tests/handler/metadata/test_ss_handler.py @@ -15,7 +15,7 @@ from adapters.services.screenscraper import ( SSAccountLimits, SSCredentialSet, ) -from adapters.services.screenscraper_types import SSGame +from adapters.services.screenscraper_types import SSGame, SSGameRom from config.config_manager import Config, MetadataMediaType from handler.metadata import ss_handler from handler.metadata.base_handler import PS1_SERIAL_INDEX_KEY @@ -29,8 +29,11 @@ from handler.metadata.ss_handler import ( _is_notgame, add_ss_auth_to_url, build_ss_game, + extract_languages_from_ss_dump, extract_media_from_ss_game, extract_metadata_from_ss_rom, + extract_regions_from_ss_dump, + find_ss_dump, get_preferred_languages, get_preferred_regions, get_rate_limited_rom_names, @@ -39,7 +42,7 @@ from handler.metadata.ss_handler import ( reset_rate_limited_roms, ) from handler.redis_handler import async_cache -from models.rom import Rom +from models.rom import LookupHashes, Rom from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE @@ -1224,6 +1227,85 @@ class TestLookupRom: assert result["name"] == "Adventure Island 2" assert is_not_game is False + @pytest.mark.asyncio + async def test_a_filename_match_reports_no_regions(self): + """A bare romnom match identifies a title, so it says nothing about the + dump on disk and must not tag it.""" + config = _make_config(region_priority=["us"]) + game = { + "id": "1234", + "noms": [{"region": "us", "text": "Adventure Island 2"}], + "medias": [], + "synopsis": [], + "dates": [], + "genres": [], + "familles": [], + "modes": [], + "joueurs": {}, + "note": {}, + "roms": [ + { + "id": 7, + "rommd5": "B330314E19126D87D156D0618C4657B0", + "regions": {"regions_shortname": ["jp"]}, + } + ], + } + handler = SSHandler() + mock_file = self._make_unhashed_file("Adventure Island II.nes") + rom = MagicMock(platform_slug="nes", platform_id=1, id=100, regions=[]) + + with ( + patch("handler.metadata.ss_handler.cm.get_config", return_value=config), + patch.object(handler.ss_service, "get_game_info", return_value=game), + ): + result, _ = await handler.lookup_rom(rom, 3, [mock_file]) + + assert result["ss_id"] == 1234 + assert "regions" not in result + + @pytest.mark.asyncio + async def test_a_hash_match_reports_the_dumps_tags(self): + """A hash picks one entry out of `jeu.roms`, and that entry is the file.""" + config = _make_config(region_priority=["us"]) + game = { + "id": "1234", + "noms": [{"region": "us", "text": "Adventure Island 2"}], + "medias": [], + "synopsis": [], + "dates": [], + "genres": [], + "familles": [], + "modes": [], + "joueurs": {}, + "note": {}, + "roms": [ + { + "id": 7, + "rommd5": "999999", + "regions": {"regions_shortname": ["us"]}, + }, + { + "id": 8, + "rommd5": "ABC123", + "regions": {"regions_shortname": ["jp"]}, + "langues": {"langues_shortname": ["ja"]}, + }, + ], + } + handler = SSHandler() + mock_file = self._make_mock_file() + rom = MagicMock(platform_slug="nes", platform_id=1, id=100, regions=[]) + + with ( + patch("handler.metadata.ss_handler.cm.get_config", return_value=config), + patch.object(handler.ss_service, "get_game_info", return_value=game), + ): + result, _ = await handler.lookup_rom(rom, 3, [mock_file]) + + assert result["regions"] == ["Japan"] + assert result["languages"] == ["Japanese"] + @pytest.mark.asyncio async def test_no_hash_no_filename_skips_lookup(self): """With neither a hash nor a filename there is nothing to match on, so the @@ -2026,3 +2108,90 @@ class TestDevCredentials: ), ): assert SSHandler.has_dev_credentials() is expected + + +class TestExtractFromSSDump: + """`jeu.roms` lists every dump of a game; only ours describes the file.""" + + # Shaped after a real jeuInfos payload, trimmed to the keys read here. + ROMS = [ + { + "id": 4219, + "romfilename": "Super Mario Bros.", + "rommd5": "B330314E19126D87D156D0618C4657B0", + "romsha1": "8EE8032491DEE422534B82F107DE0E9F5F9D44F9", + "romcrc": "A5C2849E", + "trad": 0, + "regions": {"regions_shortname": ["wor"], "regions_en": ["World"]}, + }, + { + "id": 154585, + "romfilename": "Super Mario Bros. (W) [T Fre].nes", + "rommd5": "811B027EAF99C2DEF7B933C5208636DE", + "romsha1": "", + "romcrc": "", + "trad": 1, + "regions": {"regions_shortname": ["us", "jp", "ss"]}, + "langues": {"langues_shortname": ["fr"], "langues_en": ["French"]}, + }, + ] + + def _game(self) -> SSGame: + # `romid` names a dump that is not ours, which is why hashes decide. + return cast(SSGame, {"id": 1245, "romid": "999999", "roms": self.ROMS}) + + def test_the_dump_is_found_by_md5_whatever_romid_says(self): + dump = find_ss_dump( + self._game(), + LookupHashes(crc=None, md5="811b027eaf99c2def7b933c5208636de", sha1=None), + ) + + assert dump is not None + assert dump["id"] == 154585 + + def test_the_dump_is_found_by_sha1(self): + dump = find_ss_dump( + self._game(), + LookupHashes( + crc=None, md5=None, sha1="8ee8032491dee422534b82f107de0e9f5f9d44f9" + ), + ) + + assert dump is not None + assert dump["id"] == 4219 + + def test_a_hash_no_dump_carries_matches_nothing(self): + assert ( + find_ss_dump(self._game(), LookupHashes(crc=None, md5="0" * 32, sha1=None)) + is None + ) + + def test_no_hashes_match_nothing(self): + assert ( + find_ss_dump(self._game(), LookupHashes(crc=None, md5=None, sha1=None)) + is None + ) + + def test_regions_come_from_the_dump(self): + dump = cast(SSGameRom, self.ROMS[1]) + + # "ss" is a ScreenScraper bucket rather than a place. + assert extract_regions_from_ss_dump(dump) == ["USA", "Japan"] + + def test_languages_come_from_the_dump(self): + assert extract_languages_from_ss_dump(cast(SSGameRom, self.ROMS[1])) == [ + "French" + ] + + def test_a_dump_without_tags_reports_nothing(self): + dump = cast(SSGameRom, {"id": 1}) + + assert extract_regions_from_ss_dump(dump) == [] + assert extract_languages_from_ss_dump(dump) == [] + + def test_a_game_with_no_dumps_matches_nothing(self): + game = cast(SSGame, {"id": 1}) + + assert ( + find_ss_dump(game, LookupHashes(crc=None, md5="a" * 32, sha1=None)) is None + ) diff --git a/backend/tests/handler/test_scan_provider_tags.py b/backend/tests/handler/test_scan_provider_tags.py new file mode 100644 index 000000000..71b366724 --- /dev/null +++ b/backend/tests/handler/test_scan_provider_tags.py @@ -0,0 +1,139 @@ +"""How a scan applies the regions and languages a hash-matched provider reports. + +A hash names one dump, so its tags fill a gap the filename left, never overwrite it. +""" + +from collections.abc import Iterator +from typing import Any +from unittest.mock import AsyncMock, patch + +import pytest +from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan + +from handler.metadata.hasheous_handler import HasheousRom +from handler.metadata.ss_handler import SSRom +from handler.scan_handler import MetadataSource, ScanType +from models.rom import Rom + +HASHEOUS_MATCH = HasheousRom( + hasheous_id=1, + name="Mario Kart 64", + igdb_id=None, + tgdb_id=None, + ra_id=None, + regions=["Japan"], + languages=["Japanese"], +) +SS_MATCH = SSRom(ss_id=42, name="Mario Kart 64", regions=["Europe"]) + + +@pytest.fixture +def hasheous_lookup() -> Iterator[AsyncMock]: + """Patch the Hasheous hash lookup and the two proxied catalog fetches.""" + with ( + patch( + "handler.scan_handler.meta_hasheous_handler.lookup_rom", + new=AsyncMock(return_value=(HASHEOUS_MATCH, True)), + ) as lookup, + patch( + "handler.scan_handler.meta_hasheous_handler.get_igdb_game", + new=AsyncMock(return_value=HasheousRom(hasheous_id=1)), + ), + patch( + "handler.scan_handler.meta_hasheous_handler.get_ra_game", + new=AsyncMock(return_value=HasheousRom(hasheous_id=1)), + ), + ): + yield lookup + + +@pytest.fixture +def ss_lookup() -> Iterator[AsyncMock]: + """Patch the ScreenScraper hash lookup, the only one that names a dump.""" + with patch( + "handler.scan_handler.meta_ss_handler.lookup_rom", + new=AsyncMock(return_value=(SS_MATCH, False)), + ) as by_hash: + yield by_hash + + +@pytest.fixture +def ss_name_search() -> Iterator[AsyncMock]: + """Patch the ScreenScraper name search, which identifies a title, not a dump.""" + with ( + patch( + "handler.scan_handler.meta_ss_handler.lookup_rom", + new=AsyncMock(return_value=(SSRom(ss_id=None), False)), + ), + patch( + "handler.scan_handler.meta_ss_handler.get_rom", + new=AsyncMock(return_value=SSRom(ss_id=42, name="Mario Kart 64")), + ) as by_name, + ): + yield by_name + + +async def _scan( + source: MetadataSource, + fs_name: str = "Mario Kart 64.z64", + **rom_overrides: Any, +) -> Rom: + platform = add_n64_platform(hasheous_id=4, ss_id=14) + rom = add_rom(platform, fs_name, "Mario Kart 64", **rom_overrides) + + return await run_scan( + platform, rom, scan_type=ScanType.COMPLETE, metadata_sources=[source] + ) + + +async def test_hasheous_fills_untagged_regions_and_languages( + hasheous_lookup: AsyncMock, +): + result = await _scan(MetadataSource.HASHEOUS, regions=[], languages=[]) + + assert result.regions == ["Japan"] + assert result.languages == ["Japanese"] + + +async def test_hasheous_leaves_the_filename_tags_alone(hasheous_lookup: AsyncMock): + result = await _scan( + MetadataSource.HASHEOUS, + fs_name="Mario Kart 64 (USA) (En).z64", + regions=["USA"], + languages=["English"], + ) + + assert result.regions == ["USA"] + assert result.languages == ["English"] + + +async def test_screenscraper_fills_untagged_regions(ss_lookup: AsyncMock): + result = await _scan(MetadataSource.SS, regions=[]) + + assert result.regions == ["Europe"] + + +async def test_screenscraper_leaves_the_filename_tags_alone(ss_lookup: AsyncMock): + result = await _scan( + MetadataSource.SS, fs_name="Mario Kart 64 (Japan).z64", regions=["Japan"] + ) + + assert result.regions == ["Japan"] + + +async def test_a_screenscraper_name_match_reports_no_regions(ss_name_search: AsyncMock): + """A title matched by name says nothing about which dump is on disk.""" + result = await _scan(MetadataSource.SS, regions=[]) + + assert result.ss_id == 42 + assert result.regions == [] + + +async def test_a_tag_an_earlier_scan_stored_is_refreshed(hasheous_lookup: AsyncMock): + """The filename owns the slot, not whatever a provider left on the row.""" + result = await _scan( + MetadataSource.HASHEOUS, regions=["Europe"], languages=["French"] + ) + + assert result.regions == ["Japan"] + assert result.languages == ["Japanese"]