Commit Graph

192 Commits

Author SHA1 Message Date
Georges-Antoine Assi
568aa818de refactor: tighten the library structure naming and docstrings
Rename `FirmwareTemplate.platform_path` to `firmware_dir`: it returns the
firmware folder, while the same name on `StructureTemplate` returns the platform
folder. Name the watcher's index for the segment it points at.

Fold the two reads of a raw structure key into `_raw_template`, and drop the
docstrings that only restated a one-line delegation or a signature.

Remove `footer-create-summary-default`, which no component references and whose
copy still named Structure A.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 08:53:55 -04:00
Georges-Antoine Assi
a7ecfd96a9 feat!: make filesystem.structure the single library layout
`filesystem.structure` now spells out the whole layout rather than only the part
below a platform folder. A template is relative to the library root, `{platform}`
marks the platform folder, and `{game}` marks where a game begins.

Merge `{gameFile}` and `{gameDir}` into one `{game}` terminal. The information a
terminal carried was the depth, not the kind: at a declared level a file is a
game of its own and a folder is one multi-file game, which a stat answers. That
drops the two-template idiom for a level holding both, and `_discover_default_roms`
with it, since the default scan is now just `roms/{platform}/{game}`.

Retire the auto-detected `{platform}/roms` layout, along with
`filesystem.roms_folder` and `filesystem.firmware_folder`, which named one path
segment each that a template now contains. Both are refused at startup with the
template that reproduces the layout, so an instance that relied on either says so
instead of scanning an empty library and marking every rom missing. Firmware gets
its own `structure.firmware` key rather than following the rom layout implicitly.

`get_roms_fs_structure` keeps meaning the folder a platform's games start in, so
the `.physical` sentinel paths already in the database still resolve. Per-platform
overrides have to agree with `default` on where the platform folder sits;
relocating one platform needs platform discovery and the watcher to union several
roots, which is left out.

The setup wizard reports `library_ready` plus the configured template instead of
a `struct_a`/`struct_b` discriminator, so the banner shows the layout in force
rather than guessing it client-side.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 08:39:21 -04:00
Georges-Antoine Assi
dd7f46b52c fix: make metadata exports and matching follow the library structure
Testing the custom library structure against a live library turned up four
defects, all of them a path being reduced to a bare file name.

Both exporters wrote a rom's `fs_name` alone, so every game a template nests
was exported as if it sat in the platform folder: ES-DE and Pegasus could not
find any of them. They now write the rom's path relative to the platform
folder, the folder the metadata files themselves live in, and copy exported
media into the matching subfolder so two identically named roms keep their own
artwork.

Merging into an existing gamelist.xml / metadata.pegasus.txt keyed entries by
file name too, so identically named roms in different folders both merged into
the first entry and produced duplicates. Entries are now keyed by path, with a
Pegasus block matched by the folder its listed files sit in.

Reading a gamelist.xml had the same collision: two roms sharing a file name
both took the metadata of whichever entry was parsed last. A rom's own path now
wins, and a bare file name stays a fallback key for the tools that write those,
dropped when two entries share it.

Default discovery surfaced hidden folders as multi-file games, unlike
structured discovery which skips them. exclude_multi_roms now owns that rule
for both.

Also validate `exclude`'s exclusion_type: an unknown value reached
`Config.__getattribute__` and returned a 500 rather than a 422.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 07:31:05 -04:00
Georges-Antoine Assi
6b01e9943e refactor: trim review-pass comments and cover LocationChip
Cut the comments that explain rather than note: the migration's four-paragraph
docstring, the upload-path and digest-SQL docstrings, and the mark-missing note
in the scan loop. Drop an em-dash from LocationChip's header per CLAUDE.md.

Reword 0126's downgrade error so it no longer embeds a SELECT, which bandit
reads as string-built SQL, and mark the dialect-selected backfill nosec B608 the
way the other migrations do.

Add the LocationChip test its HashChip sibling already had, covering the copy
going through useClipboard (the composable is what applies the secure-context
guard).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 20:17:28 -04:00
Georges-Antoine Assi
f105622513 fix: address code review on the library structure unique index and relocation
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.

Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.

Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.

Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.

Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:14:58 -04:00
Georges-Antoine Assi
a73667a5ca refactor: rename the parsed template type to StructureTemplate
`LibraryStructure` named two unrelated things: the A/B enum for which of
RomM's two folder layouts a library uses, and this branch's parsed
per-platform template. Both were imported into handler/filesystem.

The parsed template is now `StructureTemplate`, with `parse_library_structure`
and `parse_platform_structures` following it to `parse_structure_template` and
`parse_platform_templates`. `LibraryStructure` again refers only to the enum.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 17:50:08 -04:00
Georges-Antoine Assi
9dcaf89890 fix: address PR review feedback on library structure and relocation
A grouping folder is no longer also a game. With `{gameDir}` and
`{category}/{gameFile}` declared together, the category folder was surfaced
as a multi-file game *and* descended into, listing its contents twice. A
folder any template descends into is now treated as a grouping level.

Relocation runs for every platform, not only those with a custom structure.
Dropping a platform's template moves every game back to the platform root,
which previously read as a library of new games and orphaned all the saves,
play history, favorites and collection membership. A library whose paths are
unchanged still costs one query and no hashing. This also removes the need
for a manual "apply relocation" toggle.

Physical games are excluded from relocation candidates: they have no file, so
they read as having disappeared from their path on every scan.

A near-miss on the terminal macro (`{gameFolder}` for `{gameDir}`) now names
the offending section instead of only reporting a missing terminal.

Documents two limits the QA pass asked about: a move that also compresses or
extracts the game changes its size and is not detected (the size pre-filter
runs before hashing), and how reverting to the default layout behaves.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 17:01:33 -04:00
Georges-Antoine Assi
4219f56f10 Merge branch 'master' into claude/kind-goodall-0b77y7
Conflict resolution notes:

- Locale rom.json: master sorted and reworked every file; took master's and
  re-inserted `location` / `location-copied` in sorted position. Added them to
  the new tr_TR locale.
- FSRom gained a required `fs_path`, so `build_hashless_fs_rom` now takes one
  and both call sites pass the rom's own path.
- `get_roms` keeps this branch's `_collect_fs_roms` discovery while adopting
  master's one-pass build and in-place sort.
- `mark_missing_roms` takes full paths and now also excludes physical games
  (master), and the scan loop keeps master's early missing-sync plus its
  restored-rom emit alongside this branch's relocation pass. The relocation
  filter now applies only to the identify loop, so a relocated rom is no longer
  re-flagged missing at the end of the scan.
- Relocation writes rom files through master's `sync_rom_files` (which replaced
  `purge_rom_files` / `add_rom_file`), so row ids and track metadata survive.
- Master's unique index on (platform_id, fs_name) contradicts this branch's
  premise that same-named files in different folders are distinct games.
  Migration 0126 widens it to (platform_id, fs_path, fs_name); physical games
  all share one folder, so a duplicate title is still rejected.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 16:24:59 -04:00
Georges-Antoine Assi
8cc1e8bd15 style(gamelist): trim the media map comments to the non-obvious why
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 16:29:56 -04:00
Georges-Antoine Assi
65b2a050c1 refactor(gamelist): give the ES-DE media folder names one home
Fold the exporter's folder map and the importer's ESDE_MEDIA_MAP into a
single GAMELIST_MEDIA_DIRS, so writing, reading and skipping a media type
is one edit. This also picks up thumbnails/, which the scan exclusions were
missing, and drops the hand-appended "images" literal.

Serve the multi-file defaults pre-unioned as DEFAULT_EXCLUDED_MULTI_DIRS so
neither UI has to re-join two lists; v1 was still mapping EXCLUDED_MULTI_FILES
to DEFAULT_EXCLUDED_DIRS and rendering the media dirs as deletable.

Collapse the per-tag asset loop and the bespoke <mix> block into one table
keyed by tag, and skip fnmatch for the exclusion patterns that hold no glob
characters, now that the multi-file list is more than twice as long.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 16:19:55 -04:00
Georges-Antoine Assi
eec574b49b fix(metadata): give UniversalPlatformSlug a leaf home
Both CI failures came from one import cycle. RQ could no longer resolve
`endpoints.sockets.scan.scan_platforms`, and the e2e seed script failed the
same way, because `sigil` imports the platform slug enum, importing anything
under `handler.metadata` runs its `__init__`, that reaches `gamelist_handler`
which imports `handler.filesystem`, and `roms_handler` there imports `sigil`
back while it is still half-initialised.

The cycle predates this branch. It stayed hidden because `scan.py` reached
the enum through `utils.switch`, imported late enough that
`handler.filesystem` was already loaded; naming the adapter directly moved
that import to the top of the module and the ordering luck ran out.

So the enum moves to `utils/platform_slugs.py`, which imports nothing but
`enum`. Naming a platform no longer drags in httpx, redis and the titledb
task, and the 29 call sites point at the module that owns it rather than
picking it up from a 1000-line metadata handler that happens to re-export
it. `import adapters.services.sigil` now also works on its own, which it
did not before.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 14:28:49 -04:00
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
Georges-Antoine Assi
8db38f3322 Merge remote-tracking branch 'origin/master' into feature/sigil-title-ids-followups
# Conflicts:
#	backend/handler/filesystem/roms_handler.py
#	backend/tests/endpoints/sockets/test_scan.py
2026-09-04 10:33:45 -04:00
Georges-Antoine Assi
13ac6668b7 chore(review): tighten the files scan and folder upload code
Backend:
- Drop the HashPolicy enum: FULL had no caller and INCREMENTAL was the
  default, so refresh_rom_files uses the existing_files knob directly.
- Narrow RomFilesRefresh to the counters callers read.
- Build ParsedRomFiles once so the incremental return stops dropping the
  title id fields.
- Give the assembling suffix one home in config, read by both the
  assembler and the scanner's excluded extensions.
- Fold the duplicated destination collision check into one helper, and
  branch /start on the upload target itself.
- Load the lighter rom for the refresh emit and the upload endpoints,
  keep the flat file stat off the event loop, and reuse the directory
  listing for the RA hash lookup.

Frontend:
- Route the platform scan dialog and the scan view through
  useScanTrigger, so a scan started while one runs is refused rather
  than emitted and rejected by the backend.
- Rename the socket payload type to ScanRequest, away from the
  useScanProviders type of the same name.
- Drop the dead uploading prop and folder icon, reuse singleRomTitle,
  and resolve each file's relative path once per listing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-03 18:00:01 -04:00
zurdi
fc8cfbc6f1 feat(scan): add a files scan that reconciles rom folders incrementally
Files added to an already-scanned folder ROM could only be picked up by a
complete or hashes rescan, which rehash every known file. The new `files`
scan type scans new games like quick and re-lists the files of existing
folder ROMs, hashing only new or changed files and recomputing the
ROM-level hashes only when a top-level file changed. Per-rom update and
unmatched scans reuse the same incremental mode, and the filesystem watcher
enqueues it instead of quick.

Also stores rom_files.last_modified as Double (MariaDB FLOAT rounds a
current mtime to about 128 seconds), adds the CHEAT value missing from the
PostgreSQL category enum, maps `patches/` to the patch category and
excludes upload temp files from scans.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017WbesTQXohyAWWcLV5iiEN
2026-09-03 17:11:03 -04:00
Georges-Antoine Assi
355eee2190 refactor(scan): give the binary identity one shape and one writer
`RomIdentity` replaces the title_id / save_target / save_target_layout
triple that was spelled out separately on `ParsedRomFiles`, in `FSRom`,
and again in the scan's attribute merge.

`switch.normalize_identity` is now the single place that forces a Switch
id onto the base game's, which both the scan and `PUT /roms/{id}/identity`
call. The rule was written twice before, and the two copies disagreed
about what an update's save target should be. The endpoint keeps its
merge semantics: an omitted field is still left alone.

`get_rom_files` is a read again. It records which files can carry their
title id, and the new `embed_switch_title_ids` step performs the renames,
so writing to the user's library is a named call the scan makes rather
than a side effect smuggled out on a parse result.

The Switch family now lives in `utils/switch.py` in RomM's own terms,
instead of being recovered by filtering the sigil adapter's slug map.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 17:26:18 -04:00
Georges-Antoine Assi
97a16e2c79 refactor: tighten comments and tests on the sigil branch
Reverts the FileRow hash-chip loop. It was left over from the per-file
version chip that no longer exists, so it is unrelated to title ids.

Cuts the comments that restate the code or defend an obvious choice, and
the `Args:` block on `get_matching_missing_rom` that repeated its own
parameter names. The CNMT content-type rationale now lives only on
`CONTENT_TYPE_CATEGORIES`.

Tests exercise the production path: the title id regex is checked with
`fullmatch`, the way the caller uses it, and `test_identity` builds its
auth header the way every other endpoint test does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 17:13:20 -04:00
Georges-Antoine Assi
bcafc3d504 refactor(scan): tighten the sigil title id plumbing
Rename embedding now goes through the handler's own rename primitive
(`rename_fs_rom`), so it inherits the library-root path validation and
per-path locking every other write in that class gets, and builds the new
name with the repo's multi-part extension helpers.

Extraction no longer reads files it can never parse: archives, manuals,
soundtracks and screenshots are skipped, and on non-Switch platforms it
stops after the first result, since only Switch looks at a per-file
content type.

Also collapses the two rom-level branches (dropping a closure), gives the
Switch family one home in RomM's own terms instead of deriving it from
sigil's slug string, logs an unrecognized save target layout instead of
dropping it silently, deletes the `ScannedFSRomValues` mirror of `FSRom`,
drops a dead `rom.version` locale key, and slims the sigil Docker builds
to one layer with a filtered clone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 16:34:36 -04:00
nendo
48d48b152f feat(roms): accept binary identity from a client
RomM reads a ROM's identity during a scan wherever it can open the file.
An encrypted Switch dump it cannot, and the keys that would open it stay
off the server, so a client holding them can PUT what it extracted under
roms.write. A Switch update or DLC id resolves to its base first, since
reassociating a renamed non-hashable ROM matches on that field and an
update id there would strand the entry.
2026-08-31 11:20:19 +09:00
nendo
53bdc371cd refactor(scan): give Switch title-id knowledge its own module
What a base-game id looks like, how to recover one from an update or DLC
id, and how a content type maps to a category are facts about the
platform, not about scanning a filesystem, and they sat in the middle of
a handler that is nine hundred lines of other concerns. The rename that
embeds an id stays with the filesystem code that owns file operations
and imports the patterns it needs.
2026-08-30 13:23:54 +09:00
nendo
64a1b57661 refactor(scan): name the save fields for what they address
`save_id` collided with two other meanings in the codebase: `Save` is a
model, and `DeviceSaveSync.save_id` is a foreign key to it. Neither is
what this field holds, which is the on-disk name an emulator gives a
game's saves. It becomes `save_target`, and `save_usage`, which said
nothing about what it decided, becomes `save_target_layout`. Both carry
a `doc=` so the meaning is at hand where the columns are read.

The per-file copies are gone. Nothing read `RomFile.save_id`, and the
per-file `title_id` and `title_version` only fed display chips, while
the category derived from the binary content type is what actually
drives update and DLC behaviour and stays. Save layout belongs to a
game rather than to one of its files, so a client can no longer read a
file's value and build a wrong directory from it.
2026-08-30 13:22:53 +09:00
nendo
1055fcff84 fix(scan): stop reading the user's Switch decryption keys
Extraction handed sigil a path to the console's prod.keys so it could
decrypt retail XCI and NSP headers, which made RomM responsible for a
user secret and let native code read it. Encrypted retail dumps now
resolve nothing rather than being decrypted server-side; decrypted dumps
still resolve, since NCA headers are tried as plaintext first. A client
that already holds the keys is the right place for that work.
2026-08-30 13:19:08 +09:00
Georges-Antoine Assi
dac52447c8 refactor(scan): apply the scanned values with a single update
`FSRom.update` needs a TypedDict, not a `dict[str, Any]` — mypy rejects
the latter with typeddict-item. Declare the rebuild's output shape as
`ScannedFSRomValues` next to `FSRom` and update from that, so the write
stays one call and every key and value type is still checked.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 21:59:30 -04:00
Georges-Antoine Assi
e7c4cb2ab6 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>
2026-08-28 18:18:47 -04:00
nendo
5425a227ab Merge upstream master into feature/sigil-title-ids
Upstream took 0108 through 0110, so the four sigil migrations rechain
onto 0110_walkthrough_docs as 0111 through 0114. RomFile keeps both the
title id index and upstream's new rom_id/category composite, and
models/rom.py keeps SaveUsage alongside the new document types.
2026-08-26 19:40:48 +09:00
Georges-Antoine Assi
427510082d Merge pull request #4206 from sdornan/claude/normalize-region-language-tags
fix(scan): normalize region and language tags to one canonical spelling
2026-08-16 16:55:01 -04:00
Georges-Antoine Assi
a1d2cb0d4f fix(scan): keep an empty "Reg-" tag out of the region facet
A "Reg-" prefix with nothing behind it stored an empty string as a
region. It now falls through to the ordinary tags like any other
unrecognized value.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-16 16:47:49 -04:00
nendo
95f30b409c Merge upstream master into feature/sigil-title-ids
Resolve conflicts:
- rom_files/roms indexes: union the title-id index with upstream's new
  hash-search indexes.
- scan.py: keep upstream's ScreenScraper scan refactor, retaining the
  LIBRARY_BASE_PATH and UniversalPlatformSlug imports the body still uses.
- cleanup_orphaned_resources tests: take upstream's version.
- Renumber the sigil migrations onto upstream's 0107 head as 0108/0109/0110
  so the alembic chain stays single-headed.
2026-08-17 03:57:25 +09:00
Georges-Antoine Assi
8f3460e820 Merge pull request #4198 from XenuIsWatching/fix/scan-memory-and-listing-perf
perf(scan): cut scan memory and drop a quadratic file listing check
2026-08-16 14:22:57 -04:00
Sam Dornan
17b20ba423 fix(scan): canonicalize legacy collection criteria and bound migration memory
Review follow-ups on the region and language normalization.

Smart collections created by early versions store a single value under
`selected_region` / `selected_language` rather than a list, and
get_smart_collection_criteria still reads those keys. The migrations only
rewrote the list-valued ones, so a legacy collection kept filtering on "US"
against rows that had become "USA" and silently matched nothing. Both keys
are now handled, preserving each value's scalar or list shape.

The roms backfill also loaded every tagged row before writing anything, so
peak memory scaled with the library on a migration that runs at startup. It
now walks the table by id, holding one batch at a time. The collections pass
still reads in one go: that is one row per user-created collection.

Also strip the "Reg-" capture, since the separator class doesn't swallow a
following space and "[Reg- PAL]" stored " PAL" as its own facet value, and
add a test enforcing the REGION_ALIASES constraint that was only a comment.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 19:18:31 -05:00
Sam Dornan
5d565d3ae0 fix(scan): normalize region and language tags to one canonical spelling
parse_tags only canonicalized a region or language written as a shortcode.
A tag written as a name kept the filename's casing, and a "Reg-" prefixed
code outside the shortcode table was stored verbatim, so one library could
hold "USA", "usa", "Usa" and "US" as four values. Each became its own entry
in the filter dropdowns and its own bucket in the platform stats.

Both kinds now resolve through a case-insensitive lookup, with a region
alias table for the spellings the frontend's regionToEmoji already knew
about (US, EU, EUR, JP, BRA, CHN, GLOBAL) plus WR for World.

The region pass runs before the language pass but after both exact-code
checks, because Nl/NL and No/NO differ only by case: exact matching keeps
Dutch and Norwegian, and a lowercased "nl" resolves to the region.

Migrations 0108 and 0109 rewrite rows scanned before this. They also
normalize smart_collections.filter_criteria, whose saved values are
exact-matched against roms.regions, so a collection filtering on "US"
would otherwise silently match nothing. roms_facets follows through the
triggers added in 0100.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 19:01:00 -05:00
Ryan McClelland
9da03db857 perf(scan): build filesystem ROM entries in a single pass
get_roms built a list of plain dicts for every entry, then rebuilt the
whole thing as FSRom instances and handed that to sorted(). Both lists
are alive at once, so a platform folder holding tens of thousands of
files carries two full copies plus the sorted output.

Build FSRom directly and sort in place. The nested flag is simply the
inverse of flat, so it no longer needs to be carried through an
intermediate dict.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TLTDjv3niosCXZWtjKELK2
2026-08-14 09:11:11 -07:00
Sam Dornan
f15ec3e42d fix(hashing): surface unreadable zip and tar archives
The zip and tar readers swallowed read failures and returned an empty
iterator, which the hashing path can't tell apart from an empty archive:
it falls back to hashing the container's raw bytes, so the ROM gets
hashes that match no hash database and nothing explains why.

Raise ArchiveReadError instead, as the 7z and rar readers already do, so
the fallback is logged. Member streaming is now wrapped too, since chunks
are consumed outside the reader's error handling and a bad CRC escaped as
a raw zipfile error rather than falling back.

Fixes #4159

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 16:05:23 -05:00
Sam Dornan
63aa82566e refactor(hashing): call CHD probe inline instead of via a thread
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 21:21:21 -05:00
Sam Dornan
a3d6fef4ac Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-05 14:05:57 -05:00
Sam Dornan
dc933fe4b5 fix(hashing): extract CHD SHA-1 for folder-based ROMs
The folder branch of get_rom_files probed for a CHD header at
<walked dir>/<rom folder name> instead of the file being walked, so the
path never existed and chd_sha1_hash came out empty for every file of
every per-game-folder ROM, single-disc included.

This also degraded metadata matching, since Hasheous lookups fall back
to the container's MD5/SHA-1/CRC when the disc-data SHA-1 is missing,
and those match nothing for a CHD.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 13:59:46 -05:00
Ryan McClelland
b785a457f5 perf(scan): stop hashing single-file ROMs twice
Every chunk was streamed through two independent sets of hashers: one for
the RomFile and one accumulating the ROM-level hash. That second set is
only meaningful for a multi-file ROM, whose hash spans the concatenation
of its top-level files and so cannot be derived from the per-file digests.

For a single-file ROM the two sets see identical bytes and produce
identical digests, so the ROM-level pass was pure duplicate work. Nested
files inside a multi-file ROM were worse: they were fed through throwaway
accumulators whose results were discarded at the call site.

Make the accumulators optional and skip them where they are not needed,
reusing the file's own hashers as the ROM-level values for a single-file
ROM. Multi-file top-level files keep the second pass, since theirs is the
case that needs it.

Measured on a Raspberry Pi 4 against a 134 MB Nintendo 3DS ROM, page
cache warmed, best of three, comparing CPU time to exclude contention:
36.5 MB/s -> 60.3 MB/s, a 1.65x speedup, with byte-identical CRC, MD5 and
SHA1 at both the file and ROM level. Most libraries are predominantly
single-file, so this applies broadly rather than to an edge case.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 13:56:10 -07:00
nendo
6042a1c56b Merge upstream master into feature/sigil-title-ids
Re-integrate the sigil title-id feature on top of upstream's scan
reconciliation refactor and migration additions.

Scan reconciliation:
- _identify_rom now persists rom files via db_rom_handler.sync_rom_files
  instead of purge_rom_files + per-file add_rom_file. The obsolete
  RomFile copy-list (title_id/save_id/title_version) is removed; those
  fields now ride along through ROM_FILE_SCANNED_COLUMNS.
- Add title_id, save_id, title_version to ROM_FILE_SCANNED_COLUMNS so
  sync_rom_files copies them onto reconciled rows. Without this the
  extracted ids/version silently drop to NULL on rescan.
- Single-file embedding rename (renamed_rom_fs_name) preserved in both
  the new-entry and update paths of _identify_rom.

Migrations renumbered to chain after the new upstream head:
- 0102_sigil_title_ids -> 0104_sigil_title_ids (down: 0103_roms_facets_provider_ids)
- 0103_sigil_title_version -> 0105_sigil_title_version (down: 0104_sigil_title_ids)

Tests:
- Reworked TestIdentifyRomPersistsFileTitleVersion to capture
  sync_rom_files and assert the scanned RomFile carries title_id and
  title_version; added a direct assertion that ROM_FILE_SCANNED_COLUMNS
  includes the sigil columns.
2026-07-24 07:20:10 +09:00
nendo
aba14c0d59 Add opt-in Switch title ID filename embedding
New config.yml flag filesystem.embed_switch_title_ids (default off)
renames Switch/Switch 2 files during scan to embed their binary
title id and version (Name [TITLEID][vN].ext), then reconciles the DB
record. Idempotent (skips names already carrying a title-id bracket),
collision-safe, and Switch-only. Single-file roms update Rom.fs_name;
multi-part inner files update only their RomFile name. Driven by the
CNMT-extracted per-file ids, this is the correct form of the filename
embedding the original PR group attempted via filename heuristics.
2026-07-24 06:14:41 +09:00
nendo
4e696b389a Extract per-file Switch content type and version via CNMT
Drop the top-level-only gate so update and DLC files in nested folders
get extracted. Consume sigil's new content type and version: set the
RomFile category from the binary content type (application/patch/addon
-> GAME/UPDATE/DLC), authoritative over folder names for Switch when
CNMT succeeds, and store the title version in a new BigInteger column.
Updates now carry their own ...800 id and version instead of collapsing
to the base.
2026-07-24 06:04:07 +09:00
nendo
ccf43ed87e Add binary title ID extraction via sigil during scans
New SigilService adapter wraps the optional sigil cffi binding (guarded
import, degrades to a no-op when absent) and extracts platform-native
title/save IDs from ROM binaries during the scan's file pass, gated to
nine platforms and independent of the hashable-platform gate. Switch
resolves prod.keys from the platform's scanned firmware. Per-file
title_id/save_id land on rom_files, rom-level title_id/save_id and a
SaveUsage enum land on roms (base Switch ID derived arithmetically when
only update/DLC files exist). Config flag
filesystem.skip_title_id_extraction mirrors skip_hash_calculation.
2026-07-24 02:54:20 +09:00
Georges-Antoine Assi
969d9b3f9e fix(archives): fail archive hashing when a member can't be read
A member that failed or timed out mid-archive ended the member stream
silently, so the caller kept the composite hash built from the members
that happened to succeed. Raise ArchiveReadError instead and fall back to
hashing the archive's raw bytes, with no archive_members recorded.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 07:37:39 -04:00
TowyTowy
8c54a884a9 fix(scan): resolve "Reg-" prefixed region shortcodes to full names
PR #3035 made region/language shortcode lookups case-sensitive by keying
REGIONS_BY_SHORTCODE on the uppercase codes, and updated the plain tag
lookups to match against the raw (unlowered) tag. The "Reg-" prefix branch
was missed: it still lowercased the captured shortcode before looking it up,
so it could never hit the now-uppercase-keyed dict. As a result a tag like
"[Reg-J]" was stored as the raw "J" instead of resolving to "Japan".

Match the shortcode with its original case, like the other lookups, so
"[Reg-J]" resolves to "Japan" and "[Reg-U]" to "USA". Non-shortcode values
(e.g. "[Reg-PAL]") are still kept verbatim via the fallback.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-15 20:22:16 +02:00
TowyTowy
aba4d0cda1 fix(scan): strip leading dot from dot-separated version tags
VERSION_TAG_REGEX only treated whitespace, underscore, and hyphen as
separators after the version prefix, so a dot-separated tag like
"(v.1.0)" or "(Ver. 1.00)" fell through to the no-separator branch and
captured the dot into the version (".1.0", ". 1.00"). This wrong value
was then persisted to Rom.version on scan and on rename.

Add "." to the separator character class so the dot is consumed like the
other separators. Digit-prefixed tags such as "(v1.0)" are unaffected
(they still match the no-separator branch), and non-version "v*" tags are
still ignored.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-15 11:31:52 +02:00
Georges-Antoine Assi
c49e144311 Merge pull request #3640 from tmgast/feature/soundtrack-metadata-columns
Add a music query API for soundtracks
2026-07-04 12:18:32 -04:00
Georges-Antoine Assi
5d4316cf52 stirp version tags 2026-07-03 08:04:08 -04:00
Georges-Antoine Assi
d929b94fe2 run fmt 2026-07-03 07:56:23 -04:00
copilot-swe-agent[bot]
2621a62bee fix: tighten version tag detection for v-prefixed tags
Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com>
2026-07-02 11:10:02 +00:00
nendo
8a94854b81 Add a music query API for soundtracks
RomM stores soundtracks but exposes no way to consume them as a music library: a
client has to enumerate ROMs and pull each one's tracks individually, and the
per-track metadata lives in the `rom_files.audio_meta` JSON blob, which is
unindexable on MariaDB, so any library-wide filter or sort degrades to a full
scan.

This adds a queryable, music-first API for soundtracks, backed by a typed and
indexed `track_meta` table migrated from that JSON.

It also lets users upload soundtracks, manuals, and screenshots to any ROM, not
only folder-based ones. When the target is a single-file ROM, the client warns
that the upload will migrate it to a multi-file (folder) structure, then performs
that migration in place automatically.
2026-07-02 11:16:07 +09:00
Claude
f7f0ca9c2c feat: allow a list of structure templates per platform (union discovery)
A single fixed-depth template can't describe a platform that holds loose
games in its root AND organizes others into grouping subfolders — `{gameFile}`
drops the grouped games, `{category}/{gameFile}` drops the loose ones. Let a
platform's `filesystem.structure` value be a list of templates; discovery is
their union, deduplicated by full path:

  structure:
    nes:
      - "{gameFile}"             # loose top-level games
      - "{category}/{gameFile}"  # games inside grouping subfolders

- config: accept str | list[str]; platform_structure() returns a tuple of
  parsed structures; parse_platform_structures() + validation handle both forms.
- fs handler: _collect_fs_roms unions each structure's discovery, dedup by
  (fs_path, fs_name).
- tests: list parsing, per-platform list config loading, and the mixed
  loose+grouped discovery case.
- docs: config.example.yml leads with the mixed-layout list example.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sk2dzM3K9qxWBdPAeGb7us
2026-06-23 01:45:07 +00:00