`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>
Give 0o644 a single home in utils/filesystem as SERVED_FILE_MODE, used by
both the ZIP cache and FSHandler._atomic_write. Collapse the mode repair to
one call site behind a single stat per cache hit, close the temp descriptor
unconditionally, and log the build where the namespace is already in scope.
Deduplicate the test fixtures and drive the concurrency test with a barrier
on flock instead of a sleep, so the race is guaranteed rather than timed.
Co-Authored-By: Claude Opus 5 (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 group_by_meta_id dedup window ordered each sibling group by
is_main_sibling then fs_name_no_ext, so absent a manual override the
gallery entry went to whichever filename sorted first: "(Demo)" beat
"(Europe)" beat "(USA)".
Two ordering terms now sit between those: a full release outranks a
pre-release, then the configured scan.priority.region order decides.
Release status comes first because a demo is not a substitute for the
game, so a Japanese release wins over a USA demo.
scan.priority.region already existed but only steered metadata and
artwork selection, so its description is reworded across all locales.
Regions live in a JSON column that no covering index can carry, and 0107
measured what one uncovered reference costs this window: the plan drops
from `type=index, Using index` to `type=ALL, key=NULL`, four times per
gallery page load. 0108 adds a STORED generated column over regions[0]
and covers it in idx_roms_sibling_cover instead, so the ranking reads a
scalar. The engine keeps it in sync and ALTER TABLE populates existing
rows, so no scan hook and no backfill are needed.
Pre-release detection matches the filename rather than the parsed `tags`
column: tags keep the dumper's casing, and fs_name_no_ext is already in
the index.
Reordering the priority list changes which rom represents a group, so the
cached gallery sidecars are dropped when the setting changes.
Closes#1528
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)
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>
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>
Streaming means valid entries are consumed before the parser reaches
any damage further down the file, so a truncated or corrupt gamelist
returned whatever had been read so far. The previous full-document
parse rejected such a file outright and imported nothing.
Clear the accumulated entries when a parse error escapes both the
incremental pass and the fallback, restoring that behavior. Errors
raised while building an entry still keep what was read, as before.
Also filter the fallback path to game/folder elements so it matches the
incremental path, and hoist the lowercase filename and suffix tuple out
of the per-extension loop in exclude_single_files.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TLTDjv3niosCXZWtjKELK2
exclude_single_files collected every excluded name into a list, then
filtered the input against it with `f not in excluded_files`. That
membership test rescans the list once per file, so a platform folder
holding tens of thousands of loose files spends most of the call in
list scans rather than pattern matching.
Decide per file in a single pass instead. Behavior is unchanged,
including for duplicate file names.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TLTDjv3niosCXZWtjKELK2
A scan with `roms_ids` set only narrowed which roms get metadata, not the
work around them: it still listed the platform folder, re-resolved the
platform's metadata, re-hashed every firmware file, synced the whole
platform's missing-file state twice, and walked every other rom in batches
to mark it present. Rescanning one file therefore cost time proportional to
the platform, not to the file.
Resolve a scoped scan's work from the database instead, via a new
`_scan_selected_roms` that skips all of the platform-wide reconciliation.
The gamelist cache warm-up stays, since hash matching reads from it.
`refresh_smart_collections` was likewise recomputing every smart collection
across the whole library after any scan; a scoped one now uses the targeted
`refresh_smart_collections_for_roms`.
A library scan never reaches an entry whose file is gone, since it walks the
filesystem. A database-driven one does, and scanning marks a rom present
unconditionally, so the scoped path checks the path first and marks it
missing rather than resurrecting it. That check needs `directory_exists`
alongside `file_exists`, which also derives `flat`/`nested` for the `FSRom`
a library scan gets from splitting its listing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Centralize the *_no_tags / *_no_ext / *_extension columns (derived from a
file name) behind @validates hooks instead of computing them by hand at
every write site:
- Add pure helpers (compute_file_name_parts and friends) to models.base;
the filesystem base handler now delegates to them.
- Add @validates on Rom (fs_name), BaseAsset (file_name, inherited by all
asset subclasses), and Firmware (file_name).
- update_rom keeps the fs_name-derived columns in sync on bulk update(),
which also fixes the rename path never updating fs_extension.
- Drop the now-redundant computations at the scan/rename call sites.
Also fix the migration backfill loop and a pre-existing list[str | None]
type mismatch surfaced in scan_handler. Add tests for the helpers, the
validators, and the update_rom bulk-sync path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Apply the same lazy-factory pattern to FSLaunchboxHandler and FSSyncHandler
that ssh_sync_handler now uses. With both opt-in features deferred to
first-use, the tolerate_missing_base escape hatch on FSHandler is no longer
needed — every handler now fails loudly on mkdir failure, which is the
right behavior for the always-on core paths (assets, library, resources).
Touched call sites:
- resources_handler._resolve_local_file_uri (launchbox)
- sync_watcher.py, endpoints/device.py, tasks/manual/sync_folder_scan.py
(fs_sync)
Net effect:
- Default installs never poke /romm/launchbox or /romm/sync at startup.
- Misconfigured opt-in users get a clear, actionable PermissionError at
the call site instead of a silent warning followed by mystery failures.
- tolerate_missing_base, its tests, and one stale log import are gone.
Importer (gamelist/launchbox file:// flows) and exporters (gamelist.xml,
metadata.pegasus.txt local exports) now hardlink media assets when source
and destination share a filesystem, falling back transparently to a copy
on EXDEV / EPERM / EOPNOTSUPP / EMLINK / EACCES (cross-device, FAT32,
exFAT, network mounts, etc.). Saves disk space and is effectively
instantaneous on large files (videos, manuals, miximages).
Covers keep a real copy (allow_link=False) because _store_cover resizes
the small cover in place via PIL.Image.save, which would truncate the
shared inode and corrupt the user's source image.
Also makes FSSyncHandler tolerate a missing/unwritable /romm/sync at
startup: an OSError from mkdir now logs a warning instead of crashing
the whole app at module-import time. Sync calls still fail at use time
if the mount remains broken — the right place to surface the error.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Rom.regions can contain raw filename text like "europe" or "EUROPE"
(filename parsing in roms_handler doesn't normalize casing), so the
direct dict lookup missed those tags and the locale silently fell back
to scan.priority.region. Replace the dict access with a helper that
lowercases both sides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When a ROM filename carries a region tag (e.g. (Europe)), use that
region first when picking artwork and localized titles, falling back to
the configured scan.priority.region. Previously the configured priority
was the only signal, so a US-first config would force US covers onto
European ROMs even when an EU asset was available.
Adds a shared name->provider-shortcode map and threads the rom through
the IGDB and SS lookup APIs so the rom-aware locale/region selection
can run for both providers.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This list was created based on latest DAT files from No-Intro and
Redump.org.
With all those extracted files in a folder, this command retrieved
language codes from filenames (only considering games with at least two
languages, to avoid false positives):
```shell
rg -N "^.*game name=\"(.*?)\".*" -r '$1' | \
rg -N "^.* \(([A-Z][a-z](,[A-Z][a-z])+)\).*" -r '$1' | \
rg -N -o "[A-Z][a-z]" | \
sort | \
uniq -c
```