refactor(scan): tighten the sigil title id extraction paths

Quality pass over the title id feature, no behaviour change.

Give the Switch platform family one home by deriving it from the sigil
slug map, and drop the two inline tuples and the local frozenset that
restated it. Express the base-title-id rule once: a base id is its own
derived base. Compose the bracket regex from the 16-hex pattern instead
of repeating it.

Return the embedded name from the extraction closure rather than writing
it through nonlocal, which removes the is_rom_level flag and the repeated
sigil_platform guards, and factor the twice-duplicated rom-level file
tail into one helper.

Cut two per-ROM costs in _identify_rom: config.yml was re-read and
re-parsed three times per ROM, and the prod.keys firmware lookup ran one
DB query per Switch ROM despite depending only on the platform. Both are
now resolved once, the latter in the per-platform callers.

Also document skip_title_id_extraction and embed_switch_title_ids, drop
the always-dashed title/save id rows from the metadata tab, and render
the file row's chips from one list.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-08-28 18:18:47 -04:00
parent 228197b4ec
commit e7c4cb2ab6
9 changed files with 461 additions and 620 deletions

View File

@@ -9,6 +9,7 @@ try:
import sigil
except ImportError:
sigil = None # type: ignore[assignment]
log.debug("sigil binding not installed, title id extraction disabled")
SWITCH_SIGIL_SLUG: Final = "switch"
@@ -29,17 +30,20 @@ SIGIL_PLATFORM_SLUGS: Final[dict[UPS, str]] = {
UPS.XBOX360: "xbox360",
}
# The Switch family needs prod.keys to decrypt headers, and is the only family
# whose files may have their title id embedded in the filename.
SWITCH_PLATFORM_SLUGS: Final = frozenset(
slug
for slug, sigil_slug in SIGIL_PLATFORM_SLUGS.items()
if sigil_slug == SWITCH_SIGIL_SLUG
)
# 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(
{"NOT_FOUND", "UNSUPPORTED", "UNSUPPORTED_FORMAT", "NEEDS_KEY"}
)
_missing_binding_logged = False
class SigilServiceError(Exception): ...
@dataclass(frozen=True)
class SigilExtractionResult:
@@ -60,12 +64,7 @@ class SigilService:
file_path: str,
prod_keys_path: str | None = None,
) -> SigilExtractionResult | None:
global _missing_binding_logged
if sigil is None:
if not _missing_binding_logged:
log.debug("sigil binding not installed, skipping title id extraction")
_missing_binding_logged = True
return None
sigil_slug = SIGIL_PLATFORM_SLUGS.get(platform_slug) # type: ignore[arg-type]
@@ -80,8 +79,7 @@ class SigilService:
result = await asyncio.to_thread(sigil.extract, file_path, **kwargs)
except Exception as exc:
code = getattr(exc, "code", None)
is_sigil_error = isinstance(exc, getattr(sigil, "SigilError", ()))
if is_sigil_error and code in ROUTINE_SIGIL_ERROR_CODES:
if code in ROUTINE_SIGIL_ERROR_CODES:
log.debug(f"Sigil found no title id for {file_path}: {code}")
else:
log.error(f"Sigil extraction failed for {file_path}: {exc}")

View File

@@ -10,6 +10,7 @@ from rq import Worker, get_current_job
from rq.job import Job, JobStatus
from sqlalchemy.exc import IntegrityError
from adapters.services.sigil import SWITCH_PLATFORM_SLUGS
from config import (
DEV_MODE,
LIBRARY_BASE_PATH,
@@ -44,13 +45,12 @@ from handler.filesystem import (
fs_resource_handler,
fs_rom_handler,
)
from handler.filesystem.roms_handler import FSRom
from handler.filesystem.roms_handler import FSRom, ParsedRomFiles
from handler.metadata import (
meta_gamelist_handler,
meta_hltb_handler,
meta_launchbox_handler,
)
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
from handler.metadata.launchbox_handler.types import LAUNCHBOX_PLATFORMS_DIR
from handler.metadata.ss_handler import begin_scan as begin_ss_scan
from handler.metadata.ss_handler import log_quota as log_ss_quota
@@ -381,6 +381,29 @@ def _should_hash_firmware(
)
def _resolve_prod_keys_path(platform: Platform) -> str | None:
"""Locate the console's prod.keys, which sigil needs to decrypt Switch
XCI/NSP headers, among the platform's scanned firmware."""
if platform.slug not in SWITCH_PLATFORM_SLUGS:
return None
prod_keys = db_firmware_handler.get_firmware_by_filename(platform.id, "prod.keys")
return f"{LIBRARY_BASE_PATH}/{prod_keys.full_path}" if prod_keys else None
def _apply_scanned_values(fs_rom: FSRom, parsed: ParsedRomFiles) -> None:
fs_rom["files"] = parsed.rom_files
fs_rom["crc_hash"] = parsed.crc_hash
fs_rom["md5_hash"] = parsed.md5_hash
fs_rom["sha1_hash"] = parsed.sha1_hash
fs_rom["ra_hash"] = parsed.ra_hash
fs_rom["title_id"] = parsed.title_id
fs_rom["save_id"] = parsed.save_id
fs_rom["save_usage"] = parsed.save_usage
if parsed.renamed_rom_fs_name:
fs_rom["fs_name"] = parsed.renamed_rom_fs_name
# There's an order of operations here that is important:
# 1. Read the list of roms from the filesystem
# 2. Check if ROM should be scanned based on the scan type
@@ -398,6 +421,7 @@ async def _identify_rom(
playmatch_enabled: bool,
socket_manager: socketio.AsyncRedisManager,
scan_stats: ScanStats,
prod_keys_path: str | None = None,
) -> None:
# Break early if the flag is set
if redis_client.get(STOP_SCAN_FLAG):
@@ -422,19 +446,10 @@ async def _identify_rom(
"url_screenshots": [],
}
calculate_hashes = not cm.get_config().SKIP_HASH_CALCULATION
extract_title_ids = not cm.get_config().SKIP_TITLE_ID_EXTRACTION
embed_title_ids = cm.get_config().EMBED_SWITCH_TITLE_IDS
# Switch title id extraction needs the console's prod.keys to decrypt
# XCI/NSP headers; resolve it from the scanned firmware when present.
prod_keys_path: str | None = None
if extract_title_ids and platform.slug in (UPS.SWITCH, UPS.SWITCH_2):
prod_keys = db_firmware_handler.get_firmware_by_filename(
platform.id, "prod.keys"
)
if prod_keys:
prod_keys_path = f"{LIBRARY_BASE_PATH}/{prod_keys.full_path}"
cnfg = cm.get_config()
calculate_hashes = not cnfg.SKIP_HASH_CALCULATION
extract_title_ids = not cnfg.SKIP_TITLE_ID_EXTRACTION
embed_title_ids = cnfg.EMBED_SWITCH_TITLE_IDS
newly_added: bool = rom is None
reassociated: bool = False
@@ -455,23 +470,10 @@ async def _identify_rom(
prod_keys_path=prod_keys_path,
embed_title_ids=embed_title_ids,
)
fs_rom.update(
{
"files": parsed_rom_files.rom_files,
"crc_hash": parsed_rom_files.crc_hash,
"md5_hash": parsed_rom_files.md5_hash,
"sha1_hash": parsed_rom_files.sha1_hash,
"ra_hash": parsed_rom_files.ra_hash,
"title_id": parsed_rom_files.title_id,
"save_id": parsed_rom_files.save_id,
"save_usage": parsed_rom_files.save_usage,
}
)
# A single-file rom renamed on disk to embed its title id must carry the
# new name into both the new-entry insert and any hash reassociation.
_apply_scanned_values(fs_rom, parsed_rom_files)
# The new-entry insert reads its name from rom_attrs, not fs_rom.
if parsed_rom_files.renamed_rom_fs_name:
rom_attrs["fs_name"] = parsed_rom_files.renamed_rom_fs_name
fs_rom["fs_name"] = parsed_rom_files.renamed_rom_fs_name
files_built = True
missing_match = db_rom_handler.get_matching_missing_rom(
@@ -543,22 +545,9 @@ async def _identify_rom(
prod_keys_path=prod_keys_path,
embed_title_ids=embed_title_ids,
)
fs_rom.update(
{
"files": parsed_rom_files.rom_files,
"crc_hash": parsed_rom_files.crc_hash,
"md5_hash": parsed_rom_files.md5_hash,
"sha1_hash": parsed_rom_files.sha1_hash,
"ra_hash": parsed_rom_files.ra_hash,
"title_id": parsed_rom_files.title_id,
"save_id": parsed_rom_files.save_id,
"save_usage": parsed_rom_files.save_usage,
}
)
# scan_rom persists Rom.fs_name from fs_rom["fs_name"]; keep the rom
# object in sync so its in-memory identity matches the renamed file.
_apply_scanned_values(fs_rom, parsed_rom_files)
# Keep the in-memory rom's identity matching the renamed file.
if parsed_rom_files.renamed_rom_fs_name:
fs_rom["fs_name"] = parsed_rom_files.renamed_rom_fs_name
rom.fs_name = parsed_rom_files.renamed_rom_fs_name
# For a COMPLETE rescan, wipe all downloaded resources before re-fetching so
@@ -631,8 +620,7 @@ async def _identify_rom(
if should_update_files:
# Reconcile against the existing rows instead of replacing them, so file
# ids survive a rescan and anything keyed on them (track metadata,
# persisted soundtrack covers) stays valid. title_id/save_id/title_version
# ride along via ROM_FILE_SCANNED_COLUMNS in sync_rom_files.
# persisted soundtrack covers) stays valid.
synced = db_rom_handler.sync_rom_files(_added_rom.id, fs_rom["files"])
for cover_path in synced.orphaned_cover_paths:
remove_persisted_cover(cover_path)
@@ -699,6 +687,7 @@ async def _scan_selected_roms(
)
scan_semaphore = asyncio.Semaphore(SCAN_WORKERS)
prod_keys_path = _resolve_prod_keys_path(platform)
async def scan_rom_with_semaphore(rom: Rom) -> None:
async with scan_semaphore:
@@ -730,6 +719,7 @@ async def _scan_selected_roms(
playmatch_enabled=playmatch_enabled,
socket_manager=socket_manager,
scan_stats=scan_stats,
prod_keys_path=prod_keys_path,
)
results = await asyncio.gather(
@@ -859,6 +849,7 @@ async def _identify_platform(
# Create semaphore to limit concurrent ROM scanning
scan_semaphore = asyncio.Semaphore(SCAN_WORKERS)
prod_keys_path = _resolve_prod_keys_path(platform)
async def scan_rom_with_semaphore(fs_rom: FSRom, rom: Rom | None) -> None:
"""Scan a single ROM with semaphore limiting"""
@@ -874,6 +865,7 @@ async def _identify_platform(
playmatch_enabled=playmatch_enabled,
socket_manager=socket_manager,
scan_stats=scan_stats,
prod_keys_path=prod_keys_path,
)
for fs_roms_batch in batched(fs_roms, 200, strict=False):

View File

@@ -13,6 +13,7 @@ from anyio import Path as AnyioPath
from adapters.services.sigil import (
SIGIL_PLATFORM_SLUGS,
SWITCH_PLATFORM_SLUGS,
SigilExtractionResult,
SigilService,
)
@@ -181,8 +182,7 @@ class ParsedRomFiles:
save_id: str | None = None
save_usage: SaveUsage | None = None
# Set when a single-file rom's file was renamed on disk to embed its title
# id, so the caller can reconcile Rom.fs_name. None for multi-part roms
# (whose folder name is unchanged) or when no rename happened.
# id, so the caller can reconcile Rom.fs_name.
renamed_rom_fs_name: str | None = None
@@ -194,26 +194,19 @@ SWITCH_CONTENT_TYPE_CATEGORIES: dict[str, RomFileCategory] = {
"addon": RomFileCategory.DLC,
}
# Platforms whose files may have their title id embedded in the filename.
EMBED_TITLE_ID_PLATFORM_SLUGS = frozenset((UPS.SWITCH, UPS.SWITCH_2))
# A 16-hex-digit title id in square brackets, e.g. [0100F4700B2E0000]. Used both
# to detect files that already carry an embedded id (idempotency) and to
# validate the id before embedding it.
SWITCH_TITLE_ID_BRACKET_REGEX = re.compile(r"\[[0-9A-Fa-f]{16}\]")
SWITCH_TITLE_ID_REGEX = re.compile(r"^[0-9A-Fa-f]{16}$")
SWITCH_TITLE_ID_REGEX = re.compile(r"[0-9A-Fa-f]{16}")
# An already-embedded id, e.g. [0100F4700B2E0000].
SWITCH_TITLE_ID_BRACKET_REGEX = re.compile(rf"\[{SWITCH_TITLE_ID_REGEX.pattern}\]")
def _embed_switch_title_id_in_name(
abs_file_path: Path, title_id: str, title_version: int | None
) -> Path | None:
"""Rename a Switch ROM file to embed its title id and version as
` [TITLEID][vVERSION]` before the extension, preserving existing tags.
"""Rename a Switch ROM file to embed ` [TITLEID][vVERSION]` before the
extension.
Returns the new absolute path, or None when the file was left untouched:
it already carries a 16-hex title-id bracket, the id is not a valid 16-hex
value, or the target name already exists on disk. The os.rename is the only
side effect.
Returns:
The new absolute path, or None when the file was left untouched.
"""
name = abs_file_path.name
@@ -221,7 +214,7 @@ def _embed_switch_title_id_in_name(
log.debug(f"{name} already has an embedded title id, skipping rename")
return None
if not SWITCH_TITLE_ID_REGEX.match(title_id):
if not SWITCH_TITLE_ID_REGEX.fullmatch(title_id):
log.debug(f"Title id {title_id!r} is not a 16-hex value, skipping rename")
return None
@@ -249,17 +242,6 @@ def _parse_save_usage(usage: str) -> SaveUsage | None:
return None
def _is_switch_base_title_id(title_id: str) -> bool:
"""Base-game Switch title ids have their low 12 bits cleared and an even
program-index nibble; update/DLC ids differ only in those positions."""
if len(title_id) < 4 or not title_id.endswith("000"):
return False
try:
return int(title_id[-4], 16) % 2 == 0
except ValueError:
return False
def _derive_switch_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."""
@@ -276,6 +258,11 @@ def _derive_switch_base_title_id(title_id: str) -> str | None:
return f"{title_id[:-4]}{formatted}000"
def _is_switch_base_title_id(title_id: str) -> bool:
"""A base-game id is its own derived base."""
return _derive_switch_base_title_id(title_id) == title_id
def _rom_level_title_values(
platform_slug: str,
extractions: list[SigilExtractionResult],
@@ -283,7 +270,7 @@ def _rom_level_title_values(
if not extractions:
return None, None, None
if platform_slug in (UPS.SWITCH, UPS.SWITCH_2):
if platform_slug in SWITCH_PLATFORM_SLUGS:
base = next(
(e for e in extractions if _is_switch_base_title_id(e.title_id)), None
)
@@ -488,47 +475,61 @@ class FSRomsHandler(FSHandler):
# non-hashable platforms like Switch.
sigil_platform = extract_title_ids and rom.platform_slug in SIGIL_PLATFORM_SLUGS
sigil_extractions: list[SigilExtractionResult] = []
sigil_service = SigilService()
# Filename embedding is Switch-only, even though sigil covers more
# platforms; other platforms never have their files renamed.
embed_switch = (
embed_title_ids and rom.platform_slug in EMBED_TITLE_ID_PLATFORM_SLUGS
)
embed_switch = embed_title_ids and rom.platform_slug in SWITCH_PLATFORM_SLUGS
renamed_rom_fs_name: str | None = None
async def _extract_title_id(
rom_file: RomFile, abs_file_path: Path, is_rom_level: bool = False
) -> None:
nonlocal renamed_rom_fs_name
extraction = await SigilService().extract_title_id(
rom_file: RomFile, abs_file_path: Path
) -> str | None:
"""Populate the file's title id fields, returning its new name if
embedding renamed it on disk."""
if not sigil_platform:
return None
extraction = await sigil_service.extract_title_id(
rom.platform_slug, str(abs_file_path), prod_keys_path
)
if extraction is None:
return
return None
rom_file.title_id = extraction.title_id
rom_file.save_id = extraction.save_id
rom_file.title_version = extraction.version
# For Switch, the binary CNMT content type is authoritative over the
# folder-derived category. Leave the folder category when absent.
if extraction.content_type is not None:
category = SWITCH_CONTENT_TYPE_CATEGORIES.get(extraction.content_type)
if category is not None:
rom_file.category = category
sigil_extractions.append(extraction)
if embed_switch and extraction.title_id:
new_path = _embed_switch_title_id_in_name(
abs_file_path, extraction.title_id, extraction.version
)
if new_path is not None:
# The file stays in the same directory, so only file_name
# changes; file_path is unaffected.
rom_file.file_name = new_path.name
# A single-file rom's file name IS the Rom.fs_name, so the
# caller must reconcile it. Multi-part inner files don't
# change the rom folder name.
if is_rom_level:
renamed_rom_fs_name = new_path.name
if not (embed_switch and extraction.title_id):
return None
new_path = _embed_switch_title_id_in_name(
abs_file_path, extraction.title_id, extraction.version
)
if new_path is None:
return None
rom_file.file_name = new_path.name
return new_path.name
async def _append_rom_level_file(file_hash: FileHash) -> str | None:
"""Emit the single RomFile that stands for the whole rom, returning
its new name if embedding renamed it on disk."""
rom_file = self._build_rom_file(
rom=rom,
rom_path=Path(rel_roms_path),
file_name=rom.fs_name,
file_hash=file_hash,
)
rom_files.append(rom_file)
# Archives keep hashes only; sigil reads title ids from the ROM
# binary itself.
if rom_ext in ARCHIVE_READERS:
return None
return await _extract_title_id(rom_file, rom_dir)
cnfg = cm.get_config()
excluded_file_names = cnfg.EXCLUDED_MULTI_PARTS_FILES
@@ -638,8 +639,7 @@ class FSRomsHandler(FSHandler):
)
# Extract from every file (base, updates, DLC in subfolders), not
# just the top-level one: sigil returns None for unparseable files.
if sigil_platform:
await _extract_title_id(rom_file, Path(f_path, file_name))
await _extract_title_id(rom_file, abs_file_path)
rom_files.append(rom_file)
elif hashable_platform and rom_ext in ARCHIVE_READERS:
# Multi-file archive: compute a composite hash across all
@@ -762,39 +762,23 @@ class FSRomsHandler(FSHandler):
f"{abs_fs_path}/{rom.fs_name}",
)
file_hash = _make_file_hash(
crc_c,
md5_h,
sha1_h,
chd_sha1_hash=_chd_sha1_hash(rom_dir),
renamed_rom_fs_name = await _append_rom_level_file(
_make_file_hash(
crc_c,
md5_h,
sha1_h,
chd_sha1_hash=_chd_sha1_hash(rom_dir),
)
)
rom_file = self._build_rom_file(
rom=rom,
rom_path=Path(rel_roms_path),
file_name=rom.fs_name,
file_hash=file_hash,
)
if sigil_platform:
await _extract_title_id(rom_file, rom_dir, is_rom_level=True)
rom_files.append(rom_file)
else:
file_hash = FileHash(
crc_hash="",
md5_hash="",
sha1_hash="",
chd_sha1_hash="",
renamed_rom_fs_name = await _append_rom_level_file(
FileHash(
crc_hash="",
md5_hash="",
sha1_hash="",
chd_sha1_hash="",
)
)
rom_file = self._build_rom_file(
rom=rom,
rom_path=Path(rel_roms_path),
file_name=rom.fs_name,
file_hash=file_hash,
)
# Archives keep hashes only; sigil reads title ids from the ROM
# binary itself.
if sigil_platform and rom_ext not in ARCHIVE_READERS:
await _extract_title_id(rom_file, rom_dir, is_rom_level=True)
rom_files.append(rom_file)
rom_title_id, rom_save_id, rom_save_usage = _rom_level_title_values(
rom.platform_slug, sigil_extractions

View File

@@ -723,6 +723,79 @@ class TestScanAuthorization:
get_jobs.assert_not_called()
def patch_identify_rom(
mocker,
*,
parsed: ParsedRomFiles,
roms_fs_structure: str,
name_with_no_tags: str,
platform_slug: str,
**config_flags: bool,
) -> tuple[Mock, Platform]:
"""Stub out everything `_identify_rom` reaches so only the wiring under test
is exercised, returning the patched db handler and the platform to scan."""
mocker.patch.object(scan_module, "redis_client", Mock(get=Mock(return_value=None)))
fs = scan_module.fs_rom_handler
mocker.patch.object(
fs,
"parse_tags",
return_value=ParsedTags(
version="", revision="", regions=[], languages=[], other_tags=[]
),
)
mocker.patch.object(fs, "get_roms_fs_structure", return_value=roms_fs_structure)
mocker.patch.object(
fs, "get_file_name_with_no_tags", return_value=name_with_no_tags
)
mocker.patch.object(fs, "get_rom_files", AsyncMock(return_value=parsed))
config = MagicMock()
config.SKIP_HASH_CALCULATION = False
for flag, value in config_flags.items():
setattr(config, flag, value)
mocker.patch.object(scan_module.cm, "get_config", return_value=config)
mocker.patch.object(
scan_module, "scan_rom", AsyncMock(return_value=MagicMock(is_identified=False))
)
db = mocker.patch.object(scan_module, "db_rom_handler")
db.add_rom.return_value = MagicMock(is_identified=False, id=99)
platform = Platform(name=platform_slug, slug=platform_slug, fs_slug=platform_slug)
platform.id = 1
return db, platform
async def run_identify_rom(platform: Platform, fs_rom: FSRom) -> None:
await _identify_rom(
platform=platform,
fs_rom=fs_rom,
rom=None,
scan_type=ScanType.HASHES,
roms_ids=[],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
)
def make_fs_rom(fs_name: str) -> FSRom:
return {
"fs_name": fs_name,
"flat": True,
"nested": False,
"files": [],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
}
class TestIdentifyRomReassociation:
"""`_identify_rom` reassociates a renamed/moved file with its missing entry.
@@ -909,82 +982,31 @@ class TestIdentifyRomTitleIdEmbedRename:
@pytest.fixture
def patched(self, mocker):
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(return_value=None))
)
fs = scan_module.fs_rom_handler
mocker.patch.object(
fs,
"parse_tags",
return_value=ParsedTags(
version="", revision="", regions=[], languages=[], other_tags=[]
db, platform = patch_identify_rom(
mocker,
parsed=ParsedRomFiles(
rom_files=[],
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
ra_hash="",
title_id="0100ABCD12340000",
renamed_rom_fs_name=self.NEW_NAME,
),
roms_fs_structure="switch/roms",
name_with_no_tags="Game",
platform_slug="switch",
SKIP_TITLE_ID_EXTRACTION=False,
EMBED_SWITCH_TITLE_IDS=True,
)
mocker.patch.object(fs, "get_roms_fs_structure", return_value="switch/roms")
mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="Game")
mocker.patch.object(
fs,
"get_rom_files",
AsyncMock(
return_value=ParsedRomFiles(
rom_files=[],
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
ra_hash="",
title_id="0100ABCD12340000",
renamed_rom_fs_name=self.NEW_NAME,
)
),
)
config = MagicMock()
config.SKIP_HASH_CALCULATION = False
config.SKIP_TITLE_ID_EXTRACTION = False
config.EMBED_SWITCH_TITLE_IDS = True
mocker.patch.object(scan_module.cm, "get_config", return_value=config)
mocker.patch.object(
scan_module,
"scan_rom",
AsyncMock(return_value=MagicMock(is_identified=False)),
)
db = mocker.patch.object(scan_module, "db_rom_handler")
db.add_rom.return_value = MagicMock(is_identified=False, id=99)
db.get_matching_missing_rom.return_value = None
return db
def _platform(self):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
platform.id = 1
return platform
return db, platform
async def test_new_entry_carries_embedded_name(self, patched):
db = patched
fs_rom: FSRom = {
"fs_name": "Game.nsp",
"flat": True,
"nested": False,
"files": [],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
}
await _identify_rom(
platform=self._platform(),
fs_rom=fs_rom,
rom=None,
scan_type=ScanType.HASHES,
roms_ids=[],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
)
db, platform = patched
fs_rom = make_fs_rom("Game.nsp")
await run_identify_rom(platform, fs_rom)
# The initial insert carries the renamed on-disk name, and the shared
# fs_rom dict is updated so scan_rom persists the same name.
@@ -1020,21 +1042,6 @@ class TestIdentifyRomPersistsFileTitleVersion:
@pytest.fixture
def patched(self, mocker):
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(return_value=None))
)
fs = scan_module.fs_rom_handler
mocker.patch.object(
fs,
"parse_tags",
return_value=ParsedTags(
version="", revision="", regions=[], languages=[], other_tags=[]
),
)
mocker.patch.object(fs, "get_roms_fs_structure", return_value="switch/roms")
mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="Game")
update_file = RomFile(
file_name="Game [UPD][v655360].nsp",
file_path="switch/roms",
@@ -1043,72 +1050,34 @@ class TestIdentifyRomPersistsFileTitleVersion:
title_id=self.UPDATE_TITLE_ID,
title_version=self.UPDATE_TITLE_VERSION,
)
mocker.patch.object(
fs,
"get_rom_files",
AsyncMock(
return_value=ParsedRomFiles(
rom_files=[update_file],
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
ra_hash="",
title_id=self.UPDATE_TITLE_ID,
)
db, platform = patch_identify_rom(
mocker,
parsed=ParsedRomFiles(
rom_files=[update_file],
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
ra_hash="",
title_id=self.UPDATE_TITLE_ID,
),
)
config = MagicMock()
config.SKIP_HASH_CALCULATION = False
config.SKIP_TITLE_ID_EXTRACTION = False
config.EMBED_SWITCH_TITLE_IDS = False
mocker.patch.object(scan_module.cm, "get_config", return_value=config)
mocker.patch.object(
scan_module,
"scan_rom",
AsyncMock(return_value=MagicMock(is_identified=False)),
roms_fs_structure="switch/roms",
name_with_no_tags="Game",
platform_slug="switch",
SKIP_TITLE_ID_EXTRACTION=False,
EMBED_SWITCH_TITLE_IDS=False,
)
# The persist loop calls this per saved file; keep it inert.
mocker.patch.object(scan_module, "persist_soundtrack_cover")
db = mocker.patch.object(scan_module, "db_rom_handler")
db.add_rom.return_value = MagicMock(is_identified=False, id=99)
db.get_matching_missing_rom.return_value = None
db.sync_rom_files.side_effect = lambda rom_id, files: SyncedRomFiles(
files=list(files), orphaned_cover_paths=[]
)
return db
def _platform(self):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
platform.id = 1
return platform
return db, platform
async def test_rebuilt_file_keeps_title_version(self, patched):
db = patched
fs_rom: FSRom = {
"fs_name": "Game.nsp",
"flat": True,
"nested": False,
"files": [],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
}
await _identify_rom(
platform=self._platform(),
fs_rom=fs_rom,
rom=None,
scan_type=ScanType.HASHES,
roms_ids=[],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
)
db, platform = patched
await run_identify_rom(platform, make_fs_rom("Game.nsp"))
db.sync_rom_files.assert_called_once()
rom_id, synced_files = db.sync_rom_files.call_args.args

View File

@@ -1373,70 +1373,74 @@ class TestFSRomsHandler:
assert parsed.ra_hash == ""
SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id"
@pytest.fixture
def sigil_config(monkeypatch):
cnfg = Config(
EXCLUDED_PLATFORMS=[],
EXCLUDED_SINGLE_EXT=[],
EXCLUDED_SINGLE_FILES=[],
EXCLUDED_MULTI_FILES=[],
EXCLUDED_MULTI_PARTS_EXT=[],
EXCLUDED_MULTI_PARTS_FILES=[],
PLATFORMS_BINDING={},
PLATFORMS_VERSIONS={},
ROMS_FOLDER_NAME="roms",
FIRMWARE_FOLDER_NAME="bios",
)
cnfg.has_structure_path_b = True
monkeypatch.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cnfg)
return cnfg
def make_sigil_handler(tmp_path: Path) -> FSRomsHandler:
handler = FSRomsHandler()
handler.base_path = tmp_path
return handler
def make_single_file_rom(tmp_path: Path, platform: Platform, fs_name: str) -> Rom:
roms_path = tmp_path / platform.fs_slug / "roms"
roms_path.mkdir(parents=True, exist_ok=True)
(roms_path / fs_name).write_bytes(b"rom-bytes")
return Rom(
id=1,
fs_name=fs_name,
fs_path=f"{platform.fs_slug}/roms",
platform=platform,
)
def make_multi_part_rom(
tmp_path: Path, platform: Platform, fs_name: str, file_names: list[str]
) -> Rom:
rom_dir = tmp_path / platform.fs_slug / "roms" / fs_name
rom_dir.mkdir(parents=True, exist_ok=True)
for file_name in file_names:
file_path = rom_dir / file_name
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_bytes(b"rom-bytes")
return Rom(
id=1,
fs_name=fs_name,
fs_extension="",
fs_path=f"{platform.fs_slug}/roms",
platform=platform,
)
class TestSigilTitleIdExtraction:
"""Title id extraction via the sigil adapter during get_rom_files."""
SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id"
@pytest.fixture
def config(self):
cnfg = Config(
EXCLUDED_PLATFORMS=[],
EXCLUDED_SINGLE_EXT=[],
EXCLUDED_SINGLE_FILES=[],
EXCLUDED_MULTI_FILES=[],
EXCLUDED_MULTI_PARTS_EXT=[],
EXCLUDED_MULTI_PARTS_FILES=[],
PLATFORMS_BINDING={},
PLATFORMS_VERSIONS={},
ROMS_FOLDER_NAME="roms",
FIRMWARE_FOLDER_NAME="bios",
)
cnfg.has_structure_path_b = True
return cnfg
def _make_handler(self, tmp_path: Path) -> FSRomsHandler:
handler = FSRomsHandler()
handler.base_path = tmp_path
return handler
def _make_single_file_rom(
self, tmp_path: Path, platform: Platform, fs_name: str
) -> Rom:
roms_path = tmp_path / platform.fs_slug / "roms"
roms_path.mkdir(parents=True, exist_ok=True)
(roms_path / fs_name).write_bytes(b"rom-bytes")
return Rom(
id=1,
fs_name=fs_name,
fs_path=f"{platform.fs_slug}/roms",
platform=platform,
)
def _make_multi_part_rom(
self, tmp_path: Path, platform: Platform, fs_name: str, file_names: list[str]
) -> Rom:
rom_dir = tmp_path / platform.fs_slug / "roms" / fs_name
rom_dir.mkdir(parents=True, exist_ok=True)
for file_name in file_names:
file_path = rom_dir / file_name
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_bytes(b"rom-bytes")
return Rom(
id=1,
fs_name=fs_name,
fs_extension="",
fs_path=f"{platform.fs_slug}/roms",
platform=platform,
)
@pytest.mark.asyncio
async def test_single_file_extraction_attaches_values(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
extraction = SigilExtractionResult(
title_id="0100ABCD12340000",
@@ -1445,12 +1449,10 @@ class TestSigilTitleIdExtraction:
)
mock_extract = AsyncMock(return_value=extraction)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(
rom, prod_keys_path="/bios/switch/prod.keys"
)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(
rom, prod_keys_path="/bios/switch/prod.keys"
)
assert len(parsed.rom_files) == 1
assert parsed.rom_files[0].title_id == "0100ABCD12340000"
@@ -1466,11 +1468,11 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_multi_part_extraction_covers_nested_files(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_multi_part_rom(
handler = make_sigil_handler(tmp_path)
rom = make_multi_part_rom(
tmp_path,
platform,
"Zelda",
@@ -1510,10 +1512,8 @@ class TestSigilTitleIdExtraction:
mock_extract = AsyncMock(side_effect=fake_extract)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
by_name = {rf.file_name: rf for rf in parsed.rom_files}
@@ -1542,15 +1542,13 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_content_type_overrides_folder_category(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
handler = make_sigil_handler(tmp_path)
# Folder name "dlc" would otherwise derive category DLC, but the binary
# content type says this is the base application.
rom = self._make_multi_part_rom(
tmp_path, platform, "Zelda", ["dlc/Zelda [base].nsp"]
)
rom = make_multi_part_rom(tmp_path, platform, "Zelda", ["dlc/Zelda [base].nsp"])
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
@@ -1562,20 +1560,18 @@ class TestSigilTitleIdExtraction:
)
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
assert parsed.rom_files[0].category == RomFileCategory.GAME
@pytest.mark.asyncio
async def test_folder_category_preserved_when_content_type_absent(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_multi_part_rom(
handler = make_sigil_handler(tmp_path)
rom = make_multi_part_rom(
tmp_path, platform, "Zelda", ["dlc/Zelda [addon].nsp"]
)
@@ -1590,10 +1586,8 @@ class TestSigilTitleIdExtraction:
)
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
rom_file = parsed.rom_files[0]
# Folder-derived category survives, and title_version stays None.
@@ -1602,13 +1596,11 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_switch_base_derivation_from_update_only_folder(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_multi_part_rom(
tmp_path, platform, "Zelda", ["Zelda [update].nsp"]
)
handler = make_sigil_handler(tmp_path)
rom = make_multi_part_rom(tmp_path, platform, "Zelda", ["Zelda [update].nsp"])
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
@@ -1618,10 +1610,8 @@ class TestSigilTitleIdExtraction:
)
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
assert parsed.rom_files[0].title_id == "0100ABCD12340800"
assert parsed.title_id == "0100ABCD12340000"
@@ -1630,11 +1620,11 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_switch_base_derivation_from_dlc_odd_nibble(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game [DLC].nsp")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game [DLC].nsp")
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
@@ -1644,10 +1634,8 @@ class TestSigilTitleIdExtraction:
)
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
assert parsed.title_id == "0100ABCD12350000"
assert parsed.save_id == "0100ABCD12350000"
@@ -1655,11 +1643,11 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_non_switch_platform_uses_first_extraction(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.iso")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.iso")
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
@@ -1669,17 +1657,15 @@ class TestSigilTitleIdExtraction:
)
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with (
patch(self.SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
with (
patch(SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
assert parsed.rom_files[0].title_id == "ULUS-10041"
assert parsed.rom_files[0].save_id == "ULUS10041"
@@ -1689,11 +1675,11 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_3ds_extraction_maps_folder_split_usage(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo 3DS", slug="3ds", fs_slug="3ds")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.3ds")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.3ds")
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
@@ -1705,17 +1691,15 @@ class TestSigilTitleIdExtraction:
)
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with (
patch(self.SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
with (
patch(SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
assert parsed.rom_files[0].save_id == "0004000e/0011c500"
assert parsed.rom_files[0].title_id == "0004000E0011C500"
@@ -1725,11 +1709,11 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_dreamcast_extraction_maps_file_prefix_usage(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Dreamcast", slug="dc", fs_slug="dc")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.chd")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.chd")
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
@@ -1739,17 +1723,15 @@ class TestSigilTitleIdExtraction:
)
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with (
patch(self.SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
with (
patch(SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
assert parsed.rom_files[0].title_id == "MK-51035"
assert parsed.rom_files[0].save_id == "MK-51035"
@@ -1758,18 +1740,16 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_non_sigil_platform_skips_extraction(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo 64", slug="n64", fs_slug="n64")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.z64")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.z64")
mock_extract = AsyncMock()
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom, calculate_hashes=False)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom, calculate_hashes=False)
mock_extract.assert_not_awaited()
assert parsed.rom_files[0].title_id is None
@@ -1778,24 +1758,24 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_extraction_disabled_skips_extraction(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
mock_extract = AsyncMock()
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom, extract_title_ids=False)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom, extract_title_ids=False)
mock_extract.assert_not_awaited()
assert parsed.title_id is None
@pytest.mark.asyncio
async def test_archive_rom_skips_extraction(self, tmp_path: Path, config: Config):
async def test_archive_rom_skips_extraction(
self, tmp_path: Path, sigil_config: Config
):
import io
import zipfile
@@ -1805,7 +1785,7 @@ class TestSigilTitleIdExtraction:
zf.writestr("game.bin", b"fake PSX disc content")
platform = Platform(name="PlayStation", slug="psx", fs_slug="psx")
handler = self._make_handler(tmp_path)
handler = make_sigil_handler(tmp_path)
roms_path = tmp_path / "psx" / "roms"
roms_path.mkdir(parents=True)
(roms_path / "game.zip").write_bytes(buf.getvalue())
@@ -1818,17 +1798,15 @@ class TestSigilTitleIdExtraction:
mock_extract = AsyncMock()
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with (
patch(self.SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
with (
patch(SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
mock_extract.assert_not_awaited()
assert parsed.rom_files[0].title_id is None
@@ -1836,18 +1814,16 @@ class TestSigilTitleIdExtraction:
@pytest.mark.asyncio
async def test_non_hashable_archive_rom_skips_extraction(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "game.zip")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "game.zip")
mock_extract = AsyncMock()
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
mock_extract.assert_not_awaited()
assert parsed.title_id is None
@@ -1913,65 +1889,13 @@ class TestEmbedSwitchTitleIdInName:
class TestSwitchTitleIdEmbedding:
"""Config-gated on-disk renaming of Switch files during get_rom_files."""
SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id"
@pytest.fixture
def config(self):
cnfg = Config(
EXCLUDED_PLATFORMS=[],
EXCLUDED_SINGLE_EXT=[],
EXCLUDED_SINGLE_FILES=[],
EXCLUDED_MULTI_FILES=[],
EXCLUDED_MULTI_PARTS_EXT=[],
EXCLUDED_MULTI_PARTS_FILES=[],
PLATFORMS_BINDING={},
PLATFORMS_VERSIONS={},
ROMS_FOLDER_NAME="roms",
FIRMWARE_FOLDER_NAME="bios",
)
cnfg.has_structure_path_b = True
return cnfg
def _make_handler(self, tmp_path: Path) -> FSRomsHandler:
handler = FSRomsHandler()
handler.base_path = tmp_path
return handler
def _make_single_file_rom(
self, tmp_path: Path, platform: Platform, fs_name: str
) -> Rom:
roms_path = tmp_path / platform.fs_slug / "roms"
roms_path.mkdir(parents=True, exist_ok=True)
(roms_path / fs_name).write_bytes(b"rom-bytes")
return Rom(
id=1,
fs_name=fs_name,
fs_path=f"{platform.fs_slug}/roms",
platform=platform,
)
def _make_multi_part_rom(
self, tmp_path: Path, platform: Platform, fs_name: str, file_names: list[str]
) -> Rom:
rom_dir = tmp_path / platform.fs_slug / "roms" / fs_name
rom_dir.mkdir(parents=True, exist_ok=True)
for file_name in file_names:
file_path = rom_dir / file_name
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_bytes(b"rom-bytes")
return Rom(
id=1,
fs_name=fs_name,
fs_extension="",
fs_path=f"{platform.fs_slug}/roms",
platform=platform,
)
@pytest.mark.asyncio
async def test_flag_off_leaves_file_unchanged(self, tmp_path: Path, config: Config):
async def test_flag_off_leaves_file_unchanged(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
extraction = SigilExtractionResult(
title_id="0100ABCD12340000",
@@ -1979,10 +1903,8 @@ class TestSwitchTitleIdEmbedding:
usage="folder-exact",
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=False)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=False)
assert parsed.rom_files[0].file_name == "Game.nsp"
assert parsed.renamed_rom_fs_name is None
@@ -1990,11 +1912,11 @@ class TestSwitchTitleIdEmbedding:
@pytest.mark.asyncio
async def test_single_file_renamed_and_reconciled(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Moonlighter.xci")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Moonlighter.xci")
extraction = SigilExtractionResult(
title_id="0100F4700B2E0000",
@@ -2003,10 +1925,8 @@ class TestSwitchTitleIdEmbedding:
version=0,
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
new_name = "Moonlighter [0100F4700B2E0000][v0].xci"
assert parsed.rom_files[0].file_name == new_name
@@ -2016,11 +1936,13 @@ class TestSwitchTitleIdEmbedding:
assert not (tmp_path / "switch/roms/Moonlighter.xci").exists()
@pytest.mark.asyncio
async def test_already_embedded_file_skipped(self, tmp_path: Path, config: Config):
async def test_already_embedded_file_skipped(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
handler = make_sigil_handler(tmp_path)
fs_name = "Game [0100ABCD12340000][v0].nsp"
rom = self._make_single_file_rom(tmp_path, platform, fs_name)
rom = make_single_file_rom(tmp_path, platform, fs_name)
extraction = SigilExtractionResult(
title_id="0100ABCD12340000",
@@ -2028,10 +1950,8 @@ class TestSwitchTitleIdEmbedding:
usage="folder-exact",
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
assert parsed.rom_files[0].file_name == fs_name
assert parsed.renamed_rom_fs_name is None
@@ -2039,11 +1959,11 @@ class TestSwitchTitleIdEmbedding:
@pytest.mark.asyncio
async def test_non_switch_platform_never_renamed(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.iso")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.iso")
extraction = SigilExtractionResult(
title_id="0100ABCD12340000",
@@ -2051,20 +1971,20 @@ class TestSwitchTitleIdEmbedding:
usage="folder-exact",
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
assert parsed.rom_files[0].file_name == "Game.iso"
assert parsed.renamed_rom_fs_name is None
assert (tmp_path / "psp/roms/Game.iso").exists()
@pytest.mark.asyncio
async def test_collision_target_exists_skips(self, tmp_path: Path, config: Config):
async def test_collision_target_exists_skips(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
target = tmp_path / "switch/roms/Game [0100ABCD12340000][v0].nsp"
target.write_bytes(b"existing")
@@ -2074,10 +1994,8 @@ class TestSwitchTitleIdEmbedding:
usage="folder-exact",
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
assert parsed.rom_files[0].file_name == "Game.nsp"
assert parsed.renamed_rom_fs_name is None
@@ -2085,15 +2003,13 @@ class TestSwitchTitleIdEmbedding:
assert target.read_bytes() == b"existing"
@pytest.mark.asyncio
async def test_no_title_id_not_renamed(self, tmp_path: Path, config: Config):
async def test_no_title_id_not_renamed(self, tmp_path: Path, sigil_config: Config):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=None)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=None)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
assert parsed.rom_files[0].file_name == "Game.nsp"
assert parsed.renamed_rom_fs_name is None
@@ -2101,11 +2017,11 @@ class TestSwitchTitleIdEmbedding:
@pytest.mark.asyncio
async def test_multi_part_nested_files_renamed(
self, tmp_path: Path, config: Config
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = self._make_handler(tmp_path)
rom = self._make_multi_part_rom(
handler = make_sigil_handler(tmp_path)
rom = make_multi_part_rom(
tmp_path,
platform,
"Zelda",
@@ -2139,10 +2055,8 @@ class TestSwitchTitleIdEmbedding:
version=0,
)
with pytest.MonkeyPatch.context() as m:
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
with patch(self.SIGIL_PATCH_TARGET, AsyncMock(side_effect=fake_extract)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
with patch(SIGIL_PATCH_TARGET, AsyncMock(side_effect=fake_extract)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
names = {rf.file_name for rf in parsed.rom_files}
assert "Zelda base [0100ABCD12340000][v0].nsp" in names

View File

@@ -1475,6 +1475,11 @@ Nginx receives an internal redirect header and efficiently serves the file from
Hashing can be disabled per-installation via `skip_hash_calculation` in config.yml.
Alongside hashing, scans extract platform-native title IDs from ROM binaries via
the optional `sigil` binding (Switch, PlayStation, Nintendo, Xbox and Dreamcast
families). The feature no-ops when the binding is absent, and can be turned off
with `skip_title_id_extraction`.
---
## 13. Caching (Redis)
@@ -1644,6 +1649,8 @@ filesystem:
roms_folder: "roms" # Subfolder name for ROMs
firmware_folder: "bios" # Subfolder name for BIOS
skip_hash_calculation: false
skip_title_id_extraction: false # Skip sigil title ID extraction
embed_switch_title_ids: false # Rename Switch ROMs to embed their title ID
system:
platforms:

View File

@@ -76,6 +76,10 @@
# roms_folder: 'roms'
# # Skip file hash calculations on low power devices (eg. Raspberry PI)
# skip_hash_calculation: false
# # Skip reading platform-native title IDs out of ROM binaries during scans
# skip_title_id_extraction: false
# # Rename Switch ROMs to embed ` [TITLEID][vVERSION]` in their filename
# embed_switch_title_ids: false
# scan:
# # Metadata priority during scans

View File

@@ -97,16 +97,23 @@ const audioDuration = computed(() =>
formatDuration(props.file.track_meta?.duration_seconds),
);
const hasAnyHash = computed(
() =>
Boolean(props.file.title_id) ||
props.file.title_version != null ||
Boolean(props.file.sha1_hash) ||
Boolean(props.file.chd_sha1_hash) ||
Boolean(props.file.md5_hash) ||
Boolean(props.file.crc_hash) ||
Boolean(props.file.ra_hash),
);
// Title ids get the same click-to-copy treatment as the digests.
const identifierChips = computed(() => {
const f = props.file;
const chips: { label: string; value: string | null }[] = [
{ label: t("rom.title-id"), value: f.title_id },
{
label: t("rom.version"),
value: f.title_version != null ? String(f.title_version) : null,
},
{ label: "SHA-1", value: f.sha1_hash },
{ label: "CHD SHA-1", value: f.chd_sha1_hash },
{ label: "MD5", value: f.md5_hash },
{ label: "CRC", value: f.crc_hash },
{ label: "RA", value: f.ra_hash },
];
return chips.filter((chip) => Boolean(chip.value));
});
</script>
<template>
@@ -171,47 +178,12 @@ const hasAnyHash = computed(
</template>
</div>
<div v-if="hasAnyHash" class="r-v2-file-row__hashes">
<div v-if="identifierChips.length" class="r-v2-file-row__identifiers">
<HashChip
v-if="file.title_id"
:label="t('rom.title-id')"
:value="file.title_id"
compact
/>
<HashChip
v-if="file.title_version != null"
:label="t('rom.version')"
:value="String(file.title_version)"
compact
/>
<HashChip
v-if="file.sha1_hash"
label="SHA-1"
:value="file.sha1_hash"
compact
/>
<HashChip
v-if="file.chd_sha1_hash"
label="CHD SHA-1"
:value="file.chd_sha1_hash"
compact
/>
<HashChip
v-if="file.md5_hash"
label="MD5"
:value="file.md5_hash"
compact
/>
<HashChip
v-if="file.crc_hash"
label="CRC"
:value="file.crc_hash"
compact
/>
<HashChip
v-if="file.ra_hash"
label="RA"
:value="file.ra_hash"
v-for="chip in identifierChips"
:key="chip.label"
:label="chip.label"
:value="chip.value!"
compact
/>
</div>
@@ -336,7 +308,7 @@ const hasAnyHash = computed(
opacity: 0.5;
}
.r-v2-file-row__hashes {
.r-v2-file-row__identifiers {
display: flex;
flex-wrap: wrap;
gap: 4px;

View File

@@ -1,6 +1,6 @@
<script setup lang="ts">
// MetadataTab — four sections, top to bottom:
// 1. File info — name + size only.
// 1. File info — name, size, and the platform-native ids when present.
// 2. Hashes — SHA-1, MD5, CRC, RA, all mono. RTag with eyebrow label.
// Same order as the files list so the two tabs read alike.
// 3. Verification — RTag per database; tone="success" for match,
@@ -33,8 +33,9 @@ const fileRows = computed<Row[]>(() => {
return [
{ label: t("rom.filename"), value: r.fs_name },
{ label: t("common.size"), value: size },
{ label: t("rom.title-id"), value: r.title_id ?? "—" },
{ label: t("rom.save-id"), value: r.save_id ?? "—" },
// Only the sigil platforms carry these, so skip rather than dash them.
...(r.title_id ? [{ label: t("rom.title-id"), value: r.title_id }] : []),
...(r.save_id ? [{ label: t("rom.save-id"), value: r.save_id }] : []),
];
});