Files
romm/backend/utils/switch.py
Georges-Antoine Assi fbbadb7c86 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) <noreply@anthropic.com>
2026-09-04 10:57:36 -04:00

61 lines
2.2 KiB
Python

"""Switch title-id knowledge: recognising a base-game id, recovering one from an
update or DLC id, and mapping a content type to a file category."""
import re
from typing import Final
from models.rom import RomFileCategory, RomIdentity, SaveTargetLayout
# 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]] = {
"application": RomFileCategory.GAME,
"patch": RomFileCategory.UPDATE,
"addon": RomFileCategory.DLC,
}
TITLE_ID_REGEX: Final = re.compile(r"[0-9A-Fa-f]{16}")
# An already-embedded id, e.g. [0100F4700B2E0000].
TITLE_ID_BRACKET_REGEX: Final = re.compile(rf"\[{TITLE_ID_REGEX.pattern}\]")
def derive_base_title_id(title_id: str) -> str | None:
"""Derive the base-game title id from an update/DLC id: clear the low 12
bits and decrement the program-index nibble when it is odd."""
if len(title_id) < 4:
return None
nibble_char = title_id[-4]
try:
nibble = int(nibble_char, 16)
except ValueError:
return None
if nibble % 2 == 1:
nibble -= 1
formatted = format(nibble, "x" if nibble_char.islower() else "X")
return f"{title_id[:-4]}{formatted}000"
def is_base_title_id(title_id: str) -> bool:
"""A base-game id is its own derived base."""
return derive_base_title_id(title_id) == title_id
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
non-hashable ROM matches on that column, which only works while it holds
the base game's id. A non-derivable id is left as read rather than dropped.
"""
title_id = identity.title_id
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.
return RomIdentity(
title_id=derived,
save_target=derived,
save_target_layout=SaveTargetLayout.FOLDER_EXACT,
)