Commit Graph

25 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
a2a2c0923d test(resources): name the cover re-derivation test for what it checks
The name claimed a locked cover surviving an unmatch, but the test sets
no lock and performs no unmatch. It cannot: get_cover takes url_cover as
an argument and never reads locked_fields, so an empty url is how a lock
reaches this layer. Setting one on the mock would imply a coupling that
does not exist.

Renamed to describe the behaviour it does cover, and the comment now
points at the test carrying the other half of the chain.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 10:12:40 -05: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
2c31202e60 fix(resources): clean up the temp file when a download is cancelled
_atomic_write cleaned up in `except Exception`, which does not catch
CancelledError. Stopping a scan mid-download therefore stranded a
`.romm_tmp_*` file per cancelled transfer. Catch BaseException instead.
This also covers uploads, which have always gone through this path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YKbk4cDmdKKMcBxGmsRVT5
2026-08-18 15:05:12 +00: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
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
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
e1225c8a9c fix(screenscraper): don't repeat an unchanged quota line
The last platform's quota readout and the end-of-scan summary both call
_log_ss_quota, so a completed scan printed the same numbers twice in a row.
Skip a line identical to the previous one, resetting at the start of each scan
so a new run always reports.
2026-07-29 01:30:18 +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
5a63f0d1be fixing failing tests 2026-07-01 10:44:00 -04:00
Georges-Antoine Assi
f227a3145d changes from bot review 2026-04-07 22:32:40 -04:00
Georges-Antoine Assi
438f514e76 fix tests 2025-10-28 11:38:57 -04:00
Georges-Antoine Assi
c1ac9a2133 fix screenshots dissapearing on scan 2025-10-28 11:00:45 -04:00
Georges-Antoine Assi
8975a7ed89 fix ra tests 2025-10-26 14:02:21 -04:00
Georges-Antoine Assi
bbade3e40e fix tests 2025-10-23 17:05:23 -04:00
Michael Manganiello
e4e3928d1b misc: Apply import sorting 2025-09-04 11:17:00 -03:00
Michael Manganiello
ba21cbc1e1 misc: Separate tests folder from backend code
Create separate `tests/` folder for all tests. This will also simplify
not copying tests code into the Docker image.
2025-08-08 12:49:13 -03:00