The MobyGames handler pre-encoded search terms with urllib's quote()
before passing them to MobyGamesService.list_games(), which encodes the
query itself via yarl's with_query(). Titles containing special
characters were therefore double-encoded and never matched:
'Sonic & Knuckles' -> title=Sonic+%2526+Knuckles
'... World + Bowser's Fury' -> title=...+%252B+Bowser%2527s+Fury
Pass the raw (unidecoded) term and let the service layer encode it
exactly once, matching how the ScreenScraper handler already works.
Adds regression tests for both the scan path (_search_rom) and the
manual-search path (get_matched_roms_by_name).
Same bug class as reported for ScreenScraper in #3467.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The sort key and the launchbox inverted-title matcher each carried their
own copy of the same 16 articles. Build both patterns from a single
ARTICLES tuple, and point the frontend's hand-synced copy at it.
Co-Authored-By: Claude Opus 5 (1M context) <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>
LaunchBox lookups are exact key reads, so a filename that doesn't already
read like a LaunchBox title misses. Three gaps closed:
- No-Intro inverts leading articles ("Legend of Zelda, The - Ocarina of
Time"), LaunchBox keeps them in front, so the de-inverted form is now
tried against the name and alternate-name indexes as well. Measured over
the No-Intro sets: N64 unmatched 200 -> 171, SNES 461 -> 318, Genesis
285 -> 191, GBA 683 -> 576.
- Files.xml, a filename-to-title index the dump already ships and the
update task already caches, was never read by any lookup. It now runs
ahead of the name search, which is the only route to titles whose files
are named nothing like them (MS-DOS, Amiga, Arcade). Its cache key gains
the platform, since the same dump filename exists on several systems.
- A local LaunchBox install was only reachable by an exact filename,
extension included, or by a stem equal to the title. A library of `.zip`
archives could never match an install pointing at `.z64`, and a No-Intro
stem still carries region tags. Both sides now reduce to shared forms.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A scan preferred the LaunchBox ID Playmatch reports and, when the metadata
store could not resolve it, stopped there. Playmatch answers with an ID for
nearly every ROM on some platforms (38/40 sampled N64 dumps, 39/40 SNES,
against 4/40 GBA), so those platforms never reached the filename lookup and
were left with no LaunchBox metadata at all, while a manual match still
found the game.
The branch moves out of the scan closure into `resolve_launchbox_rom` so it
can be tested without a database. An ID already stored on the ROM is still
never traded for a filename guess: it usually came from a manual match.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The debug log printed the session headers and the honeypot pair verbatim.
The token decodes to "<issued-at>::<public IP>|<user agent>|<key>|<hmac>",
so anyone pasting DEBUG logs into a bug report published their host's public
IP address. Logs are also downloadable through /api/logs.
Redact the session headers and drop the honeypot entry from the logged
payload, keeping the URL, search terms and timeout that make the line useful.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Addresses review feedback on concurrent scans (SCAN_WORKERS > 1), where the
handler singleton is shared across in-flight ROM lookups.
Read the session after awaiting the rate limiter rather than before, so a
request paced behind a peer's renewal uses the current session instead of the
one that was live when it queued, and bails out if the session went away.
Acquire the limiter before the /init renewal as well, so a wave of concurrent
403s can't burst past the cap that search requests respect. The endpoint
fixture fetch is left unpaced: it targets GitHub, not HLTB.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
HLTB sessions are short-lived and pinned to the requesting IP address and
user agent. The handler fetched one session at the start of a scan and never
renewed it, so once HLTB rejected it every remaining lookup failed for the
rest of the scan.
Retry with a renewed session on 403, and back off and retry on 429. Report
the actual cause instead of mapping every HTTP error to "check your internet
connection", which is now used only for genuine connect and timeout errors.
Also fixes two adjacent bugs:
- The honeypot key was written into the caller's payload dict in place. That
key rotates with the session, so a renewal would leave the dead key in the
body alongside the new one.
- heartbeat() sent no user agent. HLTB rejects requests without one, and the
httpx default only happens to be accepted today.
initialize() is now async so the session can be renewed from the async
request path, and uses the shared context httpx client.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
ScreenScraper's box-2D was the only media type that never got a local
file: it fed url_cover and nothing else. When any other provider won the
cover (the default, since SCAN_ARTWORK_PRIORITY puts ss fourth), the box
front was recorded as a URL and never downloaded, leaving it unreachable
from the UI. Enabling box2d_back/box2d_side could only be made to look
right by forcing ss to the top of scan.priority.cover.
box-2D now records a box2d_path when box2d is listed in scan.media, like
every sibling media type. The Artwork subtab lists the box front, and
the interactive 3D box takes its front face from that scan (falling back
to the rom cover), so all three faces come from the same source and the
3D box no longer depends on cover priority.
Fixes#4127
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>
ScreenScraper answers a bad credential set with HTTP 403 and a body that
says so, but the login-error check sat after raise_for_status(), so it
could never match the case it was written for. The scan logged
"403, message='Forbidden'", carried on, and saved every ROM without
ScreenScraper metadata, with nothing anywhere naming the credentials.
The body is now read before the status is raised, and a 403 raises a
ScreenScraperCredentialsError that says which of the two credential sets
was refused. The account endpoint is the only one that checks the account
password, so a refusal there names SCREENSCRAPER_USER and
SCREENSCRAPER_PASSWORD, and a refusal from a scraping endpoint can only
be about the RomM developer credentials. That message does not name their
variables: they are only semi-protected, and nothing should send an end
user looking for them. ScreenScraper's own wording is carried through
under both, because it cannot attribute the fault by itself: with a bad
developer id, ssuserInfos.php still blames the account. That wording
reaches the caller as well as the log, and the credentials travel in the
query string, so it is masked with the regex the log formatter already
uses.
The refusal surfaces as a 403, matching the blacklisted-version case:
both mean ScreenScraper refused RomM itself and both need an operator
change, unlike the transient failures that map to 503. Never a 401,
which the frontend reads as an expired session and acts on by returning
the user to the login page.
A refusal trips a breaker like the daily quota does: it is reported once
and the remaining requests short-circuit rather than spending a round
trip per ROM to be told the same thing. The scan-path lookups treat it
like an exhausted quota, so a scan degrades to the other providers
instead of failing outright. Manual searches still surface the error.
The account check reports a refusal but never arms that breaker.
ScreenScraper refuses a developer id it accepted a minute earlier while
the scraping endpoints keep answering, so leaving the breaker armed cost
a working scan all of its ScreenScraper metadata. Only the requests a
scan actually needs can take the provider out.
prime_account_limits() now warns whether the lookup raised or was
swallowed into an empty response, which is what left a scan with no
limits, no quota readout and no explanation.
The HTTP 401 message gains the half of ScreenScraper's error table it
was missing: the API is closed to non-members and inactive members, with
server saturation given as the cause.
Both attempts had diverging copies of the status ladder, so they now
share one mapping.
Fixes#4122
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Logging in failed once with a CSRF error and succeeded on retry.
`_csrf_tokens_match` validates the user id embedded in the token against
the current request's user. A browser holding a token bound to user N,
whose server-side session is gone (container restart, session expiry,
Redis flush), makes an anonymous login POST. N != None, so the request is
rejected. The rejection response then rotates the cookie, which is why the
second attempt works.
Keep the double-submit check and the cookie/header user agreement
unconditionally, and enforce the caller binding only when there is a
caller. An anonymous request cannot be forged this way regardless: an
attacker cannot read the cookie cross-origin, so it cannot produce the
matching header.
This is the mirror of #3420, which fixed the authenticated direction by
rotating the cookie on safe requests. That path is untouched here, and
test_authenticated_user_binding_still_enforced pins it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Ordering the gallery by a `roms_metadata` field joined the view back in and
sorted through it. `roms_metadata` is a thin view over STORED generated
columns on `roms` (migration 0098), so that join is `roms` to itself and it
leaves the sort key on a joined table, which no index can serve: the engine
filesorts the whole library for every page.
The generated columns are already indexed, so the three that are offered as
sorts now resolve straight to them and the join goes away. On a 120k-row
table this turns a full scan plus filesort into a 72-row index walk.
The remaining view columns are JSON arrays with no index and no sort that
offers them, so they keep reading the view.
Fixes#4067
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The Home "Random Pick" widget asked the API for the library total, then
for the single row at a random offset. Paging to offset N makes the
database walk and discard the N rows before it, so the pick got slower
the bigger the library: measured on an 83,000-game instance, 1.7s at the
median offset and 6.9s deep into the list, on every home page visit.
Adds GET /api/roms/random. It offers the query a batch of random primary
keys and takes any that exist, which is one index lookup per candidate
and unbiased, since every id in the table is equally likely to be
offered. A batch only misses when the query matches too little of the id
space, and it then falls back to counting the set and taking the row at a
random position, reading index entries rather than rows because the
statement selects nothing but the id. Both paths are uniform.
On the same 83,000-game library: 2.9ms median for an unscoped pick
(0.6% of picks take the fallback, 236ms), 19-25ms scoped to a platform.
The widget now resolves a pick in one request.
The endpoint takes the platform / collection scope parameters so the
gallery "Random ROM" buttons (#4068) can move onto it too.
Fixes#4066
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`hasheous_metadata` gains keys as RomM maps more of Hasheous' signature
sources, so rows written before `mame_redump_match` existed don't carry it.
On PostgreSQL `hasheous_metadata->>'mame_redump_match'` is then NULL, the OR
chain over the match flags evaluates to NULL instead of false, and `NOT (...)`
stays NULL: the unverified filter returned nothing for those rows until they
were rescanned.
Each extraction is now coalesced to false. The JSON path is untouched, since
SQLAlchemy compiles `as_boolean()` to a CASE whose ELSE branch already folds a
missing key into false.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The match flags on `hasheous_metadata` are keyed off Hasheous'
`SignatureSourceType` names, and two never lined up with what its API
actually returns:
* `MAMERedump`, the source holding Redump's disc images in CHD form, was
mapped to nothing at all. A CHD identified by its disc-data SHA1 matched,
got its metadata, and still read as unverified because no flag was set.
* `puredos_match` looked for `PureDOS`; the source is named `PureDOSDAT`, so
the flag was pinned to False for every ROM.
CHD matches now set `mame_redump_match`, which the verified filter counts and
which the Metadata tab folds into the existing Redump chip (same database,
different distribution format). Existing rows pick the flag up on their next
rescan.
Hasheous also exposes Pleasuredome, TotalDOSCollection, eXo, ScreenScraper and
Generic sources that RomM still maps to nothing; those are left alone since
folding them in widens what "verified" means.
Fixes#4030
Co-Authored-By: Claude Opus 5 (1M context) <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
KIOSK_MODE stripped every non-READ grant from all non-admins after group
and override resolution, so a logged-in user with "Saves & States: Write"
still got a 403 from POST /api/states|saves|screenshots. The permission
UI saved grants the server then silently discarded.
The cap now applies only to the synthetic guest KIOSK_MODE hands out
(User.is_kiosk_guest). It has to stay for the guest: with no permission
group of its own it falls back to the server default group ("Viewer
(legacy)" = WRITE_SCOPES), so dropping the cap outright would let
anonymous visitors upload assets and edit collections.
Fixes#4044
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Removing the read-time recompute left the cached membership blind to
everything that is not a ROM edit. A save, a state, a status, or moving
a ROM in or out of a regular collection all change what `has_saves`,
`has_states`, `statuses`, `collection_id` and `favorite` match, so the
stored counts, covers and ROM-detail chips went stale until an unrelated
edit or the next scan.
Refresh from those paths too: save and state upload, delete and
visibility toggle, `update_rom_user` when a status is set, and adding or
removing collection members. Sharing an asset is included because
`has_saves` matches other users' public saves, so it moves collections
that are not the uploader's.
These changes leave the ROM row alone, so they pass `membership_only`
and only recount a collection when the ROM actually joined or left.
Autosaves land constantly, and without it every one of them would force
a full recount of any collection the ROM already belonged to.
Reported by Greptile on #4039.
Implemented with Claude Code (Opus 5), tests first, then reviewed and
verified by me.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Recomputing every smart collection after a delete scanned the library
once per collection, synchronously on the event loop and inside a single
write transaction. Ask instead which of the changed ids each collection
matches: that resolves as a primary-key lookup, so only the collections
actually holding one of them pay for a recount.
Follow the same refresh into `update_rom` and the metadata reset. Both
change exactly the fields the saved filters match on, so cached counts
and cover mosaics no longer wait for the next scan to catch up.
Guard every call site. The ROM write is already committed by the time
the refresh runs, so a failure there must not be reported back as a
failed edit, and must not cost a bulk delete its per-ROM report.
Drop the handler-level test for leaving a collection untouched on read;
the endpoint test covers that invariant through the route the bug was
reported against.
Follow-up review of f4ac78c46 (#4029). Implemented with Claude Code
(Opus 5), then reviewed and verified by me.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A smart collection re-ran its filters across the whole library on every
request, loaded every match into memory with its joined metadata, wrote
the membership back, and only then asked for the page being displayed.
The cost tracked library size rather than collection size, was paid twice
on first load and again on every scroll, and the write bumped updated_at,
which the covers embed as a ?ts= cache-buster.
Translate the stored filter_criteria into filter_roms keyword arguments
and apply them to a bare Rom.id select instead, so membership stays in
SQL and the database returns just the rows being rendered. The criteria
vocabulary is filter_roms' own, so this composes with the gallery's
filters. smart_collection_id is dropped from the criteria: the v2 create
dialog records the route it was opened from, so a collection built while
viewing another one carries its id, which would nest and could cycle.
Bind parameters for the MATCH clauses are now named after the term they
carry. A statement can hold two of them (the collection's search term and
the gallery's), and SQLAlchemy does not uniquify explicitly named text()
parameters, so a fixed name let one term overwrite the other.
The cached rom_ids / rom_count / path_covers_* columns still back the
collections list and the ROM detail page, so refresh them on write --
smart collection create and update, after a scan, and after ROMs are
deleted -- rather than as a side effect of browsing. They are computed
for the owner: the row is shared, so a per-user criterion like favorite
would otherwise describe whoever opened the collection last.
Regular collections and the favorites filter get the smaller half of the
same treatment: an indexed subquery over collections_roms instead of an
IN list built in Python. An unknown collection or smart collection now
returns nothing rather than falling through to the entire library.
Fixes#4029
AI assistance: implemented with Claude Code (Opus 5), tests first, then
reviewed and verified by me.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The search box offered "name, filename, hash", but the term only ever
reached roms.name and roms.fs_name. A term that is hex of exactly a
digest length now also matches the hash columns on roms and rom_files,
the latter being what makes multi-disc games findable by a file's hash.
The two sides are unioned rather than OR'd. No engine merges a full-text
index with a B-tree index, so OR-ing them costs the name side its index
and scans roms end to end (3.306s against 0.005s on 300k rows). Neither
table had an index on any hash column, so 0106 adds them.
Fixes#4008
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The scan language priority defaulted to ["en", "fr"], and get_preferred_languages
appended ["en", "fr"] unconditionally on top of whatever was configured. French
was therefore impossible to remove, and a user asking for a single language still
got French descriptions.
That fallback originally existed only for ScreenScraper's `familles` and `modes`
taxonomies, which are French-authored and frequently untranslated. It was lifted
into a general language preference when the setting was introduced, at which point
it started applying to the synopsis as well.
Split the two concerns: get_preferred_languages now honors the configured order
verbatim (falling back to English only when the list is empty) and drives the
synopsis, while the new get_taxonomy_languages appends the en/fr fallbacks for
franchises and game modes. The config default drops to ["en"].
Configuring ["de"] now yields a German description or none, rather than a silently
French one, while French franchise and mode names are still used where no English
entry exists.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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>