store_media_file streamed the raw response body without decode_gzip, so
media served with Content-Encoding: gzip (the LaunchBox image CDN does
this whenever the client accepts gzip) was written to disk still
compressed. Covers, screenshots and manuals already inflated it.
Fixes#5669
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(sync): cap play sessions on sync completion and require roms.user.write
The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(config): reject empty platform binding and version values
config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(collections): require smart collection criteria to be a JSON object
Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(stats): require roms.read on /api/stats
Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal
/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins
The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(saves): bound total decompressed size when hashing zip archives
Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.
The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(psp): clamp LZ4 literal and match copies to the ZISO block size
The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.
Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(auth): revoke OAuth tokens when a user's credentials change
A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.
Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.
The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(api): reject local file URLs for user-supplied covers and manuals
file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.
These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(resources): bound cover downloads and decodes
Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.
Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test: fix mypy errors in the new tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: address Greptile review on permission and input hardening
- Date OAuth tokens to before the credential check, so a password change
that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: apply code-review findings on permission hardening
Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor: apply simplify pass on permission hardening
Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: apply review-polish pass on permission hardening
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(play-sessions): filter rom_id and device_id on PlaySession after the visibility join
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(seed): realistic, fast, debuggable seeded images
generate_test_data.py can now seed a library whose images look like a real
one, quickly, so gallery, sizing and image-conversion work can be tested
without anyone's private cover art. The default (--image-fidelity 1) is
unchanged: same seed, byte-identical files.
- --image-fidelity 2: covers drawn at the real-world size mix (measured
aggregates from one 8,396-cover library), the small cover made by RomM's
own resize rule, and debug art on every image: the game's title, system
and region; a box with rom id, size, kind and format; the original path;
pure-colour corner pixels, named corners, percent ticks, crop boxes, a
circle that shows stretching and a transparency ring.
- --image-fidelity 3: the same over texture calibrated to real bytes per
pixel, with 22% of big.png holding JPEG bytes as in real libraries.
- --image-weighted-every N (default 10): at level 2, every Nth rom id is
drawn at level 3, so one library serves layout and file-size work.
- --image-media: also write ScreenScraper media (sizes provisional).
- --image-workers / --image-limit: images are drawn in a process pool
from a per-rom random stream (seed, rom id), identical to one process.
2,000 roms with images seed in about 18 s instead of about 10 minutes.
- After a real run the seeder rotates the gallery's Redis cache, so a
fresh seed never serves the previous library's lists.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(seed): keep rows independent of image flags; survive a cache failure
- The screenshot count is drawn for every rom, whatever --images or
--image-limit say, so those flags no longer shift the rows that follow
(--no-images rows were already off in the previous seeder). With the
defaults the draws are unchanged: level 1 output is still byte-identical.
- A Redis error while rotating the gallery cache prints a warning instead
of aborting after the rows are committed, so the report still prints.
- Comments in seed_images.py trimmed to the repository's one-or-two-line rule.
- tests/tools/test_generate_test_data.py runs the seeder with inserts
recorded instead of written: rows match with --image-limit and
--no-images, and a cache failure still reports the saved seed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(seed): document seeding a test library in DEVELOPER_SETUP
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(seed): code-review fixes for seeded images
pr-ready step 2 (code-review xhigh --fix):
- level-3 noise is drawn per channel and retuned, so PNG output reaches
the measured 0.9 / 1.5 / 2.0 bytes per pixel spread
- --image-media is rejected at --image-fidelity 1, where it did nothing
- paths come from rom_fs_resources_path, get_media_resources_path,
CoverSize and MetadataMediaType instead of being rebuilt
- drop the unused path_column parameter and a no-op ImageChops call
- draw a batch's images while the next batch is built and inserted
- the cache-failure test checks the rows of the failing run
- drop a duplicate media-off test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(seed): simplify pass over seeded images
pr-ready step 3 (simplify):
- extract small_cover_size from resize_cover_to_small, so the seeder
draws the small cover at RomM's size instead of writing, reopening
and overwriting it
- draw_rom_images returns nothing and follows plan_rom_images, and
files_written is derived from the plan
- _fitted_size measures from a proportional guess instead of stepping
down one point at a time (about a quarter of level-2 draw time)
- one draw path for the pool and inline cases
- drop the ink parameter, the CORNER_RING alias, the _fade_ring wrapper
and the RomImageJob caption default; tighten comments
- trim media from the two slowest tests and use dataclasses.replace
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(seed): humanizer pass over the seeding docs
pr-ready step 5 (humanizer).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(seed): one image pipeline, dry runs write nothing, main owns its cleanup
- level 1 mosaics go through plan_rom_images/draw_rom_images like the
other levels, so they get media, workers and RomM's small-cover size
- --dry-run plans image paths but writes no files
- main() is a thin wrapper: it registers the UTC connect listener and
removes it (disposing the pool) in a finally, and the image pool
cancels queued draws on error; the test no longer patches SQLAlchemy
- the recommendation feed cache is rotated with the gallery cache
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
* fix(webp): raise the cover WebP quality to 95
Quality 90 left visible artifacts on box art with small text. On a
sample of real covers, 95 adds about 3 dB of luma PSNR for about 25%
more bytes (small covers go from 20% to 25% of the PNG size, big ones
from 27% to 36%); 100 costs another third for little gain.
Small animated covers now use the same quality instead of Pillow's
default of 80, and the ignored optimize flag is dropped from the static
WebP save.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Apply suggestion from @greptile-apps[bot]
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
* fix(scan): delete screenshots and media a rescan leaves unreferenced
A complete rescan keeps the stored artwork, so two kinds of file stayed on
disk with nothing pointing at them:
- screenshots indexed past a shorter new list, since files are named by
position and only the indexes in range were rewritten
- media of a type removed from the preferences, since providers record no
path for it and stale media was compared over the preferred types only
get_rom_screenshots now deletes the indexes past the new list, and
remove_stale_media compares every media type.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(scan): split scan_rom's merge into named steps
scan_rom held seeding the row, following Demozoo links, splicing scene
summaries, resetting rematched sources, the scene lock, rehash cleanup,
priority merges for fields, tags and artwork, and the SteamGridDB pass in one
body. Each step is now its own helper, the SteamGridDB lookup a _RomLookups
method, and the providers' answers a dict keyed by source instead of fourteen
locals. The Pouet and CSDb link follows share one helper. Behaviour is
unchanged.
McCabe complexity of scan_rom goes from 68 to 13, and the function from 664
to 215 lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scan): trim remove_stale_media's docstring per Greptile review
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(scan): move the scan vocabulary, lookups and merge into handler/scan
scan_handler.py held the scan types and metadata sources, the per-source
lookups, the merge of their answers and the orchestration in one 2,000-line
module. It now builds on a handler/scan package:
- sources.py: ScanType, MetadataSource, the tag constants, RESCAN_RULES,
should_consult, stored_match_id and the priority ordering
- lookups.py: RomLookups, the LaunchBox and Steam resolvers and
get_main_platform_igdb_id
- merge.py: the pure steps that merge the sources' answers into a rom's
columns
scan_handler.py keeps scan_platform, scan_rom, the asset scans and the media
downloads. Importers point at the module that now defines each name, and the
helpers that crossed a module boundary lost their leading underscore.
clear_rehash_misses takes the attempted sources instead of the lookups, so
merge does not depend on lookups. Behaviour is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(ci): import ScanType from handler.scan.sources in the e2e seed script
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scan): harden leftover screenshot cleanup (pr-ready: code-review)
List the screenshots folder once, use isdecimal() for the index test, and
log rather than raise when a leftover can't be removed. Point three
comments at handler/scan instead of scan_handler.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(scan): tidy the merge helpers and patch paths (pr-ready: simplify)
- fetch_sgdb_rom refetches by stored_id and builds the SGDB name list
itself, so the name sources stay private to lookups.
- follow_demozoo_link checks the source is enabled; scan_rom loops over
Pouët and CSDb.
- order_merge_sources holds the one ordering pass, and
build_metadata_handlers adds the empty SGDB entry.
- Leftover screenshots go through the quiet-delete helper, renamed
_discard_file.
- Tests patch rom lookups through handler.scan.lookups.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scan): never leave a recorded media or screenshot path without its file
- remove_stale_media only deletes a file whose owner or source changed
when that new owner stores the type again in this pass. A file nothing
records is still deleted.
- Screenshots past a shorter list are pruned by remove_screenshots_past
once the new paths are saved, in both download_rom_resources and
update_rom, so a failed cover or manual leaves them in place.
- The release-notes schema diff watches scan_handler.py beside
scan/sources.py, for ranges that span the move.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(roms): rewrite only the moved part of a renamed rom's file paths
Renaming a rom rewrote each of its files with
`str.replace(old fs_name, new fs_name)` on both the name and the path. On
disk, rename_fs_rom moves only `fs_path/old` to `fs_path/new`, so:
- a folder rom's inner file named after the folder (`Game (Disc 1).bin`
in `Game/`) was renamed in the database but not on disk;
- an fs_name that also appears in the platform path (a rom named `n64`
under `n64/roms`) rewrote the platform path too.
_moved_file_location mirrors the move instead: a single-file rom's name
changes, a folder rom's files keep their names under the renamed folder,
and anything else is left alone.
_refetch_changed_matches now returns the ids it refetched, so the
RetroAchievements badge download keys off that rather than repeating the
comparison, and the shared-media rematch uses the same _match_changed
check as the refetch loop.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scan): keep artwork a complete rescan has nothing to replace with
A complete rescan deleted the rom's cover, manual, screenshots and every
provider media folder before asking any provider, then reset the stored
paths. A provider that was down, rate limited or no longer had the art
left the rom with none.
The wipe is gone, and scan_rom no longer resets the path columns on a
complete rescan. The download step already replaces what changed:
covers, manuals and screenshots refetch when their URL differs, and
remove_stale_media drops provider media whose owner or URL changed. The
URLs and locks are still cleared, so whatever answers now can replace a
file; a file nothing replaces stays where it was.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(scan): move scan_rom's provider lookups onto a _RomLookups class
scan_rom defined 16 provider lookups as closures over its own locals
(scan type, platform, rom, rom_attrs, enabled sources, the attempted and
inconclusive sets), so none of them could be read or tested apart from
the 1,000-line function around them.
They are now methods of _RomLookups, a dataclass holding exactly what
they used to capture, along with the helpers they share (consults,
note_inconclusive, resolve_fetch and the cached match files). scan_rom
builds one instance and keeps its local names for the shared sets, so its
body is unchanged apart from the calls. SteamGridDB's lookup stays nested
because it reads the other providers' results.
scan_rom drops from 977 to 664 lines. Its own complexity is unchanged:
that comes from the merge after the lookups, not the lookups themselves.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(streaming): one teardown order for every way a session ends
A session could be torn down three ways, each spelling out its steps:
- teardown_released_session (owner release and single admin release)
- teardown_abandoned_session (stale takeover and the reaper)
- force_release_all's inline _teardown
The first two ran the same stop/playtime/activity/state/saves sequence
in two copies. The sweep differed in ways that mattered: it held no drain
marker while it worked, recorded the termination after the stop (so a
polling tab could miss it), marked the exit save pull pending only after
the stop, and deleted the key unconditionally, even if a newer claim had
replaced the one it read.
_stop_and_collect now holds the shared sequence, and both lifecycle
teardowns call it after their own opening (a drain marker for a release,
a staleness-checked marker for an abandoned session). The sweep runs
teardown_released_session for each session, like a single admin release.
With no container config left, it still records the termination, then
frees the key through the guarded release_own_session.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: apply code-review findings (pr-ready step 2)
Record playtime and clear the activity entry when force-release-all frees
a session whose container config is gone, and let the PICO-8 cartridge
fallback see a cover a complete rescan keeps.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor: apply simplify findings (pr-ready step 3)
Let _RomLookups.attempts() record the attempt it gates, drop scan_rom's
local aliases for the lookups' state, read the platform slug off the
lookups in fetch_launchbox_rom, seed the kept artwork paths into
rom_attrs for every rescan so the PICO-8 fallback reads them directly,
return None from _moved_file_location when a file did not move, and
share the playtime and activity steps through close_session_record.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: address Greptile review on #5396
Drop a cover's other formats once a new one is stored, so a kept upload
in another extension can't shadow it, and move the rename path rule onto
FSRomsHandler next to rename_fs_rom.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scan): refresh screenshots when only their order changes
Stored screenshots are named by position (0.jpg, 1.jpg, ...), but the
re-download check compared the provider's urls as an unordered set, so a
reorder was never picked up. Compare the lists directly, in both the scan
download step and update_rom.
Fixes#4103
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(scan): cover the screenshot reorder in update_rom
Address Greptile review on #5029: add an endpoint test for update_rom's
own reorder check, and narrow await_args before reading its kwargs.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(scan): drop the old screenshot when its replacement fails
With overwrite on, a failed download left the previous image at that
index. The next scan saw matching urls and a file on disk, so it kept
the stale image for good. Remove it instead, so the next scan refetches.
Addresses Greptile review on #5029.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* Run the chroma-key placeholder check off the event loop
_discard_if_chroma_key decoded every stored media image synchronously
inside an async method, so each check (about 15 to 35 ms for a 1024px
screenshot or box face) stalled the event loop and every other request or
scan task running on it. The decode now runs through asyncio.to_thread,
like the cover and logo work in the same handler.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* Hold the file lock across the chroma-key check and delete
With the check awaited on a worker thread, a concurrent writer could
replace the file between the verdict and the delete, and the replacement
was then removed on the old file's verdict. The existence check, the
decode and the unlink now run under the path's lock, and a test replaces
the file mid-check to prove the new artwork survives.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* Make the chroma-key replacement test independent of timing
The test slept 0.2s and hoped the writer had run by then; a slow writer
would let unlocked code pass. It now asserts the path lock is held during
the check before the writer starts, and that the writer cannot finish
while the check runs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Show the scraped game logo in place of the title on the v2 game page
When a ROM has a ScreenScraper wheel (ss_metadata.logo_path), the details
header renders it inside the h1, with the game name as alt text, and falls
back to the text title when there is no logo or it fails to load.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* Trim the transparent border off stored game logos
ScreenScraper wheels often sit on a padded 1024x512 canvas, so a logo shown
in place of the game title looked indented and smaller than its neighbours.
store_metadata_media now crops each logo to its visible pixels, including
logos already on disk, so a rescan fixes existing libraries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* Put the logo-as-title display behind a UI setting, off by default
Adds a showLogoTitle entry to useUISettings (synced to the user's
ui_settings like the other display preferences) and a 'Show logo as
title' toggle in the Gallery section of the User Interface settings, with
the new strings translated in every locale. GameHeader shows the logo only
when the setting is on. Also clears the existing em-dashes from
UserInterface.vue comments, which the lint rule flags once the file changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* Outline the title logo so dark or light lettering stays readable
Some ScreenScraper wheels carry thin black text (A Link to the Past's
subtitle) that vanished on the dark theme, and white lettering has the same
problem on the light one. The logo now gets a 1px rim in the theme's text
colour, replacing the soft drop shadow.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* Size the title logo by area so square logos match wide ones
A shared 128px height cap left near-square wheels (A Link to the Past,
Aria of Sorrow) with about half the area of wide ones. Once the logo loads,
GameHeader now sets its width so every logo covers roughly the same area
(40,000 px, 22,000 on phones), within a 176px (120px) height cap and the
existing 420px width cap.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* pr-ready step 2 (code-review): harden logo trimming and logo retry
- Share one IMAGE_DECODE_ERRORS tuple (adds SyntaxError and
DecompressionBombError) across the image helpers, so a broken or
oversized logo no longer aborts store_metadata_media.
- Trim under the per-file lock and replace the file atomically, so a failed
save keeps the original and a hardlinked source is never cropped.
- Skip every multi-frame image, and crop in the image's own mode so palette
logos stay compact.
- Reset the header's logo failure and ratio whenever the logo URL changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* pr-ready step 3 (simplify): share the resource URL helper, trim dead code
- Add versionedResourceUrl to v2/utils/romFiles and use it from GameHeader,
romArtwork and ManualSubtab, so the scraped-media cache-bust rule has one
home.
- Key the header's logo load state on the URL (failedSrc, loadedLogo)
instead of resetting two refs from a watch; hoist the shared 420px cap.
- Drop logo CSS the inline sizing made dead (display, height, object-fit,
object-position).
- Read the alpha bbox with getbbox instead of a full RGBA copy, and check
transparency before counting frames.
- Use a handler fixture in TestTrimTransparentBorder.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* pr-ready step 4 (review-polish): drop a filler comment
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* pr-ready step 5 (humanizer): state three comments directly
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
* Bound logo trimming by pixel count and test phone logo sizing
- Skip trimming a logo above MAX_TRIM_PIXELS (16M), checked from the image
header before any pixel is decoded, so a large download under Pillow's
decompression-bomb threshold can't exhaust worker memory mid-scan.
- Cover the xs area and height cap in GameHeader's sizing tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Keep ScreenScraper disc art for every disc of a multi-disc game
ScreenScraper tags each disc's support-2D art with a "support" number,
but the extractor kept only the first support-2D it met, so discs 2 and
up were never downloaded or shown.
The first disc still fills physical_url/physical_path, which the cover
art, disc-spin animation and exporters read. Every later disc goes to a
new ss_metadata.physical_extra_discs list, is downloaded next to it as
physical/physical_disc<N>.png, and gets its own entry on the v2 Artwork
subtab.
Existing ROMs pick up the extra discs on their next metadata refresh.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
* Type the extra-disc test metadata so mypy can index it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
* Label the first disc's art on multi-disc games
ss_metadata now records which disc physical_url shows, so the Artwork
subtab can label it "Physical media (disc N)" alongside the later discs.
It stays plain "Physical media" for single-disc games, gamelist art, or
when no later disc's art is on disk.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
* pr-ready step 2 (code-review): harden disc numbers and rematch cleanup
- Read ScreenScraper's disc number with safe_int and clamp it to 1, so
a zero, negative or non-string "support" value counts as the first disc.
- Remove the physical folder on an ss_id change when only later discs
had art, so a rematch doesn't keep the old game's disc images.
- Collapse store_metadata_media's two result lists into one target list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
* pr-ready step 3 (simplify): one home for the media a provider dict records
- Add FSResourcesHandler.recorded_media, which lists every recorded file
including a <type>_extra_discs list, so store_metadata_media and the
update_rom cleanup share one rule and neither special-cases physical.
- Skip stripping a disc's URL once a better region already supplied it.
- Share the ScreenScraper disc tests' patch setup in an _extract helper
and spell out each test's discs instead of slicing a fixture.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
* Refetch media whose source changed and keep shared art on rematch
- A scan now deletes each stored media file whose recorded URL changed,
or a later disc's file the new metadata dropped, before storing, so a
physical.png saved from another disc's art is fetched again instead of
showing under a "(disc 1)" label.
- A rematch deletes a later disc's own file instead of the whole physical
folder, so gamelist art sharing that folder survives.
Addresses the Greptile review on this PR.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
* Keep a shared media file a higher-priority provider still records
The stale-media check could delete a shared file such as physical.png
because a lower-priority provider's URL for it changed, even though the
file held a higher-priority provider's unchanged art. Each provider now
leaves alone the paths the providers before it still record.
Addresses the second Greptile review on this PR.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
* Decide stale shared media by which provider owns the path
The previous rule kept any path a higher-priority provider recorded, so
when ScreenScraper newly claimed a physical.png that still held older
gamelist art, neither provider refetched it. A shared path's file now
belongs to the first provider, in priority order, that records it, and
the file is refetched when that owner or its URL differs between the
previous and current metadata. Every provider is compared in one pass,
including ones outside this scan's sources.
Addresses the third Greptile review on this PR.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
* Name the fields of recorded media instead of using bare tuples
RecordedMedia was a four-item tuple alias that callers unpacked by
position, with a comment spelling out what each slot held. It is now a
NamedTuple with explicit fields and a path property, and the per-path
ownership claim in remove_stale_media gets the same treatment.
Addresses review feedback on this PR.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* perf(scan): download a rom's media files concurrently
download_rom_resources fetched the cover, manual, each screenshot, each
provider media type and every RetroAchievements badge one after another,
so a single ROM never used more than one of the ScreenScraper account's
request slots.
They now download together. ScreenScraper media still goes through its
existing thread and rate limiters, and badges share a new cap of 8 in
flight across all scans. The path columns and changed provider media
dicts are written back in one update.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf
* style(tests): sort imports with the Trunk isort config
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf
* fix(scan): code-review fixes for concurrent media downloads
- Run provider media dicts one after another, since they share paths
- Await every download before raising the first failure (gather_all)
- Fetch each duplicate media or badge path once (store_ra_badges)
- Reuse store_ra_badges in update_rom
- Share the in-flight test helper and trim comments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf
* refactor(scan): simplify pass on concurrent media downloads
- Move gather_all to utils/concurrency and unpack its results directly
- Let write_file_streamed create the badge directory instead of every badge
- Share the in-flight test helper through tests/concurrency_stubs
- Stub downloads with AsyncMock through one fixture, drop a redundant test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf
* fix(scan): save the paths that landed when a provider download fails
Cover, manual and screenshot paths are written before a provider media or
badge failure is re-raised, so a failure there no longer loses them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf
* fix(scan): save each download group's results independently
Paths, provider media and badges each keep their own outcome, and every
change that landed is written before the first failure is re-raised. The
test builds a real Rom instead of a namespace.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DAQNWjH7teMsMkFMuUrLTf
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* chore(mypy): switch to strict mode with listed exceptions
Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.
That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
sites patched a dependency through the module that imported it
(`scan_module.fs_rom_handler`); they now import the same object from
its source, so every patch targets what it did before. Tests that
replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
NotRequired dump_* keys spelled out, and the media dict never has them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G
* chore(mypy): give every generic its type arguments
Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.
- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
JSON and endpoint bodies map string keys to mixed values, so the Any is
real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
_exclude_hidden are generic over the Select they're given, and
_build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.
Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
async_cache, so it is cast to Redis[bytes] rather than changed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G
* test(upload): assert cleanup against the patched upload directory
The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G
* chore(mypy): keep the row type through the ROM filter helpers
filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Addresses Greptile's review of #4613:
- Write the small cover and the WebP copies in a worker thread, since
Pillow's work now scales with an animation's frames.
- Annotate the new converter fixture and the artwork test's tmp_path.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Simplify pass over the animated cover change:
- Encode animated small covers as WebP whatever the source, which drops
the per-format GIF/APNG blending params and makes their WebP copy a
plain file copy.
- Fold the is_animated gate into frame_durations and decode the small
cover's frames in the same pass that reads their durations.
- Write uploaded animated artwork through the atomic write_file.
- Share test fixture constants and the animation encoder, and pin the
per-frame pixel budget with a GIF whose canvas grows mid-animation.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Code-review pass over the animated cover change:
- Cap the pixels decoded across an animation (MAX_ANIMATION_PIXELS),
counted per frame since a GIF canvas can grow mid-animation, so an
oversized animation falls back to its first frame.
- Fall back to the first frame when a later frame fails to decode,
instead of dropping the cover or escaping the error handlers.
- Store uploaded animated artwork as uploaded, like downloaded covers.
- Re-encode composited frames so each replaces the last (no GIF/APNG
ghost trails), and keep GIF loop counts when converting to WebP.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The small cover and the WebP copies were written through PIL, which keeps
only the first frame, so an animated SteamGridDB cover showed as a still
image everywhere once applied. Resize and convert every frame with its
timing, copy WebP sources instead of re-encoding them, and keep all
frames of uploaded animated artwork.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The rationale for the locking scheme lives in the migration docstring and the
PR; the code only needs the part a reader cannot recover from it.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Review of the artwork-provenance work turned up two gaps behind the cleanup.
The new skip gate compared files on disk against the number of urls, so a
permanently dead url held the count below the target forever and every scan
refetched the entire set. Going index by index refetches only what is absent,
and lets `_store_screenshot` report success instead of the caller stating the
file back off the disk it just wrote.
The SGDB block still read `path_cover_s` to decide whether a cover was hand
supplied, the inferred marker `locked_fields` exists to replace. That also
shielded scraped covers from a better ranked source, which is the behaviour
this branch set out to fix, so it now asks the lock like the block above it.
The rest is cleanup: drop the dead `screenshots_exist`, give the column one
normal form across its writers, hoist the duplicated clear-out dict in
`delete_rom_manuals`, and drop the blanket backfill UPDATE, since a NULL
already reads as "no locks" everywhere.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Unify manuals and walkthroughs on one document model instead of a
separate walkthrough subsystem. Walkthroughs are RomFiles under a new
WALKTHROUGH category with an optional RomFileDocMeta provenance sidecar,
and reading progress is a per-user RomFileUser row keyed on rom_file_id
so the same mechanism covers manuals and walkthroughs.
Backend:
- models: RomFileCategory.WALKTHROUGH, DocSource, RomFileDocMeta,
RomFileUser; migration 0110 (enum value + two tables, cross-DB)
- serve .txt/.html documents inline (HTML under a sandboxing CSP);
add .txt to allowed manual files
- endpoints: walkthrough upload / GameFAQs fetch / delete, and per-user
reading-progress GET (ROMS_READ) / PUT (ROMS_USER_WRITE, like notes, so a
kiosk guest capped to the read scopes cannot write)
- last_page is range-checked, so an out-of-range value is a 400 rather than
an integer column overflow
- the guide body is read under the size cap instead of being buffered in
full and truncated afterwards
- GameFAQs import extracts text only (stored as .txt); no remote HTML is
persisted or served. Host-allowlisted on top of the SSRF-safe client
- a Cloudflare bot challenge is detected and reported as "open it in your
browser and upload the text" instead of an opaque 403
- reading-progress upsert retries as an update on a unique-constraint
race, so concurrent saves for one user/file can't 500
- a GameFAQs guide is removed from disk again if indexing it fails,
rather than being left unreferenced
- tests for CRUD, progress, the GameFAQs parser/URL validation, and
hidden-rom masking on every walkthrough route
Frontend (v2):
- TextViewer (.txt/.html), useReadingProgress composable, WalkthroughSubtab
(upload + add-from-GameFAQs-URL + delete + progress), wired into MediaTab
- ManualSubtab renders .txt manuals; walkthrough category surfaced in
FilesTab; regenerated types; i18n keys across all locales
- a pending scroll position is committed before the viewer follows a new
document, so switching files mid-debounce no longer drops it
- WalkthroughSubtab gates upload, the GameFAQs URL field, and delete on
useCan("rom.edit"), as ManualSubtab already does
AI assistance: implemented with Claude Code (Opus 4.8). The data-model
design, backend, migration, tests, and v2 UI were AI-authored under human
direction. Alternative approach to #2892.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
From review. get_rom_screenshots recorded a path for every url whether or
not the download landed, pointing the database at files that were never
written. Only record paths that made it to disk, and decide the early
return by counting files on disk rather than trusting the recorded list,
so a set left short by a failed run is retried instead of being frozen by
an unchanged url set.
The existing with-urls test asserted the old behaviour with a stand-in
that wrote nothing, so it now writes the files it claims to store.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Streamed downloads opened the destination directly, so an interrupted
transfer truncated the file in place. A truncated file is worse than a
missing one: it still satisfies the *_exists checks, so later scans skip
it and never refetch. The error paths cleaned it up, but only when the
process survived to run them, which a SIGKILL or host reboot does not.
write_file_streamed now writes to a temp file in the destination
directory and renames it over the target once the caller's block
completes, reusing the _atomic_write helper uploads already use. The
handle closes before the rename, so the target never sees a partial
flush.
The _discard_partial_file calls that followed a streamed write are gone.
There is no longer a partial file to remove, and the target now holds
either nothing or the previous good copy, which those calls would
delete. Refreshing a cover no longer costs the existing one when the
transfer dies.
The two disk-full tests patched write_file_streamed itself, so they were
asserting against the non-atomicity this removes. They now fail the
write from the response stream and exercise the real path.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
(cherry picked from commit 9b81fef29564d053c0ba4bb21f2192e0b9dc1f50)
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>
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>
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>
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>
ScreenScraper serves a solid chroma-key green (#00FF00) square when a
requested image (box-2D front/back/side) doesn't exist. RomM stored it as
real artwork, so the v2 3D box painted a bright green face and the flat
cover showed green in the gallery.
Detect the placeholder at download time and drop it: covers fall back to
the procedural placeholder, and a discarded box-2D face falls back to the
dark cover placeholder the box already paints (rather than bright green).
- Add _is_chroma_key_placeholder + _discard_if_chroma_key in the resources
handler; wire into _store_cover and store_media_file.
- store_media_file also cleans up pre-existing green files on rescan.
Generated-By: PostHog Code
Task-Id: 5534668f-a2b6-4575-b6c1-73dcd965062c
Discover manuals only for the allowed extensions (.pdf, .md) instead of
globbing {rom.id}.*, so stray files (e.g. {rom.id}.part) are never treated
as a manual. Select deterministically by newest mtime when multiple allowed
manuals coexist. Drop the redundant .md token from the frontend accept lists.
Generated-By: PostHog Code
Task-Id: 1d785bcc-ea5c-4b99-b619-73625a9e218c
The previous validator did a preflight `socket.getaddrinfo` before each
httpx request. Two problems:
* DNS rebinding / TOCTOU: httpx re-resolves at connect time, so a
hostname can answer with a public IP for the validator and a
private IP for the real request. The preflight check did not
constrain the connection.
* Event-loop blocking: `socket.getaddrinfo` is synchronous, and the
media-download callers are async. Slow resolvers stalled
unrelated requests.
Replace it with two layers, both wired automatically onto every httpx
client built by `utils.context`:
1. A request event hook running `validate_url_for_http_request`
(syntactic checks only: scheme, reserved hostnames, literal IPs,
internal TLDs). No DNS, no call-site responsibility.
2. `SSRFProtectedAsyncBackend` / `SSRFProtectedSyncBackend`, custom
httpcore network backends that resolve the hostname inside
`connect_tcp`, reject any address in a forbidden range, then
connect to that *same* validated address. The async variant uses
`loop.getaddrinfo` so it doesn't block the loop. httpcore calls
`start_tls(server_hostname=<URL host>)` after `connect_tcp`, so
TLS SNI and cert verification still use the original hostname
even though the TCP layer connects by IP.
Drop the explicit `validate_url_for_http_request(...)` calls from
`resources_handler.py` — the event hook covers them. Consolidate the
URL validator and its tests under `utils/ssrf.py` /
`tests/utils/test_ssrf.py` so the SSRF surface lives in one module.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Apply the same lazy-factory pattern to FSLaunchboxHandler and FSSyncHandler
that ssh_sync_handler now uses. With both opt-in features deferred to
first-use, the tolerate_missing_base escape hatch on FSHandler is no longer
needed — every handler now fails loudly on mkdir failure, which is the
right behavior for the always-on core paths (assets, library, resources).
Touched call sites:
- resources_handler._resolve_local_file_uri (launchbox)
- sync_watcher.py, endpoints/device.py, tasks/manual/sync_folder_scan.py
(fs_sync)
Net effect:
- Default installs never poke /romm/launchbox or /romm/sync at startup.
- Misconfigured opt-in users get a clear, actionable PermissionError at
the call site instead of a silent warning followed by mystery failures.
- tolerate_missing_base, its tests, and one stale log import are gone.
Importer (gamelist/launchbox file:// flows) and exporters (gamelist.xml,
metadata.pegasus.txt local exports) now hardlink media assets when source
and destination share a filesystem, falling back transparently to a copy
on EXDEV / EPERM / EOPNOTSUPP / EMLINK / EACCES (cross-device, FAT32,
exFAT, network mounts, etc.). Saves disk space and is effectively
instantaneous on large files (videos, manuals, miximages).
Covers keep a real copy (allow_link=False) because _store_cover resizes
the small cover in place via PIL.Image.save, which would truncate the
shared inode and corrupt the user's source image.
Also makes FSSyncHandler tolerate a missing/unwritable /romm/sync at
startup: an OSError from mkdir now logs a warning instead of crashing
the whole app at module-import time. Sync calls still fail at use time
if the mount remains broken — the right place to surface the error.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
LaunchBox produced file:// URIs relative to /romm/launchbox, but the
resources handler resolved them under /romm/library via fs_rom_handler,
so local images/manuals/screenshots were never found. Switch LaunchBox
to a distinct launchbox-file:// scheme and add FSLaunchboxHandler +
_resolve_local_file_uri to route each scheme to the correct root.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Problem
_check_content_type used the full Content-Type header string (lowercased) and matched it with startswith(...) against allowed prefixes.
That is mostly fine when the server sends a bare type like application/pdf. It breaks down when vendors send parameters on the same header (e.g. name="…", charset=…). In theory application/force-download; name="…" should still start with application/force-download, but in practice you can get:
Leading whitespace or a UTF‑8 BOM before the type token, so the string no longer starts with your prefix even though the MIME type is correct.
Confusing logs: logging only the lowercased full header is fine, but the decision should be based on the standardized MIME essence (type + subtype, no parameters), which is what other stacks use for “what is this?”
So the fix is to parse the header the usual way and only then apply your allowlist.
What changed
_content_type_essence(header_value)
Takes everything before the first ; (the essence).
Strips whitespace, lowercases, strips a leading BOM (\ufeff) so odd clients/proxies don’t break the check.
_check_content_type
Reads the raw content-type header once.
Runs startswith on the essence, not on the full header with parameters.
Rejects if the essence is empty (missing or useless header).
Logging uses the raw header string (or (missing header)), so operators still see exactly what the server sent.
Call sites and allowed prefixes (image/, application/pdf, etc.) are unchanged; only how the string is normalized before comparison changes.
Security / SSRF
This does not replace URL / SSRF controls; it only makes post-fetch type checking consistent with how Content-Type is defined (essence vs parameters). You are not widening the allowlist—same prefixes, stricter handling of “empty” and clearer matching on the actual type token.
Risk / regression
Low: same allowed prefixes, strictly more tolerant of benign formatting (whitespace, BOM, parameters). The only stricter case is empty essence after strip (e.g. malformed header), which correctly fails the check.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
I have reviewed the proposal and these edits will handle cases where the string we match against for the content_type is cleaned up more before comparing against the allow list of content_types.
I have tested this, and confirm that I do not get any errors loading PDFs for game manuals using this. Please consider this, as this should be compatible with the existing content type allowlist, and easily work with any new types added to it.