Priming the account, the quota lines and the end-of-scan skip list are
ScreenScraper's own bookkeeping, so they move out of the scan socket and
behind begin_scan(), log_quota() and log_scan_summary(). The scan keeps
only the decision it owns: whether this scan uses ScreenScraper at all.
The quota-line bookkeeping joins the skipped ROMs in a _ScanState
instance, so the tracking that resets together lives together and needs
no global statement.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Settings -> Library Management -> Missing made three whole-library passes
per request, two of which produced data the page never renders, and none
of which could be cached because "missing" counts as a filter.
- The tab now opts out of the char index, the filter values and the
ordered id index, so the endpoint serves its total from a plain COUNT.
- `missing_from_fs` gets a composite index with `name_sort_key`, and the
filter compiles to an equality: MariaDB does not treat `IS NOT FALSE`
as indexable, so the index would otherwise only ever be scanned end to
end. The column is NOT NULL, so both forms match the same rows.
- The filter-value list is keyed on the scope (search / platform /
collection) alone. It is built from a query that never applies the
row-level filters, so a filtered request now answers with, and warms,
the same whole-library entry an unfiltered one does.
Fixes#3992
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Restrict ROM file deletion to the ROMS/DELETE grant. The new
DELETE /roms/{rom_id}/files/{file_id} route gated on ROMS_WRITE alone and,
unlike its manual/soundtrack/screenshot siblings, carried no category guard,
so a group holding write-but-not-delete could remove game files from disk
while whole-ROM deletion still required ROMS/DELETE.
Gate mutating streaming routes on ROMS_USER_WRITE instead of ROMS_READ,
matching the play-session routes. ROMS_USER_WRITE is always-on for
authenticated users, but absent from READ_SCOPES, which is all KIOSK_MODE
grants an anonymous visitor. Kiosk visitors all share user_id=-1, so session
ownership could not separate them and any visitor could claim sessions and
overwrite another's save states.
Restore the ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES gate on the cleanup
task's cron_string. It was dropped in 06cafd4b1, whose message refers to
update_switch_titledb, leaving the documented opt-out inert and scheduling a
destructive task nightly. That commit also broke two of the task's own tests.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Four points from the PR review:
- Leave the process-global ScreenScraper state alone when a scan does not use
ScreenScraper. DEV_MODE runs scans in-process, so overlapping scans could
otherwise clear each other's learned limits and skipped ROMs.
- Return pacing to the defaults when the per-scan state resets. Priming re-reads
the account moments later; should that fail, the conservative default is safe
for whatever account the credentials now name, whereas the previous scan's
allowance may be more than this one is entitled to.
- Stop a rate-limited ROM from trying the next lookup. A refusal that survives
the retry now propagates out of the handler and is caught once per ROM in
fetch_ss_rom, instead of being swallowed per call site and sending the caller
on to spend another retried request against a budget that is already gone.
_is_daily_quota_error excludes the rate-limit 429 so the two stay distinct.
- Hand the request slot back before inspecting and re-encoding a cover, so
local image work no longer holds a ScreenScraper thread.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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.
LaunchBox cloud lookups read from a Redis store that only the metadata
update task fills, but nothing surfaced when that store was empty. The
provider reported healthy, every search returned zero results, and the
logs said nothing.
- heartbeat now reports unhealthy until the store is populated, and an
empty store logs what to set to fix it
- the update task can be run manually whenever LAUNCHBOX_API_ENABLED is
on, instead of also requiring the scheduled-update flag
- the ~600k entry dump was buffered into a single pipeline, peaking at
1.7GB of RSS and writing nothing at all if the job was killed part way
through. Writes now go out in batches and parsed elements are dropped
as they are consumed, which caps the run at ~260MB. The task also gets
its own timeout, since the default 5 minutes does not cover a 100MB
download plus a 500MB parse
- alternate name lookups ignored the platform, so "Super Mario World" on
PlayStation matched Super Mario Bros.
- Coleco ADAM was spelled wrong, and Famicom / Super Famicom pointed at
platform names LaunchBox does not use
Fixes#3981
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Scan job discovery only looked at the high priority queue and only
recognised scan_platforms, so two kinds of in-flight scan went unseen.
Watcher scans are delayed through the scheduler and land in the low
priority queue, so the concurrency guard let a manual scan start
alongside one and the stop handler left it queued to run afterwards.
The scheduled rescan enqueues its own task and calls scan_platforms in
process, so the worker reports the task's name. That made stopping it a
silent no-op: with no running job matched, the stop flag it polls was
never set.
Discovery now spans both queues plus the scheduler and matches either
function name. The scheduler registry also holds the standing cron entry
for the scheduled rescan, which is a schedule rather than a pending
scan, so only delayed scan_platforms jobs count as queued.
Clearing the stop flag at scan start is now scoped to the scan that owns
it, so a scan starting next to one that has not yet polled the flag
cannot drop a stop request meant for it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The limits ride along on every response, so learning them from the first
scrape response meant the opening requests of a scan ran at the default one
thread and 50 requests per minute, and the quota only became visible once a
platform finished.
ssuserInfos.php reports the same ssuser block up front. Unlike the scraping
endpoints it does not consume the daily quota (measured: two reads 90s apart
moved requeststoday by 0), so a scan can ask once at startup and pace itself
correctly from the first request, logging the quota and the SCAN_WORKERS
advisory before the first ROM is touched.
Best effort: a refused or unreachable lookup logs a warning and the scan
carries on.
ScreenScraper returns the account's allowances on every response, but only
maxthreads was read. Use the rest:
- Pace requests against the reported maxrequestspermin (falling back to the
documented threads x 50), so fast lookups can no longer overrun the
per-minute budget without ever exceeding the thread cap.
- Report the remaining daily and unrecognized-ROM quotas after each platform
and at the end of a scan, and warn once when either drops below 10%.
- Hint once per scan when SCAN_WORKERS is below the thread allowance (scans
slower than the account allows) or above it (extra workers just queue).
- Raise a distinct error when a request is refused twice for exceeding the
rate, so the ROM is reported as skipped in the scan summary instead of being
saved with no ScreenScraper data.
- Route ScreenScraper media downloads (covers, screenshots, manuals, mixed
media) through the same limiters, since they are api2 endpoints that count
against the same allowances, and derive their timeout from the account's
advertised download speed.
Fixes#3978
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`scan_handler` enqueued a scan on every request without checking whether
one was already running. A client that lost the progress socket, which
happens routinely on mobile when the tab is backgrounded, has no way to
tell a scan is still in flight, so pressing scan again looks reasonable
and silently queues a second full library scan behind the first. Three
scans of the same library ran back to back on a real instance this way.
Reject the request instead, reusing the `scan:done_ko` channel that
`reject_unauthorized_scan` already uses to report a refused scan.
`stop_scan_handler` only ever cancelled the running job, so the queued
duplicates it left behind started as soon as it stopped. It now cancels
queued scans as well.
Its first lookup loop was also dead: it searched `high_prio_queue` for a
job named `scan_platform` with `is_started` set, but RQ records the name
as `endpoints.sockets.scan.scan_platforms`, and a started job is no
longer in the queue. The second loop hardcoded the full path, which is
what the first one drifted away from, so both lookups now derive the
name from the function object and are shared with the new guard.
Finally, clear the stop flag when a scan starts. It is only cleared by
the scan that observes it, so a stop requested against a scan that ended
first would leave the flag set and abort the next scan before it began.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Files marked missing_from_fs were still advertised, so FPKGi listed a
package whose download URL no longer resolves.
Title ids now come from a CUSA/PPSA id in the rom or package file names
when present, falling back to the generated RomM id. It is resolved once
per rom so a base game and its updates/DLC stay grouped.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
FPKGi installs one package per entry, but the feed served a single entry
per rom pointing at the rom download URL, which zips multi-file roms.
Each .pkg file now gets its own entry with its own size and download URL,
named after its category (or file name) when a rom holds several packages.
Adds an optional content_type filter so FPKGi's per-category content URLs
can each point at RomM.
Fixes#3962
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
update_rom_note and delete_rom_note selected on note_id and user_id only,
so the rom resolved from the path never constrained which note was
touched. Pairing a note id with any other rom id in the path reached that
note regardless.
Both handlers now filter on rom_id as well, and the endpoints pass the
rom they resolved.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The screenshot, soundtrack, manual and note routes looked up the rom by
path id but never ran the visibility gate that the core rom routes and
roms/files.py already apply, so a hidden rom stayed reachable through its
child resources.
Add assert_rom_visible() after each lookup. update_rom_note and
delete_rom_note took {id} in the path without resolving it at all, so
they now load the rom first.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Addresses the Greptile review on #3952.
- Reject oversized asset uploads from Content-Length in middleware, before
FastAPI parses and spools the multipart body to temporary storage. The
handler-level check stays as a backstop for chunked requests.
- Apply the limit to screenshot fields on the save, state and standalone
screenshot endpoints, not just the primary file.
- Clamp the autocleanup limit to at least 1 so a non-positive value cannot
wipe every save in a slot.
- Document the new settings in env.template.
Rename MAX_SAVE_UPLOAD_SIZE_BYTES to MAX_ASSET_UPLOAD_SIZE_BYTES now that it
covers states and screenshots too.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The ROM detail response only filled `user_collections` from a rom's
standard collections (the collections_roms join), so smart collections
were silently omitted from the detail overview's Collections row.
Add smart-collection membership to the response: `UserCollectionSchema`
gains an `is_smart` flag and a `smart_for_user` builder that keeps the
smart collections whose cached rom_ids include the rom (respecting own /
public visibility), and `DetailedRomSchema` appends them alongside the
standard ones. The v2 overview renders them with the smart kind badge and
routes them to the smart-collection view.
Fixes#3934
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Pull the cover priority (embedded track cover, then the game's cover art)
out of from_row into a named helper on the schema, and cover the no-art
case that the endpoint tests didn't reach.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Rescans reconcile rom_files in place since #3900, so file ids survive a
rescan and no longer need routing around. Playlist and favorite entries
reference rom_file_id directly instead of (rom_id, md5_hash).
This drops the machinery the hash key required: soundtrack audio is no
longer force-hashed during scans (which overrode NON_HASHABLE_PLATFORMS
and SKIP_HASH_CALCULATION), soundtrack uploads no longer hash on write,
adding an unhashed track no longer returns 400, and the min(file id)
subquery that collapsed identical copies within a rom is gone. Two files
with the same content are now two independently addressable tracks.
A file that leaves the library takes its entries with it via the FK
cascade, rather than leaving a dangling entry that resurrects if the
content comes back.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A file that stopped carrying audio tags, or vanished from disk, had its
track_meta row dropped (directly or by cascade), leaving its persisted
cover on disk with nothing pointing at it.
sync_rom_files now reports those cover paths so the scan unlinks them,
keeping filesystem work out of the database handler.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A platform scan already clears `missing_from_fs` for an entry whose file
came back under the same name, but the ROM is skipped by `should_scan_rom`
so nothing emits `scan:scanning_rom` for it. An open gallery keeps showing
the stale "missing" badge until a refetch, which reads as the platform scan
ignoring missing games (a single-game scan does emit, and looks fixed).
Snapshot the flagged ids before the pre-loop sync clears them, then emit for
the restored entries after `bulk_mark_present`.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Rescans deleted and re-inserted every rom_files row, so file ids churned
on each scan and anything keyed on them (track metadata, persisted
soundtrack covers) was orphaned.
Rows are now matched by path first, then by content hash so a file
renamed or moved inside the ROM keeps its id, mirroring the ROM-level
reassociation. Only changed columns are written, vanished files are
deleted, and archive_members is carried over (the hand-written copy
dropped it).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Spotify-style library features for soundtrack tracks: per-user favorites
(liked songs) and user-owned playlists with manual ordering and optional
public read-only sharing.
Track references are stored as (rom_id, md5_hash) rather than rom_file_id:
scans purge and re-insert rom_files rows, so file ids churn while rom ids
and content hashes are stable. Entries survive rescans and renames, and
resolve to the current file at query time; entries whose content is gone
are omitted from listings until the file returns.
To make the content hash reliably present, soundtrack audio files are now
always hashed individually during scans (including NON_HASHABLE_PLATFORMS
and SKIP_HASH_CALCULATION, whose file-size concerns don't apply to audio),
and soundtrack uploads compute crc/md5/sha1 on write. Existing libraries
backfill via a HASHES scan; adding an unhashed track returns 400.
New playlists.read/playlists.write scopes are wired through the granular
permission system (PermEntity.PLAYLISTS); the migration mirrors every
group's collections grants onto the playlists entity so existing groups
keep working without admin intervention.
Endpoints under /api/music: favorites GET/POST/DELETE, is_favorite and
md5_hash on track rows, playlists CRUD, playlist tracks GET/POST/DELETE
and PUT /tracks/order.
Move the per-play status update (last_played, now_playing, and the
finished/empty -> incomplete rewind) off the optimistic launch-time write
and onto play-session ingest, so it reflects real play and is recorded once.
Backend: ingest now updates rom_user status when a session is the newest
play, leaving deliberate statuses (completed_100 / retired / never_playing)
untouched and skipping backfilled older sessions so they can't resurrect
now_playing.
Frontend: new usePlaySession composable records a session and ingests it on
exit; wired into Ruffle and Stream. EmulatorJS already ingests via the
embedded v1 Player, so its launch-time recordLaunch is dropped. The dead
recordLaunch / applyLaunchStatus helpers are removed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
In DEV_MODE the content endpoints serve a single-file ROM straight through
FileResponse, which raises a RuntimeError at send time when the file no
longer exists on disk (e.g. a renamed or moved ROM whose old entry is now
missing). Check the path first and raise a clean 404 instead.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The reassociation lookup OR'd the individual hashes across the Rom and its
RomFiles, so a lone CRC32 collision (or one shared child-file hash) could
move an unrelated missing entry onto the scanned file, attaching the wrong
collections, notes, and assets. Require all three of CRC, MD5, and SHA1 to
match on the ROM row instead; any missing hash yields no match.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
When a ROM file is renamed or moved, the scan matched files to DB rows
solely by (platform_id, fs_name), so the old row was flagged missing and
the renamed file became a brand-new entry, orphaning all user data
(collections, notes, per-user status, uploaded saves/states/screenshots).
Now, when a scanned file matches no existing fs_name, the scan hashes it
first and looks for an existing missing_from_fs entry on the same platform
with a matching hash. On a match it moves that entry onto the new file and
clears its missing state, preserving user data linked by rom_id, instead
of inserting a duplicate. Empty hashes never match, so non-hashable
platforms and SKIP_HASH_CALCULATION fall back to creating a new entry.
File hashing is hoisted so it runs once per new file and is reused for
both the reassociation probe and the downstream scan.
Fixes#3618
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Bound the user-authored fields. `description` (TEXT) and `custom_name`
(VARCHAR(400)) had no length constraint, so an oversized value reached the
database and surfaced as an unhandled DataError, turning a bad request into
a 500. Both are now validated against the column limits, which are defined
next to the columns so the bounds can't drift from the schema. The
`custom_name` case predates this branch but shares the line of code.
Make platform updates a true partial update. The shared API service took a
whole Platform object and sent every field, so the v1 rename drawer replayed
whatever description it happened to be holding; if another client had changed
the description in the meantime, renaming silently reverted it. The service
now takes explicit optional fields, so omitting one means "leave it alone"
rather than "write back my cached copy".
Watch the two form fields independently. Re-seeding both whenever either
canonical value changed meant a socket update touching only the name threw
away an unsaved description edit, and vice versa.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Custom platforms could only be distinguished by name, which is often not
enough context (e.g. a "Sega - Genesis/Mega Drive (Unofficial)" folder
holding aftermarket and unlicensed dumps). Platforms now carry an
optional free-text description, mirroring collections.
The column is nullable and defaults to "", matching custom_name, so a
rescan (which merges a freshly scanned Platform over the existing row)
leaves it untouched. update_platform patches only the fields sent, so an
omitted description is preserved and an empty string clears it.
Surfaced in the v2 UI only: the Settings tab name form now covers both
custom_name and description, and PlatformHead renders the description as
a chip alongside the metadata chips. v1 is frozen and gets no new UI, but
round-trips the field unchanged through the shared API service.
Closes#3402
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Expose the scan.* section of config.yml (metadata & artwork priority,
per-field artwork overrides, region priority, language priority, media
types, gamelist and pegasus export) in an editable v2 Settings page.
Backend:
- Add PUT /api/config/scan (platforms.write) with a validated
ScanSettingsPayload and ConfigManager.update_scan_settings().
- Expose GAMELIST_AUTO_EXPORT_ON_SCAN and PEGASUS_AUTO_EXPORT_ON_SCAN
in ConfigResponse / GET /api/config.
- Preserve the streaming section on runtime config writes (previously
dropped on every write).
Frontend:
- New Settings/ScanSettings.vue page + ScanPriorityList.vue reorderable
list (drag + up/down for keyboard/gamepad); region/language use
RComboboxField.
- Wire the scan-settings route, permissions, and sidebar entry.
- Regenerate OpenAPI types; add all new strings to every locale.
Closes#3849
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Several endpoints authorized cross-user access by the is_public flag (or
by scope alone for streaming) without re-checking whether the parent ROM
or platform is hidden from the caller. A user blocked from a ROM/platform
could still download a public save/state/screenshot attached to it, or
claim a streaming session for it, by supplying the asset/ROM id directly.
Route all four through the existing assert_rom_visible() 404-masking
helper, right after loading the record and before any file access or
broker launch, matching the ROM detail/content endpoints.
- saves.py / states.py / screenshots.py download_* : public sharing no
longer overrides the hidden-resource boundary.
- streaming.py claim_session : hidden ROM/platform can no longer be
launched via its id; broker is never contacted.
Regression tests cover hidden-ROM and hidden-platform cascade for each
endpoint, plus a positive control that public sharing still works when
the ROM is visible.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A platform folder created on disk (optionally bound in Library
Management) has no database row until its first scan imports a ROM, so
it was invisible to the scan platform picker and a first scan could not
be triggered for it. The picker also filtered to rom_count > 0, hiding
even zero-ROM database platforms (e.g. those created via romm-cli).
Backend:
- Add GET /platforms/filesystem returning folders on disk without a
database row yet (locally-resolved metadata, id -1, rom_count 0).
- scan_platforms / the scan socket now accept platform_fs_slugs so a
folder can be scanned by slug; database platforms stay accepted by id.
Frontend (v2):
- Fetch filesystem folders, key the scan picker by fs_slug, include
zero-ROM database platforms, and tag never-scanned folders.
Fixes#3832
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A slot-less POST /api/saves behaves as a filename upsert, and two
details combined into silent save corruption.
1. get_save_by_filename only filtered by slot when one was passed, so a
slot-less lookup could match (and overwrite) a save row living in a
named slot. Scope slot=None to the null-slot save (Save.slot IS NULL)
so a slot-less upload can never adopt a row from another slot.
get_save_by_content_hash keeps its documented cross-slot slot=None
behavior (dedup-only, non-destructive).
2. The upsert branch only wrote file_size_bytes and content_hash while
the bytes landed under a path derived from the request's emulator, so
the row's hash could disagree with the file it still pointed at. Also
persist file_path/emulator, and remove the now-orphaned file when the
row's location changes.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
failed_items was just the length of failed_ids. Remove the redundant
counter from the delete endpoints (roms + firmware) and the response
type; callers that need the count derive it from failed_ids.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The bulk delete endpoint deletes per-ROM and can partially fail, but the
v2 dialog pruned every requested ROM from the selection and gallery. A
ROM that failed to delete stayed in the library yet lost its selected
state, so the user couldn't retry the failed subset.
Return the failed IDs from the delete endpoints (roms + firmware, both
via BulkOperationResponse) and, on the client, only prune the ROMs that
were actually removed. Failed ROMs stay selected and visible for retry;
the single-ROM route only navigates away when its ROM was deleted.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Per-platform slot capabilities were duplicated across the frontend store's
hardcoded platformCapabilities() map and the backend's pydantic Field bounds,
independent of the broker's own ceiling. Consolidate the RomM-side knowledge
into one _PLATFORM_CAPABILITIES table in the streaming endpoint:
- /config now ships each container's capabilities, and the frontend selector
reads them instead of keeping its own copy.
- The SaveState/LoadState request bounds derive from the table, and the routes
validate the exact per-platform ceiling before calling the broker (clean 422
instead of a broker 502).
The broker remains the ultimate enforcer; RomM no longer keeps two independent
hardcoded copies of its slot semantics.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Extract the repeated urllib request construction (URL, secret, payload,
headers, urlopen, parsing) shared by the six broker functions into
_broker_request and its best-effort _broker_request_safe variant. The
best-effort wrappers collapse to a few lines each and the nosec B310
annotation now lives in one place.
Slim the tests with a _streaming() context manager plus _auth/_claim_ok
helpers, removing the repeated cm.get_config patch boilerplate.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>