Commit Graph

74 Commits

Author SHA1 Message Date
zurdi
fc8cfbc6f1 feat(scan): add a files scan that reconciles rom folders incrementally
Files added to an already-scanned folder ROM could only be picked up by a
complete or hashes rescan, which rehash every known file. The new `files`
scan type scans new games like quick and re-lists the files of existing
folder ROMs, hashing only new or changed files and recomputing the
ROM-level hashes only when a top-level file changed. Per-rom update and
unmatched scans reuse the same incremental mode, and the filesystem watcher
enqueues it instead of quick.

Also stores rom_files.last_modified as Double (MariaDB FLOAT rounds a
current mtime to about 128 seconds), adds the CHEAT value missing from the
PostgreSQL category enum, maps `patches/` to the patch category and
excludes upload temp files from scans.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017WbesTQXohyAWWcLV5iiEN
2026-09-03 17:11:03 -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
9588287984 Merge pull request #4305 from rommapp/refactor/rom-ids-scope-assets
refactor(assets): make rom_ids the only ROM scope on saves and states
2026-08-29 17:50:23 -04:00
Georges-Antoine Assi
b75c499d8b refactor(assets): make rom_ids the only ROM scope on saves and states
The saves handler carried two ROM filters that ANDed together, and the states
handler had only the singular one, so the same "which ROMs" question had three
answers across two sibling handlers. Collapse both onto rom_ids: a single-ROM
lookup is just a one-element scope, which is what the three internal callers in
the saves endpoint now pass.

That leaves the routes to fold their own public rom_id param into the scope.
Rather than write the fold twice, narrow_rom_id_scope joins utils/validation
beside RomIdScope, keeping the documented "combined with rom_id" semantics: both
filters still apply together, so the effective scope is their intersection.

GET /api/states gains the rom_ids param GET /api/saves got in #4304, declared
with the same shared RomIdScope, so a client syncing a known set of ROMs can
discover states the same way it discovers saves, under the same cap and the same
422 on a bad scope.

One behaviour shift falls out of the handler's old falsy check: rom_id=0 used to
be ignored and return the whole library, and now scopes to nothing, which is
what RomIdScope's positive-ID rule says a zero means.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 17:38:08 -04:00
Georges-Antoine Assi
c0ab254c59 Merge pull request #4077 from Spinnich/fix/missing-firmware-cleanup
feat(firmware): let missing firmware be found, cleaned up, and kept out of the player
2026-08-29 17:04:23 -04:00
Georges-Antoine Assi
cffe65971e refactor(saves): take rom_ids as a repeated query param
Comma-separated ID params in this codebase are a download-route convention
(/roms/download, and the two file_ids params), built by hand for URLs the
browser navigates to. Every JSON API route that takes a list of IDs repeats
the parameter instead, and roms' platform_ids documents that form explicitly.
GET /api/saves is a JSON route, so it should match those.

Declare the scope once as a shared RomIdScope annotation: the cap and the
positive-ID rule become schema constraints that both routes enforce alike and
that now appear in the OpenAPI schema as maxItems and exclusiveMinimum, so
clients can read the limits instead of discovering them from an error. That
drops the hand-rolled parser and the two validation-to-HTTPException
translations; a bad scope is a 422 on both routes.

One semantic change: the query param can no longer express an explicit empty
scope, since an omitted parameter is the only empty form. Negotiate keeps it,
as a JSON body can still send [].

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 16:24:45 -04:00
Georges-Antoine Assi
65819d15b4 refactor(saves): move the rom_ids validators to utils/validation
The scope validator and its cap were sitting in the saves DB handler, which
made two endpoints the first non-test callers to import a behavioral symbol
straight through the handler.database facade, for a helper with no DB content
and that get_saves never calls. They belong beside the repo's other
endpoint-facing validators.

Fold the comma-separated ID parse into a shared parse_comma_separated_ids so
the "comma-separated integers" message the tests assert on has one home, and
call it from the ROM download route that already had it inline. Both scope
validators now raise ValidationError like the rest of the module, which lets
negotiate validate in the endpoint body next to its other request-shape
checks: the two routes reject a bad scope with the same 400 instead of one
returning 400 and the other 422.

Also narrow the sync-record lookup to the newest row per slot (superseded rows
were fetched and discarded), and share one second_rom / second_save fixture
instead of three near-identical builders across the new tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 16:09:51 -04:00
Georges-Antoine Assi
841a7a2f9f fix(settings): scope a cleanup to every selected platform
The cleanup tasks took a single platform_id while both Missing tabs
offer a multi-select, so picking two platforms ran the unscoped
cleanup over the whole library. The confirmation dialog still named
the selection, so the tab deleted more than it said it would.

Take platform_ids on both cleanup tasks and filter firmware by the
whole list, so what runs matches what the dialog names.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 15:56:56 -04:00
Georges-Antoine Assi
e36d7646b2 feat(saves): scope save discovery to a set of ROM IDs
Sync clients that hold a subset of the library had no bounded way to ask
for the saves relevant to the ROMs on the device: `GET /api/saves` filters
one ROM at a time, and negotiation always evaluated the user's whole
slotted save set, offering downloads for ROMs the device cannot play.

Add a `rom_ids` scope to both. `GET /api/saves` takes a comma-separated
list (matching the `/roms/download` convention) and `POST /api/sync/negotiate`
takes a list in the request body, so a client with many ROMs is not bound by
URL length. Negotiation widens the scope with the ROMs the client sent saves
for, so a client save is never misread as an upload because its ROM was
omitted. The scope is read-only: an omitted ROM is outside the request, never
a deletion signal.

Both share one limit and one validation rule in the saves handler, and both
reject a scope that is non-positive or over the cap rather than truncating.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 15:44:44 -04:00
Georges-Antoine Assi
e32c8c68cd refactor(firmware): reuse shared helpers in the missing firmware code
Swap the hand-rolled platform picker in MissingFirmwareSection for the
shared PlatformSelect, and fold the triplicated firmware builder in the
tests into an add_firmware factory fixture.

Keep Platform out of list_firmware: the relationship is lazy="joined",
so every row also ran Platform's rom_count and fs_size_bytes aggregate
subqueries over roms, for data no caller reads.

In useTaskCompletion, the resolver already identifies the live wait, so
drop the parallel generation counter and the unused cancel export.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 15:42:22 -04:00
Georges-Antoine Assi
c45587fe7c Merge remote-tracking branch 'origin/master' into fix/missing-firmware-cleanup
# Conflicts:
#	frontend/src/locales/pt_BR/settings.json
#	frontend/src/v2/views/Player/EmulatorJS.vue
2026-08-29 15:18:00 -04:00
Georges-Antoine Assi
42ebaaec49 feat: split company metadata into publishers and developers
Metadata providers (ScreenScraper, RetroAchievements, LaunchBox,
Flashpoint, gamelist, IGDB) distinguish the publisher from the developer
of a game, but RomM amalgamated both into a single `companies` list at
ingestion, so the distinction was unrecoverable. This adds `publishers`
and `developers` as new, refined fields end to end while keeping
`companies` (the merged union) working exactly as before.

Backend:
- Handlers now emit publishers/developers alongside the unchanged
  companies list; IGDB requests the involved_companies developer/
  publisher flags to split by role.
- Migration 0112 adds generated_publishers/generated_developers columns
  on roms, projects them through the roms_metadata view, mirrors them
  into roms_facets, and adds publisher/developer virtual-collection
  types (triggers/functions rebuilt for MariaDB/MySQL + PostgreSQL).
- Filters, facets, endpoints, smart collections and the gamelist/pegasus
  exporters all carry the new fields; exporters prefer the explicit
  split and fall back to the companies heuristic for un-rescanned ROMs.

Frontend (v2):
- Shared filter store + API service, gallery filter drawer, URL
  persistence, game detail display (Developers/Publishers with a
  Companies fallback), edit dialog, smart-collection criteria, and a
  publisher/developer "group virtual collections by" option.
- Also relabels the confusing "company"->"Developer" group-by option
  to "Company" now that a proper Developer option exists.

Fixes #3518

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-27 14:44:30 -04:00
Sam Dornan
5c43a97687 feat(gallery): pick a game's default version by region priority
The group_by_meta_id dedup window ordered each sibling group by
is_main_sibling then fs_name_no_ext, so absent a manual override the
gallery entry went to whichever filename sorted first: "(Demo)" beat
"(Europe)" beat "(USA)".

Two ordering terms now sit between those: a full release outranks a
pre-release, then the configured scan.priority.region order decides.
Release status comes first because a demo is not a substitute for the
game, so a Japanese release wins over a USA demo.

scan.priority.region already existed but only steered metadata and
artwork selection, so its description is reworded across all locales.

Regions live in a JSON column that no covering index can carry, and 0107
measured what one uncovered reference costs this window: the plan drops
from `type=index, Using index` to `type=ALL, key=NULL`, four times per
gallery page load. 0108 adds a STORED generated column over regions[0]
and covers it in idx_roms_sibling_cover instead, so the ranking reads a
scalar. The engine keeps it in sync and ALTER TABLE populates existing
rows, so no scan hook and no backfill are needed.

Pre-release detection matches the filename rather than the parsed `tags`
column: tags keep the dumper's casing, and fs_name_no_ext is already in
the index.

Reordering the priority list changes which rom represents a group, so the
cached gallery sidecars are dropped when the setting changes.

Closes #1528

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 11:55:07 -05:00
Sam Dornan
f22aadf77a fix(scan): re-read filename tags on a complete rescan
A rom parsed its filename tags when it was first inserted and never again,
so a change to parse_tags only reached rows scanned after it. The freshly
parsed values were built for every rom but only consumed on the insert
path, and scan_rom reseeded the tag columns from the existing row, so no
scan type could refresh them.

A complete rescan (or an explicit per-rom selection) now writes them back.
A hashes rescan still doesn't, since it is scoped to re-reading file bytes.

scan_rom also carries "version" forward now. It was the one tag column
missing from its attrs, so a re-parsed version would have been dropped, as
the value written by the reassociation path already was.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 21:38:12 -05:00
Spinnich
6f167afeb8 perf(roms): sort metadata fields on the indexed roms column
Ordering the gallery by a `roms_metadata` field joined the view back in and
sorted through it. `roms_metadata` is a thin view over STORED generated
columns on `roms` (migration 0098), so that join is `roms` to itself and it
leaves the sort key on a joined table, which no index can serve: the engine
filesorts the whole library for every page.

The generated columns are already indexed, so the three that are offered as
sorts now resolve straight to them and the join goes away. On a 120k-row
table this turns a full scan plus filesort into a 72-row index walk.

The remaining view columns are JSON arrays with no index and no sort that
offers them, so they keep reading the view.

Fixes #4067

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 02:03:48 +00:00
Spinnich
3e02fb94ff fix(firmware): let missing firmware be found and cleaned up
A scan flags firmware whose file vanished, but nothing could act on the
flag: stale BIOS entries could only be found by opening each platform's
Firmware tab one at a time, the player still offered them (auto-selecting
the sole entry, so the game failed to boot with nothing pointing at the
BIOS), and platform firmware counts included them.

Adds a `missing` filter to the firmware list endpoint, a
`cleanup_missing_firmware` manual task alongside the ROM one, and a
Missing firmware tab in Library management that lists every flagged entry
library-wide with a bulk cleanup. The player now asks for present
firmware only, and firmware selection moved to a `playerFirmware` util
that never picks a missing entry. `firmware_count` counts only firmware
present on disk; the rows themselves still ship so the Firmware tab can
strike them through.

`FirmwareSchema` gains `platform_id` so the library-wide list can group
by platform.

Fixes #4075

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 23:52:21 +00:00
Georges-Antoine Assi
79a8322470 Merge pull request #4060 from rommapp/fix/hasheous-mameredump-verified
fix(hasheous): read the CHD and DOS signature sources
2026-08-01 19:48:56 -04:00
Georges-Antoine Assi
509e4d156d fix(hasheous): keep unverified ROMs that predate a match key
`hasheous_metadata` gains keys as RomM maps more of Hasheous' signature
sources, so rows written before `mame_redump_match` existed don't carry it.
On PostgreSQL `hasheous_metadata->>'mame_redump_match'` is then NULL, the OR
chain over the match flags evaluates to NULL instead of false, and `NOT (...)`
stays NULL: the unverified filter returned nothing for those rows until they
were rescanned.

Each extraction is now coalesced to false. The JSON path is untouched, since
SQLAlchemy compiles `as_boolean()` to a CASE whose ELSE branch already folds a
missing key into false.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 19:31:32 -04:00
Georges-Antoine Assi
f020354e74 Merge pull request #4054 from Spinnich/perf/gallery-dedup-cover-index
perf(roms): extend the sibling covering index to cover the ROM grouping query
2026-08-01 17:51:37 -04:00
Spinnich
1de87ad77b test(roms): guard the dedup window's index coverage
The bug 0107 fixes was silent: the window grew two columns the index never
followed, and nothing failed. Pin the shape the migrations build, and assert the
window reads only columns that index covers, so the next metadata provider added
to the COALESCE chain fails here instead of quietly restoring the full scan.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 20:10:48 +00:00
Georges-Antoine Assi
e464ce765a test(collections): resolve hash smart collections through the gallery query
The hash search tests reached membership through
`get_smart_collection_roms`, which no longer exists now that a smart
collection is served as a composed query. Ask for the collection the way
the gallery does instead, so the criterion is still exercised end to end.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 15:08:42 -04:00
Georges-Antoine Assi
33d68c32a5 Merge branch 'master' into perf/smart-collection-gallery-query 2026-08-01 15:02:58 -04:00
Georges-Antoine Assi
c951b6eb46 some clenaup 2026-08-01 14:49:58 -04:00
Spinnich
7399c19479 fix(collections): refresh smart collections on per-user state changes
Removing the read-time recompute left the cached membership blind to
everything that is not a ROM edit. A save, a state, a status, or moving
a ROM in or out of a regular collection all change what `has_saves`,
`has_states`, `statuses`, `collection_id` and `favorite` match, so the
stored counts, covers and ROM-detail chips went stale until an unrelated
edit or the next scan.

Refresh from those paths too: save and state upload, delete and
visibility toggle, `update_rom_user` when a status is set, and adding or
removing collection members. Sharing an asset is included because
`has_saves` matches other users' public saves, so it moves collections
that are not the uploader's.

These changes leave the ROM row alone, so they pass `membership_only`
and only recount a collection when the ROM actually joined or left.
Autosaves land constantly, and without it every one of them would force
a full recount of any collection the ROM already belonged to.

Reported by Greptile on #4039.

Implemented with Claude Code (Opus 5), tests first, then reviewed and
verified by me.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 22:18:53 +00:00
Spinnich
b5d276e2ed fix(collections): refresh smart collections per ROM, not per request
Recomputing every smart collection after a delete scanned the library
once per collection, synchronously on the event loop and inside a single
write transaction. Ask instead which of the changed ids each collection
matches: that resolves as a primary-key lookup, so only the collections
actually holding one of them pay for a recount.

Follow the same refresh into `update_rom` and the metadata reset. Both
change exactly the fields the saved filters match on, so cached counts
and cover mosaics no longer wait for the next scan to catch up.

Guard every call site. The ROM write is already committed by the time
the refresh runs, so a failure there must not be reported back as a
failed edit, and must not cost a bulk delete its per-ROM report.

Drop the handler-level test for leaving a collection untouched on read;
the endpoint test covers that invariant through the route the bug was
reported against.

Follow-up review of f4ac78c46 (#4029). Implemented with Claude Code
(Opus 5), then reviewed and verified by me.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 21:11:11 +00:00
Spinnich
f4ac78c46b perf(collections): serve smart collections from a composed query
A smart collection re-ran its filters across the whole library on every
request, loaded every match into memory with its joined metadata, wrote
the membership back, and only then asked for the page being displayed.
The cost tracked library size rather than collection size, was paid twice
on first load and again on every scroll, and the write bumped updated_at,
which the covers embed as a ?ts= cache-buster.

Translate the stored filter_criteria into filter_roms keyword arguments
and apply them to a bare Rom.id select instead, so membership stays in
SQL and the database returns just the rows being rendered. The criteria
vocabulary is filter_roms' own, so this composes with the gallery's
filters. smart_collection_id is dropped from the criteria: the v2 create
dialog records the route it was opened from, so a collection built while
viewing another one carries its id, which would nest and could cycle.

Bind parameters for the MATCH clauses are now named after the term they
carry. A statement can hold two of them (the collection's search term and
the gallery's), and SQLAlchemy does not uniquify explicitly named text()
parameters, so a fixed name let one term overwrite the other.

The cached rom_ids / rom_count / path_covers_* columns still back the
collections list and the ROM detail page, so refresh them on write --
smart collection create and update, after a scan, and after ROMs are
deleted -- rather than as a side effect of browsing. They are computed
for the owner: the row is shared, so a per-user criterion like favorite
would otherwise describe whoever opened the collection last.

Regular collections and the favorites filter get the smaller half of the
same treatment: an indexed subquery over collections_roms instead of an
IN list built in Python. An unknown collection or smart collection now
returns nothing rather than falling through to the entire library.

Fixes #4029

AI assistance: implemented with Claude Code (Opus 5), tests first, then
reviewed and verified by me.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 20:23:31 +00:00
Spinnich
b1ee3a9f6e fix(roms): search the gallery by CRC32, MD5, SHA-1 and RA hash
The search box offered "name, filename, hash", but the term only ever
reached roms.name and roms.fs_name. A term that is hex of exactly a
digest length now also matches the hash columns on roms and rom_files,
the latter being what makes multi-disc games findable by a file's hash.

The two sides are unioned rather than OR'd. No engine merges a full-text
index with a B-tree index, so OR-ing them costs the name side its index
and scans roms end to end (3.306s against 0.005s on 300k rows). Neither
table had an index on any hash column, so 0106 adds them.

Fixes #4008

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 18:49:28 +00:00
Georges-Antoine Assi
56a57da11e fix(backend): tolerate calendar-invalid gamelist dates on PostgreSQL
The gamelist branch of generated_first_release_date is gated on an
8-digits/T/6-digits regex, which does not prove the digits form a real
date. EmulationStation, ES-DE and Skyscraper write "00000000T000000" for
an unknown release date, and make_timestamp raises on it. Because the
column is STORED, that aborts the 0098 ALTER TABLE on upgrade, and any
later INSERT of such a ROM on installs already past 0098.

romm_gamelist_epoch_ms now traps the error and returns NULL, matching the
range guard the MariaDB branch already applied. 0105 replaces the
function in place for installs that have already run 0098.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 21:03:54 -04:00
Spinnich
0526ded376 test(roms): drop the tautological index assertion
Asserting the model declares the index only restates `models/rom.py`. The
migration test covers what matters: the index exists in a database the
migrations built. Also pin the predicate test to the literal it compiles
to, so an unrelated `IS NOT NULL` elsewhere in the query cannot fail it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 14:24:21 +00:00
Spinnich
fdb000576a perf(roms): stop the Missing tab scanning the whole library
Settings -> Library Management -> Missing made three whole-library passes
per request, two of which produced data the page never renders, and none
of which could be cached because "missing" counts as a filter.

- The tab now opts out of the char index, the filter values and the
  ordered id index, so the endpoint serves its total from a plain COUNT.
- `missing_from_fs` gets a composite index with `name_sort_key`, and the
  filter compiles to an equality: MariaDB does not treat `IS NOT FALSE`
  as indexable, so the index would otherwise only ever be scanned end to
  end. The column is NOT NULL, so both forms match the same rows.
- The filter-value list is keyed on the scope (search / platform /
  collection) alone. It is built from a query that never applies the
  row-level filters, so a filtered request now answers with, and warms,
  the same whole-library entry an unfiltered one does.

Fixes #3992

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 12:13:03 +00:00
Georges-Antoine Assi
49d1ae71b2 Fix smart collections dropping newer filters
Smart collections silently ignored several filters at both ends:

- The backend never applied has_soundtrack, has_saves, has_states, or
  player_counts from stored criteria, so a "has soundtrack" smart
  collection contained every game. get_roms_scalar also dropped
  has_soundtrack before it reached filter_roms.
- The v2 criteria serializer had no fields for has_saves/has_states and
  only stored tri-state filters when true, so "unmatched" or "has
  saves" produced empty criteria and the no-filters guard blocked the
  save.

Criteria now carry saves/states filters and explicit false states, the
backend applies them, and summaries render negative states with the
existing "show-not-*" labels.

Fixes #3888

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-25 13:53:02 -04:00
Georges-Antoine Assi
e2827b9886 Merge branch 'master' into fix/server-stats-breakdown-perf 2026-07-23 15:50:08 -04:00
Spinnich
f69e4756a7 perf(stats): aggregate server-stats breakdowns from roms_facets
The Server Stats page ran two full scans of the multi-gigabyte `roms`
table on every visit: the metadata-coverage breakdown counted eleven
provider-id columns per platform, and the region breakdown pulled every
row's regions into Python. Both were returned in the same request as the
cheap summary counts, so the whole page stayed blank until they finished.

Mirror the provider match ids into the narrow `roms_facets` table
(migration 0102, kept in sync by the same triggers as the existing facet
columns) and read both breakdowns from it, so neither query touches
`roms`. Split the v2 Server Stats view into a summary-first request and a
separate breakdown request so the six top cards render immediately.

Fixes #3901

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 17:27:09 +00:00
Georges-Antoine Assi
a84ad2289d refactor(music): key playlists and favorites on rom_file_id
Rescans reconcile rom_files in place since #3900, so file ids survive a
rescan and no longer need routing around. Playlist and favorite entries
reference rom_file_id directly instead of (rom_id, md5_hash).

This drops the machinery the hash key required: soundtrack audio is no
longer force-hashed during scans (which overrode NON_HASHABLE_PLATFORMS
and SKIP_HASH_CALCULATION), soundtrack uploads no longer hash on write,
adding an unhashed track no longer returns 400, and the min(file id)
subquery that collapsed identical copies within a rom is gone. Two files
with the same content are now two independently addressable tracks.

A file that leaves the library takes its entries with it via the FK
cascade, rather than leaving a dangling entry that resurrects if the
content comes back.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 10:58:53 -04:00
Georges-Antoine Assi
8c5e3d8eae Merge branch 'master' into feature/music-playlists 2026-07-23 10:48:53 -04:00
Georges-Antoine Assi
1ee41f9a66 fix(scan): don't write NULL over NOT NULL columns when reconciling files
A scanned row leaves unset columns as None and the model defaults only
apply on insert, so the reconciliation path could write NULL into
file_size_bytes or has_embedded_cover. Unset values now leave the stored
value alone.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 10:08:01 -04:00
Georges-Antoine Assi
d9050eb4cc fix(scan): unlink soundtrack covers orphaned by dropped track metadata
A file that stopped carrying audio tags, or vanished from disk, had its
track_meta row dropped (directly or by cascade), leaving its persisted
cover on disk with nothing pointing at it.

sync_rom_files now reports those cover paths so the scan unlinks them,
keeping filesystem work out of the database handler.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 09:44:12 -04:00
Georges-Antoine Assi
83ad2b3132 fix(scan): reconcile rom_files in place instead of purging them
Rescans deleted and re-inserted every rom_files row, so file ids churned
on each scan and anything keyed on them (track metadata, persisted
soundtrack covers) was orphaned.

Rows are now matched by path first, then by content hash so a file
renamed or moved inside the ROM keeps its id, mirroring the ROM-level
reassociation. Only changed columns are written, vanished files are
deleted, and archive_members is carried over (the hand-written copy
dropped it).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 08:54:50 -04:00
nendo
70e583b9a0 Add music favorites and playlists API
Spotify-style library features for soundtrack tracks: per-user favorites
(liked songs) and user-owned playlists with manual ordering and optional
public read-only sharing.

Track references are stored as (rom_id, md5_hash) rather than rom_file_id:
scans purge and re-insert rom_files rows, so file ids churn while rom ids
and content hashes are stable. Entries survive rescans and renames, and
resolve to the current file at query time; entries whose content is gone
are omitted from listings until the file returns.

To make the content hash reliably present, soundtrack audio files are now
always hashed individually during scans (including NON_HASHABLE_PLATFORMS
and SKIP_HASH_CALCULATION, whose file-size concerns don't apply to audio),
and soundtrack uploads compute crc/md5/sha1 on write. Existing libraries
backfill via a HASHES scan; adding an unhashed track returns 400.

New playlists.read/playlists.write scopes are wired through the granular
permission system (PermEntity.PLAYLISTS); the migration mirrors every
group's collections grants onto the playlists entity so existing groups
keep working without admin intervention.

Endpoints under /api/music: favorites GET/POST/DELETE, is_favorite and
md5_hash on track rows, playlists CRUD, playlist tracks GET/POST/DELETE
and PUT /tracks/order.
2026-07-23 15:32:32 +09:00
Georges-Antoine Assi
15554f905e Merge branch 'master' into perf/materialize-virtual-collections 2026-07-22 20:17:16 -04:00
Georges-Antoine Assi
753556af7b perf(backend): materialize virtual collection membership
virtual_collections was a view that unnested five JSON arrays per rom on
every read, so both the collection list and opening a single collection
scanned the whole library. Opening a collection with a handful of roms
cost as much as one with thousands, since the name is computed inside the
view and nothing can be narrowed down early.

Membership now lives in virtual_collection_roms, one narrow row per
(type, name, rom_id) plus that rom's covers, derived from the generated_*
columns and maintained by triggers on roms (deletions ride the foreign
key cascade). The view becomes a plain aggregate over that table, so the
model, schemas and API shape are unchanged, and filtering roms by a
virtual collection is an indexed subquery instead of an IN list of every
member id.

Covers are no longer aggregated in the view, which materialized every
member's cover path on every request; the handler resolves at most five
per collection, matching the smart collection cap and what both UIs
render.

On a synthetic 50k-rom library the list goes from 1.42s to 0.128s and a
single collection from 0.111s to 0.0006s, with identical output.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 10:06:05 -04:00
Georges-Antoine Assi
6224c9e48c perf(backend): mirror ROM filter values into a narrow trigger-maintained table
Building the filter dropdowns aggregated the facet columns straight off
`roms`. Those columns are cheap to compute since #3826, but they sit inline
with the raw provider-metadata blobs, so the aggregation read every row of a
multi-gigabyte table: seconds of pure disk reading on any database whose
buffer pool is smaller than the table (the stock 128-256 MB defaults always
are on a large library).

`roms_facets` holds only the filter values and is kept in sync by AFTER
INSERT/UPDATE triggers on `roms`, so every write path stays consistent
without an application hook. Deletes ride the ON DELETE CASCADE foreign key.

Fixes #3882

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 10:05:07 -04:00
Spinnich
98e8ae7599 feat(platforms): add editable platform descriptions
Custom platforms could only be distinguished by name, which is often not
enough context (e.g. a "Sega - Genesis/Mega Drive (Unofficial)" folder
holding aftermarket and unlicensed dumps). Platforms now carry an
optional free-text description, mirroring collections.

The column is nullable and defaults to "", matching custom_name, so a
rescan (which merges a freshly scanned Platform over the existing row)
leaves it untouched. update_platform patches only the fields sent, so an
omitted description is preserved and an empty string clears it.

Surfaced in the v2 UI only: the Settings tab name form now covers both
custom_name and description, and PlatformHead renders the description as
a chip alongside the metadata chips. v1 is frozen and gets no new UI, but
round-trips the field unchanged through the shared API service.

Closes #3402

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 19:00:30 +00:00
Georges-Antoine Assi
aab49aefc8 Fix slot-less save upload DB/file desync (#3833)
A slot-less POST /api/saves behaves as a filename upsert, and two
details combined into silent save corruption.

1. get_save_by_filename only filtered by slot when one was passed, so a
   slot-less lookup could match (and overwrite) a save row living in a
   named slot. Scope slot=None to the null-slot save (Save.slot IS NULL)
   so a slot-less upload can never adopt a row from another slot.
   get_save_by_content_hash keeps its documented cross-slot slot=None
   behavior (dedup-only, non-destructive).

2. The upsert branch only wrote file_size_bytes and content_hash while
   the bytes landed under a path derived from the request's emulator, so
   the row's hash could disagree with the file it still pointed at. Also
   persist file_path/emulator, and remove the now-orphaned file when the
   row's location changes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 22:05:39 -04:00
Georges-Antoine Assi
dfac9dab2b perf(backend): make roms_metadata fast via generated columns
The roms_metadata VIEW re-derived its facet columns by JSON-parsing up to
eight raw provider-metadata blobs on every roms row, on every query, making
galleries, search, and sorts CPU-bound on large libraries.

Move the per-row derivation into STORED generated columns on roms (rm_*),
maintained automatically by the database engine (no application hook, no
background job). roms_metadata is redefined as a thin projection over them,
so the RomMetadata model, every handler query, and the virtual_collections
view are unchanged and inherit the speedup. Indexes on the release-date,
rating, and player-count columns back the corresponding sorts and filters.

On a 75k-row MariaDB library: release-date sort 1.15s -> 0.05s, facet-value
scan 3.35s -> 0.18s, player-count filter 0.54s -> 0.04s; virtual_collections
4.2s -> 1.3s. Generated columns match the old view byte-for-byte across all
rows except the quoted-string dates the old view silently truncated to 0.

Cross-engine correctness:
- MariaDB JSON_UNQUOTE before every numeric CAST avoids strict-mode INSERT
  truncation on quoted values.
- PostgreSQL to_timestamp()/jsonb_build_array() are only STABLE and illegal
  in generated columns; the gamelist date and age-ratings derivations run
  through IMMUTABLE wrapper functions. Gamelist dates are parsed as UTC on
  both engines so the stored value is time-zone independent.

Fixes #3768.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 09:19:34 -04:00
Georges-Antoine Assi
602faccc5c fix: generate virtual collections from all metadata sources
The virtual_collections view read only roms.igdb_metadata, so franchises,
genres, companies and play modes set manually or provided by non-IGDB sources
(ScreenScraper, Flashpoint, gamelist) never produced auto-generated
collections, even though the same values already drove /api/roms filtering and
the game detail page.

Redefine the view to source each grouping from the roms_metadata view, which
coalesces manual and provider metadata in priority order. Matching values now
merge into a single collection regardless of their source. The 3-ROM minimum
threshold is unchanged.

Fixes #3187

Generated-By: PostHog Code
Task-Id: 10289bf4-b0d0-4856-80c9-1be93c926f37
2026-07-06 10:39:03 -04:00
Georges-Antoine Assi
0cf0b041de feat(gallery): count public saves/states in has-saves / has-states filters
The has-saves / has-states filters matched only the current user's own
saves/states. Match public (community) ones too, so a ROM with another
user's shared save/state is surfaced by the filter — mirroring the
owner-or-public visibility used elsewhere (get_rom_shared_saves/states).

Generated-By: PostHog Code
Task-Id: feda1257-eb36-4566-9898-528087459416
2026-07-01 11:50:58 -04:00
Georges-Antoine Assi
8c370fbc22 Merge branch 'master' into fix/filter-values-cache-schema-version 2026-06-30 08:22:19 -04:00
Spinnich
a08b7dfbda fix(roms): namespace filter-values cache by schema version
The /api/roms filter_values dict is cached in Redis keyed only by a
runtime data-version that survives app upgrades. When a filter field is
added (e.g. tags), entries written by the previous version lack the new
key, so the response fails validation (filter_values.tags "Field
required") and returns 500 until the entry's 7-day TTL elapses or a scan
invalidates it.

Embed a schema version in the cache key so reads after an upgrade ignore
entries written under the old shape and recompute instead. Pre-namespace
keys are bypassed for free by the changed key format. Bump
ROM_FILTERS_CACHE_SCHEMA_VERSION whenever the cached dict gains or loses
a field.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 10:47:16 +00:00
Spinnich
14a0a98661 feat(roms): filter games by custom tags
Adds a "Tag" gallery filter so a library can be narrowed by the custom
tags parsed from filenames (No-Intro / Redump nomenclature, e.g. Proto,
Beta, Demo), mirroring the existing data-derived multi-value filters
(regions, languages). Closes #3546.

Backend:
- New `_filter_by_tags` over `Rom.tags` with any/all/none logic; wired
  through filter_roms, get_roms_scalar, the /roms endpoint (tags +
  tags_logic), and the unscoped cache gate.
- Tags are data-derived, so the selectable list is surfaced via
  filter_values: added to _collect_filter_values, with_filter_values,
  get_rom_filters, and RomFiltersDict.
- Smart collections apply the criterion via get_smart_collection_roms.

Frontend (v1 + v2):
- Wired into the galleryFilter store, rom API service, request cache key,
  both filter drawers, v2 URL persistence, the v2 refetch watcher, and
  smart-collection serialization/summary + create dialog.
- Added the `platform.tag` key to all locales (distinct from the existing
  `platform.tags` section heading).

Tests:
- Backend handler (any/all/none + unknown-value), endpoint, filter_values,
  and smart-collection coverage.
- Frontend smartCollectionCriteria serialization/summary coverage.

AI assistance: implemented with Claude Code (Anthropic).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 11:29:12 +00:00