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>
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>
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>
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>
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>
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>
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>
The Server Stats page ran two full scans of the multi-gigabyte `roms`
table on every visit: the metadata-coverage breakdown counted eleven
provider-id columns per platform, and the region breakdown pulled every
row's regions into Python. Both were returned in the same request as the
cheap summary counts, so the whole page stayed blank until they finished.
Mirror the provider match ids into the narrow `roms_facets` table
(migration 0102, kept in sync by the same triggers as the existing facet
columns) and read both breakdowns from it, so neither query touches
`roms`. Split the v2 Server Stats view into a summary-first request and a
separate breakdown request so the six top cards render immediately.
Fixes#3901
Co-Authored-By: Claude Opus 4.8 <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>
remove_persisted_cover swallowed OSError, so clearing cover_path
regardless dropped the only reference to a file still on disk. It now
reports whether the file is gone, and the path is kept for the next scan
to retry when it isn't.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A scanned row leaves unset columns as None and the model defaults only
apply on insert, so the reconciliation path could write NULL into
file_size_bytes or has_embedded_cover. Unset values now leave the stored
value alone.
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>
Reusing the file row across rescans meant a track that kept its tags but
lost its embedded cover held on to the old cover_path, so the music API
kept serving an obsolete image and its file was never removed.
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.
virtual_collections was a view that unnested five JSON arrays per rom on
every read, so both the collection list and opening a single collection
scanned the whole library. Opening a collection with a handful of roms
cost as much as one with thousands, since the name is computed inside the
view and nothing can be narrowed down early.
Membership now lives in virtual_collection_roms, one narrow row per
(type, name, rom_id) plus that rom's covers, derived from the generated_*
columns and maintained by triggers on roms (deletions ride the foreign
key cascade). The view becomes a plain aggregate over that table, so the
model, schemas and API shape are unchanged, and filtering roms by a
virtual collection is an indexed subquery instead of an IN list of every
member id.
Covers are no longer aggregated in the view, which materialized every
member's cover path on every request; the handler resolves at most five
per collection, matching the smart collection cap and what both UIs
render.
On a synthetic 50k-rom library the list goes from 1.42s to 0.128s and a
single collection from 0.111s to 0.0006s, with identical output.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Building the filter dropdowns aggregated the facet columns straight off
`roms`. Those columns are cheap to compute since #3826, but they sit inline
with the raw provider-metadata blobs, so the aggregation read every row of a
multi-gigabyte table: seconds of pure disk reading on any database whose
buffer pool is smaller than the table (the stock 128-256 MB defaults always
are on a large library).
`roms_facets` holds only the filter values and is kept in sync by AFTER
INSERT/UPDATE triggers on `roms`, so every write path stays consistent
without an application hook. Deletes ride the ON DELETE CASCADE foreign key.
Fixes#3882
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
rom.screenshots has no guaranteed order, so indexing into it picked a
different row on PostgreSQL than on MariaDB and failed CI. Fetch the
original screenshot by its known id instead.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
When more than one missing entry shares the same CRC/MD5/SHA1 (e.g.
duplicate content stored twice), limit(1) returned an arbitrary row, so
reassociation could move user data onto the wrong game nondeterministically.
Fetch up to two matches and reassociate only when exactly one exists;
otherwise fall back to creating a new entry.
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>
Adds client-side filters to the v2 manual cover-search dialog so users
can narrow SteamGridDB results without endless scrolling:
- Source (SteamGridDB / each metadata provider)
- Resolution (dynamically built from the results present)
- Style (alternate / blurred / material / no logo / white logo)
- Uploader (searchable list of contributors)
- Content toggles (NSFW / humor / epilepsy, NSFW off by default)
- Sort by relevance or most votes
Backend surfaces the rich per-cover metadata SGDB already returned but
was discarding: SGDBResource / SearchCoverSchema now carry width,
height, style, author, score and content flags, and the cover-search
path fetches every content variant so the picker can toggle them
client-side. Auto-scan cover selection is unchanged and stays
safe-by-default.
New keys translated across all 18 locales.
Closes#3749
Co-Authored-By: Claude Opus 4.8 (1M context) <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>
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>
bulk_mark_present issued an unconditional UPDATE setting missing_from_fs=False
on every matched row, including rows already present. Since Rom.updated_at has
onupdate=utc_now, every scan re-stamped all skipped/unchanged ROMs of a
platform, defeating updated_after-based incremental consumers and busting every
cover URL (?ts={updated_at}) on each scan.
Mirror the missing-side guard (mark_missing_roms) by restricting the UPDATE to
rows that actually flip via Rom.missing_from_fs.is_(True), so an unchanged
platform issues no updates.
Fixes#3836
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Unknown provider slugs in scan.priority.cover/screenshot/manual are
already dropped by the downstream availability filter, so they never
crash a scan, but they silently did nothing. Surface likely typos with
a load-time warning, consistent with scan.media handling. A drift-guard
test keeps VALID_SCAN_PRIORITY_SOURCES in sync with MetadataSource.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>