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>
`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>
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>
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>
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>
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>
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>
The rebase put the branch's keyword-only `existing_files` alongside
master's title id flags, and mypy resolves a `**dict[str, bool]` against
every parameter, so the bag no longer type checks. Name the two flags the
cases actually vary.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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
`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>
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>
Upstream took 0113, so the sigil migration rechains onto
0113_roms_locked_fields as 0114. The sigil build stage keeps its place
ahead of the emulator stage, which upstream renamed for js-dos.
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.
`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.
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.
The rationale for the locking scheme lives in the migration docstring and the
PR; the code only needs the part a reader cannot recover from it.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Review of the artwork-provenance work turned up two gaps behind the cleanup.
The new skip gate compared files on disk against the number of urls, so a
permanently dead url held the count below the target forever and every scan
refetched the entire set. Going index by index refetches only what is absent,
and lets `_store_screenshot` report success instead of the caller stating the
file back off the disk it just wrote.
The SGDB block still read `path_cover_s` to decide whether a cover was hand
supplied, the inferred marker `locked_fields` exists to replace. That also
shielded scraped covers from a better ranked source, which is the behaviour
this branch set out to fix, so it now asks the lock like the block above it.
The rest is cleanup: drop the dead `screenshots_exist`, give the column one
normal form across its writers, hoist the duplicated clear-out dict in
`delete_rom_manuals`, and drop the blanket backfill UPDATE, since a NULL
already reads as "no locks" everywhere.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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>
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.
Sigil reads the IP.BIN product number off the boot header, which is the
name flycast gives the per-game VMU file, so a Dreamcast ROM resolves the
same way every other supported platform does. The extractor is flagged
experimental upstream, having been validated against a small sample of
real discs.
save_id is the literal on-disk save location, and azahar, dolphin and
cemu all build those directories with lowercase hex. On case-sensitive
storage an uppercase id addressed a second directory beside the
emulator's own, so a game's saves split across the two. Sigil now emits
the path in the case the emulator writes; the pin moves with it, and
0111 recases the ids already stored so an existing library does not have
to be rescanned. title_id keeps its canonical uppercase form.
Unify manuals and walkthroughs on one document model instead of a
separate walkthrough subsystem. Walkthroughs are RomFiles under a new
WALKTHROUGH category with an optional RomFileDocMeta provenance sidecar,
and reading progress is a per-user RomFileUser row keyed on rom_file_id
so the same mechanism covers manuals and walkthroughs.
Backend:
- models: RomFileCategory.WALKTHROUGH, DocSource, RomFileDocMeta,
RomFileUser; migration 0110 (enum value + two tables, cross-DB)
- serve .txt/.html documents inline (HTML under a sandboxing CSP);
add .txt to allowed manual files
- endpoints: walkthrough upload / GameFAQs fetch / delete, and per-user
reading-progress GET (ROMS_READ) / PUT (ROMS_USER_WRITE, like notes, so a
kiosk guest capped to the read scopes cannot write)
- last_page is range-checked, so an out-of-range value is a 400 rather than
an integer column overflow
- the guide body is read under the size cap instead of being buffered in
full and truncated afterwards
- GameFAQs import extracts text only (stored as .txt); no remote HTML is
persisted or served. Host-allowlisted on top of the SSRF-safe client
- a Cloudflare bot challenge is detected and reported as "open it in your
browser and upload the text" instead of an opaque 403
- reading-progress upsert retries as an update on a unique-constraint
race, so concurrent saves for one user/file can't 500
- a GameFAQs guide is removed from disk again if indexing it fails,
rather than being left unreferenced
- tests for CRUD, progress, the GameFAQs parser/URL validation, and
hidden-rom masking on every walkthrough route
Frontend (v2):
- TextViewer (.txt/.html), useReadingProgress composable, WalkthroughSubtab
(upload + add-from-GameFAQs-URL + delete + progress), wired into MediaTab
- ManualSubtab renders .txt manuals; walkthrough category surfaced in
FilesTab; regenerated types; i18n keys across all locales
- a pending scroll position is committed before the viewer follows a new
document, so switching files mid-debounce no longer drops it
- WalkthroughSubtab gates upload, the GameFAQs URL field, and delete on
useCan("rom.edit"), as ManualSubtab already does
AI assistance: implemented with Claude Code (Opus 4.8). The data-model
design, backend, migration, tests, and v2 UI were AI-authored under human
direction. Alternative approach to #2892.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
region_names_for_priority expanded the configured shortcodes into a flat
list of region names and _region_rank turned each name's index into its
rank. Two names claiming one shortcode ("nl" for both Holland and
Netherlands) therefore ranked unequally, so a Holland-tagged rom always
beat a Netherlands-tagged one instead of both falling through to the
filename tiebreak. The helper's own comment claimed otherwise.
It now returns name -> rank keyed on the shortcode's position, so aliases
tie. Unknown and repeated shortcodes still contribute nothing rather than
shifting the ranks after them, which is now covered by tests too.
Reported by Greptile and Copilot on #4260.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The name claimed a locked cover surviving an unmatch, but the test sets
no lock and performs no unmatch. It cannot: get_cover takes url_cover as
an argument and never reads locked_fields, so an empty url is how a lock
reaches this layer. Setting one on the mock would imply a coupling that
does not exist.
Renamed to describe the behaviour it does cover, and the comment now
points at the test carrying the other half of the chain.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
From review. get_rom_screenshots recorded a path for every url whether or
not the download landed, pointing the database at files that were never
written. Only record paths that made it to disk, and decide the early
return by counting files on disk rather than trusting the recorded list,
so a set left short by a failed run is retried instead of being frozen by
an unchanged url set.
The existing with-urls test asserted the old behaviour with a stand-in
that wrote nothing, so it now writes the files it claims to store.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
_atomic_write cleaned up in `except Exception`, which does not catch
CancelledError. Stopping a scan mid-download therefore stranded a
`.romm_tmp_*` file per cancelled transfer. Catch BaseException instead.
This also covers uploads, which have always gone through this path.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YKbk4cDmdKKMcBxGmsRVT5
Streamed downloads opened the destination directly, so an interrupted
transfer truncated the file in place. A truncated file is worse than a
missing one: it still satisfies the *_exists checks, so later scans skip
it and never refetch. The error paths cleaned it up, but only when the
process survived to run them, which a SIGKILL or host reboot does not.
write_file_streamed now writes to a temp file in the destination
directory and renames it over the target once the caller's block
completes, reusing the _atomic_write helper uploads already use. The
handle closes before the rename, so the target never sees a partial
flush.
The _discard_partial_file calls that followed a streamed write are gone.
There is no longer a partial file to remove, and the target now holds
either nothing or the previous good copy, which those calls would
delete. Refreshing a cover no longer costs the existing one when the
transfer dies.
The two disk-full tests patched write_file_streamed itself, so they were
asserting against the non-atomicity this removes. They now fail the
write from the response stream and exercise the real path.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
(cherry picked from commit 9b81fef29564d053c0ba4bb21f2192e0b9dc1f50)
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>
Region tags now resolve only through the canonical REGIONS names and
shortcodes, so alternate spellings such as (US) or (EU) stay plain tags.
Existing rows keep whatever parse_tags wrote for them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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.
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>
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>
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>
get_cover() called _store_cover() once for CoverSize.SMALL and once for
CoverSize.BIG with the same URL, and each call performed a complete fetch.
The small cover has no distinct source: it is the large image downloaded in
full and then resized in place, so the second request only re-retrieved bytes
already on disk. Every cover cost twice the bandwidth, doubled the load on
every provider, and on ScreenScraper spent a second request from the
account's quota, since media is served from the same authenticated api2
endpoints as metadata lookups.
_store_cover() now takes no size: it fetches once into big.png and derives
small.png from it, the way store_artwork() already did.
A missing small cover no longer triggers a fetch at all. get_cover()
downloads only when overwriting or when the large cover is absent, and
otherwise rebuilds the small one from the large one already on disk via
_derive_small_cover(). That drops the half-written pair case from one request
to none, and keeps a good large cover out of the blast radius of a download
that might fail. The derive path resolves its source through _get_cover_path,
so an uploaded big.jpg or a converted big.webp yields a matching small file
rather than assuming a .png extension.
Failure paths now clean up both destinations. Undecodable bytes are
discarded rather than left on disk, where they satisfy cover_exists() and
stop any later scan from refetching a working cover, and a discarded
chroma-key placeholder also clears a small cover left by an earlier scan.
_derive_small_cover() is the exception: it did not write those bytes, so a
large cover it cannot decode is left in place and only the partial small one
is dropped.
Fixes#4102
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A *_path with no matching *_url can never be fetched, so it must not
survive when the file it names is missing. No provider produces that
state today (each gates the path on the URL), but store_metadata_media
now guarantees every path it leaves behind points at a real file.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Metadata providers record where each media file should live at match time,
and the path was persisted whether or not the download produced a file. A
non-200 response, an unexpected content type, a transport error, or a
discarded ScreenScraper chroma-key placeholder all leave nothing on disk,
so the ROM kept pointing at a file that was never there.
Local gamelist/Pegasus exports then warned once per ROM per phantom asset
and left an empty assets/<subdir>/ behind, and the frontend built box-face
URLs that 404.
store_media_file now reports whether the file is on disk afterwards, and
store_metadata_media clears the *_path entry for anything that didn't land
while keeping the *_url so a later scan can retry. Both exporters skip a
missing source quietly instead of warning, and no longer create the
destination directory before knowing the source exists.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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>
Synology NAS shares carry a `#recycle` folder at the root of every share,
which RomM picked up as a platform directory. Add it to
DEFAULT_EXCLUDED_DIRS, and make the exclusion list match glob patterns so
the long-standing `.Trash-*` entry actually excludes anything.
Exclusions are now applied before the directories are stat'ed, and a
directory that raises OSError during Structure B detection is skipped with
a warning instead of propagating. An unreadable folder used to bubble a
500 out of `/api/heartbeat`, which the frontend retried in a loop during
first-time setup.
Fixes#4043
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>
The 3DS nests its save under two directory levels, so sigil reports it as
a '/'-separated save_id (00040000/00033500) flagged with usage=folder-split
rather than a flat id. Add SaveUsage.FOLDER_SPLIT, migrate the saveusage
enum (0106), regenerate the frontend SaveUsage type, and bump the sigil
pin to 98f3c62.
The last platform's quota readout and the end-of-scan summary both call
_log_ss_quota, so a completed scan printed the same numbers twice in a row.
Skip a line identical to the previous one, resetting at the start of each scan
so a new run always reports.