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>
A member that failed or timed out mid-archive ended the member stream
silently, so the caller kept the composite hash built from the members
that happened to succeed. Raise ArchiveReadError instead and fall back to
hashing the archive's raw bytes, with no archive_members recorded.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
PR #3035 made region/language shortcode lookups case-sensitive by keying
REGIONS_BY_SHORTCODE on the uppercase codes, and updated the plain tag
lookups to match against the raw (unlowered) tag. The "Reg-" prefix branch
was missed: it still lowercased the captured shortcode before looking it up,
so it could never hit the now-uppercase-keyed dict. As a result a tag like
"[Reg-J]" was stored as the raw "J" instead of resolving to "Japan".
Match the shortcode with its original case, like the other lookups, so
"[Reg-J]" resolves to "Japan" and "[Reg-U]" to "USA". Non-shortcode values
(e.g. "[Reg-PAL]") are still kept verbatim via the fallback.
Co-Authored-By: Claude <noreply@anthropic.com>
VERSION_TAG_REGEX only treated whitespace, underscore, and hyphen as
separators after the version prefix, so a dot-separated tag like
"(v.1.0)" or "(Ver. 1.00)" fell through to the no-separator branch and
captured the dot into the version (".1.0", ". 1.00"). This wrong value
was then persisted to Rom.version on scan and on rename.
Add "." to the separator character class so the dot is consumed like the
other separators. Digit-prefixed tags such as "(v1.0)" are unaffected
(they still match the no-separator branch), and non-version "v*" tags are
still ignored.
Co-Authored-By: Claude <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
RomM stores soundtracks but exposes no way to consume them as a music library: a
client has to enumerate ROMs and pull each one's tracks individually, and the
per-track metadata lives in the `rom_files.audio_meta` JSON blob, which is
unindexable on MariaDB, so any library-wide filter or sort degrades to a full
scan.
This adds a queryable, music-first API for soundtracks, backed by a typed and
indexed `track_meta` table migrated from that JSON.
It also lets users upload soundtracks, manuals, and screenshots to any ROM, not
only folder-based ones. When the target is a single-file ROM, the client warns
that the upload will migrate it to a multi-file (folder) structure, then performs
that migration in place automatically.
Centralize the *_no_tags / *_no_ext / *_extension columns (derived from a
file name) behind @validates hooks instead of computing them by hand at
every write site:
- Add pure helpers (compute_file_name_parts and friends) to models.base;
the filesystem base handler now delegates to them.
- Add @validates on Rom (fs_name), BaseAsset (file_name, inherited by all
asset subclasses), and Firmware (file_name).
- update_rom keeps the fs_name-derived columns in sync on bulk update(),
which also fixes the rename path never updating fs_extension.
- Drop the now-redundant computations at the scan/rename call sites.
Also fix the migration backfill loop and a pre-existing list[str | None]
type mismatch surfaced in scan_handler. Add tests for the helpers, the
validators, and the update_rom bulk-sync path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adopt master's ROM schema design (sibling_roms + files, batched
get_files_for_roms / get_siblings_for_roms) while preserving the v2-branch
features master lacks: per-user is_main_sibling on siblings and audio_meta
on rom files.
Conflict resolution:
- responses/rom.py: keep master's sibling_roms/files fields; re-graft
is_main_sibling via SiblingRomSchema.from_rom(rom, is_main_sibling=...);
restore the eager-relationship fallback in
SimpleRomSchema.from_orm_with_request (None sentinel) so the v2
/{id}/simple endpoint still returns siblings/files.
- roms_handler.py: get_siblings_for_roms now left-joins RomUser and returns
(Rom, is_main_sibling) tuples; keep both branch and master file helpers.
- drop the redundant branch-only sibling_ids field and
get_sibling_data_for_roms.
- generated types resolved to match (sibling_roms + files; RomFileSchema
keeps audio_meta and gains archive_members).
- update v2 components and the RelatedGameCard mock to read sibling_roms.
- fix stale exclude={"siblings"} -> "sibling_roms" in scan emit payloads.
- re-chain the audio_meta migration as 0083 (after master's 0082) to keep a
single Alembic head.
- package.json: union of branch tooling + master dependency bumps; lock
regenerated.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Extract has_structure_path_a as its own cached property and have
has_structure_path_b delegate to it, removing duplicated isdir checks.
detect_library_structure and get_platforms_directory now read the named
properties instead of re-implementing the roms-path check inline.
Keep the inconclusive/bad-structure fallback defaulting to Structure A so
a malformed library raises FolderStructureNotMatchException rather than
listing the bare library root as a flat list of platforms.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
When a top-level `roms/` folder exists (Structure A), never detect the
library as Structure B, even if individual `<platform>/roms/` directories
also exist. This prevents existing Structure A libraries from being broken
after upgrading to 4.9.0.
- `has_structure_path_b` in `config_manager.py` now returns `False` early
when `{LIBRARY_BASE_PATH}/{ROMS_FOLDER_NAME}` is an existing directory
- `detect_library_structure()` in `platforms_handler.py` now explicitly
checks Structure A (`os.path.exists(roms_path)`) before consulting
`cnfg.has_structure_path_b`
- Updated test to assert Structure A wins when both layouts coexist
Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com>
The archive branch of get_rom_files (introduced in #3412) was missing
the RAHasherService.calculate_hash call that exists in the non-archive
branch, causing all archive-format ROMs to produce an empty ra_hash
during scanning regardless of platform.
The RA hash call is now made for archive ROMs, mirroring the existing
non-archive behaviour. The RA_BUFFER_HASH_UNSUPPORTED skip logic in
RAHasherService already handles disc-based platforms (PSX, PS2, PSP,
Saturn, Dreamcast, etc.) so those continue to be excluded automatically.
Also improves handling of folder-based multi-file ROMs whose directories
contain compressed files. RAHasher cannot process archives via the /*
glob and fails with "Could not open file". The fix mirrors the existing
CHD folder logic: for cartridge platforms the largest archive in the
folder is passed directly to RAHasher for buffer hashing; for disc
platforms the call is skipped as buffer hashing is unsupported.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
FSAssetsHandler.compute_content_hash and _compute_zip_hash were
building full paths via f"{self.base_path}/{file_path}". self.base_path
is already a pathlib.Path (resolved by FSHandler.__init__), so the
f-string forced it to str, hard-coded the separator, and re-parsed --
fine on Linux but a footgun if a caller ever sneaks a leading slash or
the path needs Path semantics elsewhere.
Switch both spots to self.base_path / file_path, which is what every
other FSHandler subclass in this module already does (e.g.
FSRomsHandler, FSResourcesHandler, FSSyncHandler all join Path objects
directly).
Cleanup pass on save-sync addressing three independent failure modes
that interact in production data: content_hash drift between client
and server, null-slot archival saves leaking into sync flows, and
content-hash dedupe collapsing legitimately-distinct slots.
Bug fixes
- compute_content_hash dispatched on zipfile.is_zipfile(relative_path),
which silently returned False whenever the process's CWD wasn't
ASSETS_BASE_PATH. Every zip save fell through to the raw-MD5 branch,
persisting hashes that disagreed with clients computing the intended
per-entry zip-hash. Resolve to a full path before the dispatch.
- _build_negotiate_plan, sync_push_pull_task, and sync_watcher all
treated null-slot saves as sync-eligible. Null-slot saves represent
web-UI / archival uploads; including them in negotiate plans matched
them against device pushes by filename and overwrote archival data.
Filter null-slot saves at all three call sites.
- get_save_by_content_hash matched on (rom_id, user_id, content_hash)
only, so identical bytes uploaded to different slots collapsed into
one record. Scope the lookup by slot when provided so clone-save-
to-new-slot creates a distinct row per slot.
- get_save_by_filename matched on (rom_id, user_id, file_name) only.
When two uploads to different slots happened in the same wall-clock
second (the datetime tag is per-second), the second upload UPDATED
the first record's slot instead of creating a distinct row. Scope
the filename lookup by slot too.
One-shot recovery
- New recompute_save_content_hashes manual task walks every Save row,
recomputes via the fixed dispatch, and updates rows whose values
differ. Idempotent; safe to re-run.
- Backend startup runs a COUNT(content_hash IS NULL) query and, if
any rows exist, enqueues the recompute task on the low-priority
RQ queue. The API process moves on; the worker handles the
recompute out-of-band. Subsequent restarts find zero NULL hashes
and skip. Admins can also trigger the task manually.
Test infrastructure
- Added tests/_zipfile_shim.reload_zipfile() mirroring the pattern
from utils/zip_cache.py for the same zipfile-inflate64 + CPython
3.13.5 incompatibility. Test fixtures that build ZIPs call it
immediately before opening the archive.
Internal members of multi-file archives (zip/tar/7z/rar) are now hashed
individually (crc/md5/sha1) and stored in a new `archive_members` JSON
column on the archive's RomFile, alongside the existing composite hash
used for hash-database matching. Only the archive itself is surfaced as
a RomFile so full_path keeps pointing at a file that exists on disk,
which is the constraint that previously forced us to choose between
composite-only or broken downloads.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Consolidate all archive readers (zip/tar/7z/rar) and 7z-internal helpers
into a single utils/archives.py module to keep the archive surface area
in one place.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per-internal-member RomFiles produced full_paths that didn't exist on
disk, breaking downloads and zip-building. Stream entries into the
composite hash only and emit one RomFile pointing at the archive itself.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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 helper to the three other per-file FileHash constructions
(folder-walk hash, empty-archive fallback, single-file hash). The
all-empty FileHash literals are left alone since the helper would be
strictly more obscure for that case.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add read_rar_archive_files via the existing 7zz binary (which natively
handles RAR3/RAR5 read), and collapse the per-extension reader dispatch
into an ARCHIVE_READERS dict so future formats are one entry away. Also
extract a small _make_file_hash helper to remove the repeated nested
ternaries in the inner loop.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pull file/archive readers (zip/tar/gz/bz2/7z), CHD parsing, and the
shared libmagic MIME detector out of roms_handler.py into a new
utils/archives.py. Rename the previously underscore-prefixed
read_zip_archive_files / read_tar_archive_files to match the existing
read_7z_archive_files convention, and consolidate the duplicated
"with lock: detector.from_file()" pattern into a detect_mime_type helper.
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.
User-configured EXCLUDED_MULTI_PARTS_EXT/FILES are intentionally not
applied to archive internal files. Archives are curated ROM sets where
every file is relevant — user custom exclusions (e.g. "bin") could
silently produce incorrect composite hashes. Only the hardcoded
DEFAULT_EXCLUDED_FILES/EXTENSIONS (junk like .DS_Store, gamelist.xml)
are applied.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Use AnyioPath.stat() instead of os.path.getmtime in async context (ASYNC240)
- Add assert to narrow rom_md5_h/rom_sha1_h from HASH|None to HASH (mypy/union-attr)
- Auto-formatted long log.error calls in archive_7zip.py (ruff)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>