Commit Graph

184 Commits

Author SHA1 Message Date
Georges-Antoine Assi
a7ecfd96a9 feat!: make filesystem.structure the single library layout
`filesystem.structure` now spells out the whole layout rather than only the part
below a platform folder. A template is relative to the library root, `{platform}`
marks the platform folder, and `{game}` marks where a game begins.

Merge `{gameFile}` and `{gameDir}` into one `{game}` terminal. The information a
terminal carried was the depth, not the kind: at a declared level a file is a
game of its own and a folder is one multi-file game, which a stat answers. That
drops the two-template idiom for a level holding both, and `_discover_default_roms`
with it, since the default scan is now just `roms/{platform}/{game}`.

Retire the auto-detected `{platform}/roms` layout, along with
`filesystem.roms_folder` and `filesystem.firmware_folder`, which named one path
segment each that a template now contains. Both are refused at startup with the
template that reproduces the layout, so an instance that relied on either says so
instead of scanning an empty library and marking every rom missing. Firmware gets
its own `structure.firmware` key rather than following the rom layout implicitly.

`get_roms_fs_structure` keeps meaning the folder a platform's games start in, so
the `.physical` sentinel paths already in the database still resolve. Per-platform
overrides have to agree with `default` on where the platform folder sits;
relocating one platform needs platform discovery and the watcher to union several
roots, which is left out.

The setup wizard reports `library_ready` plus the configured template instead of
a `struct_a`/`struct_b` discriminator, so the banner shows the layout in force
rather than guessing it client-side.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 08:39:21 -04:00
Georges-Antoine Assi
dd7f46b52c fix: make metadata exports and matching follow the library structure
Testing the custom library structure against a live library turned up four
defects, all of them a path being reduced to a bare file name.

Both exporters wrote a rom's `fs_name` alone, so every game a template nests
was exported as if it sat in the platform folder: ES-DE and Pegasus could not
find any of them. They now write the rom's path relative to the platform
folder, the folder the metadata files themselves live in, and copy exported
media into the matching subfolder so two identically named roms keep their own
artwork.

Merging into an existing gamelist.xml / metadata.pegasus.txt keyed entries by
file name too, so identically named roms in different folders both merged into
the first entry and produced duplicates. Entries are now keyed by path, with a
Pegasus block matched by the folder its listed files sit in.

Reading a gamelist.xml had the same collision: two roms sharing a file name
both took the metadata of whichever entry was parsed last. A rom's own path now
wins, and a bare file name stays a fallback key for the tools that write those,
dropped when two entries share it.

Default discovery surfaced hidden folders as multi-file games, unlike
structured discovery which skips them. exclude_multi_roms now owns that rule
for both.

Also validate `exclude`'s exclusion_type: an unknown value reached
`Config.__getattribute__` and returned a 500 rather than a 422.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 07:31:05 -04:00
Georges-Antoine Assi
b930a37448 Merge remote-tracking branch 'origin/master' into fix/ss-quota-breaker-recovery
# Conflicts:
#	backend/endpoints/roms/__init__.py
2026-09-06 22:54:48 -04:00
Georges-Antoine Assi
6161f8057d refactor(screenscraper): report a short-circuited lookup per rom
A tripped breaker answers in ScreenScraper's place, so the empty match it
produces is not a miss and must not clear the rom's stored ss_id. The scan
learned that by sampling the module-wide is_breaker_tripped() at three points,
which reads another rom's trip as this rom's evidence.

SSHandler now raises ScreenScraperExhaustedError instead of swallowing the
breaker's error, carrying the match it would have returned so the name the
filename lookup derives locally (Switch title database, MAME, PS2 OPL) still
reaches the scan. fetch_ss_rom catches it the way it already catches
ScreenScraperRateLimitError, and drops ScreenScraper from attempted_sources
from a plain local, so the signal is exactly this rom's own lookups.

Also folds in a cleanup pass over the branch: the dead default_factory arm in
_ScanState.reset(), one home for the ssuserInfos.php path, asyncio.wait_for
around the quota probe so it cannot block behind a media download holding the
concurrency slot, and shared fixtures for the ScreenScraper tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 21:35:25 -04:00
Sam Dornan
8494744ee7 Merge branch 'master' into claude/igdb-keywords-themes-perspectives
Resolve conflicts in the v2 Home view and its test: keep both the
recommendations row from this branch and the live multiplayer sessions
row from master.

Master added migrations 0119 through 0121 that forked the Alembic chain
against this branch's 0119 through 0122. Renumber this branch's
migrations to 0122 through 0125 so they chain after 0121_state_disc_file.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D9EiQ8VWDJfzhEViDdj84d
2026-09-06 00:24:13 +00:00
Spinnich
0d7ce16d16 fix(screenscraper): let the daily-quota breaker recover
HTTP 431 means a ROM did not match and the daily cap on proposing unknown
ROMs for review is reached; scraping is unaffected, so it becomes a
not-found with one informational line per scan instead of a refusal that
takes the provider out.

HTTP 431 is really two answers at once and only one of them concerns the
scan. The scrape allowance (430) still trips a breaker, since every
remaining ROM would otherwise cost a round trip to be told the same thing,
but it now arms only after repeated refusals, ignores the ones already in
flight when a refusal was counted, and re-checks the free account endpoint
so it recovers without a scan to reset it. The account check can no longer
arm it at all.

A recoverable breaker can clear itself while a rom is still gathering its
other providers, so a complete rescan read it as having answered and wiped
the rom's id. It is now sampled where ScreenScraper is consulted.

The manual-match search gathers every provider without return_exceptions,
so it now swallows an exhausted ScreenScraper the way the scan lookups do.

Fixes #4123

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 15:08:18 +00:00
Georges-Antoine Assi
e57c5e471c Merge pull request #4353 from Spinnich/fix/complete-rescan-clears-attempted-ids
fix(scan): let a complete rescan clear the ids it rematched
2026-09-04 21:59:48 -04:00
Georges-Antoine Assi
8b2931a56d fix(scan): don't let a Hasheous outage read as a conclusive miss
`_request` swallowed a non-404 HTTP error and a timeout into an empty dict,
which `lookup_rom` then reported as conclusive: Hasheous answered and knows
nothing about these hashes. A 500 or a timeout therefore de-verified a rom on
a rehash and cleared its id on a complete rescan.

Both paths now raise, so the conclusive flag already carried by `lookup_rom`
tells the two empty matches apart on its own.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 20:58:18 -04:00
Georges-Antoine Assi
4db67ff039 Merge pull request #4352 from Spinnich/fix/ra-skip-games-without-achievements
fix(retroachievements): don't match ROMs against games with no achievement set
2026-09-04 20:25:58 -04:00
Georges-Antoine Assi
996d12adea feat(metadata): add RPG Maker platform and resolve easyrpg folders
Batocera, RetroBat and ES-DE all ship an `easyrpg` folder for RPG Maker
2000/2003 games, but RomM had no platform for them, so the folder fell
through as an unmatched platform that matched no metadata.

Add UniversalPlatformSlug.RPG_MAKER and wire it to the two providers that
carry the platform: ScreenScraper (system 231, "EasyRPG") for metadata and
libretro (system "RPG Maker") for thumbnails. IGDB, MobyGames and TheGamesDB
have no RPG Maker platform, so they stay unmapped, the same way DOOM is
wired.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 19:09:21 -04:00
Spinnich
24bc4c221b fix(scan): don't let a failed lookup clear the id it couldn't check
A complete rescan clears the id of every source it consulted that came back
empty. That reads an outage as a conclusive miss for the providers that report
a failure as an empty match, so a rescan run while one was down wiped the id it
would otherwise have confirmed, hand-set ones included.

Each of those now reports the failure and leaves the tolerance to the caller,
which is what the gather loop's discard already assumed:

- Pouët, CSDb and Demozoo stop swallowing the 503 their own `_request` raises,
  and Pouët's title search raises it rather than answering "no unique title".
- SteamGridDB and Flashpoint stop catching `Exception` around a whole lookup;
  HLTB stops catching it around its search.
- ScreenScraper answers empty for every remaining ROM once its daily-quota or
  credentials breaker trips, so the scan reads that state off the service and
  drops it from the sources the rescan may clear.

SteamGridDB resolves outside the gather and so needs the discard at its call
site. Search keeps degrading to no thumbnail, since its cover art sits on top
of matches the other providers already produced.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 20:49:51 +00:00
Spinnich
b45a410991 test(retroachievements): cover the hash index cache filename bump
Nothing failed if the cache filename went back to ra_hashes_v2.json, which
would leave upgraded installs serving the unfiltered index until its mtime
aged past REFRESH_RETROACHIEVEMENTS_CACHE_DAYS.

Back the resources directory with a real temp directory so the freshness
check reads a real mtime, and assert a v2 index on disk is refetched rather
than reused.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 18:49:17 +00:00
Spinnich
bbc1e63d69 fix(retroachievements): don't match ROMs against games with no achievement set
The hash index was built with RA's f=0, so it mapped hashes of games that
exist on RetroAchievements but have no achievements. Those ROMs came out of
a scan with an ra_id set, which lit up every RA signal (achievements tab,
match chip, has_ra filter, smart collections) while answering the only
question those signals are asked: no, there is nothing to earn here.

Measured live against N64 (system 2), 45% of indexed hashes pointed at
set-less games; NES and PlayStation are above 60%.

Switch to f=1 and bump the cache filename, since the freshness check is an
mtime test and installs would otherwise keep the stale index for up to
REFRESH_RETROACHIEVEMENTS_CACHE_DAYS.

Fixes #4343

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 18:49:17 +00:00
Georges-Antoine Assi
eec574b49b fix(metadata): give UniversalPlatformSlug a leaf home
Both CI failures came from one import cycle. RQ could no longer resolve
`endpoints.sockets.scan.scan_platforms`, and the e2e seed script failed the
same way, because `sigil` imports the platform slug enum, importing anything
under `handler.metadata` runs its `__init__`, that reaches `gamelist_handler`
which imports `handler.filesystem`, and `roms_handler` there imports `sigil`
back while it is still half-initialised.

The cycle predates this branch. It stayed hidden because `scan.py` reached
the enum through `utils.switch`, imported late enough that
`handler.filesystem` was already loaded; naming the adapter directly moved
that import to the top of the module and the ordering luck ran out.

So the enum moves to `utils/platform_slugs.py`, which imports nothing but
`enum`. Naming a platform no longer drags in httpx, redis and the titledb
task, and the 29 call sites point at the module that owns it rather than
picking it up from a 1000-line metadata handler that happens to re-export
it. `import adapters.services.sigil` now also works on its own, which it
did not before.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 14:28:49 -04:00
Georges-Antoine Assi
fbbadb7c86 refactor(scan): give the title id one resolver and one identity shape
The Tinfoil feed was left behind when `_switch_productid_format` changed
from taking a `re.Match` to taking a `str`, so `/feeds/tinfoil` raised a
TypeError for any Switch rom carrying a product id in its filename but no
titledb id. It went unnoticed because `feeds.py` sits outside the changed
files mypy sees.

That call site was reachable only because "prefer the id the scan read over
the one scraped from the filename" lived in a second helper above the lookup,
leaving each caller to remember it. The resolution now happens inside
`_switch_productid_format`, so the three providers and the feed all get it
without repeating a preamble.

Also:

- Move `SWITCH_PLATFORM_SLUGS` to the sigil adapter so `utils/switch.py`
  stops importing the metadata base handler. The cycle that import created
  was papered over with a function-local import, and `normalize_identity`
  now takes the fact it needs rather than the whole slug set.
- Merge a partial identity update onto the stored identity before
  normalizing it. Normalizing rewrites the whole triple, so a client sending
  only a title id was getting the derived base id next to its old save
  target.
- Add `RomIdentity.from_rom` so the triple has one home on the read side
  too, and drop `asdict` from `as_rom_attrs`.
- Hold the `SigilExtractionResult` on `TitleIdEmbedCandidate` instead of
  copying two of its fields.
- Drop a guard in `_rom_level_identity` that could not fire, derive once in
  `normalize_identity`, and return only the parse from `_rebuild_rom_files`,
  which already owns `fs_rom["fs_name"]`.
- Read the parsed config in the heartbeat rather than forcing a YAML
  re-parse per request, and make `SigilService.is_enabled` a classmethod
  like every other one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 10:57:36 -04:00
Sam Dornan
0feedde197 Merge remote-tracking branch 'origin/master' into claude/igdb-keywords-themes-perspectives 2026-09-03 09:25:03 -05:00
Georges-Antoine Assi
e19394e969 feat(scan): surface title id extraction and feed it to metadata matching
The optional binding used to no-op in silence: an absent sigil was
indistinguishable from a file with no title id. `SigilService.is_enabled`
plus `FILESYSTEM.TITLE_ID_EXTRACTION_ENABLED` on the heartbeat put the
feature on the same footing as every other optional capability, and give
a client of `PUT /roms/{id}/identity` a way to ask whether the server
reads binaries at all.

The extracted id also reaches the layer that already matches on Switch
product ids. Until now that layer could only scrape one out of the
filename, which made `embed_switch_title_ids` the de facto transport:
users had to let RomM rewrite their filenames for matching to improve.
`switch_product_id` prefers the id read from the binary, so extraction
helps everyone with the binding and the rename stays cosmetic.

MobyGames' `get_rom` takes the rom, like its IGDB and ScreenScraper
siblings, and the product-id lookup now happens only on Switch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 17:26:19 -04:00
Georges-Antoine Assi
c96c20a033 fix(metadata): resolve Switch DLC ids to the base game before titledb
`_switch_productid_format` zeroed one nibble, which clears an update's
0x800 bitmask but leaves DLC's addon index in the low 12 bits. Only the
base application has a titledb entry, so a DLC filename resolved to
nothing.

It now calls `derive_base_title_id`, the rule the scan already uses, so
both paths normalize an id the same way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 17:26:18 -04:00
Georges-Antoine Assi
d344faca4c style(steam): trim docstrings and narrow await_args in tests
Cut the prose that restated the code: the 0115 header now matches 0114's
one-line form, and get_app_details/get_library_capsule_url keep a summary
plus the one fact the code can't convey.

Bind await_args before reading it, so a never-awaited mock fails the
assertion instead of raising AttributeError.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 19:28:23 -04:00
Georges-Antoine Assi
2c98488951 refactor(steam): move the CDN probe into the adapter, trim the heartbeat
The portrait-capsule HEAD request was the one Steam call living outside
SteamService, with its own session, user-agent and timeout. It moves in as
get_library_capsule_url, following LibretroThumbnailsService.head, so the
handler just picks the capsule or falls back to the header image.

get_app_details grows a filters passthrough, and the heartbeat asks for
"basic" instead of pulling a whole store page to read one success flag.

Guard the facet mirror against a provider that reaches the model but not a
migration's trigger column list: test_every_provider_id_is_mirrored writes
every METADATA_SOURCE_COLUMNS id and asserts each roms_facets twin follows.
Verified against triggers rebuilt without steam_id, where it fails naming
the missing provider.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 19:20:14 -04:00
Georges-Antoine Assi
a7a15754b0 Merge remote-tracking branch 'origin/master' into claude/steam-metadata-provider
# Conflicts:
#	backend/config/__init__.py
#	backend/config/config_manager.py
#	backend/endpoints/heartbeat.py
#	backend/endpoints/responses/heartbeat.py
#	backend/endpoints/responses/rom.py
#	backend/endpoints/roms/__init__.py
#	backend/handler/database/roms_handler.py
#	backend/handler/metadata/__init__.py
#	backend/handler/scan_handler.py
#	backend/models/rom.py
#	backend/tasks/scheduled/scan_library.py
#	backend/watcher.py
#	env.template
#	frontend/src/__generated__/models/Body_update_rom_api_roms__id__put.ts
#	frontend/src/__generated__/models/DetailedRomSchema.ts
#	frontend/src/__generated__/models/MetadataSourcesDict.ts
#	frontend/src/__generated__/models/SimpleRomSchema.ts
#	frontend/src/locales/bg_BG/settings.json
#	frontend/src/locales/cs_CZ/settings.json
#	frontend/src/locales/de_DE/settings.json
#	frontend/src/locales/en_GB/settings.json
#	frontend/src/locales/en_US/settings.json
#	frontend/src/locales/es_ES/settings.json
#	frontend/src/locales/fr_FR/settings.json
#	frontend/src/locales/hu_HU/settings.json
#	frontend/src/locales/it_IT/settings.json
#	frontend/src/locales/ja_JP/settings.json
#	frontend/src/locales/ko_KR/settings.json
#	frontend/src/locales/pl_PL/settings.json
#	frontend/src/locales/pt_BR/settings.json
#	frontend/src/locales/ro_RO/settings.json
#	frontend/src/locales/ru_RU/settings.json
#	frontend/src/locales/tr_TR/settings.json
#	frontend/src/locales/zh_CN/settings.json
#	frontend/src/locales/zh_TW/settings.json
#	frontend/src/services/api/rom.ts
#	frontend/src/stores/heartbeat.ts
#	frontend/src/v2/components/EditRom/MetadataIdSection.vue
#	frontend/src/v2/components/GameDetails/RelatedGameCard.vue
#	frontend/src/v2/components/GameDetails/providers.ts
#	frontend/src/v2/components/Scan/ScanInfoDialog.vue
#	frontend/src/v2/utils/metadataProviders.ts
#	frontend/src/v2/views/Settings/ScanSettings.vue
2026-09-01 16:49:24 -04:00
Georges-Antoine Assi
45c8a1057f fix(metadata): guard every scene id parse against the int() digit limit
CPython's int() raises past 4300 digits. The bare-digit branch of
scene_id_or_none already caught that, but the URL parsers, the filename
tag extractors and the Pouet 302 Location parser all called int() on an
unbounded (\d+) capture, so a pasted URL or a scanned filename carrying a
long digit run surfaced as a 500.

Promote pouet_handler's private _int_or_none to utils.int_or_none, next
to valid_youtube_id, and route every scene id conversion through it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 21:23:49 -04:00
Georges-Antoine Assi
afd8b1007d refactor(metadata): move scene_id_or_none into the metadata package
The helper lived in the roms endpoint and reached back into the three scene
handlers through deferred imports. handler.metadata already imports all three
eagerly, so it can own the helper outright and drop the workaround; the branch
chain over `kind` becomes a lookup table. Its test moves beside the other
metadata tests.

Also drop the issue references from the provider docstrings, the config
comments, and the outbound User-Agent headers, which now match the
`RomM/{version}` form the other handlers already send.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 20:59:11 -04:00
Georges-Antoine Assi
fe12b42eea refactor(metadata): merge the scene metadata migrations
0114 and 0115 were near-identical: both carried their own copy of the JSON
variant, the facets mirror lists, the MySQL/Postgres trigger builders, and
both rebuilt the roms_facets triggers. Fold them into one revision that adds
demozoo_id, pouet_id and csdb_id (plus their metadata blobs and indexes) and
rebuilds the triggers once.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 20:59:02 -04:00
Georges-Antoine Assi
5f7379938f fix(metadata): clear the standing mypy and test failures
format_credit_line took list[dict[str, str]], which the DemozooCredit and
PouetCredit TypedDicts are not assignable to. It reads two keys and
stringifies them, so it takes a Sequence[Mapping[str, object]].

Give the screenshot loop its own name: it reassigned the str the
external-links loop above had already bound.

Read the awaited URL through await_args_list, which is a list, rather
than await_args, which is None until the mock is called.

Point the untagged-ROM test at the invariant it can actually hold. An
untagged ROM falls back to a title search, which the next test covers, so
it now asserts a disabled handler stays off the network instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:48:56 -04:00
Georges-Antoine Assi
fc46c3eb1c Merge branch 'master' into feat/demozoo-pouet-phase0
Renumber the two migrations onto master's head: 0108/0109 collided with
0108_roms_primary_region and 0109_rom_files_category_index, leaving the
chain with two heads. They are now 0114 and 0115 behind 0113.

Both rebuild the roms_facets sync triggers from a hardcoded column list,
so add the publishers and developers columns 0112 introduced. Without
them the rebuilt triggers would have silently stopped mirroring the two.

Adopt master's provider taxonomy. METADATA_PROVIDER_GROUPS now carries
demozoo, pouet, and csdb as catalogs, which replaces the branch's own
GENERAL_PROVIDER_KEYS set and feeds the setup wizard, the scan dialog,
and Settings from one registry. CSDb reaches the scan explainer for the
first time; it was already selectable there.

Regenerate the frontend types: DetailedRomSchema was missing the three
metadata blobs the backend has always declared on RomSchema, and the
blobs are now typed rather than Record<string, unknown>.

Correct the setup strings that still called the three sources enabled by
default, and sort the locale keys.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:32:11 -04:00
Georges-Antoine Assi
f353f3c1fe fix(metadata): cap every provider read and validate embedded video ids
Move the response cap onto MetadataHandler as _fetch_capped and route
Demozoo, Pouet, and CSDb through it. Only CSDb was capped before, while
Demozoo and Pouet read an unbounded body into memory before decoding it.
Pouet's title search now streams too: an ambiguous title answers 200 with
HTML we never parse, but the body was still being buffered.

Validate youtube_video_id where it is read rather than where Demozoo
parses it. The four metadata blobs it reads from are writable through the
raw_*_metadata form fields, so the id reaching the embed URL never had to
come from a provider, and IGDB and LaunchBox never checked it at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:15:50 -04:00
Georges-Antoine Assi
1ae540004a refactor(metadata): tidy the scene hardening pass
Accumulate the capped CSDb read in a bytearray, dropping the separate
chunk list and byte counter.

Move the non-string coercion into http_url() so all five call sites can
pass a raw JSON value.

Prove the cap abandons a body mid-stream: the oversized response is now
an endless generator, so the test hangs if the read is not cut short.
Stub the rate limiter it shares with the rest of the suite.

Collapse the duplicated demozoo_url cases into one parametrized test and
fold the malformed-XML assert into the existing parse test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:03:27 -04:00
Georges-Antoine Assi
c0d01c58ee fix(metadata): harden the scene metadata handlers
Security review follow-ups on the Demozoo, Pouet, and CSDb handlers.

Default the three sources to off, matching every other provider. They
were the only ones defaulting to on, so an upgrade began contacting
demozoo.org, pouet.net, and csdb.dk on the next scan with no operator
opt-in, reachable through the unauthenticated metadata heartbeat.

Guard the bare id conversion in scene_id_or_none. str.isdigit() accepts
superscripts and other digits int() rejects, so a pasted "²" raised out
of the Edit ROM endpoint as a 500.

Filter the remote demozoo_url through http_url(). It was the only one of
the three URL fields taking a string from the API rather than building
one from a hardcoded template and an integer id.

Match a YouTube id against an explicit ASCII class. isalnum() is
Unicode-aware, so it accepted ids the embed URL never can.

Stream the CSDb response against a byte budget. The cap ran after the
whole body was already buffered, so it bounded the parse but not memory.

Catch defusedxml's refusals. EntitiesForbidden derives from ValueError
and ParseError from SyntaxError, so the existing handler caught neither
and an entity-declaring document raised out of production_from_xml.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 20:49:14 -04:00
Sam Dornan
b2e3de4772 Merge branch 'master' into claude/steam-metadata-provider
Resolves the additive conflicts against master:

- config, handler registry and the roms endpoint imports keep both the
  Steam and the new UPC-lookup entries.
- Renumbers the Steam migration to 0113 (master took 0109) and rebases it
  onto 0112_publisher_developer_split.
- Syncs the migration's pre-Steam facet mirror list with 0112, which added
  publishers/developers to the roms_facets triggers.
- Groups SteamMetadata's publishers/developers with the shared provider
  keys, now that master has made them a shared field.
2026-08-29 16:36:58 -05:00
Georges-Antoine Assi
a7b580ade8 Merge pull request #4286 from sdornan/claude/github-issue-4285-164dcd
fix: restore HowLongToBeat lookups and repair endpoint discovery
2026-08-29 08:46:43 -04:00
Georges-Antoine Assi
2a7953ed58 refactor: share the HLTB search wire contract with endpoint discovery
The discovery script imported build_search_payload from hltb_handler, which
pulls in handler/metadata/__init__ and so instantiates every metadata handler,
opens Redis and writes a config file at import time. That import side effect is
why the workflow needed a dummy ROMM_BASE_PATH.

The script also hand-forked the rest of the protocol (base headers, the /init
mint, the session headers and the honeypot body merge), so it validated a
candidate route against a copy of what the handler sends rather than against
the real thing.

Move the contract into utils/hltb_search.py, a leaf module both sides import,
and drop ROMM_BASE_PATH from CI.

Pace failed session mints too: _ensure_session retried on every lookup, so a
down or IP-blocking HLTB cost each ROM in a scan its own rate-limited /init
round trip.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 08:31:14 -04:00
Sam Dornan
2be8cfcb4c Merge branch 'master' into claude/igdb-keywords-themes-perspectives
Master's #3898 landed the publisher/developer split, which this branch had
built its own narrower version of. Drop ours and rebuild on top of theirs:

- Delete 0113_company_role_columns; 0112_publisher_developer_split supersedes
  it and derives the roles from all seven providers rather than two.
- Renumber 0110/0111/0112 to 0113/0114/0115 behind master's new head.
- Carry generated_publishers/generated_developers through the view and facet
  trigger rebuilds in 0114/0115, which would otherwise drop them.
- Order 0115's view projections as 0114 leaves them: PostgreSQL rejects a
  CREATE OR REPLACE VIEW that renames an existing column.
- Take master's IGDB role extraction; extract_tokens already dedupes.
2026-08-27 18:55:58 -05:00
Georges-Antoine Assi
d62452b069 refactor: give the publisher/developer derivations one home
Follow-up cleanup on the company metadata split.

- Hasheous returns `involved_companies` keyed by id, not as the list IGDB
  itself returns, so iterating it yielded the dict's string keys and raised
  on `c.get("publisher")`. Read it through the same pydash accessor the
  sibling `companies` line uses, and cover both shapes with a test.
- ss/ra/flashpoint/gamelist bind the publisher and developer lists once and
  build `companies` from them, so the merged list cannot drift from the
  split it is meant to be the union of. Follows launchbox's existing shape.
- The exporters shared one copy of the "prefer the explicit field, fall back
  to the companies ordering" rule; it now lives on `RomMetadata` as
  `primary_developer` / `primary_publisher`.
- Migration 0112 gates its two backfills on a probe. No stored blob carries
  the new keys before a re-scan, so they otherwise scan the whole roms table
  twice, and rewrite every roms_facets row, to write nothing.
- Smart collections no longer claim a `selected_publisher` legacy key that
  never shipped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 18:38:02 -04:00
Sam Dornan
75fcb8582c test: mint and search the same HLTB endpoint in the lazy-mint tests
The lazy-mint tests POSTed to a hard-coded /api/search/site while the handler
still defaulted search_url to /api/find, so the mint and the search addressed
unrelated endpoints and the tests would have passed with the two out of sync.

Handlers under test are now built pointed at one endpoint, requests go to
handler.search_url, and the mint is asserted against f"{search_url}/init" rather
than against search_init_url, which the mint reads and so can never contradict.

Stops naming /api/bleed throughout the file as well, since this branch is what
makes that endpoint dead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 14:44:25 -05:00
Sam Dornan
d975aa8bc3 fix: restore HowLongToBeat lookups and repair endpoint discovery
HLTB lookups have returned nothing since HLTB rotated their search endpoint.
The published fixture still pointed at /api/bleed, which now 404s on both GET
and POST, and the handler fetches that fixture from master at every startup, so
every install was affected regardless of image version. The live endpoint is
/api/search/site, with the session mint at /api/search/site/init, which the
handler already derives as f"{search_url}/init".

The automation meant to keep the fixture current could not have fixed this on
its own. It only ran on workflow_dispatch, so it never ran unprompted, and HLTB
has since migrated to Turbopack: the homepage no longer serves a pages-router
_app chunk, so both app-chunk regexes matched nothing. The endpoint is also a
plain literal in the bundle now rather than the .concat() obfuscation the token
regex expected.

Discovery now reads _buildManifest.js, where Next.js lists every route as a
plain literal, and selects the route that has an /init sibling, the same pairing
HLTBHandler assumes. That rule uniquely picks /api/search/site out of the 90 API
routes in the manifest, and rejects near misses such as /api/forum/search. Each
candidate then has to mint a real session before the fixture is written, so a
dead URL cannot be published again.

A failed startup was also permanent and silent: _request() returned early
whenever there was no session and nothing re-minted one, so a container that
lost the mint at boot served no HLTB metadata for its whole lifetime with no
error after the startup warning. Failures are now logged, and lookups mint
lazily behind a lock so a scan's concurrent lookups do not each hit /init.

Fixes #4285

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 14:19:31 -05:00
Sam Dornan
6a8cb34645 feat(steam): add the Steam storefront as a metadata provider
Steam covers the PC platforms RomM otherwise has thin metadata for, and
its store payload is provider-grade on its own: title, description,
portrait capsule art, screenshots, genres, developers, publishers,
release date and Metacritic score, with no API key.

Valve documents no storefront API, so this reads the two endpoints that
back the store's own search box and app pages, paced well under the ~200
requests per 5 minutes they tolerate. Every failure path degrades to "no
match" rather than aborting a scan, and the provider is opt-in behind
STEAM_API_ENABLED, matching HowLongToBeat and Flashpoint.

Matching is gated on the platform slug so the three PC platforms are the
only ones that spend a request. The storefront's search index carries
DLC, soundtracks and tools alongside games, so hits are filtered by type
and then confirmed against the app page, which is the only place a demo
or a video is distinguishable from a game. A (steam-12345) filename tag
pins a match by hand when the title is ambiguous.

SteamMetadata reuses the key names the other providers already use for
the values they share, so wiring Steam into the generated facet columns
later is a SQL change with no stored-row reshaping.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-22 13:35:42 -05:00
Sam Dornan
b65ff57ce6 fix(backend): satisfy mypy and bandit on the new tests and tools
Four findings trunk reports on files this branch adds, none of which CI
tolerates.

`_make_game` claimed `dict`, so passing it to `extract_metadata_from_igdb_rom`
(which takes `Game`) was an arg-type error. It builds a real `Game` now.
`Game` is `total=False` over a base that requires `id`, so the three keys the
factory set to `None` are simply absent instead: every reader goes through
`.get()`, which cannot tell the two apart. `alternative_names` and
`game_localizations` need their element type spelled out, because mypy will not
push a union context into a dict literal.

`series_keys` takes a `Rom` and the diversity tests pass a stand-in, for the
reason the module docstring gives. Cast at the one call that reaches a
`Rom`-typed signature rather than grow the fake a database row's worth of
attributes.

`backfill_igdb_tags` reads fields named by a loop variable, which a TypedDict
answers as `object`. It reads through a plain-mapping view instead.

Bandit read `token == "--report"` as a hardcoded password on the strength of
the variable's name. Renamed, rather than suppressed.
2026-08-22 10:15:30 -05:00
Sam Dornan
704959b624 Merge branch 'master' into claude/igdb-keywords-themes-perspectives
Three text conflicts and one alembic head collision that git merged clean.

Master added a Ports section to the overview tab and i18n-ified the related
headings; this branch replaced the IGDB "Similar games" section with the
recommendations index. Both survive: Ports keeps its RelatedGamesGrid, and
Similar games keeps SimilarGamesGrid behind the recommendations toggle.
`rom.related-similar-games` was master's key for the section this branch
replaces, so it goes with it; `recommendations.similar-games` is its home now.

Both sides added OverviewTab.test.ts. The two suites now share one mount
helper.

Master's 0108_roms_primary_region and this branch's 0108_rom_similarity both
revised 0107, which alembic reads as two heads. This branch's four migrations
move to 0109 to 0112 behind master's. Verified up, down and up again on
MariaDB, including down past master's 0108: the generated region column, the
five new facet columns, rom_similarity and the widened sibling-cover index all
survive the round trip.
2026-08-22 10:08:05 -05:00
Georges-Antoine Assi
9e6337ec12 Merge pull request #4243 from rommapp/claude/ss-dev-credentials-banner
feat(metadata): warn when ScreenScraper dev credentials are missing
2026-08-19 15:32:04 -04:00
Georges-Antoine Assi
6a8d34bcad Merge pull request #4242 from sdornan/claude/fervent-noyce-aba3ea
test: fix flaky LaunchBox release date property test (DST fold)
2026-08-19 15:06:36 -04:00
Georges-Antoine Assi
24743b03d8 feat(metadata): warn when ScreenScraper dev credentials are missing
Developer credentials are injected at build time, so a build made
outside our CI (packaged from source, e.g. nixpkgs) has none and
ScreenScraper refuses every request whatever the user account is.

The heartbeat now reports whether they are set, and the v2 metadata
sources page shows a warning banner naming the two environment
variables to set.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 14:45:31 -04:00
Georges-Antoine Assi
edff89f913 Merge pull request #4239 from sdornan/claude/filename-underscores-scraping-513712
Match LaunchBox dumps that separate words with underscores
2026-08-19 14:43:15 -04:00
Sam Dornan
323d7e9879 test: pin a DST timezone in the ambiguous release date test
CI runs with TZ unset, so no local time is ambiguous and both folds of
1981-10-25T01:00 named the same instant. The assertion held trivially and
would not have caught a regression in first-occurrence handling.

Pin America/New_York for the duration of the test, since a naive
datetime.timestamp() reads the process timezone, and assert the two folds
really are an hour apart so the test fails loudly instead of going vacuous
if that ever stops holding.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 10:32:37 -05:00
Sam Dornan
1c907c1557 test: fix flaky LaunchBox release date property test
st.datetimes() generates naive datetimes with fold=1 (the second
occurrence of an ambiguous local time on a DST fall-back day), which made
test_valid_iso_dates_parse_to_timestamp unsatisfiable: datetime.isoformat()
omits fold, so both occurrences reach parse_release_date as the same
string, while dt.timestamp() honours fold. The two sides then differ by
the DST offset.

Constrain the strategy to fold=0. This loses no coverage, since every
fold=1 value maps onto its fold=0 twin that the strategy already
generates, and it matches what fromisoformat returns for a string with no
fold information. Also add a deterministic test pinning the behaviour:
both folds serialize to the same ISO string, and the parser resolves it to
the first occurrence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 10:26:11 -05:00
Sam Dornan
1cd29d7285 Match LaunchBox dumps that separate words with underscores
The LaunchBox name lookup rewrites a search term before hitting the
metadata index: " - " becomes ": ", and a trailing article is moved back
to the front. Both rewrites are anchored on literal spaces, so a dump
named with underscores reaches neither, and the folded fallback cannot
recover it either because the article is left in the wrong position.

Legend_of_Zelda,_The_-_A_Link_to_the_Past.smc missed every index stage
while its space-separated equivalent matched. Swap underscores for
spaces before the rewrites so both forms resolve to the same term.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 07:45:05 -05:00
Sam Dornan
808745e7ae fix(hltb): don't mistake markup or a redirect for a rewritten page
Two ways the 502 could fire on a page RomM can still read:

The hydration tag was matched by exact attribute order, so a CSP nonce or a
reordered attribute would have been reported as a rewrite. The id alone
identifies it.

`raise_for_status` lets a 3xx through, so a hop HLTB added later would reach
the parser as a page with no payload. Redirects are now followed; the client
validates every hop against SSRF, redirects included.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-18 20:38:33 -05:00
Sam Dornan
03fe992101 fix(hltb): map every transport failure on the game page to 503
`ConnectTimeout` is the likely failure when HLTB is slow or unreachable, and
it is not a subclass of `ConnectError`, so it escaped `update_rom` as a bare
500 rather than the actionable 503 the other providers give.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-18 20:30:28 -05:00
Sam Dornan
e7440a2dfc fix(hltb): fetch metadata when a HowLongToBeat ID is set by hand
`update_rom` fetches from every metadata provider whose ID changed, except
HLTB, which had no by-ID lookup at all. A hand-entered ID was stored and the
How Long to Beat tab stayed empty.

HLTB's API only exposes search, so `get_rom_by_id` reads the record from the
`__NEXT_DATA__` payload the game page already ships. The canonical
`/game/{id}` path is requested directly, as `/game?id=` answers with a
redirect the shared httpx client does not follow, and the game page dates a
release in full where search returns just the year.

A page RomM can no longer read raises 502 naming the cause instead of
reporting a game with no times, since that failure is otherwise
indistinguishable from the bug this fixes.

Fixes #2926

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-18 20:19:26 -05:00
Georges-Antoine Assi
7de0beb128 Merge pull request #4228 from TowyTowy/fix/ss-switch-fallback-manual-url
fix(ss): don't use the Switch icon URL as the manual URL
2026-08-18 19:20:59 -04:00