Files
romm/backend/handler/database/collections_handler.py
Georges-Antoine Assi a688676de7 fix: enforce ROM visibility on assets, sync, collections, stats and scan events (#5498)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: fix mypy errors in the new tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: apply review-polish pass on permission hardening

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: state that ROM visibility is enforced as access control

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs

Visibility is access control, so per-id save/state/screenshot routes now 404
when the save's ROM is hidden from the caller (hidden ROM, hidden platform or
age limit), and the save/state lists and identifier lists leave those rows
out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a
hidden platform 404 on every per-id route, drop out of both lists, and can't
be created against a hidden platform.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): answer a hidden ROM's save summary like a missing one

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(permissions): enforce ROM visibility in sync, installs and feeds

Hidden ROMs/platforms and age-limited ROMs are access control, so the
paths that skipped the caller's visibility now apply it:

- sync negotiate: saves on hidden ROMs are neither offered, paired nor
  reported as conflicts; a client save on one negotiates like an unknown ROM
- push-pull SSH sync: resolves the device owner's visibility and skips
  saves on hidden ROMs in both directions
- device installs: list and claim leave out requests whose ROM became
  hidden (they stay pending), and outcome notifications don't name it
- recommendations: a hidden seed ROM is no longer named
- music playlists: track_count counts only tracks on visible ROMs
- audit events: firmware targets on hidden platforms are filtered
- setup library: supported platforms honour the caller's visibility
- feeds: a hidden platform found by slug reads as missing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(visibility): hide ROMs from virtual collections, stats and scan events

Virtual collections apply the caller's visibility in SQL: a collection with
no visible member is left out (404 by id), member ids and covers skip hidden
ROMs, and the limit counts only visible collections.

Stats save, state and screenshot totals skip assets of hidden ROMs.

Scan events no longer broadcast to every socket. Progress and end events go
to a scan room that sockets of users holding platforms.write or tasks.run
join on connect. scanning_rom and scanning_platform go to the user rooms of
those followers who can see that ROM or platform, resolved once per scan
and grouped by visibility. get_rom_audience now builds on a shared
get_user_visibilities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: apply code-review findings on ROM visibility enforcement

Match virtual collection members by ROM id, build the cover visibility clauses
once, filter feed platforms by visibility in SQL, resolve every id before a
batch save or state delete, filter push-pull saves in the query, and narrow the
hides query to the requested users.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: apply simplify pass on ROM visibility enforcement

Require an explicit visibility filter on the saves, states and memory card
queries, share one roms_facets visibility join and one owned-asset helper,
filter virtual collection members by hidden ids, batch the scan audience's
scope lookup, and move the empty-room emit guard into socket_handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: start the scan audience before emitting from scan_rom

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: apply humanizer pass on the visibility rule

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(streaming): don't mount a memory card on a hidden platform

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address Greptile review on ROM visibility enforcement

Refresh a running scan's audience after a permission change, fix the precedence
of the scan-room join assertion, and narrow mock await_args before reading them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* revert: drop per-visibility scan event audience

Scan events go back to every socket. Removes handler/scan/audience.py,
the scan room join on connect, the permissions generation bump and the
batched OAuth scope resolution that only the audience used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:33:11 -05:00

775 lines
27 KiB
Python

import functools
from collections.abc import Callable, Mapping, Sequence
from datetime import datetime, timezone
from itertools import batched
from typing import Any, cast
from sqlalchemy import (
Select,
and_,
delete,
false,
insert,
literal,
or_,
select,
union_all,
update,
)
from sqlalchemy.engine import Row
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import (
QueryableAttribute,
Session,
load_only,
raiseload,
selectinload,
)
from sqlalchemy.orm.attributes import set_committed_value
from sqlalchemy.sql.elements import ColumnElement
from config import FRONTEND_RESOURCES_PATH
from decorators.database import INJECTED_SESSION, begin_session
from handler.auth.rom_visibility import UNRESTRICTED, RomVisibilityFilter
from handler.database.rom_filters import RomFilterParams
from models.collection import (
SMART_COLLECTION_MAX_COVERS,
Collection,
CollectionRom,
SmartCollection,
VirtualCollection,
VirtualCollectionRom,
)
from models.rom import Rom, RomFacets
from utils.sql_dialect import json_array_contains_value
from .base_handler import DBBaseHandler, affected_rows
MAX_VIRTUAL_COLLECTION_COVERS = 5
# Collections per statement, to keep any single statement small.
COLLECTIONS_BATCH_SIZE = 100
def _roms_load_options() -> list[Any]:
return [
selectinload(Collection.roms)
.load_only(
Rom.id,
Rom.path_cover_s,
Rom.path_cover_l,
)
.options(raiseload(Rom.platform), raiseload(Rom.metadatum))
]
# Default for a `query` parameter that with_roms fills before the body runs.
INJECTED_COLLECTION_QUERY = cast(Select[Collection], None)
def with_roms[**P, R](func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
kwargs["query"] = select(Collection).options(*_roms_load_options())
return func(*args, **kwargs)
return wrapper
class DBCollectionsHandler(DBBaseHandler):
@begin_session
@with_roms
def add_collection(
self,
collection: Collection,
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
session: Session = INJECTED_SESSION,
) -> Collection:
collection = session.merge(collection)
session.flush()
return session.scalars(query.filter_by(id=collection.id).limit(1)).one()
@begin_session
@with_roms
def get_collection(
self,
id: int,
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
session: Session = INJECTED_SESSION,
) -> Collection | None:
return session.scalar(query.filter_by(id=id).limit(1))
@begin_session
@with_roms
def get_collection_by_name(
self,
name: str,
user_id: int,
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
session: Session = INJECTED_SESSION,
) -> Collection | None:
return session.scalar(query.filter_by(name=name, user_id=user_id).limit(1))
@begin_session
@with_roms
def get_favorite_collection(
self,
user_id: int,
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
session: Session = INJECTED_SESSION,
) -> Collection | None:
return session.scalar(
query.filter_by(is_favorite=True, user_id=user_id).limit(1)
)
def _collections_query(
self,
updated_after: datetime | None = None,
) -> Select[Collection]:
query = select(Collection)
if updated_after:
query = query.filter(Collection.updated_at > updated_after)
return query.order_by(Collection.name.asc())
@begin_session
def get_collections(
self,
updated_after: datetime | None = None,
session: Session = INJECTED_SESSION,
) -> Sequence[Collection]:
query = self._collections_query(updated_after=updated_after)
return session.scalars(query.options(*_roms_load_options())).unique().all()
@begin_session
def get_collection_ids(
self,
updated_after: datetime | None = None,
session: Session = INJECTED_SESSION,
) -> list[Row[int, int, bool]]:
"""Id, owner and visibility only, so neither eager load fires."""
query = self._collections_query(updated_after=updated_after)
return list(
session.execute(
query.with_only_columns(
Collection.id, Collection.user_id, Collection.is_public
)
).all()
)
@begin_session
@with_roms
def update_collection(
self,
id: int,
data: dict[str, Any],
rom_ids: list[int] | None = None,
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
session: Session = INJECTED_SESSION,
) -> Collection:
session.execute(
update(Collection)
.where(Collection.id == id)
.values(**data)
.execution_options(synchronize_session="evaluate")
)
if rom_ids is not None:
# Delete all existing CollectionRom entries for this collection
session.execute(
delete(CollectionRom).where(CollectionRom.collection_id == id)
)
# Insert new CollectionRom entries for this collection
if rom_ids:
# Filter out rom_ids that no longer exist in the roms table to
# avoid foreign key constraint violations (e.g. after a rescan)
valid_rom_ids = set(
session.scalars(select(Rom.id).where(Rom.id.in_(rom_ids))).all()
)
if valid_rom_ids:
session.execute(
insert(CollectionRom),
[
{"collection_id": id, "rom_id": rom_id}
for rom_id in valid_rom_ids
],
)
return session.scalars(query.filter_by(id=id).limit(1)).one()
@begin_session
@with_roms
def add_roms_to_collection(
self,
id: int,
rom_ids: list[int],
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
session: Session = INJECTED_SESSION,
) -> Collection:
if rom_ids:
valid_rom_ids = set(
session.scalars(select(Rom.id).where(Rom.id.in_(rom_ids))).all()
)
existing_ids = set(
session.scalars(
select(CollectionRom.rom_id).where(
CollectionRom.collection_id == id
)
).all()
)
new_ids = valid_rom_ids - existing_ids
if new_ids:
try:
with session.begin_nested():
session.execute(
insert(CollectionRom),
[
{"collection_id": id, "rom_id": rom_id}
for rom_id in new_ids
],
)
except IntegrityError:
# Concurrent request inserted the same rows; data is consistent
pass
session.execute(
update(Collection)
.where(Collection.id == id)
.values(updated_at=datetime.now(timezone.utc))
.execution_options(synchronize_session="evaluate")
)
return session.scalars(query.filter_by(id=id).limit(1)).one()
@begin_session
@with_roms
def remove_roms_from_collection(
self,
id: int,
rom_ids: list[int],
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
session: Session = INJECTED_SESSION,
) -> Collection:
if rom_ids:
result = session.execute(
delete(CollectionRom).where(
CollectionRom.collection_id == id,
CollectionRom.rom_id.in_(rom_ids),
)
)
if affected_rows(result) > 0:
session.execute(
update(Collection)
.where(Collection.id == id)
.values(updated_at=datetime.now(timezone.utc))
.execution_options(synchronize_session="evaluate")
)
return session.scalars(query.filter_by(id=id).limit(1)).one()
@begin_session
def delete_collection(
self,
id: int,
session: Session = INJECTED_SESSION,
) -> None:
session.execute(
delete(Collection)
.where(Collection.id == id)
.execution_options(synchronize_session="evaluate")
)
# Virtual collections
def _attach_covers(
self,
session: Session,
collections: Sequence[VirtualCollection],
visibility: RomVisibilityFilter,
) -> None:
"""Fill in each collection's covers from its visible membership rows.
The view deliberately doesn't aggregate covers: on a large library that
is megabytes of cover paths per request, while callers render a handful.
Each collection gets its own primary-key lookup capped at
MAX_VIRTUAL_COLLECTION_COVERS rows, batched into UNION ALL statements,
so the cost follows the number of collections rather than the size of
the library.
"""
if not collections:
return
def covers_select(collection: VirtualCollection) -> Select[*tuple[Any, ...]]:
query = visibility.restrict(
select(
VirtualCollectionRom.type,
VirtualCollectionRom.name,
VirtualCollectionRom.path_cover_s,
VirtualCollectionRom.path_cover_l,
),
VirtualCollectionRom.rom_id,
)
return (
query.where(
VirtualCollectionRom.type == collection.type,
VirtualCollectionRom.name == collection.name,
or_(
VirtualCollectionRom.path_cover_s != "",
VirtualCollectionRom.path_cover_l != "",
),
)
.order_by(VirtualCollectionRom.rom_id)
.limit(MAX_VIRTUAL_COLLECTION_COVERS)
)
covers: dict[tuple[str, str], tuple[list[str], list[str]]] = {}
for batch in batched(collections, COLLECTIONS_BATCH_SIZE, strict=False):
selects = [covers_select(collection) for collection in batch]
statement = selects[0] if len(selects) == 1 else union_all(*selects)
for row in session.execute(statement).all():
small, large = covers.setdefault((row.type, row.name), ([], []))
if row.path_cover_s:
small.append(row.path_cover_s)
if row.path_cover_l:
large.append(row.path_cover_l)
for collection in collections:
small, large = covers.get((collection.type, collection.name), ([], []))
collection.path_covers_s = small
collection.path_covers_l = large
def _only_visible(
self,
query: Select[VirtualCollection],
visibility: RomVisibilityFilter,
*member_filters: ColumnElement[bool],
) -> Select[VirtualCollection]:
"""Narrow `query` to the collections with a member `visibility` keeps."""
if visibility.is_unrestricted:
return query
visible = (
visibility.restrict(
select(VirtualCollectionRom.type, VirtualCollectionRom.name),
VirtualCollectionRom.rom_id,
)
.where(*member_filters)
.group_by(VirtualCollectionRom.type, VirtualCollectionRom.name)
.subquery()
)
return query.join(
visible,
and_(
visible.c.type == VirtualCollection.type,
visible.c.name == VirtualCollection.name,
),
)
def _drop_hidden_members(
self,
session: Session,
collections: Sequence[VirtualCollection],
visibility: RomVisibilityFilter,
) -> None:
"""Narrow each collection's members to the ones `visibility` keeps."""
if visibility.is_unrestricted or not collections:
return
hidden = set(visibility.hidden_rom_ids)
row_hidden = visibility.row_hidden_clause(
platform_id_col=RomFacets.platform_id, min_age_col=RomFacets.min_age
)
if row_hidden is not None:
hidden.update(
session.scalars(select(RomFacets.rom_id).where(row_hidden)).all()
)
# Committed, so the session never tries to write the view back.
for collection in collections:
set_committed_value(collection, "rom_ids", set(collection.rom_ids) - hidden)
@begin_session
def get_virtual_collection(
self,
id: str,
visibility: RomVisibilityFilter = UNRESTRICTED,
session: Session = INJECTED_SESSION,
) -> VirtualCollection | None:
name, type = VirtualCollection.from_id(id)
collection = session.scalar(
select(VirtualCollection).filter_by(name=name, type=type).limit(1)
)
if not collection:
return None
self._drop_hidden_members(session, [collection], visibility)
if not collection.rom_ids:
return None
self._attach_covers(session, [collection], visibility)
return collection
@begin_session
def get_virtual_collections(
self,
type: str,
limit: int | None = None,
only_fields: Sequence[QueryableAttribute[Any]] | None = None,
visibility: RomVisibilityFilter = UNRESTRICTED,
session: Session = INJECTED_SESSION,
) -> Sequence[VirtualCollection]:
query = (
self._only_visible(
select(VirtualCollection).filter(
or_(VirtualCollection.type == type, literal(type == "all"))
),
visibility,
or_(VirtualCollectionRom.type == type, literal(type == "all")),
)
.limit(limit)
.order_by(VirtualCollection.name.asc())
)
if only_fields:
# Identifier-only callers never render covers.
query = query.options(load_only(*only_fields))
return session.scalars(query).unique().all()
collections = session.scalars(query).unique().all()
self._drop_hidden_members(session, collections, visibility)
self._attach_covers(session, collections, visibility)
return collections
def get_virtual_collection_rom_ids(self, id: str) -> Select[int]:
"""Select the rom ids of a virtual collection, as an indexed subquery."""
name, type = VirtualCollection.from_id(id)
return select(VirtualCollectionRom.rom_id).where(
VirtualCollectionRom.type == type, VirtualCollectionRom.name == name
)
# Smart collections
@begin_session
def add_smart_collection(
self,
smart_collection: SmartCollection,
session: Session = INJECTED_SESSION,
) -> SmartCollection:
smart_collection = session.merge(smart_collection)
session.flush()
return session.scalars(
select(SmartCollection).filter_by(id=smart_collection.id)
).one()
@begin_session
def get_smart_collection(
self,
id: int,
session: Session = INJECTED_SESSION,
) -> SmartCollection | None:
return session.scalar(select(SmartCollection).filter_by(id=id).limit(1))
@begin_session
def get_smart_collection_by_name(
self,
name: str,
user_id: int,
session: Session = INJECTED_SESSION,
) -> SmartCollection | None:
return session.scalar(
select(SmartCollection).filter_by(name=name, user_id=user_id).limit(1)
)
def _smart_collections_query(
self,
user_id: int | None = None,
updated_after: datetime | None = None,
) -> Select[SmartCollection]:
query = select(SmartCollection).order_by(SmartCollection.name.asc())
if user_id is not None:
# Get user's smart collections and public ones
query = query.filter(
(SmartCollection.user_id == user_id) | SmartCollection.is_public
)
if updated_after:
query = query.filter(SmartCollection.updated_at > updated_after)
return query
@begin_session
def get_smart_collections(
self,
user_id: int | None = None,
updated_after: datetime | None = None,
session: Session = INJECTED_SESSION,
) -> Sequence[SmartCollection]:
query = self._smart_collections_query(
user_id=user_id, updated_after=updated_after
)
return session.scalars(query).unique().all()
@begin_session
def get_smart_collection_ids(
self,
user_id: int | None = None,
updated_after: datetime | None = None,
session: Session = INJECTED_SESSION,
) -> list[int]:
"""Ids only, so no `SmartCollection` is built and no eager user join fires."""
query = self._smart_collections_query(
user_id=user_id, updated_after=updated_after
)
return list(session.scalars(query.with_only_columns(SmartCollection.id)).all())
@begin_session
def get_smart_collections_for_rom(
self,
rom_id: int,
user_id: int,
session: Session = INJECTED_SESSION,
) -> Sequence[SmartCollection]:
# Membership is a cached JSON array of rom ids on the collection, so
# push containment + visibility into SQL rather than loading every
# collection's rom_ids blob into Python and scanning it (see #3934).
return (
session.scalars(
select(SmartCollection)
.where(
json_array_contains_value(SmartCollection.rom_ids, rom_id),
or_(
SmartCollection.user_id == user_id,
SmartCollection.is_public,
),
)
.options(
load_only(
SmartCollection.id,
SmartCollection.name,
SmartCollection.is_public,
)
)
.order_by(SmartCollection.name.asc())
)
.unique()
.all()
)
@begin_session
def update_smart_collection(
self,
id: int,
data: dict[str, Any],
session: Session = INJECTED_SESSION,
) -> SmartCollection:
session.execute(
update(SmartCollection)
.where(SmartCollection.id == id)
.values(**data)
.execution_options(synchronize_session="evaluate")
)
return session.scalars(select(SmartCollection).filter_by(id=id)).one()
@begin_session
def delete_smart_collection(
self,
id: int,
session: Session = INJECTED_SESSION,
) -> None:
session.execute(
delete(SmartCollection)
.where(SmartCollection.id == id)
.execution_options(synchronize_session="evaluate")
)
def build_smart_collection_query[S: Select[*tuple[Any, ...]]](
self,
*,
query: S,
smart_collection: SmartCollection,
user_id: int | None,
session: Session,
) -> S:
"""Apply a smart collection's stored criteria to a ROM query.
The criteria are `filter_roms`'s own vocabulary, so membership composes
into SQL and the database can return just the page being viewed, rather
than the whole matching library being assembled in Python first (#4029).
Relationships are not eager-loaded, so the result is for filtering, not
for serializing ROMs. The caller owns the query's joins, including
`RomUser` for the per-user criteria (favorite, statuses, saves, states).
"""
from handler.database import db_rom_handler
filters = RomFilterParams.from_stored_criteria(smart_collection.filter_criteria)
if filters is None:
# Criteria the model rejects: match nothing rather than drop the
# constraint, which would show more than the collection claims.
return query.filter(false())
return db_rom_handler.filter_roms(
query=query,
filters=filters,
user_id=user_id,
collection_user_id=smart_collection.user_id,
include_related=False,
session=session,
)
@begin_session
def get_smart_collection_members(
self,
smart_collection: SmartCollection,
user_id: int | None = None,
session: Session = INJECTED_SESSION,
) -> Sequence[Row[int, str | None, str | None]]:
"""Every member's id and cover paths, in the collection's own order.
Only the columns the cached membership needs, so refreshing never
hydrates ROM metadata.
"""
from handler.database import db_rom_handler
criteria = smart_collection.filter_criteria
query, _ = db_rom_handler.get_roms_query(
order_by=criteria.get("order_by", "name"),
order_dir=criteria.get("order_dir", "asc"),
search_term=criteria.get("search_term"),
user_id=user_id,
)
covers_query = self.build_smart_collection_query(
query=query,
smart_collection=smart_collection,
user_id=user_id,
session=session,
).with_only_columns(Rom.id, Rom.path_cover_s, Rom.path_cover_l)
return session.execute(covers_query).all()
@begin_session
def refresh_smart_collection(
self,
id: int,
session: Session = INJECTED_SESSION,
) -> SmartCollection | None:
"""Recompute a smart collection's cached membership columns.
Those columns back the collections list and the ROM detail page, and are
maintained on write: when the collection changes, and when the library
does. They describe the owner's view, since the row is shared and
criteria like `favorite` or `has_saves` answer differently per user.
"""
smart_collection = session.scalar(
select(SmartCollection).filter_by(id=id).limit(1)
)
if not smart_collection:
return None
members = self.get_smart_collection_members(
smart_collection, user_id=smart_collection.user_id, session=session
)
rom_ids = [member.id for member in members]
covers_small = [
f"{FRONTEND_RESOURCES_PATH}/{member.path_cover_s}"
for member in members
if member.path_cover_s
][:SMART_COLLECTION_MAX_COVERS]
covers_large = [
f"{FRONTEND_RESOURCES_PATH}/{member.path_cover_l}"
for member in members
if member.path_cover_l
][:SMART_COLLECTION_MAX_COVERS]
# Compare without the cache-buster: it is read from `updated_at` before
# the write bumps it, so a stored URL never carries the row's current
# timestamp and comparing whole URLs would rewrite on every refresh.
if (
smart_collection.rom_ids == rom_ids
and [u.split("?", 1)[0] for u in smart_collection.path_covers_small]
== covers_small
and [u.split("?", 1)[0] for u in smart_collection.path_covers_large]
== covers_large
):
return smart_collection
timestamp = smart_collection.updated_at
return self.update_smart_collection(
id,
{
"rom_ids": rom_ids,
"path_covers_small": [f"{c}?ts={timestamp}" for c in covers_small],
"path_covers_large": [f"{c}?ts={timestamp}" for c in covers_large],
},
session=session,
)
@begin_session
def refresh_smart_collections(
self,
session: Session = INJECTED_SESSION,
) -> int:
"""Refresh every smart collection, e.g. once the library has changed."""
ids = session.scalars(select(SmartCollection.id)).all()
for id in ids:
self.refresh_smart_collection(id, session=session)
return len(ids)
@begin_session
def refresh_smart_collections_scoped_to(
self,
collection_id: int,
session: Session = INJECTED_SESSION,
) -> None:
"""Refresh the smart collections whose criteria name `collection_id`, since
sharing, unsharing or deleting it changes what their criteria match."""
rows = session.execute(
select(SmartCollection.id, SmartCollection.filter_criteria)
).all()
for smart_collection_id, criteria in rows:
# A raw match, so rows with unrelated invalid criteria stay unparsed.
if isinstance(criteria, Mapping) and str(
criteria.get("collection_id")
) == str(collection_id):
self.refresh_smart_collection(smart_collection_id, session=session)
@begin_session
def refresh_smart_collections_for_roms(
self,
rom_ids: Sequence[int],
membership_only: bool = False,
session: Session = INJECTED_SESSION,
) -> None:
"""Refresh the collections a handful of changed ROMs touch.
Editing one ROM rarely moves any collection, and asking whether given
ids match is an indexed lookup, so only the collections that actually
hold one of them pay for a recount.
`membership_only` is for changes that leave the ROM row alone, like a
save, a state, a status or collection membership: nothing about the ROM
can have moved except whether it matches, so a member that stayed one
needs no recount. That matters because autosaves land constantly. The
default suits a library change, where a ROM that stayed a member can
still have a new name, sort position or cover to reflect.
"""
from handler.database import db_rom_handler
if not rom_ids:
return
candidates = set(rom_ids)
for smart_collection in session.scalars(select(SmartCollection)).all():
matching = db_rom_handler.get_smart_collection_matches(
smart_collection=smart_collection,
rom_ids=candidates,
user_id=smart_collection.user_id,
session=session,
)
cached = candidates & set(smart_collection.rom_ids)
moved = matching != cached if membership_only else bool(matching or cached)
if moved:
self.refresh_smart_collection(smart_collection.id, session=session)