Commit Graph

105 Commits

Author SHA1 Message Date
Georges-Antoine Assi
c3e7aed3ea style: cut the artwork lock comments to the fact each one carries
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>
2026-08-29 20:38:22 -04:00
Georges-Antoine Assi
5f9eb14719 refactor(resources): fetch the screenshots that are missing, not the whole set
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>
2026-08-29 19:56:39 -04:00
Georges-Antoine Assi
005db06525 Merge remote-tracking branch 'origin/master' into fix/artwork-provenance-update-scan 2026-08-29 19:21:27 -04:00
Georges-Antoine Assi
3c95231294 feat: walkthrough documents with reading progress and GameFAQs import
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>
2026-08-25 19:40:20 -04:00
Sam Dornan
1b282d90c0 fix(resources): stop recording screenshots that never landed
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>
2026-08-19 10:12:18 -05:00
Sam Dornan
7931b70d24 fix(resources): correct misleading error message in store_ra_badge
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-18 11:58:40 -05:00
Sam Dornan
ce78561c41 fix(resources): publish downloaded resources atomically
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)
2026-08-18 14:57:06 +00:00
Georges-Antoine Assi
392cc9b0e2 Merge pull request #4143 from Spinnich/fix/cover-downloaded-twice
fix(resources): fetch each cover once instead of once per size
2026-08-08 12:05:48 -04:00
Georges-Antoine Assi
97b3a32148 cleanup 2026-08-08 11:23:53 -04:00
Spinnich
d8522991e3 fix(resources): fetch each cover once instead of once per size
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>
2026-08-06 20:35:18 +00:00
Sam Dornan
d758c8f472 fix(ss): store the box-2D front locally so it survives cover priority
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>
2026-08-06 12:38:35 -05:00
Sam Dornan
984c40c158 fix(media): clear a recorded media path that has no URL to fetch from
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>
2026-08-05 15:07:16 -05:00
Sam Dornan
656c5d7d23 fix(media): stop recording paths for media that never landed
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>
2026-08-05 14:54:45 -05:00
Spinnich
c2786429fd fix(screenscraper): address review feedback on quota awareness
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>
2026-07-29 13:55:19 +00:00
Spinnich
5fb27a55f9 feat(screenscraper): make scanning aware of the account's reported limits
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>
2026-07-28 17:09:52 +00:00
Ryan McClelland
32f9ac1b90 fix(resources): handle write failures when the disk is full
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>
2026-07-27 13:34:41 -07:00
Georges-Antoine Assi
579e12574c fix(backend): discard ScreenScraper chroma-key green placeholder art
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
2026-07-11 07:57:36 -04:00
Georges-Antoine Assi
e7de380aac fix(roms): restrict manual matching to allowed extensions
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
2026-07-05 12:20:41 -04:00
Georges-Antoine Assi
82bd5e30b8 feat(roms): support markdown manuals and enforce allowed file types
Generated-By: PostHog Code
2026-07-05 08:49:47 -04:00
Georges-Antoine Assi
30451d5651 fix(security): move SSRF defense into the HTTP client path
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>
2026-05-27 17:58:14 -04:00
Claude
26bdc11e13 refactor(filesystem): lazy-init launchbox + sync handlers, drop tolerate_missing_base
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.
2026-05-24 14:59:03 +00:00
Georges-Antoine Assi
adb050f164 commit and push 2026-05-19 07:31:25 -04:00
Georges-Antoine Assi
757fafae5f feat(fs): hardlink import/export assets when possible, harden sync init
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>
2026-05-18 07:38:11 -04:00
Georges-Antoine Assi
90945685e4 Stuff 2026-05-17 12:43:33 -04:00
Georges-Antoine Assi
40689d7e39 Fix LaunchBox local-media file:// paths resolving under library root
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>
2026-04-17 22:59:00 -04:00
Georges-Antoine Assi
f227a3145d changes from bot review 2026-04-07 22:32:40 -04:00
Alex Vanderveen
6aca8fdfcf Parse Content-Type essence before validating resource downloads
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.
2026-04-07 20:25:55 -04:00
Georges-Antoine Assi
b36a8b0cdf manual types should support octet-stream and force-download response 2026-04-07 14:22:43 -04:00
Georges-Antoine Assi
bae0d0c698 more changes from rview 2026-04-03 11:29:55 -04:00
Georges-Antoine Assi
ceddf2f9e9 changes from bot review 2026-04-03 11:24:02 -04:00
Georges-Antoine Assi
ec8583016b mega ton of fixes for 4.8 2026-04-03 10:54:31 -04:00
Georges-Antoine Assi
997e2c44aa start pre-4.8 cleanup 2026-03-12 23:02:12 -04:00
Georges-Antoine Assi
ee8b55e6ef last set of changes 2026-03-07 09:56:17 -05:00
Georges-Antoine Assi
76bdfb4891 changes from self review 2026-03-07 09:36:45 -05:00
Georges-Antoine Assi
b3659a1226 changes from bot review 2026-03-07 08:58:42 -05:00
Georges-Antoine Assi
b030b98062 attempt to fix vuln reported in PR 2026-03-06 19:42:56 -05:00
Georges-Antoine Assi
eb5e32ed78 [HOTFIX] Fix importing media from gamelist.xml 2025-11-10 17:06:20 -05:00
Georges-Antoine Assi
436b1972c4 tweaks from self review 2025-10-28 12:10:53 -04:00
Georges-Antoine Assi
c1ac9a2133 fix screenshots dissapearing on scan 2025-10-28 11:00:45 -04:00
Georges-Antoine Assi
4be180d1bd ensire dest folders exist on scan 2025-10-26 13:41:19 -04:00
Georges-Antoine Assi
78bfdf0543 fixes from bot review 2025-10-24 19:13:13 -04:00
Georges-Antoine Assi
d928c9705f fix media storage for gamelistxml 2025-10-24 19:06:45 -04:00
Georges-Antoine Assi
463bb27ea9 Add config to store media on disk 2025-10-24 16:04:54 -04:00
Georges-Antoine Assi
9fa15d20f0 totally refactor scan types 2025-10-23 16:57:40 -04:00
Georges-Antoine Assi
5aa344b3ce select media format for scan 2025-10-22 19:08:42 -04:00
Georges-Antoine Assi
290162e56b import media assets 2025-10-22 12:44:58 -04:00
Georges-Antoine Assi
3cfc52234a start work on gamelist.xml extraction 2025-10-16 23:16:39 -04:00
Georges-Antoine Assi
38006e7aa0 [ROMM-2497] Add button to delete manual 2025-10-07 10:21:02 -04:00
Georges-Antoine Assi
5d9119ebe1 [ROMM-2467] Uncompress gzipped images 2025-09-21 16:06:45 -04:00
Georges-Antoine Assi
bf631cfa74 fix updating image preview + force webp 2025-09-05 09:42:25 -04:00