From fbbadb7c86e19edc331c09dabadef842e0f96d33 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 4 Sep 2026 10:57:36 -0400 Subject: [PATCH] refactor(scan): give the title id one resolver and one identity shape The Tinfoil feed was left behind when `_switch_productid_format` changed from taking a `re.Match` to taking a `str`, so `/feeds/tinfoil` raised a TypeError for any Switch rom carrying a product id in its filename but no titledb id. It went unnoticed because `feeds.py` sits outside the changed files mypy sees. That call site was reachable only because "prefer the id the scan read over the one scraped from the filename" lived in a second helper above the lookup, leaving each caller to remember it. The resolution now happens inside `_switch_productid_format`, so the three providers and the feed all get it without repeating a preamble. Also: - Move `SWITCH_PLATFORM_SLUGS` to the sigil adapter so `utils/switch.py` stops importing the metadata base handler. The cycle that import created was papered over with a function-local import, and `normalize_identity` now takes the fact it needs rather than the whole slug set. - Merge a partial identity update onto the stored identity before normalizing it. Normalizing rewrites the whole triple, so a client sending only a title id was getting the derived base id next to its old save target. - Add `RomIdentity.from_rom` so the triple has one home on the read side too, and drop `asdict` from `as_rom_attrs`. - Hold the `SigilExtractionResult` on `TitleIdEmbedCandidate` instead of copying two of its fields. - Drop a guard in `_rom_level_identity` that could not fire, derive once in `normalize_identity`, and return only the parse from `_rebuild_rom_files`, which already owns `fs_rom["fs_name"]`. - Read the parsed config in the heartbeat rather than forcing a YAML re-parse per request, and make `SigilService.is_enabled` a classmethod like every other one. Co-Authored-By: Claude Opus 5 (1M context) --- backend/adapters/services/sigil.py | 11 ++++++--- backend/endpoints/feeds.py | 6 ++--- backend/endpoints/heartbeat.py | 3 +-- backend/endpoints/roms/__init__.py | 21 +++++++--------- backend/endpoints/sockets/scan.py | 24 +++++++------------ backend/handler/filesystem/roms_handler.py | 24 ++++++++----------- backend/handler/metadata/base_handler.py | 24 +++++++++---------- backend/handler/metadata/igdb_handler.py | 22 ++++++++--------- backend/handler/metadata/moby_handler.py | 22 ++++++++--------- backend/handler/metadata/ss_handler.py | 22 ++++++++--------- backend/handler/scan_handler.py | 6 ++--- backend/models/rom.py | 17 +++++++++++-- .../handler/filesystem/test_roms_handler.py | 4 +++- .../handler/metadata/test_base_handler.py | 24 ++++++++++++++++--- backend/utils/switch.py | 18 +++----------- 15 files changed, 124 insertions(+), 124 deletions(-) diff --git a/backend/adapters/services/sigil.py b/backend/adapters/services/sigil.py index 219e28e1c..925e92644 100644 --- a/backend/adapters/services/sigil.py +++ b/backend/adapters/services/sigil.py @@ -28,6 +28,10 @@ SIGIL_PLATFORM_SLUGS: Final[dict[str, str]] = { UPS.XBOX360: "xbox360", } +# The Switch family in RomM's own terms. Its headers need prod.keys to decrypt, +# and it is the only family whose files may carry their title id in the filename. +SWITCH_PLATFORM_SLUGS: Final = frozenset({UPS.SWITCH, UPS.SWITCH_2}) + # Errors that are expected for arbitrary library files (no title id present, # format sigil can't parse, missing decryption keys). Logged at debug level. ROUTINE_SIGIL_ERROR_CODES: Final = frozenset( @@ -48,11 +52,12 @@ class SigilService: """Service to extract platform-native title ids from ROM binaries via the optional `sigil` cffi binding.""" - def is_enabled(self) -> bool: + @classmethod + def is_enabled(cls) -> bool: """Whether this build can read title ids at all. - An absent binding is indistinguishable from a file with no title id in - the results alone, so admins and clients read this instead of guessing. + The results alone can't say: an absent binding looks like a file with + no title id. """ return sigil is not None diff --git a/backend/endpoints/feeds.py b/backend/endpoints/feeds.py index f28e6e69a..7ddddc6a7 100644 --- a/backend/endpoints/feeds.py +++ b/backend/endpoints/feeds.py @@ -46,7 +46,6 @@ from handler.filesystem import fs_rom_handler from handler.metadata import meta_igdb_handler from handler.metadata.base_handler import ( SONY_SERIAL_REGEX, - SWITCH_PRODUCT_ID_REGEX, SWITCH_TITLEDB_REGEX, ) from handler.metadata.base_handler import UniversalPlatformSlug as UPS @@ -225,7 +224,6 @@ async def tinfoil_index_feed( titledb: dict[str, dict] = {} for rom in roms: tdb_match = SWITCH_TITLEDB_REGEX.search(rom.fs_name) - pid_match = SWITCH_PRODUCT_ID_REGEX.search(rom.fs_name) if tdb_match: ( _search_term, @@ -239,12 +237,12 @@ async def tinfoil_index_feed( titledb[key] = TinfoilFeedTitleDBSchema( **index_entry ).model_dump() - elif pid_match: + else: ( _search_term, index_entry, ) = await meta_igdb_handler._switch_productid_format( - pid_match, rom.fs_name + rom, rom.fs_name, rom.fs_name ) if index_entry: key = str(index_entry.get("nsuId", None)) diff --git a/backend/endpoints/heartbeat.py b/backend/endpoints/heartbeat.py index d1be8f98c..a3499b729 100644 --- a/backend/endpoints/heartbeat.py +++ b/backend/endpoints/heartbeat.py @@ -88,9 +88,8 @@ async def heartbeat() -> HeartbeatResponse: Returns: HeartbeatReturn: TypedDict structure with all the defined values in the HeartbeatReturn class. """ - # Extraction needs both the optional binding and the config switch. title_id_extraction_enabled = ( - SigilService().is_enabled() and not cm.get_config().SKIP_TITLE_ID_EXTRACTION + SigilService.is_enabled() and not cm.config.SKIP_TITLE_ID_EXTRACTION ) igdb_enabled = meta_igdb_handler.is_enabled() diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 9f0db1a4a..099e3f71c 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -1,6 +1,7 @@ import binascii import json from base64 import b64encode +from dataclasses import replace from datetime import datetime, timezone from io import BytesIO from stat import S_IFREG @@ -32,6 +33,7 @@ from pydantic import BaseModel, Field from sqlalchemy.exc import IntegrityError from starlette.responses import FileResponse +from adapters.services.sigil import SWITCH_PLATFORM_SLUGS from config import ( DEV_MODE, DISABLE_DOWNLOAD_ENDPOINT_AUTH, @@ -2598,21 +2600,16 @@ async def update_rom_identity( cleaned_data = data.model_dump(exclude_unset=True) if cleaned_data.get("title_id"): - normalized = switch.normalize_identity( - rom.platform_slug, RomIdentity(**cleaned_data) - ) - # Only the fields the client sent are written, so an omitted one keeps - # whatever the rom already has. - cleaned_data = { - key: value - for key, value in normalized.as_rom_attrs().items() - if key in cleaned_data - } + # Normalizing rewrites the whole triple, so it is merged onto the stored + # identity first rather than onto an otherwise-empty one. + merged = replace(RomIdentity.from_rom(rom), **cleaned_data) + cleaned_data = switch.normalize_identity( + rom.platform_slug in SWITCH_PLATFORM_SLUGS, merged + ).as_rom_attrs() updated_row = db_rom_handler.update_rom(id, cleaned_data) - # The rom fetched above is already loaded with the relationships the schema - # reads, so the new values are copied onto it rather than loading it again. + # The rom is already loaded with the relationships the schema reads. for key, value in cleaned_data.items(): setattr(rom, key, value) rom.updated_at = updated_row.updated_at diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 49d895d21..3c4fd7f18 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -1,9 +1,9 @@ from __future__ import annotations import asyncio +from collections.abc import Sequence from dataclasses import dataclass from itertools import batched -from collections.abc import Sequence from typing import Any, Final import socketio # type: ignore @@ -13,6 +13,7 @@ from rq.exceptions import AbandonedJobError from rq.job import Job, JobStatus from sqlalchemy.exc import IntegrityError +from adapters.services.sigil import SWITCH_PLATFORM_SLUGS from config import DEV_MODE, REDIS_URL, SCAN_TIMEOUT, SCAN_WORKERS, TASK_RESULT_TTL from config.config_manager import MetadataMediaType from config.config_manager import config_manager as cm @@ -86,7 +87,6 @@ from utils.audio_tags import remove_persisted_cover from utils.context import initialize_context from utils.gamelist_exporter import GamelistExporter from utils.pegasus_exporter import PegasusExporter -from utils.switch import SWITCH_PLATFORM_SLUGS STOP_SCAN_FLAG: Final = "scan:stop" @@ -451,12 +451,8 @@ async def _rebuild_rom_files( extract_title_ids: bool, embed_title_ids: bool, existing_files: Sequence[RomFile] | None = None, -) -> tuple[ParsedRomFiles, str | None]: - """Re-read a rom's files onto `fs_rom`, embedding title ids when enabled. - - Returns: - The parse, and the rom's new `fs_name` when embedding renamed it. - """ +) -> ParsedRomFiles: + """Re-read a rom's files onto `fs_rom`, embedding title ids when enabled.""" parsed = await fs_rom_handler.get_rom_files( rom, calculate_hashes=calculate_hashes, @@ -481,7 +477,7 @@ async def _rebuild_rom_files( if renamed_rom_fs_name: fs_rom["fs_name"] = renamed_rom_fs_name - return parsed, renamed_rom_fs_name + return parsed # There's an order of operations here that is important: @@ -560,7 +556,7 @@ async def _identify_rom( # the files and check whether they belong to an existing entry that went # missing (a renamed or moved ROM), so its collections, notes, and # uploaded assets carry over instead of being orphaned on a duplicate. - parsed_rom_files, renamed_rom_fs_name = await _rebuild_rom_files( + parsed_rom_files = await _rebuild_rom_files( Rom( **rom_attrs, platform=platform, @@ -571,8 +567,7 @@ async def _identify_rom( embed_title_ids=embed_title_ids, ) # The new-entry insert reads its name from rom_attrs, not fs_rom. - if renamed_rom_fs_name: - rom_attrs["fs_name"] = renamed_rom_fs_name + rom_attrs["fs_name"] = fs_rom["fs_name"] files_built = True missing_match = db_rom_handler.get_matching_missing_rom( @@ -637,7 +632,7 @@ async def _identify_rom( if calculate_hashes: log.debug(f"Calculating file hashes for {rom.fs_name}...") - _, renamed_rom_fs_name = await _rebuild_rom_files( + await _rebuild_rom_files( rom, fs_rom, calculate_hashes=calculate_hashes, @@ -651,8 +646,7 @@ async def _identify_rom( ), ) # Keep the in-memory rom's name matching the renamed file. - if renamed_rom_fs_name: - rom.fs_name = renamed_rom_fs_name + rom.fs_name = fs_rom["fs_name"] # For a COMPLETE rescan, wipe all downloaded resources before re-fetching so # stale files (e.g. a cover from the wrong region) can't be reused. The diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 0500aeb7f..02769ce2b 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -15,6 +15,7 @@ from anyio import Path as AnyioPath from adapters.services.sigil import ( SIGIL_PLATFORM_SLUGS, + SWITCH_PLATFORM_SLUGS, SigilExtractionResult, SigilService, ) @@ -188,8 +189,7 @@ class TitleIdEmbedCandidate: """A parsed file whose name can carry the Switch title id read from it.""" rom_file: RomFile - title_id: str - version: int | None + extraction: SigilExtractionResult # Renaming this file renames the rom, so the caller reconciles `fs_name`. is_rom_level: bool @@ -295,14 +295,11 @@ def _rom_level_identity( if not extractions: return RomIdentity() - chosen = extractions[0] - if platform_slug in switch.SWITCH_PLATFORM_SLUGS: - chosen = next( - (e for e in extractions if switch.is_base_title_id(e.title_id)), chosen - ) - + chosen = next( + (e for e in extractions if switch.is_base_title_id(e.title_id)), extractions[0] + ) return switch.normalize_identity( - platform_slug, + platform_slug in SWITCH_PLATFORM_SLUGS, RomIdentity( title_id=chosen.title_id, save_target=chosen.save_target, @@ -533,7 +530,7 @@ class FSRomsHandler(FSHandler): # Title id extraction is independent of hashing support: it covers # non-hashable platforms like Switch. sigil_platform = extract_title_ids and rom.platform_slug in SIGIL_PLATFORM_SLUGS - is_switch = rom.platform_slug in switch.SWITCH_PLATFORM_SLUGS + is_switch = rom.platform_slug in SWITCH_PLATFORM_SLUGS sigil_extractions: list[SigilExtractionResult] = [] embed_candidates: list[TitleIdEmbedCandidate] = [] sigil_service = SigilService() @@ -562,8 +559,7 @@ class FSRomsHandler(FSHandler): embed_candidates.append( TitleIdEmbedCandidate( rom_file=rom_file, - title_id=extraction.title_id, - version=extraction.version, + extraction=extraction, is_rom_level=is_rom_level, ) ) @@ -1035,8 +1031,8 @@ class FSRomsHandler(FSHandler): rom_file = candidate.rom_file new_name = await self._embed_switch_title_id_in_name( Path(rom_file.file_path, rom_file.file_name), - candidate.title_id, - candidate.version, + candidate.extraction.title_id, + candidate.extraction.version, ) if new_name is None: continue diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index ba6f28e0e..b1fe22b4b 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -17,6 +17,7 @@ from tasks.scheduled.update_switch_titledb import ( SWITCH_TITLEDB_INDEX_KEY, ) from utils.context import ctx_httpx_client +from utils.switch import derive_base_title_id if TYPE_CHECKING: from models.rom import Rom @@ -276,21 +277,18 @@ class MetadataHandler(abc.ABC): return search_term, None - @staticmethod - def switch_product_id(rom: "Rom", fs_name: str) -> str | None: - """The Switch product id to search by, preferring the one the scan read - out of the binary over one scraped from the filename.""" - if rom.title_id and SWITCH_PRODUCT_ID_REGEX.fullmatch(rom.title_id.upper()): - return rom.title_id.upper() - - match = SWITCH_PRODUCT_ID_REGEX.search(fs_name) - return match.group(1) if match else None - async def _switch_productid_format( - self, product_id: str, search_term: str + self, rom: "Rom", fs_name: str, search_term: str ) -> tuple[str, dict | None]: - # Imported here because utils.switch imports this module for the slugs. - from utils.switch import derive_base_title_id + """Match by Switch product id, preferring the one the scan read out of + the binary over one scraped from the filename.""" + if rom.title_id and SWITCH_PRODUCT_ID_REGEX.fullmatch(rom.title_id.upper()): + product_id = rom.title_id.upper() + else: + match = SWITCH_PRODUCT_ID_REGEX.search(fs_name) + if not match: + return search_term, None + product_id = match.group(1) # Updates and DLC share the base application's product ID, off by the # low 12 bits, and only the base has a titledb entry. diff --git a/backend/handler/metadata/igdb_handler.py b/backend/handler/metadata/igdb_handler.py index c9e46d8c7..cffd35e04 100644 --- a/backend/handler/metadata/igdb_handler.py +++ b/backend/handler/metadata/igdb_handler.py @@ -830,19 +830,17 @@ class IGDBHandler(MetadataHandler): # Support for switch productID filename format if platform_igdb_id == SWITCH_IGDB_ID: - product_id = self.switch_product_id(rom, fs_name) - if product_id: - search_term, index_entry = await self._switch_productid_format( - product_id, search_term + search_term, index_entry = await self._switch_productid_format( + rom, fs_name, search_term + ) + if index_entry: + fallback_rom = IGDBRom( + igdb_id=None, + name=index_entry["name"], + summary=index_entry.get("description", ""), + url_cover=index_entry.get("iconUrl", ""), + url_screenshots=index_entry.get("screenshots", None) or [], ) - if index_entry: - fallback_rom = IGDBRom( - igdb_id=None, - name=index_entry["name"], - summary=index_entry.get("description", ""), - url_cover=index_entry.get("iconUrl", ""), - url_screenshots=index_entry.get("screenshots", None) or [], - ) # Support for MAME arcade filename format if platform_igdb_id in ARCADE_IGDB_IDS: diff --git a/backend/handler/metadata/moby_handler.py b/backend/handler/metadata/moby_handler.py index 196d5fdcf..c494b049b 100644 --- a/backend/handler/metadata/moby_handler.py +++ b/backend/handler/metadata/moby_handler.py @@ -216,19 +216,17 @@ class MobyGamesHandler(MetadataHandler): # Support for switch productID filename format if platform_moby_id == SWITCH_MOBY_ID: - product_id = self.switch_product_id(rom, fs_name) - if product_id: - search_term, index_entry = await self._switch_productid_format( - product_id, search_term + search_term, index_entry = await self._switch_productid_format( + rom, fs_name, search_term + ) + if index_entry: + fallback_rom = MobyGamesRom( + moby_id=None, + name=index_entry["name"], + summary=index_entry.get("description", ""), + url_cover=index_entry.get("iconUrl", ""), + url_screenshots=index_entry.get("screenshots", None) or [], ) - if index_entry: - fallback_rom = MobyGamesRom( - moby_id=None, - name=index_entry["name"], - summary=index_entry.get("description", ""), - url_cover=index_entry.get("iconUrl", ""), - url_screenshots=index_entry.get("screenshots", None) or [], - ) # Support for MAME arcade filename format if platform_moby_id in ARCADE_MOBY_IDS: diff --git a/backend/handler/metadata/ss_handler.py b/backend/handler/metadata/ss_handler.py index d10f513e0..923cca460 100644 --- a/backend/handler/metadata/ss_handler.py +++ b/backend/handler/metadata/ss_handler.py @@ -958,19 +958,17 @@ class SSHandler(MetadataHandler): # Support for switch productID filename format if platform_ss_id == SWITCH_SS_ID: - product_id = self.switch_product_id(rom, file_name) - if product_id: - search_term, index_entry = await self._switch_productid_format( - product_id, search_term + search_term, index_entry = await self._switch_productid_format( + rom, file_name, search_term + ) + if index_entry: + fallback_rom = SSRom( + ss_id=None, + name=index_entry["name"], + summary=index_entry.get("description", ""), + url_cover=index_entry.get("iconUrl", ""), + url_screenshots=index_entry.get("screenshots", None) or [], ) - if index_entry: - fallback_rom = SSRom( - ss_id=None, - name=index_entry["name"], - summary=index_entry.get("description", ""), - url_cover=index_entry.get("iconUrl", ""), - url_screenshots=index_entry.get("screenshots", None) or [], - ) # Support for MAME arcade filename format if platform_ss_id in ARCADES_SS_IDS: diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 6359ab12f..1542df989 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -74,7 +74,7 @@ from logger.logger import log from models.assets import Save, Screenshot, State from models.firmware import Firmware from models.platform import Platform -from models.rom import Rom, RomFile, RomFileCategory +from models.rom import Rom, RomFile, RomFileCategory, RomIdentity from models.user import User from utils import emoji from utils.audio_tags import persist_embedded_cover, remove_persisted_cover @@ -519,9 +519,7 @@ async def scan_rom( "md5_hash": rom.md5_hash, "sha1_hash": rom.sha1_hash, "ra_hash": rom.ra_hash, - "title_id": rom.title_id, - "save_target": rom.save_target, - "save_target_layout": rom.save_target_layout, + **RomIdentity.from_rom(rom).as_rom_attrs(), "fs_size_bytes": rom.fs_size_bytes, "is_physical": rom.is_physical, "upc": rom.upc, diff --git a/backend/models/rom.py b/backend/models/rom.py index 622378587..e13acc111 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -4,7 +4,7 @@ import copy import enum import re from collections.abc import Sequence -from dataclasses import asdict, dataclass +from dataclasses import dataclass from datetime import datetime from functools import cached_property from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict @@ -132,9 +132,22 @@ class RomIdentity: save_target: str | None = None save_target_layout: SaveTargetLayout | None = None + @classmethod + def from_rom(cls, rom: "Rom") -> "RomIdentity": + """The identity a ROM already carries.""" + return cls( + title_id=rom.title_id, + save_target=rom.save_target, + save_target_layout=rom.save_target_layout, + ) + def as_rom_attrs(self) -> dict[str, Any]: """The identity as `Rom` column values, for a scan's attribute merge.""" - return asdict(self) + return { + "title_id": self.title_id, + "save_target": self.save_target, + "save_target_layout": self.save_target_layout, + } # Document-category files (manuals, walkthroughs) share one substrate: a diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 75db003fc..a160b1c0d 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1904,7 +1904,9 @@ class TestSwitchTitleIdEmbedding: assert parsed.rom_files[0].file_name == "Game.nsp" assert (tmp_path / "switch/roms/Game.nsp").exists() # The rename is offered to the caller, not performed. - assert [c.title_id for c in parsed.embed_candidates] == ["0100ABCD12340000"] + assert [c.extraction.title_id for c in parsed.embed_candidates] == [ + "0100ABCD12340000" + ] assert parsed.embed_candidates[0].is_rom_level @pytest.mark.asyncio diff --git a/backend/tests/handler/metadata/test_base_handler.py b/backend/tests/handler/metadata/test_base_handler.py index 68ec97a82..0580164d4 100644 --- a/backend/tests/handler/metadata/test_base_handler.py +++ b/backend/tests/handler/metadata/test_base_handler.py @@ -328,7 +328,8 @@ class TestMetadataHandlerMethods: mock_exists.return_value = True mock_hget.return_value = json.dumps({"name": "Product Game"}) - result = await handler._switch_productid_format(product_id, "original") + rom = Rom(fs_name="Game.nsp", title_id=product_id) + result = await handler._switch_productid_format(rom, "Game.nsp", "original") mock_hget.assert_called_once_with( "romm:switch_product_id", # SWITCH_PRODUCT_ID_KEY @@ -350,7 +351,8 @@ class TestMetadataHandlerMethods: (None, "Game.nsp", None), ], ) - def test_switch_product_id_prefers_the_extracted_id( + @pytest.mark.asyncio + async def test_switch_productid_format_prefers_the_extracted_id( self, handler: MetadataHandler, title_id: str | None, @@ -359,7 +361,23 @@ class TestMetadataHandlerMethods: ): rom = Rom(fs_name=fs_name, title_id=title_id) - assert handler.switch_product_id(rom, fs_name) == expected + with patch.object( + async_cache, "exists", new_callable=AsyncMock + ) as mock_exists, patch.object( + async_cache, "hget", new_callable=AsyncMock + ) as mock_hget: + mock_exists.return_value = True + mock_hget.return_value = None + + await handler._switch_productid_format(rom, fs_name, "original") + + if expected is None: + mock_hget.assert_not_called() + else: + mock_hget.assert_called_once_with( + "romm:switch_product_id", # SWITCH_PRODUCT_ID_KEY + expected, + ) @pytest.mark.asyncio async def test_mame_format_found(self, handler: MetadataHandler): diff --git a/backend/utils/switch.py b/backend/utils/switch.py index 541acf475..673ca860b 100644 --- a/backend/utils/switch.py +++ b/backend/utils/switch.py @@ -4,13 +4,8 @@ update or DLC id, and mapping a content type to a file category.""" import re from typing import Final -from handler.metadata.base_handler import UniversalPlatformSlug as UPS from models.rom import RomFileCategory, RomIdentity, SaveTargetLayout -# The Switch family in RomM's own terms. Its headers need prod.keys to decrypt, -# and it is the only family whose files may carry their title id in the filename. -SWITCH_PLATFORM_SLUGS: Final = frozenset({UPS.SWITCH, UPS.SWITCH_2}) - # Maps sigil's Switch CNMT content type to the RomFile category. Authoritative # over folder-derived categories when the binary parse succeeds. CONTENT_TYPE_CATEGORIES: Final[dict[str, RomFileCategory]] = { @@ -45,7 +40,7 @@ def is_base_title_id(title_id: str) -> bool: return derive_base_title_id(title_id) == title_id -def normalize_identity(platform_slug: str, identity: RomIdentity) -> RomIdentity: +def normalize_identity(is_switch: bool, identity: RomIdentity) -> RomIdentity: """Force a Switch identity onto the base game's, leaving others untouched. Every writer of `Rom.title_id` goes through here: reassociating a renamed @@ -53,15 +48,8 @@ def normalize_identity(platform_slug: str, identity: RomIdentity) -> RomIdentity the base game's id. A non-derivable id is left as read rather than dropped. """ title_id = identity.title_id - if ( - platform_slug not in SWITCH_PLATFORM_SLUGS - or not title_id - or is_base_title_id(title_id) - ): - return identity - - derived = derive_base_title_id(title_id) - if derived is None: + derived = derive_base_title_id(title_id) if is_switch and title_id else None + if derived is None or derived == title_id: return identity # Switch saves are keyed by the base title id itself.