A rehashed ROM whose new hashes no longer match Hasheous kept its old
`hasheous_id` and `hasheous_metadata`: the merge loop only writes truthy
values, so an empty match cannot overwrite the values seeded from the
existing ROM, and the verification flags stayed on a ROM that no longer
earned them.
Clearing on any empty match would be wrong, though: `lookup_rom` returns the
same empty fallback whether Hasheous answered "unknown hashes" or was simply
unreachable (#2236), so an outage would silently de-verify a whole library.
Have `lookup_rom` return whether it reached a definitive answer, mirroring
`meta_ss_handler.lookup_rom`, and only clear the match on a conclusive miss.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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>
A ROM's "verified" state comes entirely from the Hasheous signature match
flags in `hasheous_metadata`, but `ScanType.HASHES` was missing from both
Hasheous gates in `scan_rom`. A rehash recomputed the file hashes and then
never re-asked Hasheous about them, so the verification chips stayed dark
(#4001). RetroAchievements was already gated in, which is why its provider
icon appeared while nothing lit up.
A follow-up update scan didn't help either: that branch is gated on
`rom.hasheous_id`, which is never set for a ROM that has yet to match.
Add `HASHES` to `fetch_hasheous_hash_match` and `fetch_hasheous_rom`, and
to the "don't overwrite existing base fields" branch: Hasheous now returns
a name/cover/summary on a rehash, and `_identify_rom` short-circuits before
the cover download, so a changed `url_cover` would point at an image that
is never fetched.
Fixes#4001
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
ScreenScraper's FAQ gives the per-minute budget as `threads x 50`, while
`maxrequestspermin` came back as `1024 x (threads + 1)` on every account
measured. Reading the field as the unreliable one, pacing took the lower of
the two, pinning a 9-thread account to 450 requests per minute against a real
allowance of 10240.
ScreenScraper confirms the API was changed without the documentation
following it, and that the reported field is the authoritative one, so pace
at it and drop the formula.
That leaves no basis for a default rate either. Until the account reports,
the one-thread default is the guard: a single in-flight request cannot outrun
any budget ScreenScraper hands out, and priming reads the account before the
first ROM, so at most one request is ever unpaced.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The scheduled cleanup task now always carries the configured cron string,
so assert that instead of expecting None, and set the cron string to None
explicitly to exercise the unschedule branch in init().
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Asserting the model declares the index only restates `models/rom.py`. The
migration test covers what matters: the index exists in a database the
migrations built. Also pin the predicate test to the literal it compiles
to, so an unrelated `IS NOT NULL` elsewhere in the query cannot fail it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
SteamGridDB does not remove assets taken down under DMCA; it returns them
with "lock": true and strips the URL signature, so the CDN serves a
placeholder image reading "This asset has been removed in response to a
DMCA takedown notice" for both the full asset and its thumbnail.
Filter locked grids in _get_game_covers, the single funnel for scan
matching, ID lookups and the manual cover picker.
Closes#4003
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 store is written in batches, so an initial import answers for the
names committed so far long before it holds the whole dump. Checking
that the name index exists reported the provider healthy off a fraction
of the entries, and a run that died partway left it that way for good.
Flag the initial import and clear it once a run completes, so only a
finished import counts as healthy. A refresh keeps serving the previous
dump, so it is not flagged.
Co-Authored-By: Claude Opus 5 (1M context) <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>
Importing the task module first, as the worker does when it resolves the job,
pulled endpoints.roms in and closed an import cycle through decorators.database.
RQ hides the ImportError behind "Invalid attribute name: run", so the cleanup
never ran and orphaned chunked-upload directories piled up.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
ScreenScraper's FAQ defines the per-minute budget, and the reported
maxrequestspermin field, as threads x 50. The field does not follow it. Two
accounts report 1024 x (threads + 1) instead:
threads 9 -> 10240 (threads x 50 = 450)
threads 6 -> 7168 (threads x 50 = 300)
At those rates the limiter never engages, so pacing did nothing for either
account. Every neighbouring field does match its documented rule (both thread
counts and both maxdownloadspeed values reconcile exactly with the FAQ's
participation ladder plus the donation bonus), so the outlier is treated as
unreliable and the lower of the two budgets wins.
Also: state the maxdownloadspeed unit as fact now the FAQ confirms Kb/s per
thread, and say when the daily quotas actually reset (midnight French time)
rather than "tomorrow".
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>
The orphaned resource cleanup listed the resource tree through
`anyio.Path`, which dispatches to a worker thread for every entry it
yields and again for every `is_dir()` call. On a library with ~30k ROM
resource directories that is ~60k thread round trips to read data the
directory listing already contains.
Measured on a 30,262-directory library (Raspberry Pi 4, ext4):
anyio iterdir + is_dir() 50.3s
os.scandir 0.15s
`os.scandir` reports the entry type from the directory read itself, so
no per-entry stat is needed. The walk moves into a helper run once via
`asyncio.to_thread`, keeping the event loop free while doing the whole
traversal in a single thread hop rather than tens of thousands.
Cold and warm runs of the old code were within 1% of each other, so this
was thread-dispatch overhead rather than disk I/O.
A directory that cannot be listed now logs and yields an empty set
instead of aborting the walk, so one unreadable platform cannot strand
every other platform's orphans.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`cleanup_orphaned_resources` decides what to delete purely by asking whether
a resource directory's id is absent from the database, with no sanity floor.
If `get_platforms()` ever comes back empty while artwork is still on disk
(database unavailable, mid-migration, half-restored backup), every platform
directory is treated as orphaned and removed in a single pass.
That was tolerable when the task only ran on an admin's click. Now that it
can run unattended at 5 AM via `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES`,
nobody is watching when it happens.
Bail out when the database reports zero platforms but platform directories
exist on disk, and log a warning saying so. A genuinely emptied library can
still be cleaned by running the task manually with `{"force": true}`, which
the run-task endpoint already forwards to `run()`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Orphaned covers and screenshots left behind by deleted ROMs accumulate
indefinitely, because the only way to reclaim them is to trigger the
cleanup task by hand. On a long-lived instance the resources directory
grows without bound, which is a problem when it shares a filesystem with
the database.
Move the task to `tasks/scheduled/` and turn it into a `PeriodicTask`
with an opt-in cron schedule, defaulting to 5:00 AM so it runs after the
nightly scan and metadata tasks have settled.
`enabled` stays `True` rather than tracking the new env var, because the
run-task endpoint requires both `enabled` and `manual_run`. Gating it
would have silently removed the ability to run the cleanup by hand,
which is how it works today. The cron string is what is opt-in, and
`init()` unschedules when it is unset.
Add the new flag to the init script's scheduler condition, so enabling
only this schedule still starts `rqscheduler`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The streamed resource downloads wrapped their writes in `except
httpx.TransportError`, which does not cover the `OSError` raised by
`f.write()` when the filesystem is out of space. The error escaped the
handler and the partially written file stayed on disk.
A truncated file is worse than a missing one: it satisfies the
`cover_exists` / `screenshots_exist` checks and the `file_exists` guards
in `store_ra_badge` and `store_media_file`, so later scans skip it and
never refetch it. The artwork stays permanently corrupt.
Catch `OSError` on every resource write path (covers, screenshots,
manuals, RA badges, media files and uploaded artwork) and remove the
partial file so the next scan refetches it. A stream that drops
mid-transfer leaves the same truncated file, so the transport-error
branches now discard it too. The cleanup helper swallows its own
`OSError` so it can never mask the original failure.
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>
Smart collections silently ignored several filters at both ends:
- The backend never applied has_soundtrack, has_saves, has_states, or
player_counts from stored criteria, so a "has soundtrack" smart
collection contained every game. get_roms_scalar also dropped
has_soundtrack before it reached filter_roms.
- The v2 criteria serializer had no fields for has_saves/has_states and
only stored tri-state filters when true, so "unmatched" or "has
saves" produced empty criteria and the no-filters guard blocked the
save.
Criteria now carry saves/states filters and explicit false states, the
backend applies them, and summaries render negative states with the
existing "show-not-*" labels.
Fixes#3888
Co-Authored-By: Claude Fable 5 <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>
Non-string region_mode values (YAML list/mapping) now take the
warn-and-fallback path instead of raising TypeError on the frozenset
membership check during startup.
get_preferred_regions only applies prefer_config reordering when
selecting media (for_media=True); name and release-date selection keep
the rom-tags-first ordering, matching the documented scope.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
ScreenScraper scraping added the fanart and title-screen URLs to
url_screenshots even though the same images are persisted to their
dedicated fanart/ and title_screen/ media folders, downloading and
storing every image twice. Restrict url_screenshots to the actual
screenshot media type; the dedicated media still renders in the artwork
gallery. The gamelist handler had the same pattern with title_screen
and gets the same fix.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
New opt-in config key scan.priority.region_mode with values
prefer_rom_tags (default, current behavior) and prefer_config. With
prefer_config, the configured region priority outranks the rom's
filename region tags when selecting ScreenScraper media, and the rom's
own tags remain the fallback when the configured regions have no media.
Unknown values warn and fall back to prefer_rom_tags, and the key
survives runtime config-file rewrites.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The Playmatch /api/v2/health endpoint returns the plain-text body
"Healthy", but heartbeat() routed it through the JSON-parsing
_request(), so decoding always failed and the Metadata Sources page
showed "Connection failed" for a healthy service. Do a raw GET and
treat any 2xx response as healthy, matching the Hasheous handler.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>