mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
feat(roms): filter games by matched metadata provider
Adds a "Metadata provider" gallery filter so a library can be narrowed by which providers each ROM matched (IGDB, MobyGames, ScreenScraper, etc.), mirroring the existing multi-value filters (player count, age rating). Backend: - New `_filter_by_metadata_providers` keyed off each provider's id column on Rom, with any/all/none logic; wired through filter_roms, get_roms_scalar, the /roms endpoint, and the unscoped cache gate. - Smart collections apply the criterion via get_smart_collection_roms. - Unknown provider slugs are ignored (no-op) so stale bookmarks or hand-edited URLs don't error. Frontend (v1 + v2): - Shared METADATA_PROVIDER_OPTIONS registry; provider list is a fixed set rather than data-derived, so options are static. - 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. - Added the `platform.metadata-provider` key to all locales. Tests: - Backend handler, endpoint, and smart-collection coverage (any/all/none plus unknown-slug). - Frontend smartCollectionCriteria serialization/summary coverage. Also normalized collections_handler.py to LF (it was the only CRLF file in the backend, which tripped git-diff-check on the edited lines). AI assistance: implemented with Claude Code (Anthropic). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -444,6 +444,17 @@ def get_roms(
|
||||
),
|
||||
),
|
||||
] = None,
|
||||
metadata_providers: Annotated[
|
||||
list[str] | None,
|
||||
Query(
|
||||
description=(
|
||||
"Matched metadata provider (igdb, moby, ss, ra, launchbox, hasheous,"
|
||||
" flashpoint, hltb, gamelist, libretro). Multiple values are allowed by"
|
||||
" repeating the parameter, and results that match any of the values"
|
||||
" will be returned."
|
||||
),
|
||||
),
|
||||
] = None,
|
||||
# Logic operators for multi-value filters
|
||||
genres_logic: Annotated[
|
||||
str,
|
||||
@@ -499,6 +510,12 @@ def get_roms(
|
||||
description="Logic operator for player counts filter: 'any' (OR), 'all' (AND) or 'none' (NOT).",
|
||||
),
|
||||
] = "any",
|
||||
metadata_providers_logic: Annotated[
|
||||
str,
|
||||
Query(
|
||||
description="Logic operator for metadata providers filter: 'any' (OR), 'all' (AND) or 'none' (NOT).",
|
||||
),
|
||||
] = "any",
|
||||
order_by: Annotated[
|
||||
str,
|
||||
Query(
|
||||
@@ -558,6 +575,7 @@ def get_roms(
|
||||
regions=regions,
|
||||
languages=languages,
|
||||
player_counts=player_counts,
|
||||
metadata_providers=metadata_providers,
|
||||
# Logic operators
|
||||
genres_logic=genres_logic,
|
||||
franchises_logic=franchises_logic,
|
||||
@@ -568,6 +586,7 @@ def get_roms(
|
||||
languages_logic=languages_logic,
|
||||
statuses_logic=statuses_logic,
|
||||
player_counts_logic=player_counts_logic,
|
||||
metadata_providers_logic=metadata_providers_logic,
|
||||
group_by_meta_id=group_by_meta_id,
|
||||
updated_after=updated_after,
|
||||
include_file_stats=True,
|
||||
@@ -595,6 +614,7 @@ def get_roms(
|
||||
or regions
|
||||
or languages
|
||||
or player_counts
|
||||
or metadata_providers
|
||||
or updated_after
|
||||
or matched is not None
|
||||
or favorite is not None
|
||||
|
||||
@@ -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"),
|
||||
)
|
||||
|
||||
@@ -115,6 +115,24 @@ RUFFLE_SUPPORTED_PLATFORMS = [
|
||||
UPS.BROWSER,
|
||||
]
|
||||
|
||||
# Maps a metadata-provider slug (the value sent by the gallery filter, matching
|
||||
# the frontend provider registry and the MetadataSource enum) to the Rom column
|
||||
# that holds that provider's match id. A populated column means the ROM matched
|
||||
# that provider. Providers without a per-ROM match id (e.g. sgdb, playmatch) are
|
||||
# intentionally absent.
|
||||
METADATA_PROVIDER_COLUMNS: dict[str, QueryableAttribute] = {
|
||||
"igdb": Rom.igdb_id,
|
||||
"moby": Rom.moby_id,
|
||||
"ss": Rom.ss_id,
|
||||
"ra": Rom.ra_id,
|
||||
"launchbox": Rom.launchbox_id,
|
||||
"hasheous": Rom.hasheous_id,
|
||||
"flashpoint": Rom.flashpoint_id,
|
||||
"hltb": Rom.hltb_id,
|
||||
"gamelist": Rom.gamelist_id,
|
||||
"libretro": Rom.libretro_id,
|
||||
}
|
||||
|
||||
# Used to remove native full-text SQL operators
|
||||
FULLTEXT_BOOLEAN_OPERATORS_REGEX = re.compile(r'[+\-~<>()"@*]')
|
||||
|
||||
@@ -700,6 +718,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_PROVIDER_COLUMNS[value]
|
||||
for value in values
|
||||
if value in METADATA_PROVIDER_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,
|
||||
@@ -727,6 +778,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",
|
||||
@@ -737,6 +789,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,
|
||||
@@ -963,6 +1016,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:
|
||||
@@ -1093,6 +1151,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"),
|
||||
@@ -1103,6 +1162,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),
|
||||
|
||||
@@ -85,6 +85,49 @@ def test_get_all_roms(
|
||||
assert items[0]["sibling_roms"] == []
|
||||
|
||||
|
||||
def test_get_roms_filter_by_metadata_providers(
|
||||
client: TestClient, access_token: str, rom: Rom, platform: Platform
|
||||
):
|
||||
rom_igdb = db_rom_handler.add_rom(
|
||||
Rom(
|
||||
platform_id=platform.id,
|
||||
name="rom_igdb",
|
||||
slug="rom_igdb",
|
||||
fs_name="rom_igdb.zip",
|
||||
fs_name_no_tags="rom_igdb",
|
||||
fs_name_no_ext="rom_igdb",
|
||||
fs_extension="zip",
|
||||
fs_path=f"{platform.slug}/roms",
|
||||
igdb_id=MOCK_IGDB_ID,
|
||||
)
|
||||
)
|
||||
|
||||
response = client.get(
|
||||
"/api/roms",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
params={"platform_id": platform.id, "metadata_providers": ["igdb"]},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
body = response.json()
|
||||
assert {item["id"] for item in body["items"]} == {rom_igdb.id}
|
||||
|
||||
# "none" logic returns the ROMs not matched to the selected provider.
|
||||
response = client.get(
|
||||
"/api/roms",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
params={
|
||||
"platform_id": platform.id,
|
||||
"metadata_providers": ["igdb"],
|
||||
"metadata_providers_logic": "none",
|
||||
},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
body = response.json()
|
||||
assert {item["id"] for item in body["items"]} == {rom.id}
|
||||
|
||||
|
||||
def test_get_all_roms_with_files(
|
||||
client: TestClient, access_token: str, rom: Rom, platform: Platform
|
||||
):
|
||||
|
||||
@@ -22,3 +22,23 @@ def test_get_smart_collection_roms_normalizes_legacy_selected_status_lists(
|
||||
"finished",
|
||||
"completed_100",
|
||||
]
|
||||
|
||||
|
||||
def test_get_smart_collection_roms_passes_metadata_providers(admin_user: User, mocker):
|
||||
get_roms_scalar = mocker.patch("handler.database.db_rom_handler.get_roms_scalar")
|
||||
smart_collection = SmartCollection(
|
||||
name="IGDB and Moby matches",
|
||||
description="",
|
||||
user_id=admin_user.id,
|
||||
filter_criteria={
|
||||
"metadata_providers": ["igdb", "moby"],
|
||||
"metadata_providers_logic": "all",
|
||||
},
|
||||
)
|
||||
|
||||
db_collection_handler.get_smart_collection_roms(
|
||||
smart_collection, user_id=admin_user.id
|
||||
)
|
||||
|
||||
assert get_roms_scalar.call_args.kwargs["metadata_providers"] == ["igdb", "moby"]
|
||||
assert get_roms_scalar.call_args.kwargs["metadata_providers_logic"] == "all"
|
||||
|
||||
@@ -894,3 +894,63 @@ def test_screenshots(screenshot: Screenshot, platform: Platform, admin_user: Use
|
||||
rom = db_rom_handler.get_rom(id=screenshot.rom_id)
|
||||
assert rom is not None
|
||||
assert len(rom.screenshots) == 1
|
||||
|
||||
|
||||
def _add_rom_with_providers(platform: Platform, slug: str, **provider_ids) -> Rom:
|
||||
return db_rom_handler.add_rom(
|
||||
Rom(
|
||||
platform_id=platform.id,
|
||||
name=slug,
|
||||
slug=slug,
|
||||
fs_name=f"{slug}.zip",
|
||||
fs_name_no_tags=slug,
|
||||
fs_name_no_ext=slug,
|
||||
fs_extension="zip",
|
||||
fs_path=f"{platform.slug}/roms",
|
||||
**provider_ids,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_filter_by_metadata_providers(rom: Rom, platform: Platform):
|
||||
# `rom` fixture has no provider ids (unmatched).
|
||||
rom_igdb = _add_rom_with_providers(platform, "rom_igdb", igdb_id=1)
|
||||
rom_moby = _add_rom_with_providers(platform, "rom_moby", moby_id=2)
|
||||
rom_both = _add_rom_with_providers(platform, "rom_both", igdb_id=3, moby_id=4)
|
||||
|
||||
# "any" (OR): matched to at least one of the selected providers.
|
||||
any_igdb = db_rom_handler.get_roms_scalar(metadata_providers=["igdb"])
|
||||
assert {r.id for r in any_igdb} == {rom_igdb.id, rom_both.id}
|
||||
|
||||
any_either = db_rom_handler.get_roms_scalar(
|
||||
metadata_providers=["igdb", "moby"], metadata_providers_logic="any"
|
||||
)
|
||||
assert {r.id for r in any_either} == {rom_igdb.id, rom_moby.id, rom_both.id}
|
||||
|
||||
# "all" (AND): matched to every selected provider.
|
||||
all_both = db_rom_handler.get_roms_scalar(
|
||||
metadata_providers=["igdb", "moby"], metadata_providers_logic="all"
|
||||
)
|
||||
assert {r.id for r in all_both} == {rom_both.id}
|
||||
|
||||
# "none" (NOT): matched to none of the selected providers.
|
||||
none_igdb = db_rom_handler.get_roms_scalar(
|
||||
metadata_providers=["igdb"], metadata_providers_logic="none"
|
||||
)
|
||||
assert {r.id for r in none_igdb} == {rom.id, rom_moby.id}
|
||||
|
||||
|
||||
def test_filter_by_metadata_providers_unknown_value_is_ignored(
|
||||
rom: Rom, platform: Platform
|
||||
):
|
||||
"""Unknown provider slugs are dropped so the filter is a no-op rather than
|
||||
raising, keeping a stale bookmark or hand-edited URL from 500-ing."""
|
||||
rom_igdb = _add_rom_with_providers(platform, "rom_igdb", igdb_id=1)
|
||||
|
||||
only_unknown = db_rom_handler.get_roms_scalar(metadata_providers=["bogus"])
|
||||
assert {r.id for r in only_unknown} == {rom.id, rom_igdb.id}
|
||||
|
||||
known_and_unknown = db_rom_handler.get_roms_scalar(
|
||||
metadata_providers=["igdb", "bogus"]
|
||||
)
|
||||
assert {r.id for r in known_and_unknown} == {rom_igdb.id}
|
||||
|
||||
@@ -21,7 +21,11 @@ import storeGalleryFilter, {
|
||||
import storePlatforms from "@/stores/platforms";
|
||||
import storeRoms from "@/stores/roms";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import { romStatusMap, type PlayingStatus } from "@/utils";
|
||||
import {
|
||||
METADATA_PROVIDER_OPTIONS,
|
||||
romStatusMap,
|
||||
type PlayingStatus,
|
||||
} from "@/utils";
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
@@ -80,7 +84,13 @@ const {
|
||||
filterPlayerCounts,
|
||||
selectedPlayerCounts,
|
||||
playerCountsLogic,
|
||||
selectedMetadataProviders,
|
||||
metadataProvidersLogic,
|
||||
} = storeToRefs(galleryFilterStore);
|
||||
|
||||
// Provider options are a fixed registry (not data-derived like the other
|
||||
// lists), so they live in a shared constant rather than coming from the API.
|
||||
const filterMetadataProviders = ref(METADATA_PROVIDER_OPTIONS);
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
|
||||
const onFilterChange = debounce(
|
||||
@@ -160,6 +170,14 @@ const onFilterChange = debounce(
|
||||
: null,
|
||||
playerCountsLogic:
|
||||
selectedPlayerCounts.value.length > 0 ? playerCountsLogic.value : null,
|
||||
metadataProviders:
|
||||
selectedMetadataProviders.value.length > 0
|
||||
? selectedMetadataProviders.value.join(",")
|
||||
: null,
|
||||
metadataProvidersLogic:
|
||||
selectedMetadataProviders.value.length > 0
|
||||
? metadataProvidersLogic.value
|
||||
: null,
|
||||
}).forEach(([key, value]) => {
|
||||
if (value) {
|
||||
url.searchParams.set(key, value);
|
||||
@@ -249,6 +267,14 @@ const filters = [
|
||||
setLogic: (logic: FilterLogicOperator) =>
|
||||
galleryFilterStore.setPlayerCountsLogic(logic),
|
||||
},
|
||||
{
|
||||
label: t("platform.metadata-provider"),
|
||||
selected: selectedMetadataProviders,
|
||||
items: filterMetadataProviders,
|
||||
logic: metadataProvidersLogic,
|
||||
setLogic: (logic: FilterLogicOperator) =>
|
||||
galleryFilterStore.setMetadataProvidersLogic(logic),
|
||||
},
|
||||
{
|
||||
label: t("platform.status"),
|
||||
selected: selectedStatuses,
|
||||
@@ -297,6 +323,8 @@ onMounted(async () => {
|
||||
statusesLogic: urlStatusesLogic,
|
||||
playerCounts: urlPlayerCounts,
|
||||
playerCountsLogic: urlPlayerCountsLogic,
|
||||
metadataProviders: urlMetadataProviders,
|
||||
metadataProvidersLogic: urlMetadataProvidersLogic,
|
||||
} = router.currentRoute.value.query;
|
||||
|
||||
// Check for query params to set filters
|
||||
@@ -479,6 +507,18 @@ onMounted(async () => {
|
||||
}
|
||||
}
|
||||
|
||||
if (urlMetadataProviders !== undefined) {
|
||||
const metadataProviders = (urlMetadataProviders as string)
|
||||
.split(",")
|
||||
.filter((mp) => mp.trim());
|
||||
galleryFilterStore.setSelectedFilterMetadataProviders(metadataProviders);
|
||||
if (urlMetadataProvidersLogic !== undefined) {
|
||||
galleryFilterStore.setMetadataProvidersLogic(
|
||||
urlMetadataProvidersLogic as FilterLogicOperator,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if search term is set in the URL (empty string is ok)
|
||||
const freshSearch = urlSearch !== undefined && urlSearch !== searchTerm.value;
|
||||
if (freshSearch) {
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Липсваща платформа от файловата система",
|
||||
"no-firmware-found": "Няма намерен фърмуер",
|
||||
"player-count": "Брой играчи",
|
||||
"metadata-provider": "Доставчик на метаданни",
|
||||
"region": "Регион",
|
||||
"removing-firmware": "Премахване на {n} фърмуер файл от RomM | Премахване на {n} фърмуер файла от RomM",
|
||||
"removing-platform-1": "Премахване на платформа",
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
"missing-from-filesystem": "Platforma chybí v systému souborů",
|
||||
"no-firmware-found": "Nenalezen žádný firmware",
|
||||
"player-count": "Počet hráčů",
|
||||
"metadata-provider": "Poskytovatel metadat",
|
||||
"region": "Region",
|
||||
"removing-firmware": "Odstraňování {n} firmwarů z RomM | Odstraňování {n} firmwaru z RomM | Odstraňování {n} firmware z RomM | Odstraňování {n} firmwarů z RomM",
|
||||
"removing-platform-1": "Odstraňuje se platforma",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Plattform fehlt im Dateisystem",
|
||||
"no-firmware-found": "Keine Firmware gefunden",
|
||||
"player-count": "Spieleranzahl",
|
||||
"metadata-provider": "Metadatenanbieter",
|
||||
"region": "Region",
|
||||
"removing-firmware": "Entferne {n} Firmware aus RomM | Entferne {n} Firmwares aus RomM",
|
||||
"removing-platform-1": "Löschen Plattform",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Missing platform from filesystem",
|
||||
"no-firmware-found": "No firmware found",
|
||||
"player-count": "Player count",
|
||||
"metadata-provider": "Metadata provider",
|
||||
"region": "Region",
|
||||
"removing-firmware": "Removing {n} firmware file from RomM | Removing {n} firmware files from RomM",
|
||||
"removing-platform-1": "Removing platform",
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
"missing-from-filesystem": "Missing platform from filesystem",
|
||||
"no-firmware-found": "No firmware found",
|
||||
"player-count": "Player count",
|
||||
"metadata-provider": "Metadata provider",
|
||||
"region": "Region",
|
||||
"removing-firmware": "Removing {n} firmware file from RomM | Removing {n} firmware files from RomM",
|
||||
"removing-platform-1": "Removing platform",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Plataforma faltante del sistema de archivos",
|
||||
"no-firmware-found": "No se encontraron firmwares",
|
||||
"player-count": "Número de jugadores",
|
||||
"metadata-provider": "Proveedor de metadatos",
|
||||
"region": "Región",
|
||||
"removing-firmware": "Eliminando {n} firmware de RomM | Eliminando {n} firmwares de RomM",
|
||||
"removing-platform-1": "Eliminando",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Plateforme manquante du système de fichiers",
|
||||
"no-firmware-found": "Aucun firmware trouvé",
|
||||
"player-count": "Nombre de joueurs",
|
||||
"metadata-provider": "Fournisseur de métadonnées",
|
||||
"region": "Région",
|
||||
"removing-firmware": "Suppression de {n} firmware de RomM | Suppression de {n} firmwares de RomM",
|
||||
"removing-platform-1": "Confirmez le retrait de",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Platform hiányzik a fájlrendszerből",
|
||||
"no-firmware-found": "Firmware nem található",
|
||||
"player-count": "Játékosok száma",
|
||||
"metadata-provider": "Metaadat-szolgáltató",
|
||||
"region": "Régió",
|
||||
"removing-firmware": "Eltávolítottál {n} firmware fájlt a RomM-ból | Eltávolítottál {n} firmware fájlokat a RomM-ból",
|
||||
"removing-platform-1": "Platform eltávolítása",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Piattaforma mancante dal filesystem",
|
||||
"no-firmware-found": "Nessun firmware trovato",
|
||||
"player-count": "Numero di giocatori",
|
||||
"metadata-provider": "Fornitore di metadati",
|
||||
"region": "Regione",
|
||||
"removing-firmware": "Rimozione di {n} firmware da RomM | Rimozione di {n} firmware da RomM",
|
||||
"removing-platform-1": "Stai eliminando la piattaforma",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "ファイルシステムにプラットフォームが存在しません",
|
||||
"no-firmware-found": "ファームウェアが見つかりません",
|
||||
"player-count": "プレイヤー",
|
||||
"metadata-provider": "メタデータプロバイダー",
|
||||
"region": "地域",
|
||||
"removing-firmware": "{n} 個のファームウェアをRomMから削除中",
|
||||
"removing-platform-1": "RomMからプラットフォームを削除しようとしています",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "파일시스템에서 플랫폼 누락",
|
||||
"no-firmware-found": "펌웨어 없음",
|
||||
"player-count": "플레이어 수",
|
||||
"metadata-provider": "메타데이터 제공자",
|
||||
"region": "지역",
|
||||
"removing-firmware": "{n} 개 펌웨어를 RomM에서 제거 중",
|
||||
"removing-platform-1": "플랫폼",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Platforma brakuje w systemie plików",
|
||||
"no-firmware-found": "Nie znaleziono oprogramowania",
|
||||
"player-count": "Liczba graczy",
|
||||
"metadata-provider": "Dostawca metadanych",
|
||||
"region": "Region",
|
||||
"removing-firmware": "Usuwanie {n} firmware z RomM | Usuwanie {n} firmware'ów z RomM",
|
||||
"removing-platform-1": "Usuwanie platformy",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Plataforma ausente do sistema de arquivos",
|
||||
"no-firmware-found": "Nenhum firmware encontrado",
|
||||
"player-count": "Niver ar c'hoarierien",
|
||||
"metadata-provider": "Provedor de metadados",
|
||||
"region": "Região",
|
||||
"removing-firmware": "Removendo {n} firmware do RomM | Removendo {n} firmwares do RomM",
|
||||
"removing-platform-1": "Removendo plataforma",
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
"missing-from-filesystem": "Platformă lipsă din sistemul de fișiere",
|
||||
"no-firmware-found": "Niciun firmware găsit",
|
||||
"player-count": "Numărul de jucători",
|
||||
"metadata-provider": "Furnizor de metadate",
|
||||
"region": "Regiune",
|
||||
"removing-firmware": "Eliminarea a {n} firmware din RomM | Eliminarea a {n} firmware-uri din RomM",
|
||||
"removing-platform-1": "Confirmă eliminarea",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "Платформа отсутствует в файловой системе",
|
||||
"no-firmware-found": "Прошивка не найдена",
|
||||
"player-count": "Количество игроков",
|
||||
"metadata-provider": "Источник метаданных",
|
||||
"region": "Регион",
|
||||
"removing-firmware": "Удаление {n} прошивку из RomM | Удаление {n} прошивок из RomM",
|
||||
"removing-platform-1": "Удаление платформы",
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
"missing-from-filesystem": "Platform dosya sisteminde bulunamadı",
|
||||
"no-firmware-found": "Firmware bulunamadı",
|
||||
"player-count": "Oyuncu sayısı",
|
||||
"metadata-provider": "Üst veri sağlayıcısı",
|
||||
"region": "Bölge",
|
||||
"removing-firmware": "RomM'den {n} firmware dosyası kaldırılıyor | RomM'den {n} firmware dosyası kaldırılıyor",
|
||||
"removing-platform-1": "Platform kaldırılıyor",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "平台在文件系统中缺失",
|
||||
"no-firmware-found": "没有找到固件",
|
||||
"player-count": "玩家人数",
|
||||
"metadata-provider": "元数据提供方",
|
||||
"region": "地区",
|
||||
"removing-firmware": "正在从RomM删除 {n} 个固件从RomM中删除",
|
||||
"removing-platform-1": "将从 RomM 中移除平台 [",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"missing-from-filesystem": "平台在檔案系統中缺失",
|
||||
"no-firmware-found": "没有找到韌體",
|
||||
"player-count": "玩家人數",
|
||||
"metadata-provider": "中繼資料提供者",
|
||||
"region": "地區",
|
||||
"removing-firmware": "正在從RomM移除 {n} 個韌體從RomM移除",
|
||||
"removing-platform-1": "將删除平台 \"",
|
||||
|
||||
@@ -165,6 +165,7 @@ export interface GetRomsParams {
|
||||
selectedRegions?: string[] | null;
|
||||
selectedLanguages?: string[] | null;
|
||||
selectedPlayerCounts?: string[] | null;
|
||||
selectedMetadataProviders?: string[] | null;
|
||||
selectedStatuses?: string[] | null;
|
||||
// Logic operators for multi-value filters
|
||||
genresLogic?: string | null;
|
||||
@@ -176,6 +177,7 @@ export interface GetRomsParams {
|
||||
languagesLogic?: string | null;
|
||||
statusesLogic?: string | null;
|
||||
playerCountsLogic?: string | null;
|
||||
metadataProvidersLogic?: string | null;
|
||||
// Cancellation: pass an AbortSignal to let the caller abort an
|
||||
// in-flight request (e.g. search-typing → previous query aborted,
|
||||
// gallery-context switch → previous platform's windows aborted).
|
||||
@@ -208,6 +210,7 @@ async function getRoms({
|
||||
selectedRegions = null,
|
||||
selectedLanguages = null,
|
||||
selectedPlayerCounts = null,
|
||||
selectedMetadataProviders = null,
|
||||
selectedStatuses = null,
|
||||
// Logic operators
|
||||
genresLogic = null,
|
||||
@@ -219,6 +222,7 @@ async function getRoms({
|
||||
languagesLogic = null,
|
||||
statusesLogic = null,
|
||||
playerCountsLogic = null,
|
||||
metadataProvidersLogic = null,
|
||||
signal = undefined,
|
||||
}: GetRomsParams) {
|
||||
const params = {
|
||||
@@ -267,6 +271,10 @@ async function getRoms({
|
||||
selectedPlayerCounts && selectedPlayerCounts.length > 0
|
||||
? selectedPlayerCounts
|
||||
: undefined,
|
||||
metadata_providers:
|
||||
selectedMetadataProviders && selectedMetadataProviders.length > 0
|
||||
? selectedMetadataProviders
|
||||
: undefined,
|
||||
// Logic operators
|
||||
genres_logic:
|
||||
selectedGenres && selectedGenres.length > 0
|
||||
@@ -304,6 +312,10 @@ async function getRoms({
|
||||
selectedPlayerCounts && selectedPlayerCounts.length > 0
|
||||
? playerCountsLogic || "any"
|
||||
: undefined,
|
||||
metadata_providers_logic:
|
||||
selectedMetadataProviders && selectedMetadataProviders.length > 0
|
||||
? metadataProvidersLogic || "any"
|
||||
: undefined,
|
||||
...(filterMatched !== null ? { matched: filterMatched } : {}),
|
||||
...(filterFavorites !== null ? { favorite: filterFavorites } : {}),
|
||||
...(filterDuplicates !== null ? { duplicate: filterDuplicates } : {}),
|
||||
|
||||
10
frontend/src/services/cache/api.ts
vendored
10
frontend/src/services/cache/api.ts
vendored
@@ -78,6 +78,11 @@ class CachedApiService {
|
||||
params.selectedPlayerCounts && params.selectedPlayerCounts.length > 0
|
||||
? params.selectedPlayerCounts
|
||||
: undefined,
|
||||
metadata_providers:
|
||||
params.selectedMetadataProviders &&
|
||||
params.selectedMetadataProviders.length > 0
|
||||
? params.selectedMetadataProviders
|
||||
: undefined,
|
||||
// Logic operators
|
||||
genres_logic:
|
||||
params.selectedGenres && params.selectedGenres.length > 0
|
||||
@@ -115,6 +120,11 @@ class CachedApiService {
|
||||
params.selectedPlayerCounts && params.selectedPlayerCounts.length > 0
|
||||
? params.playerCountsLogic || "any"
|
||||
: undefined,
|
||||
metadata_providers_logic:
|
||||
params.selectedMetadataProviders &&
|
||||
params.selectedMetadataProviders.length > 0
|
||||
? params.metadataProvidersLogic || "any"
|
||||
: undefined,
|
||||
...(params.filterMatched !== null
|
||||
? { matched: params.filterMatched }
|
||||
: {}),
|
||||
|
||||
@@ -11,7 +11,8 @@ export type FilterType =
|
||||
| "statuses"
|
||||
| "regions"
|
||||
| "languages"
|
||||
| "playerCounts";
|
||||
| "playerCounts"
|
||||
| "metadataProviders";
|
||||
|
||||
export type FilterLogicOperator = "any" | "all" | "none";
|
||||
|
||||
@@ -50,6 +51,7 @@ const buildDefaultFilterState = () => ({
|
||||
selectedRegions: [] as string[],
|
||||
selectedLanguages: [] as string[],
|
||||
selectedPlayerCounts: [] as string[],
|
||||
selectedMetadataProviders: [] as string[],
|
||||
selectedStatuses: [] as string[],
|
||||
// Logic operators for multi-select filters
|
||||
genresLogic: "any" as FilterLogicOperator,
|
||||
@@ -61,6 +63,7 @@ const buildDefaultFilterState = () => ({
|
||||
languagesLogic: "any" as FilterLogicOperator,
|
||||
statusesLogic: "any" as FilterLogicOperator,
|
||||
playerCountsLogic: "any" as FilterLogicOperator,
|
||||
metadataProvidersLogic: "any" as FilterLogicOperator,
|
||||
});
|
||||
|
||||
export default defineStore("galleryFilter", {
|
||||
@@ -155,6 +158,12 @@ export default defineStore("galleryFilter", {
|
||||
setPlayerCountsLogic(logic: FilterLogicOperator) {
|
||||
this.playerCountsLogic = logic;
|
||||
},
|
||||
setSelectedFilterMetadataProviders(metadataProviders: string[]) {
|
||||
this.selectedMetadataProviders = metadataProviders;
|
||||
},
|
||||
setMetadataProvidersLogic(logic: FilterLogicOperator) {
|
||||
this.metadataProvidersLogic = logic;
|
||||
},
|
||||
setSelectedFilterStatuses(statuses: string[]) {
|
||||
this.selectedStatuses = statuses;
|
||||
},
|
||||
@@ -355,6 +364,7 @@ export default defineStore("galleryFilter", {
|
||||
this.selectedRegions.length > 0 ||
|
||||
this.selectedLanguages.length > 0 ||
|
||||
this.selectedPlayerCounts.length > 0 ||
|
||||
this.selectedMetadataProviders.length > 0 ||
|
||||
this.selectedStatuses.length > 0,
|
||||
);
|
||||
},
|
||||
@@ -372,6 +382,7 @@ export default defineStore("galleryFilter", {
|
||||
this.selectedRegions = [];
|
||||
this.selectedLanguages = [];
|
||||
this.selectedPlayerCounts = [];
|
||||
this.selectedMetadataProviders = [];
|
||||
this.selectedStatuses = [];
|
||||
this.filterMatched = null;
|
||||
this.filterFavorites = null;
|
||||
@@ -390,6 +401,7 @@ export default defineStore("galleryFilter", {
|
||||
this.languagesLogic = "any";
|
||||
this.statusesLogic = "any";
|
||||
this.playerCountsLogic = "any";
|
||||
this.metadataProvidersLogic = "any";
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -165,6 +165,7 @@ export default defineStore("roms", {
|
||||
selectedRegions: galleryFilter.selectedRegions,
|
||||
selectedLanguages: galleryFilter.selectedLanguages,
|
||||
selectedPlayerCounts: galleryFilter.selectedPlayerCounts,
|
||||
selectedMetadataProviders: galleryFilter.selectedMetadataProviders,
|
||||
selectedStatuses: galleryFilter.selectedStatuses,
|
||||
// Logic operators
|
||||
genresLogic: galleryFilter.genresLogic,
|
||||
@@ -176,6 +177,7 @@ export default defineStore("roms", {
|
||||
languagesLogic: galleryFilter.languagesLogic,
|
||||
statusesLogic: galleryFilter.statusesLogic,
|
||||
playerCountsLogic: galleryFilter.playerCountsLogic,
|
||||
metadataProvidersLogic: galleryFilter.metadataProvidersLogic,
|
||||
};
|
||||
return params;
|
||||
},
|
||||
|
||||
@@ -77,6 +77,24 @@ export function getRoleIcon(role: string) {
|
||||
*/
|
||||
export const defaultAvatarPath = "/assets/default/user.svg";
|
||||
|
||||
// Filterable metadata providers — the providers a ROM can be matched to,
|
||||
// keyed by the slug the backend filter expects (matches the MetadataSource
|
||||
// enum and each provider's id column on Rom). Titles are brand names, so
|
||||
// they are intentionally not translated. Shared by the v1 and v2 gallery
|
||||
// filter drawers so both offer the same options.
|
||||
export const METADATA_PROVIDER_OPTIONS: { value: string; title: string }[] = [
|
||||
{ value: "igdb", title: "IGDB" },
|
||||
{ value: "moby", title: "MobyGames" },
|
||||
{ value: "ss", title: "ScreenScraper" },
|
||||
{ value: "ra", title: "RetroAchievements" },
|
||||
{ value: "launchbox", title: "LaunchBox" },
|
||||
{ value: "hasheous", title: "Hasheous" },
|
||||
{ value: "flashpoint", title: "Flashpoint" },
|
||||
{ value: "hltb", title: "HowLongToBeat" },
|
||||
{ value: "gamelist", title: "ES-DE" },
|
||||
{ value: "libretro", title: "Libretro" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Normalize a string by converting it to lowercase and removing diacritics.
|
||||
*
|
||||
|
||||
@@ -108,6 +108,8 @@ const openHandler = () => {
|
||||
languagesLogic: galleryFilter.languagesLogic,
|
||||
selectedPlayerCounts: galleryFilter.selectedPlayerCounts,
|
||||
playerCountsLogic: galleryFilter.playerCountsLogic,
|
||||
selectedMetadataProviders: galleryFilter.selectedMetadataProviders,
|
||||
metadataProvidersLogic: galleryFilter.metadataProvidersLogic,
|
||||
selectedStatuses: galleryFilter.selectedStatuses,
|
||||
statusesLogic: galleryFilter.statusesLogic,
|
||||
},
|
||||
|
||||
@@ -8,9 +8,10 @@
|
||||
// true → positive, false → negative.
|
||||
// • Optional platform multi-select (only on Search / Collection views
|
||||
// where you can mix platforms).
|
||||
// • 9 multi-select filter groups (genres / franchises / collections /
|
||||
// • 10 multi-select filter groups (genres / franchises / collections /
|
||||
// companies / age-ratings / regions / languages / player-counts /
|
||||
// statuses) — each paired with an AND/OR/NONE logic toggle.
|
||||
// metadata-providers / statuses) — each paired with an AND/OR/NONE
|
||||
// logic toggle.
|
||||
// • Reset button at the bottom.
|
||||
//
|
||||
// Apply is implicit — the URL composable + galleryRoms watcher refresh
|
||||
@@ -30,7 +31,11 @@ import storeGalleryFilter, {
|
||||
} from "@/stores/galleryFilter";
|
||||
import storePlatforms, { type Platform } from "@/stores/platforms";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import { romStatusMap, type PlayingStatus } from "@/utils";
|
||||
import {
|
||||
METADATA_PROVIDER_OPTIONS,
|
||||
romStatusMap,
|
||||
type PlayingStatus,
|
||||
} from "@/utils";
|
||||
import PlatformSelect from "@/v2/components/shared/PlatformSelect.vue";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
@@ -86,12 +91,26 @@ const {
|
||||
filterPlayerCounts,
|
||||
selectedPlayerCounts,
|
||||
playerCountsLogic,
|
||||
selectedMetadataProviders,
|
||||
metadataProvidersLogic,
|
||||
filterStatuses,
|
||||
selectedStatuses,
|
||||
statusesLogic,
|
||||
} = storeToRefs(filter);
|
||||
const { allPlatforms } = storeToRefs(platformsStore);
|
||||
|
||||
// Provider options are a fixed registry (not data-derived like the other
|
||||
// lists). Items are the provider slugs; `providerTitle` maps each to its
|
||||
// brand name for display.
|
||||
const providerItems = computed(() =>
|
||||
METADATA_PROVIDER_OPTIONS.map((p) => p.value),
|
||||
);
|
||||
const providerLabels = new Map(
|
||||
METADATA_PROVIDER_OPTIONS.map((p) => [p.value, p.title]),
|
||||
);
|
||||
const providerTitle = (slug: string): string =>
|
||||
providerLabels.get(slug) ?? slug;
|
||||
|
||||
// ── Tri-state mapping helpers ──────────────────────────────────
|
||||
// The RSliderBtnGroup speaks string ids; the store speaks `boolean | null`.
|
||||
// One helper makes the binding bidirectional in a few lines.
|
||||
@@ -294,6 +313,15 @@ const multiSections = computed<MultiConfig[]>(() => [
|
||||
logic: playerCountsLogic,
|
||||
setLogic: (l) => filter.setPlayerCountsLogic(l),
|
||||
},
|
||||
{
|
||||
label: t("platform.metadata-provider"),
|
||||
icon: "mdi-database-outline",
|
||||
items: providerItems,
|
||||
selected: selectedMetadataProviders,
|
||||
logic: metadataProvidersLogic,
|
||||
setLogic: (l) => filter.setMetadataProvidersLogic(l),
|
||||
toTitle: providerTitle,
|
||||
},
|
||||
{
|
||||
label: t("platform.status"),
|
||||
icon: "mdi-flag-outline",
|
||||
|
||||
@@ -165,6 +165,7 @@ const {
|
||||
selectedRegions,
|
||||
selectedLanguages,
|
||||
selectedPlayerCounts,
|
||||
selectedMetadataProviders,
|
||||
selectedStatuses,
|
||||
} = storeToRefs(galleryFilterStore);
|
||||
|
||||
@@ -194,6 +195,7 @@ const filterActiveCount = computed(() => {
|
||||
selectedRegions,
|
||||
selectedLanguages,
|
||||
selectedPlayerCounts,
|
||||
selectedMetadataProviders,
|
||||
selectedStatuses,
|
||||
]) {
|
||||
if (arr.value.length > 0) n += 1;
|
||||
@@ -224,6 +226,7 @@ watch(
|
||||
selectedRegions,
|
||||
selectedLanguages,
|
||||
selectedPlayerCounts,
|
||||
selectedMetadataProviders,
|
||||
selectedStatuses,
|
||||
],
|
||||
() => {
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
// ?languages=…&languagesLogic=…
|
||||
// ?statuses=…&statusesLogic=…
|
||||
// ?playerCounts=…&playerCountsLogic=…
|
||||
// ?metadataProviders=…&metadataProvidersLogic=…
|
||||
//
|
||||
// Direction notes:
|
||||
// * URL → store fires on every `route.query` change (browser back /
|
||||
@@ -110,6 +111,7 @@ export function useGalleryFilterUrl() {
|
||||
selectedRegions,
|
||||
selectedLanguages,
|
||||
selectedPlayerCounts,
|
||||
selectedMetadataProviders,
|
||||
selectedStatuses,
|
||||
genresLogic,
|
||||
franchisesLogic,
|
||||
@@ -119,6 +121,7 @@ export function useGalleryFilterUrl() {
|
||||
regionsLogic,
|
||||
languagesLogic,
|
||||
playerCountsLogic,
|
||||
metadataProvidersLogic,
|
||||
statusesLogic,
|
||||
} = storeToRefs(filter);
|
||||
|
||||
@@ -157,6 +160,8 @@ export function useGalleryFilterUrl() {
|
||||
languagesLogic: qLogic(q.languagesLogic),
|
||||
playerCounts: qList(q.playerCounts),
|
||||
playerCountsLogic: qLogic(q.playerCountsLogic),
|
||||
metadataProviders: qList(q.metadataProviders),
|
||||
metadataProvidersLogic: qLogic(q.metadataProvidersLogic),
|
||||
statuses: qList(q.statuses),
|
||||
statusesLogic: qLogic(q.statusesLogic),
|
||||
};
|
||||
@@ -238,6 +243,14 @@ export function useGalleryFilterUrl() {
|
||||
)
|
||||
filter.setPlayerCountsLogic(url.playerCountsLogic);
|
||||
|
||||
if (!eqStrArr(url.metadataProviders, selectedMetadataProviders.value))
|
||||
filter.setSelectedFilterMetadataProviders(url.metadataProviders);
|
||||
if (
|
||||
url.metadataProvidersLogic &&
|
||||
url.metadataProvidersLogic !== metadataProvidersLogic.value
|
||||
)
|
||||
filter.setMetadataProvidersLogic(url.metadataProvidersLogic);
|
||||
|
||||
if (!eqStrArr(url.statuses, selectedStatuses.value))
|
||||
filter.setSelectedFilterStatuses(url.statuses);
|
||||
if (url.statusesLogic && url.statusesLogic !== statusesLogic.value)
|
||||
@@ -339,6 +352,13 @@ export function useGalleryFilterUrl() {
|
||||
"playerCountsLogic",
|
||||
selectedPlayerCounts.value.length > 0 ? playerCountsLogic.value : null,
|
||||
);
|
||||
setList("metadataProviders", selectedMetadataProviders.value);
|
||||
setOrDelete(
|
||||
"metadataProvidersLogic",
|
||||
selectedMetadataProviders.value.length > 0
|
||||
? metadataProvidersLogic.value
|
||||
: null,
|
||||
);
|
||||
setList("statuses", selectedStatuses.value);
|
||||
setOrDelete(
|
||||
"statusesLogic",
|
||||
@@ -392,6 +412,8 @@ export function useGalleryFilterUrl() {
|
||||
languagesLogic,
|
||||
selectedPlayerCounts,
|
||||
playerCountsLogic,
|
||||
selectedMetadataProviders,
|
||||
metadataProvidersLogic,
|
||||
selectedStatuses,
|
||||
statusesLogic,
|
||||
],
|
||||
|
||||
@@ -307,6 +307,7 @@ export default defineStore("v2GalleryRoms", {
|
||||
selectedRegions: galleryFilter.selectedRegions,
|
||||
selectedLanguages: galleryFilter.selectedLanguages,
|
||||
selectedPlayerCounts: galleryFilter.selectedPlayerCounts,
|
||||
selectedMetadataProviders: galleryFilter.selectedMetadataProviders,
|
||||
selectedStatuses: galleryFilter.selectedStatuses,
|
||||
genresLogic: galleryFilter.genresLogic,
|
||||
franchisesLogic: galleryFilter.franchisesLogic,
|
||||
@@ -317,6 +318,7 @@ export default defineStore("v2GalleryRoms", {
|
||||
languagesLogic: galleryFilter.languagesLogic,
|
||||
statusesLogic: galleryFilter.statusesLogic,
|
||||
playerCountsLogic: galleryFilter.playerCountsLogic,
|
||||
metadataProvidersLogic: galleryFilter.metadataProvidersLogic,
|
||||
};
|
||||
},
|
||||
|
||||
|
||||
79
frontend/src/v2/utils/smartCollectionCriteria.test.ts
Normal file
79
frontend/src/v2/utils/smartCollectionCriteria.test.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Composer } from "vue-i18n";
|
||||
import {
|
||||
buildSmartFilterCriteria,
|
||||
type GalleryFilterSnapshot,
|
||||
summarizeSmartFilterCriteria,
|
||||
} from "./smartCollectionCriteria";
|
||||
|
||||
// Minimal i18n stub: returns the provided fallback (or the key). Cast to the
|
||||
// real composer type since we only exercise the (key, fallback) overload.
|
||||
const tStub = ((key: string, fallback?: string) =>
|
||||
fallback ?? key) as unknown as Composer["t"];
|
||||
|
||||
// Minimal "no filters set" snapshot; individual tests override fields.
|
||||
function emptySnapshot(): GalleryFilterSnapshot {
|
||||
return {
|
||||
searchTerm: null,
|
||||
filterMatched: null,
|
||||
filterFavorites: null,
|
||||
filterDuplicates: null,
|
||||
filterPlayables: null,
|
||||
filterRA: null,
|
||||
filterMissing: null,
|
||||
filterVerified: null,
|
||||
selectedPlatforms: [],
|
||||
selectedGenres: [],
|
||||
genresLogic: "any",
|
||||
selectedFranchises: [],
|
||||
franchisesLogic: "any",
|
||||
selectedCollections: [],
|
||||
collectionsLogic: "any",
|
||||
selectedCompanies: [],
|
||||
companiesLogic: "any",
|
||||
selectedAgeRatings: [],
|
||||
ageRatingsLogic: "any",
|
||||
selectedRegions: [],
|
||||
regionsLogic: "any",
|
||||
selectedLanguages: [],
|
||||
languagesLogic: "any",
|
||||
selectedPlayerCounts: [],
|
||||
playerCountsLogic: "any",
|
||||
selectedMetadataProviders: [],
|
||||
metadataProvidersLogic: "any",
|
||||
selectedStatuses: [],
|
||||
statusesLogic: "any",
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildSmartFilterCriteria — metadata providers", () => {
|
||||
it("serializes selected providers with their logic operator", () => {
|
||||
const out = buildSmartFilterCriteria({
|
||||
...emptySnapshot(),
|
||||
selectedMetadataProviders: ["igdb", "moby"],
|
||||
metadataProvidersLogic: "all",
|
||||
});
|
||||
|
||||
expect(out.metadata_providers).toEqual(["igdb", "moby"]);
|
||||
expect(out.metadata_providers_logic).toBe("all");
|
||||
});
|
||||
|
||||
it("omits the keys entirely when no provider is selected", () => {
|
||||
const out = buildSmartFilterCriteria(emptySnapshot());
|
||||
|
||||
expect(out.metadata_providers).toBeUndefined();
|
||||
expect(out.metadata_providers_logic).toBeUndefined();
|
||||
});
|
||||
|
||||
it("surfaces providers in the human-readable summary", () => {
|
||||
const rows = summarizeSmartFilterCriteria(
|
||||
{ metadata_providers: ["igdb"], metadata_providers_logic: "any" },
|
||||
tStub,
|
||||
);
|
||||
|
||||
const row = rows.find((r) => r.key === "metadata_providers");
|
||||
expect(row).toBeDefined();
|
||||
expect(row?.values).toEqual(["igdb"]);
|
||||
expect(row?.logic).toBe("any");
|
||||
});
|
||||
});
|
||||
@@ -50,6 +50,8 @@ export interface SmartFilterCriteria {
|
||||
languages_logic?: FilterLogic;
|
||||
player_counts?: string[];
|
||||
player_counts_logic?: FilterLogic;
|
||||
metadata_providers?: string[];
|
||||
metadata_providers_logic?: FilterLogic;
|
||||
selected_status?: string[];
|
||||
statuses_logic?: FilterLogic;
|
||||
}
|
||||
@@ -83,6 +85,8 @@ export interface GalleryFilterSnapshot {
|
||||
languagesLogic: FilterLogic;
|
||||
selectedPlayerCounts: string[];
|
||||
playerCountsLogic: FilterLogic;
|
||||
selectedMetadataProviders: string[];
|
||||
metadataProvidersLogic: FilterLogic;
|
||||
selectedStatuses: string[];
|
||||
statusesLogic: FilterLogic;
|
||||
}
|
||||
@@ -172,6 +176,10 @@ export function buildSmartFilterCriteria(
|
||||
out.player_counts = snap.selectedPlayerCounts;
|
||||
out.player_counts_logic = snap.playerCountsLogic;
|
||||
}
|
||||
if (snap.selectedMetadataProviders.length > 0) {
|
||||
out.metadata_providers = snap.selectedMetadataProviders;
|
||||
out.metadata_providers_logic = snap.metadataProvidersLogic;
|
||||
}
|
||||
if (snap.selectedStatuses.length > 0) {
|
||||
out.selected_status = snap.selectedStatuses;
|
||||
out.statuses_logic = snap.statusesLogic;
|
||||
@@ -370,6 +378,14 @@ const FIELDS: FieldSpec[] = [
|
||||
defaultLabel: "Player counts",
|
||||
kind: "list",
|
||||
},
|
||||
{
|
||||
storage: "metadata_providers",
|
||||
logicStorage: "metadata_providers_logic",
|
||||
icon: "mdi-database-outline",
|
||||
labelKey: "platform.metadata-provider",
|
||||
defaultLabel: "Metadata providers",
|
||||
kind: "list",
|
||||
},
|
||||
{
|
||||
storage: "selected_status",
|
||||
logicStorage: "statuses_logic",
|
||||
|
||||
Reference in New Issue
Block a user