mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 02:22:44 +01:00
Merge remote-tracking branch 'origin/master' into chore/permissions-system-rework
# Conflicts: # backend/handler/database/stats_handler.py
This commit is contained in:
@@ -1,412 +1,414 @@
|
||||
import functools
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, insert, literal, or_, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import (
|
||||
Query,
|
||||
QueryableAttribute,
|
||||
Session,
|
||||
load_only,
|
||||
noload,
|
||||
selectinload,
|
||||
)
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.collection import (
|
||||
Collection,
|
||||
CollectionRom,
|
||||
SmartCollection,
|
||||
VirtualCollection,
|
||||
)
|
||||
from models.rom import Rom
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
|
||||
def with_roms(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
kwargs["query"] = select(Collection).options(
|
||||
selectinload(Collection.roms)
|
||||
.load_only(
|
||||
Rom.id,
|
||||
Rom.path_cover_s,
|
||||
Rom.path_cover_l,
|
||||
)
|
||||
.options(noload(Rom.platform), noload(Rom.metadatum))
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class DBCollectionsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
@with_roms
|
||||
def add_collection(
|
||||
self,
|
||||
collection: Collection,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Collection:
|
||||
collection = session.merge(collection)
|
||||
session.flush()
|
||||
|
||||
return session.scalar(query.filter_by(id=collection.id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def get_collection(
|
||||
self,
|
||||
id: int,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Collection | None:
|
||||
return session.scalar(
|
||||
query.filter_by(is_favorite=True, user_id=user_id).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def get_collections(
|
||||
self,
|
||||
updated_after: datetime | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Collection]:
|
||||
if updated_after:
|
||||
query = query.filter(Collection.updated_at > updated_after)
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
return session.scalars(query.order_by(Collection.name.asc())).unique().all()
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def update_collection(
|
||||
self,
|
||||
id: int,
|
||||
data: dict,
|
||||
rom_ids: list[int] | None = None,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def add_roms_to_collection(
|
||||
self,
|
||||
id: int,
|
||||
rom_ids: list[int],
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def remove_roms_from_collection(
|
||||
self,
|
||||
id: int,
|
||||
rom_ids: list[int],
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Collection:
|
||||
if rom_ids:
|
||||
result = session.execute(
|
||||
delete(CollectionRom).where(
|
||||
CollectionRom.collection_id == id,
|
||||
CollectionRom.rom_id.in_(rom_ids),
|
||||
)
|
||||
)
|
||||
if result.rowcount > 0:
|
||||
session.execute(
|
||||
update(Collection)
|
||||
.where(Collection.id == id)
|
||||
.values(updated_at=datetime.now(timezone.utc))
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def delete_collection(
|
||||
self,
|
||||
id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(Collection)
|
||||
.where(Collection.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
# Virtual collections
|
||||
@begin_session
|
||||
def get_virtual_collection(
|
||||
self,
|
||||
id: str,
|
||||
session: Session = None, # type: ignore
|
||||
) -> VirtualCollection | None:
|
||||
name, type = VirtualCollection.from_id(id)
|
||||
return session.scalar(
|
||||
select(VirtualCollection).filter_by(name=name, type=type).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_virtual_collections(
|
||||
self,
|
||||
type: str,
|
||||
limit: int | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[VirtualCollection]:
|
||||
query = (
|
||||
select(VirtualCollection)
|
||||
.filter(or_(VirtualCollection.type == type, literal(type == "all")))
|
||||
.limit(limit)
|
||||
.order_by(VirtualCollection.name.asc())
|
||||
)
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
return session.scalars(query).unique().all()
|
||||
|
||||
# Smart collections
|
||||
@begin_session
|
||||
def add_smart_collection(
|
||||
self,
|
||||
smart_collection: SmartCollection,
|
||||
session: Session = None, # type: ignore
|
||||
) -> SmartCollection:
|
||||
smart_collection = session.merge(smart_collection)
|
||||
session.flush()
|
||||
|
||||
return session.query(SmartCollection).filter_by(id=smart_collection.id).one()
|
||||
|
||||
@begin_session
|
||||
def get_smart_collection(
|
||||
self,
|
||||
id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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 = None, # type: ignore
|
||||
) -> SmartCollection | None:
|
||||
return session.scalar(
|
||||
select(SmartCollection).filter_by(name=name, user_id=user_id).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_smart_collections(
|
||||
self,
|
||||
user_id: int | None = None,
|
||||
updated_after: datetime | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[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)
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
return session.scalars(query).unique().all()
|
||||
|
||||
@begin_session
|
||||
def update_smart_collection(
|
||||
self,
|
||||
id: int,
|
||||
data: dict[str, Any],
|
||||
session: Session = None, # type: ignore
|
||||
) -> SmartCollection:
|
||||
session.execute(
|
||||
update(SmartCollection)
|
||||
.where(SmartCollection.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return session.query(SmartCollection).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_smart_collection(
|
||||
self,
|
||||
id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(SmartCollection)
|
||||
.where(SmartCollection.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
def get_smart_collection_roms(
|
||||
self, smart_collection: SmartCollection, user_id: int | None = None
|
||||
) -> Sequence["Rom"]:
|
||||
"""Get ROMs that match the smart collection's filter criteria."""
|
||||
from handler.database import db_rom_handler
|
||||
|
||||
# Extract filter criteria
|
||||
criteria = smart_collection.filter_criteria
|
||||
|
||||
# Convert legacy single-value criteria to arrays for backward compatibility
|
||||
def convert_legacy_filter(new_key: str, old_key: str) -> list[str] | None:
|
||||
"""Convert legacy single-value filter to array format."""
|
||||
if new_value := criteria.get(new_key):
|
||||
return new_value if isinstance(new_value, list) else [new_value]
|
||||
if old_value := criteria.get(old_key):
|
||||
return old_value if isinstance(old_value, list) else [old_value]
|
||||
return None
|
||||
|
||||
# Apply conversions
|
||||
genres = convert_legacy_filter("genres", "selected_genre")
|
||||
franchises = convert_legacy_filter("franchises", "selected_franchise")
|
||||
collections = convert_legacy_filter("collections", "selected_collection")
|
||||
companies = convert_legacy_filter("companies", "selected_company")
|
||||
age_ratings = convert_legacy_filter("age_ratings", "selected_age_rating")
|
||||
regions = convert_legacy_filter("regions", "selected_region")
|
||||
languages = convert_legacy_filter("languages", "selected_language")
|
||||
statuses = convert_legacy_filter("statuses", "selected_status")
|
||||
|
||||
# Use the existing filter_roms method with the stored criteria
|
||||
platform_ids = criteria.get("platform_ids")
|
||||
if platform_ids is None:
|
||||
if platform_id := criteria.get("platform_id"):
|
||||
platform_ids = [platform_id]
|
||||
|
||||
return db_rom_handler.get_roms_scalar(
|
||||
platform_ids=platform_ids,
|
||||
collection_id=criteria.get("collection_id"),
|
||||
virtual_collection_id=criteria.get("virtual_collection_id"),
|
||||
search_term=criteria.get("search_term"),
|
||||
matched=criteria.get("matched"),
|
||||
favorite=criteria.get("favorite"),
|
||||
duplicate=criteria.get("duplicate"),
|
||||
playable=criteria.get("playable"),
|
||||
has_ra=criteria.get("has_ra"),
|
||||
missing=criteria.get("missing"),
|
||||
verified=criteria.get("verified"),
|
||||
genres=genres,
|
||||
franchises=franchises,
|
||||
collections=collections,
|
||||
companies=companies,
|
||||
age_ratings=age_ratings,
|
||||
statuses=statuses,
|
||||
regions=regions,
|
||||
languages=languages,
|
||||
# Logic operators for multi-value filters
|
||||
genres_logic=criteria.get("genres_logic", "any"),
|
||||
franchises_logic=criteria.get("franchises_logic", "any"),
|
||||
collections_logic=criteria.get("collections_logic", "any"),
|
||||
companies_logic=criteria.get("companies_logic", "any"),
|
||||
age_ratings_logic=criteria.get("age_ratings_logic", "any"),
|
||||
regions_logic=criteria.get("regions_logic", "any"),
|
||||
languages_logic=criteria.get("languages_logic", "any"),
|
||||
statuses_logic=criteria.get("statuses_logic", "any"),
|
||||
user_id=user_id,
|
||||
order_by=criteria.get("order_by", "name"),
|
||||
order_dir=criteria.get("order_dir", "asc"),
|
||||
)
|
||||
import functools
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, insert, literal, or_, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import (
|
||||
Query,
|
||||
QueryableAttribute,
|
||||
Session,
|
||||
load_only,
|
||||
noload,
|
||||
selectinload,
|
||||
)
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.collection import (
|
||||
Collection,
|
||||
CollectionRom,
|
||||
SmartCollection,
|
||||
VirtualCollection,
|
||||
)
|
||||
from models.rom import Rom
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
|
||||
def with_roms(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
kwargs["query"] = select(Collection).options(
|
||||
selectinload(Collection.roms)
|
||||
.load_only(
|
||||
Rom.id,
|
||||
Rom.path_cover_s,
|
||||
Rom.path_cover_l,
|
||||
)
|
||||
.options(noload(Rom.platform), noload(Rom.metadatum))
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class DBCollectionsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
@with_roms
|
||||
def add_collection(
|
||||
self,
|
||||
collection: Collection,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Collection:
|
||||
collection = session.merge(collection)
|
||||
session.flush()
|
||||
|
||||
return session.scalar(query.filter_by(id=collection.id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def get_collection(
|
||||
self,
|
||||
id: int,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Collection | None:
|
||||
return session.scalar(
|
||||
query.filter_by(is_favorite=True, user_id=user_id).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def get_collections(
|
||||
self,
|
||||
updated_after: datetime | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Collection]:
|
||||
if updated_after:
|
||||
query = query.filter(Collection.updated_at > updated_after)
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
return session.scalars(query.order_by(Collection.name.asc())).unique().all()
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def update_collection(
|
||||
self,
|
||||
id: int,
|
||||
data: dict,
|
||||
rom_ids: list[int] | None = None,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def add_roms_to_collection(
|
||||
self,
|
||||
id: int,
|
||||
rom_ids: list[int],
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def remove_roms_from_collection(
|
||||
self,
|
||||
id: int,
|
||||
rom_ids: list[int],
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Collection:
|
||||
if rom_ids:
|
||||
result = session.execute(
|
||||
delete(CollectionRom).where(
|
||||
CollectionRom.collection_id == id,
|
||||
CollectionRom.rom_id.in_(rom_ids),
|
||||
)
|
||||
)
|
||||
if result.rowcount > 0:
|
||||
session.execute(
|
||||
update(Collection)
|
||||
.where(Collection.id == id)
|
||||
.values(updated_at=datetime.now(timezone.utc))
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def delete_collection(
|
||||
self,
|
||||
id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(Collection)
|
||||
.where(Collection.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
# Virtual collections
|
||||
@begin_session
|
||||
def get_virtual_collection(
|
||||
self,
|
||||
id: str,
|
||||
session: Session = None, # type: ignore
|
||||
) -> VirtualCollection | None:
|
||||
name, type = VirtualCollection.from_id(id)
|
||||
return session.scalar(
|
||||
select(VirtualCollection).filter_by(name=name, type=type).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_virtual_collections(
|
||||
self,
|
||||
type: str,
|
||||
limit: int | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[VirtualCollection]:
|
||||
query = (
|
||||
select(VirtualCollection)
|
||||
.filter(or_(VirtualCollection.type == type, literal(type == "all")))
|
||||
.limit(limit)
|
||||
.order_by(VirtualCollection.name.asc())
|
||||
)
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
return session.scalars(query).unique().all()
|
||||
|
||||
# Smart collections
|
||||
@begin_session
|
||||
def add_smart_collection(
|
||||
self,
|
||||
smart_collection: SmartCollection,
|
||||
session: Session = None, # type: ignore
|
||||
) -> SmartCollection:
|
||||
smart_collection = session.merge(smart_collection)
|
||||
session.flush()
|
||||
|
||||
return session.query(SmartCollection).filter_by(id=smart_collection.id).one()
|
||||
|
||||
@begin_session
|
||||
def get_smart_collection(
|
||||
self,
|
||||
id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> 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 = None, # type: ignore
|
||||
) -> SmartCollection | None:
|
||||
return session.scalar(
|
||||
select(SmartCollection).filter_by(name=name, user_id=user_id).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_smart_collections(
|
||||
self,
|
||||
user_id: int | None = None,
|
||||
updated_after: datetime | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[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)
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
return session.scalars(query).unique().all()
|
||||
|
||||
@begin_session
|
||||
def update_smart_collection(
|
||||
self,
|
||||
id: int,
|
||||
data: dict[str, Any],
|
||||
session: Session = None, # type: ignore
|
||||
) -> SmartCollection:
|
||||
session.execute(
|
||||
update(SmartCollection)
|
||||
.where(SmartCollection.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return session.query(SmartCollection).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_smart_collection(
|
||||
self,
|
||||
id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(SmartCollection)
|
||||
.where(SmartCollection.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
def get_smart_collection_roms(
|
||||
self, smart_collection: SmartCollection, user_id: int | None = None
|
||||
) -> Sequence["Rom"]:
|
||||
"""Get ROMs that match the smart collection's filter criteria."""
|
||||
from handler.database import db_rom_handler
|
||||
|
||||
# Extract filter criteria
|
||||
criteria = smart_collection.filter_criteria
|
||||
|
||||
# Convert legacy single-value criteria to arrays for backward compatibility
|
||||
def convert_legacy_filter(new_key: str, old_key: str) -> list[str] | None:
|
||||
"""Convert legacy single-value filter to array format."""
|
||||
if new_value := criteria.get(new_key):
|
||||
return new_value if isinstance(new_value, list) else [new_value]
|
||||
if old_value := criteria.get(old_key):
|
||||
return old_value if isinstance(old_value, list) else [old_value]
|
||||
return None
|
||||
|
||||
# Apply conversions
|
||||
genres = convert_legacy_filter("genres", "selected_genre")
|
||||
franchises = convert_legacy_filter("franchises", "selected_franchise")
|
||||
collections = convert_legacy_filter("collections", "selected_collection")
|
||||
companies = convert_legacy_filter("companies", "selected_company")
|
||||
age_ratings = convert_legacy_filter("age_ratings", "selected_age_rating")
|
||||
regions = convert_legacy_filter("regions", "selected_region")
|
||||
languages = convert_legacy_filter("languages", "selected_language")
|
||||
statuses = convert_legacy_filter("statuses", "selected_status")
|
||||
|
||||
# Use the existing filter_roms method with the stored criteria
|
||||
platform_ids = criteria.get("platform_ids")
|
||||
if platform_ids is None:
|
||||
if platform_id := criteria.get("platform_id"):
|
||||
platform_ids = [platform_id]
|
||||
|
||||
return db_rom_handler.get_roms_scalar(
|
||||
platform_ids=platform_ids,
|
||||
collection_id=criteria.get("collection_id"),
|
||||
virtual_collection_id=criteria.get("virtual_collection_id"),
|
||||
search_term=criteria.get("search_term"),
|
||||
matched=criteria.get("matched"),
|
||||
favorite=criteria.get("favorite"),
|
||||
duplicate=criteria.get("duplicate"),
|
||||
playable=criteria.get("playable"),
|
||||
has_ra=criteria.get("has_ra"),
|
||||
missing=criteria.get("missing"),
|
||||
verified=criteria.get("verified"),
|
||||
genres=genres,
|
||||
franchises=franchises,
|
||||
collections=collections,
|
||||
companies=companies,
|
||||
age_ratings=age_ratings,
|
||||
statuses=statuses,
|
||||
regions=regions,
|
||||
languages=languages,
|
||||
metadata_providers=criteria.get("metadata_providers"),
|
||||
# Logic operators for multi-value filters
|
||||
genres_logic=criteria.get("genres_logic", "any"),
|
||||
franchises_logic=criteria.get("franchises_logic", "any"),
|
||||
collections_logic=criteria.get("collections_logic", "any"),
|
||||
companies_logic=criteria.get("companies_logic", "any"),
|
||||
age_ratings_logic=criteria.get("age_ratings_logic", "any"),
|
||||
regions_logic=criteria.get("regions_logic", "any"),
|
||||
languages_logic=criteria.get("languages_logic", "any"),
|
||||
statuses_logic=criteria.get("statuses_logic", "any"),
|
||||
metadata_providers_logic=criteria.get("metadata_providers_logic", "any"),
|
||||
user_id=user_id,
|
||||
order_by=criteria.get("order_by", "name"),
|
||||
order_dir=criteria.get("order_dir", "asc"),
|
||||
)
|
||||
|
||||
@@ -44,6 +44,7 @@ from models.assets import Save, Screenshot, State
|
||||
from models.base import compute_file_name_parts
|
||||
from models.platform import Platform
|
||||
from models.rom import (
|
||||
METADATA_SOURCE_COLUMNS,
|
||||
Rom,
|
||||
RomFile,
|
||||
RomFileCategory,
|
||||
@@ -709,6 +710,39 @@ class DBRomsHandler(DBBaseHandler):
|
||||
return query.filter(not_(condition))
|
||||
return query.filter(condition)
|
||||
|
||||
def _filter_by_metadata_providers(
|
||||
self,
|
||||
query: Query,
|
||||
*,
|
||||
session: Session,
|
||||
values: Sequence[str],
|
||||
match_all: bool = False,
|
||||
match_none: bool = False,
|
||||
) -> Query:
|
||||
"""Filter on which metadata providers a ROM matched, keyed off each
|
||||
provider's id column on Rom.
|
||||
|
||||
- "any": matched at least one of the selected providers.
|
||||
- "all": matched every selected provider.
|
||||
- "none": matched none of the selected providers.
|
||||
"""
|
||||
columns = [
|
||||
METADATA_SOURCE_COLUMNS[value]
|
||||
for value in values
|
||||
if value in METADATA_SOURCE_COLUMNS
|
||||
]
|
||||
# Unknown slugs (stale bookmark / hand-edited URL) leave nothing to
|
||||
# filter on; treat that as a no-op rather than an empty result set.
|
||||
if not columns:
|
||||
return query
|
||||
|
||||
predicates = [column.isnot(None) for column in columns]
|
||||
if match_none:
|
||||
return query.filter(not_(or_(*predicates)))
|
||||
if match_all:
|
||||
return query.filter(and_(*predicates))
|
||||
return query.filter(or_(*predicates))
|
||||
|
||||
@begin_session
|
||||
def filter_roms(
|
||||
self,
|
||||
@@ -736,6 +770,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
regions: Sequence[str] | None = None,
|
||||
languages: Sequence[str] | None = None,
|
||||
player_counts: Sequence[str] | None = None,
|
||||
metadata_providers: Sequence[str] | None = None,
|
||||
# Logic operators for multi-value filters
|
||||
genres_logic: str = "any",
|
||||
franchises_logic: str = "any",
|
||||
@@ -746,6 +781,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
languages_logic: str = "any",
|
||||
statuses_logic: str = "any",
|
||||
player_counts_logic: str = "any",
|
||||
metadata_providers_logic: str = "any",
|
||||
user_id: int | None = None,
|
||||
updated_after: datetime | None = None,
|
||||
include_file_stats: bool = False,
|
||||
@@ -974,6 +1010,11 @@ class DBRomsHandler(DBBaseHandler):
|
||||
(regions, regions_logic, self._filter_by_regions),
|
||||
(languages, languages_logic, self._filter_by_languages),
|
||||
(player_counts, player_counts_logic, self._filter_by_player_counts),
|
||||
(
|
||||
metadata_providers,
|
||||
metadata_providers_logic,
|
||||
self._filter_by_metadata_providers,
|
||||
),
|
||||
]
|
||||
|
||||
for values, logic, filter_func in filters_to_apply:
|
||||
@@ -1112,6 +1153,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
regions=kwargs.get("regions", None),
|
||||
languages=kwargs.get("languages", None),
|
||||
player_counts=kwargs.get("player_counts", None),
|
||||
metadata_providers=kwargs.get("metadata_providers", None),
|
||||
# Logic operators for multi-value filters
|
||||
genres_logic=kwargs.get("genres_logic", "any"),
|
||||
franchises_logic=kwargs.get("franchises_logic", "any"),
|
||||
@@ -1122,6 +1164,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
languages_logic=kwargs.get("languages_logic", "any"),
|
||||
statuses_logic=kwargs.get("statuses_logic", "any"),
|
||||
player_counts_logic=kwargs.get("player_counts_logic", "any"),
|
||||
metadata_providers_logic=kwargs.get("metadata_providers_logic", "any"),
|
||||
user_id=kwargs.get("user_id", None),
|
||||
group_by_meta_id=kwargs.get("group_by_meta_id", False),
|
||||
include_files=kwargs.get("include_files", False),
|
||||
|
||||
@@ -4,13 +4,12 @@ from collections.abc import Sequence
|
||||
|
||||
from sqlalchemy import distinct, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm.attributes import InstrumentedAttribute
|
||||
from sqlalchemy.sql.selectable import Select
|
||||
|
||||
from decorators.database import begin_session
|
||||
from endpoints.responses.stats import MetadataCoverageItem, RegionBreakdownItem
|
||||
from models.assets import Save, Screenshot, State
|
||||
from models.rom import Rom, RomFile
|
||||
from models.rom import METADATA_SOURCE_COLUMNS, Rom, RomFile
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
@@ -28,21 +27,6 @@ def _exclude_hidden(
|
||||
return query
|
||||
|
||||
|
||||
# Metadata source columns on the Rom model, keyed by source identifier.
|
||||
_METADATA_SOURCE_COLUMNS: dict[str, InstrumentedAttribute] = {
|
||||
"igdb": Rom.igdb_id,
|
||||
"ss": Rom.ss_id,
|
||||
"moby": Rom.moby_id,
|
||||
"launchbox": Rom.launchbox_id,
|
||||
"ra": Rom.ra_id,
|
||||
"hasheous": Rom.hasheous_id,
|
||||
"tgdb": Rom.tgdb_id,
|
||||
"flashpoint": Rom.flashpoint_id,
|
||||
"hltb": Rom.hltb_id,
|
||||
"gamelist": Rom.gamelist_id,
|
||||
}
|
||||
|
||||
|
||||
class DBStatsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def get_platforms_count(
|
||||
@@ -140,7 +124,7 @@ class DBStatsHandler(DBBaseHandler):
|
||||
Rom.platform_id,
|
||||
*(
|
||||
func.count(col).label(key)
|
||||
for key, col in _METADATA_SOURCE_COLUMNS.items()
|
||||
for key, col in METADATA_SOURCE_COLUMNS.items()
|
||||
),
|
||||
).select_from(Rom),
|
||||
hidden_platform_ids,
|
||||
@@ -152,7 +136,7 @@ class DBStatsHandler(DBBaseHandler):
|
||||
for row in rows:
|
||||
result[row.platform_id] = [
|
||||
MetadataCoverageItem(source=key, matched=getattr(row, key))
|
||||
for key in _METADATA_SOURCE_COLUMNS
|
||||
for key in METADATA_SOURCE_COLUMNS
|
||||
if getattr(row, key) > 0
|
||||
]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user