diff --git a/backend/adapters/services/sigil.py b/backend/adapters/services/sigil.py index 7afe94aa7..61247215c 100644 --- a/backend/adapters/services/sigil.py +++ b/backend/adapters/services/sigil.py @@ -1,8 +1,10 @@ import asyncio +from contextvars import ContextVar from dataclasses import dataclass from pathlib import Path from typing import Final +from logger.formatter import highlight as hl from logger.logger import log from utils.filesystem import COMPRESSED_FILE_SUFFIXES from utils.m3u import first_playlist_entry @@ -34,6 +36,28 @@ SIGIL_PLATFORM_SLUGS: Final[dict[str, str]] = { # and it is the only family whose files may carry their title id in the filename. SWITCH_PLATFORM_SLUGS: Final = frozenset({UPS.SWITCH, UPS.SWITCH_2}) +# Files the current scan skipped because RomM holds no keys for their headers. +# A context var, so scans overlapping in one process (DEV_MODE) keep their own. +_needs_key_paths: ContextVar[set[str] | None] = ContextVar( + "sigil_needs_key_paths", default=None +) + + +def begin_scan() -> None: + _needs_key_paths.set(set()) + + +def log_scan_summary() -> None: + """Say how many encrypted Switch files this scan left without a title id.""" + paths = _needs_key_paths.get() + if not paths: + return + log.info( + f"{hl(str(len(paths)))} encrypted Switch files got no title id: " + "RomM doesn't decrypt Switch files. Decrypted dumps, or a client " + "holding your keys, can identify them." + ) + @dataclass(frozen=True) class SigilExtractionResult: @@ -84,12 +108,16 @@ class SigilService: result = await asyncio.to_thread( sigil.extract, file_path, platform=sigil_slug, filename_fallback=False ) - # Expected for arbitrary library files: no title id, a format sigil - # can't parse, or a Switch header RomM holds no keys for. + # A Switch header RomM holds no keys for, reported in the scan summary. + except sigil.SigilNeedsKeyError as exc: + if (paths := _needs_key_paths.get()) is not None: + paths.add(file_path) + log.debug(f"Sigil found no title id for {file_path}: {exc}") + return None + # Expected for arbitrary library files: no title id or a format sigil can't parse. except ( sigil.SigilNotFoundError, sigil.SigilUnsupportedFormatError, - sigil.SigilNeedsKeyError, ) as exc: log.debug(f"Sigil found no title id for {file_path}: {exc}") return None diff --git a/backend/alembic/versions/0084_add_roms_search_index.py b/backend/alembic/versions/0084_add_roms_search_index.py index 048c20b17..d6662e686 100644 --- a/backend/alembic/versions/0084_add_roms_search_index.py +++ b/backend/alembic/versions/0084_add_roms_search_index.py @@ -23,10 +23,12 @@ Create Date: 2026-06-16 00:00:00.000000 """ +import re + import sqlalchemy as sa from alembic import op -from models.rom import NAME_SORT_KEY_MAX_LENGTH, compute_name_sort_key +from models.rom import NAME_SORT_KEY_MAX_LENGTH from utils.database import is_mariadb, is_mysql, is_postgresql # revision identifiers, used by Alembic. @@ -41,6 +43,17 @@ PG_FS_NAME_INDEX = "idx_roms_fs_name_trgm" _BACKFILL_BATCH = 1000 +# models.rom.compute_name_sort_key when this revision was written. +_ARTICLE_PREFIX_RE = re.compile(r"^(the|a|an)\s+") +_DIGIT_RUN_RE = re.compile(r"\d+") + + +def _sort_key(name: str | None) -> str: + value = (name or "").lower() + value = _ARTICLE_PREFIX_RE.sub("", value).strip() + value = _DIGIT_RUN_RE.sub(lambda m: m.group(0).zfill(12), value) + return value[:NAME_SORT_KEY_MAX_LENGTH] + def upgrade() -> None: bind = op.get_bind() @@ -115,7 +128,7 @@ def upgrade() -> None: break bind.execute( update_stmt, - [{"_id": row.id, "_key": compute_name_sort_key(row.name)} for row in batch], + [{"_id": row.id, "_key": _sort_key(row.name)} for row in batch], ) op.create_index( diff --git a/backend/alembic/versions/0157_rom_custom_sort_key_flag.py b/backend/alembic/versions/0157_rom_custom_sort_key_flag.py new file mode 100644 index 000000000..3868f95a1 --- /dev/null +++ b/backend/alembic/versions/0157_rom_custom_sort_key_flag.py @@ -0,0 +1,105 @@ +"""Record whether each ROM's sort key is custom + +Revision ID: 0157_rom_custom_sort_key_flag +Revises: 0156_roms_platform_min_age_index +Create Date: 2026-10-31 00:00:00.000000 + +""" + +import re + +import sqlalchemy as sa +from alembic import op + +from utils.database import column_names +from utils.roms_columns import NAME_SORT_KEY_CUSTOM_COLUMN, ensure_roms_columns + +# revision identifiers, used by Alembic. +revision = "0157_rom_custom_sort_key_flag" +down_revision = "0156_roms_platform_min_age_index" +branch_labels = None +depends_on = None + +BATCH_SIZE = 1000 +# The rules models.rom.compute_name_sort_key derived keys with before this +# revision: English articles from 0084, every LaunchBox article from 5.2.0. +ENGLISH_ARTICLES = ("the", "a", "an") +MULTILINGUAL_ARTICLES = ( + "the", + "a", + "an", + "le", + "la", + "les", + "el", + "los", + "las", + "il", + "lo", + "gli", + "der", + "die", + "das", + "het", +) +DIGIT_RUN_RE = re.compile(r"\d+") +NAME_SORT_KEY_MAX_LENGTH = 500 + + +def _sort_key(name: str | None, articles: tuple[str, ...]) -> str: + value = (name or "").lower() + value = re.sub(rf"^({'|'.join(articles)})\s+", "", value).strip() + value = DIGIT_RUN_RE.sub(lambda m: m.group(0).zfill(12), value) + return value[:NAME_SORT_KEY_MAX_LENGTH] + + +def _is_derived(name: str | None, key: str) -> bool: + return key in ( + _sort_key(name, ENGLISH_ARTICLES), + _sort_key(name, MULTILINGUAL_ARTICLES), + ) + + +def _flag_custom_keys(conn: sa.Connection) -> None: + """Mark each stored key that neither earlier rule derives from its name.""" + roms = sa.table( + "roms", + sa.column("id", sa.Integer), + sa.column("name", sa.String), + sa.column("name_sort_key", sa.String), + sa.column(NAME_SORT_KEY_CUSTOM_COLUMN, sa.Boolean), + ) + last_id = 0 + while rows := conn.execute( + sa.select(roms.c.id, roms.c.name, roms.c.name_sort_key) + .where(roms.c.id > last_id) + .order_by(roms.c.id) + .limit(BATCH_SIZE) + ).all(): + last_id = rows[-1].id + custom_ids = [ + row.id + for row in rows + if row.name_sort_key is not None + and not _is_derived(row.name, row.name_sort_key) + ] + if custom_ids: + conn.execute( + sa.update(roms) + .where(roms.c.id.in_(custom_ids)) + .values({NAME_SORT_KEY_CUSTOM_COLUMN: True}) + ) + + +def upgrade() -> None: + conn = op.get_bind() + # An earlier revision's `ensure_roms_columns` may have added the column + # already, so the flags are filled either way. + ensure_roms_columns(conn) + _flag_custom_keys(conn) + + +def downgrade() -> None: + conn = op.get_bind() + if NAME_SORT_KEY_CUSTOM_COLUMN in column_names(conn, "roms"): + op.drop_column("roms", NAME_SORT_KEY_CUSTOM_COLUMN) diff --git a/backend/config/__init__.py b/backend/config/__init__.py index 46458df1a..db79dbdbe 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -272,6 +272,57 @@ OIDC_RP_INITIATED_LOGOUT: Final[bool] = safe_str_to_bool( ) OIDC_END_SESSION_ENDPOINT: Final[str] = _get_env("OIDC_END_SESSION_ENDPOINT", "") +# Authlib lets these override its per-request values, which would pin state, +# nonce or PKCE and undo their protection, or break the callback. +OIDC_RESERVED_AUTH_PARAMS: Final = frozenset( + { + "client_id", + "code_challenge", + "code_challenge_method", + "code_verifier", + "nonce", + "redirect_uri", + "response_mode", + "response_type", + "scope", + "state", + } +) + + +def parse_oidc_auth_params(raw: str) -> dict[str, str]: + """Parse a JSON object of extra OIDC authorization request parameters.""" + if not raw: + return {} + try: + params = json.loads(raw) + except json.JSONDecodeError as exc: + raise ValueError(f"OIDC_AUTH_PARAMS is not valid JSON: {exc}") from exc + if not isinstance(params, dict): + raise ValueError("OIDC_AUTH_PARAMS must be a JSON object") + + reserved = sorted(OIDC_RESERVED_AUTH_PARAMS & params.keys()) + if reserved: + raise ValueError( + f"OIDC_AUTH_PARAMS cannot set {', '.join(reserved)}, RomM manages them" + ) + # bool is an int subclass, but "True" is not a value any provider expects + invalid = sorted( + key + for key, value in params.items() + if isinstance(value, bool) or not isinstance(value, (str, int)) + ) + if invalid: + raise ValueError( + f"OIDC_AUTH_PARAMS values must be strings or integers: {', '.join(invalid)}" + ) + return {key: str(value) for key, value in params.items()} + + +OIDC_AUTH_PARAMS: Final[dict[str, str]] = parse_oidc_auth_params( + _get_env("OIDC_AUTH_PARAMS", "") +) + # SCANS SCAN_TIMEOUT: Final[int] = safe_int(_get_env("SCAN_TIMEOUT"), 60 * 60 * 4) # 4 hours SCAN_WORKERS: Final[int] = max(1, safe_int(_get_env("SCAN_WORKERS"), 4)) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index e999d44c2..131fa8b27 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -264,6 +264,9 @@ def _platform_first_layout(folder: str) -> bool | None: ROMM_USER_CONFIG_PATH: Final = f"{ROMM_BASE_PATH}/config" ROMM_USER_CONFIG_FILE: Final = f"{ROMM_USER_CONFIG_PATH}/config.yml" SQLITE_DB_BASE_PATH: Final = f"{ROMM_BASE_PATH}/database" +# Leading words dropped from a title when sorting it, unless `sorting.articles` +# names others. +DEFAULT_SORT_ARTICLES: Final = ["the", "a", "an"] DEFAULT_EXCLUDED_EXTENSIONS: Final = [ "db", "tmp", @@ -545,6 +548,7 @@ class Config: SCAN_REGION_PRIORITY: list[str] SCAN_REGION_MODE: str SCAN_LANGUAGE_PRIORITY: list[str] + SORT_ARTICLES: list[str] SCAN_MEDIA: list[str] GAMELIST_MEDIA_THUMBNAIL: MetadataMediaType GAMELIST_MEDIA_IMAGE: MetadataMediaType @@ -898,6 +902,9 @@ class ConfigManager: "scan.priority.language", ["en"], ), + SORT_ARTICLES=get_nested( + self._raw_config, "sorting.articles", DEFAULT_SORT_ARTICLES + ), SCAN_MEDIA=get_nested( self._raw_config, "scan.media", @@ -1134,6 +1141,16 @@ class ConfigManager: def _validate_config(self) -> None: """Validates the config.yml file""" + articles = self.config.SORT_ARTICLES + if not isinstance(articles, list) or not all( + isinstance(article, str) for article in articles + ): + log.critical("Invalid config.yml: sorting.articles must be a list of words") + sys.exit(3) + self.config.SORT_ARTICLES = [ + article.strip().lower() for article in articles if article.strip() + ] + if not isinstance(self.config.GAMELIST_AUTO_EXPORT_ON_SCAN, bool): log.critical("Invalid config.yml: scan.gamelist.export must be a boolean") sys.exit(3) @@ -1499,6 +1516,7 @@ class ConfigManager: "settings": self.config.EJS_SETTINGS, "controls": self._format_ejs_controls_for_yaml(), }, + "sorting": {"articles": self.config.SORT_ARTICLES}, "scan": { "priority": { "metadata": self.config.SCAN_METADATA_PRIORITY, diff --git a/backend/decorators/auth.py b/backend/decorators/auth.py index 628bc9ce5..122a7f5fe 100644 --- a/backend/decorators/auth.py +++ b/backend/decorators/auth.py @@ -15,6 +15,7 @@ from starlette.config import Config from starlette.requests import Request from config import ( + OIDC_AUTH_PARAMS, OIDC_CLAIM_ROLES, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, @@ -76,6 +77,7 @@ oauth.register( # so providers that mandate PKCE refuse the code without it. "code_challenge_method": "S256", }, + authorize_params=OIDC_AUTH_PARAMS or None, ) diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index ce7d6e1bf..d65ae2ff3 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -2153,6 +2153,7 @@ async def update_rom( **dict.fromkeys(UNMATCH_ID_FIELDS), "name": rom.fs_name, "name_sort_key": compute_name_sort_key(rom.fs_name), + "name_sort_key_custom": False, "summary": "", "url_screenshots": [], "path_screenshots": [], @@ -2273,9 +2274,12 @@ async def update_rom( # it out so update_rom re-derives only if the stored key isn't custom. submitted = (form_data.name_sort_key or "").strip() if submitted != (rom.name_sort_key or "").strip(): - cleaned_data["name_sort_key"] = compute_name_sort_key( - submitted or name_value + cleaned_data["name_sort_key"] = ( + compute_name_sort_key(submitted, articles=()) + if submitted + else compute_name_sort_key(name_value) ) + cleaned_data["name_sort_key_custom"] = bool(submitted) cleaned_data.update({"fs_name": new_fs_name}) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index bffb9c16e..0bc6ae20f 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -18,6 +18,8 @@ from rq.timeouts import JobTimeoutException from sqlalchemy.exc import IntegrityError from adapters.services.sigil import SWITCH_PLATFORM_SLUGS +from adapters.services.sigil import begin_scan as begin_sigil_scan +from adapters.services.sigil import log_scan_summary as log_sigil_scan_summary from config import DEV_MODE, SCAN_TIMEOUT, SCAN_WORKERS, TASK_RESULT_TTL from config.config_manager import config_manager as cm from endpoints.responses.platform import PlatformSchema @@ -756,8 +758,10 @@ async def _identify_rom( else None ), ) - # Keep the in-memory rom's name matching the renamed file. - rom.fs_name = fs_rom["fs_name"] + # Keep the in-memory rom's name matching the renamed file. Setting it + # re-derives the stored placeholder name, so only on a real rename. + if rom.fs_name != fs_rom["fs_name"]: + rom.fs_name = fs_rom["fs_name"] log.debug(f"Scanning {rom.fs_name}...") scanned_rom = await scan_rom( @@ -1230,6 +1234,7 @@ async def scan_platforms( # overlap, and resetting would drop the other scan's limits and skips. if MetadataSource.SS in metadata_sources: await begin_ss_scan() + begin_sigil_scan() fs_platforms: list[str] = [] if not roms_ids: @@ -1394,6 +1399,7 @@ async def scan_platforms( if MetadataSource.SS in metadata_sources: log_ss_scan_summary() + log_sigil_scan_summary() log.info(f"{emoji.EMOJI_CHECK_MARK} Scan completed") diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 410696b86..ba0e96af4 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -106,6 +106,7 @@ from utils.database import ( ROMS_SEARCH_FULLTEXT_COLUMNS, SORTABLE_NULLABLE_ROM_COLUMNS, epoch_ms_in_ranges, + exact_collation, is_non_blank, is_postgresql, release_day_ranges, @@ -648,8 +649,8 @@ def _resolve_gallery_sort_key(order_by: str, user_id: int | None) -> _GallerySor return _GallerySortKey(metadata_column, "rom_metadata", nullable=True) column = rom_column if rom_column is not None else Rom.name - # Use indexed `name_sort_key` to have fast access to names without - # articles (the, a, an) and leading digits. The key is derived from + # Use indexed `name_sort_key` to have fast access to names without the + # leading articles `sorting.articles` names. The key is derived from # `name` at write time, or holds a custom override when one is set. if column is Rom.name: column = Rom.name_sort_key @@ -2304,15 +2305,13 @@ class DBRomsHandler(DBBaseHandler): data: dict[str, Any], session: Session = INJECTED_SESSION, ) -> Rom: + if "name_sort_key" in data and "name_sort_key_custom" not in data: + # A key written without saying otherwise is the caller's own choice. + data = {**data, "name_sort_key_custom": data["name_sort_key"] is not None} if "name" in data and "name_sort_key" not in data: - # Re-derive the key from the new name, but only when the stored key - # is still the derived value (i.e. not a manual override). Mirrors - # the `@validates` logic, which the bulk update() bypasses. - existing = session.get_one(Rom, id) - if ( - existing.name_sort_key is None - or existing.name_sort_key == compute_name_sort_key(existing.name) - ): + # Re-derive the key from the new name unless it is a custom one. + # Mirrors the `@validates` logic, which the bulk update() bypasses. + if not session.get_one(Rom, id).name_sort_key_custom: data = {**data, "name_sort_key": compute_name_sort_key(data["name"])} if data.keys() & SEARCH_TITLE_COLUMNS: @@ -2466,6 +2465,56 @@ class DBRomsHandler(DBBaseHandler): .execution_options(synchronize_session="evaluate") ) + @begin_session + def get_sort_keys_after_id( + self, + after_id: int, + limit: int, + session: Session = INJECTED_SESSION, + ) -> list[tuple[int, str | None, str | None, bool]]: + """A page of `(id, name, name_sort_key, name_sort_key_custom)` after `after_id`.""" + rows = session.execute( + select(Rom.id, Rom.name, Rom.name_sort_key, Rom.name_sort_key_custom) + .where(Rom.id > after_id) + .order_by(Rom.id) + .limit(limit) + ).all() + return [(rom_id, name, key, custom) for rom_id, name, key, custom in rows] + + @begin_session + def replace_derived_sort_keys( + self, + replacements: Mapping[int, tuple[str | None, str]], + session: Session = INJECTED_SESSION, + ) -> int: + """Re-derive sort keys, each only while its name is the one it was derived from. + + Args: + replacements: ROM id to its (name, new sort key). + + Returns: + How many keys were replaced. + """ + replaced = 0 + # Exact, so an accent-only rename still counts as a change of name. + collation = exact_collation(session.get_bind()) + stored_name = Rom.name.collate(collation) if collation else Rom.name + for rom_id, (name, new) in replacements.items(): + same_name = stored_name.is_(None) if name is None else stored_name == name + replaced += affected_rows( + session.execute( + update(Rom) + .where( + Rom.id == rom_id, same_name, Rom.name_sort_key_custom.is_(False) + ) + .values(name_sort_key=new) + .execution_options(synchronize_session=False) + ) + ) + if replaced: + session.info[FILTER_VALUES_BUMP_KEY] = True + return replaced + @begin_session def mark_missing_roms( self, diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 14a179a1b..472e925b6 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -35,7 +35,11 @@ from exceptions.fs_exceptions import ( RomsNotFoundException, ) from logger.logger import log -from models.base import compute_file_extension, compute_file_name_no_ext +from models.base import ( + PICO8_CARTRIDGE_EXTENSION, + compute_file_extension, + compute_file_name_no_ext, +) from models.platform import Platform from models.rom import ( DOCUMENT_CATEGORIES, @@ -78,10 +82,6 @@ from .base_handler import ( translation_language, ) -# PICO-8 cartridges are often stored as PNG files -PICO8_CARTRIDGE_EXTENSION = ".p8.png" - - NON_HASHABLE_PLATFORMS = frozenset( ( UPS.AMAZON_ALEXA, diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index 267dac41b..edb7dfb49 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -83,6 +83,7 @@ def tag_id_from_filename(tag_regex: re.Pattern[str], fs_name: str) -> int | None class BaseRom(TypedDict): name: NotRequired[str] name_sort_key: NotRequired[str | None] + name_sort_key_custom: NotRequired[bool] summary: NotRequired[str] url_cover: NotRequired[str] url_screenshots: NotRequired[list[str]] diff --git a/backend/handler/metadata/gamelist_handler.py b/backend/handler/metadata/gamelist_handler.py index add49a3b5..eec554878 100644 --- a/backend/handler/metadata/gamelist_handler.py +++ b/backend/handler/metadata/gamelist_handler.py @@ -658,11 +658,14 @@ class GamelistHandler(MetadataHandler): rom_metadata = extract_metadata_from_gamelist_rom( game, platform, media_files, validate_path ) - name_sort_key = compute_name_sort_key(sort_name) if sort_name else None + name_sort_key = ( + compute_name_sort_key(sort_name, articles=()) if sort_name else None + ) rom_data = GamelistRom( gamelist_id=str(uuid.uuid4()), name=name, name_sort_key=name_sort_key, + name_sort_key_custom=name_sort_key is not None, summary=summary, regions=regions, languages=languages, diff --git a/backend/handler/scan/merge.py b/backend/handler/scan/merge.py index bd860660f..c7ca08710 100644 --- a/backend/handler/scan/merge.py +++ b/backend/handler/scan/merge.py @@ -131,6 +131,7 @@ def seed_rom_attrs( "fs_size_bytes": rom.fs_size_bytes, "is_physical": rom.is_physical, "upc": rom.upc, + "name_sort_key_custom": False, } file_attrs = fs_rom_file_attrs(fs_rom) @@ -157,7 +158,11 @@ def seed_rom_attrs( rom_attrs.update( { "name": rom.name, - "name_sort_key": rom.name_sort_key, + # A derived key is left out, so it follows the name this scan settles. + "name_sort_key": ( + rom.name_sort_key if rom.name_sort_key_custom else None + ), + "name_sort_key_custom": rom.name_sort_key_custom, "slug": rom.slug, "summary": rom.summary, "url_cover": rom.url_cover, @@ -491,7 +496,8 @@ def keep_base_fields(rom_attrs: dict[str, Any], rom: Rom) -> None: # Both the existing name and the seeded rom_attrs name can hold the # placeholder. Discard either when it's a placeholder so the parsed # filename fallback can win. - placeholders = (None, "", rom.fs_name, fs_name_no_tags) + # The stored no-tags name is the placeholder the ROM's name was seeded from. + placeholders = (None, "", rom.fs_name, fs_name_no_tags, rom.fs_name_no_tags) existing_name = None if rom.name in placeholders else rom.name matched_name = rom_attrs.get("name") matched_name = None if matched_name in placeholders else matched_name diff --git a/backend/models/base.py b/backend/models/base.py index 35949c02f..1ef31da19 100644 --- a/backend/models/base.py +++ b/backend/models/base.py @@ -14,6 +14,9 @@ TAG_GROUP_REGEX = re.compile(r"(?:\s*(?:\([^)]*\)|\[[^]]*\]))+\s*$") # Matches a trailing file extension, including multi-part ones like ".tar.gz". EXTENSION_REGEX = re.compile(r"\.(([a-z]+\.)*\w+)$") +# PICO-8 carts are often saved as PNG images, so the `.p8` outlives the extension. +PICO8_CARTRIDGE_EXTENSION = ".p8.png" + # Filename tags that mark a dump as a pre-release rather than the shipped game. # Lowercase and unterminated so one prefix covers its variants: "demo" also # matches "(Demo Kiosk)", "proto" also matches "(Prototype)". @@ -43,6 +46,8 @@ def compute_file_name_no_tags(file_name: str) -> str: legitimately contains parentheses/brackets mid-name is not truncated. """ name = compute_file_name_no_ext(file_name) + if file_name.lower().endswith(PICO8_CARTRIDGE_EXTENSION): + name = name[: -len(".p8")] return TAG_GROUP_REGEX.sub("", name).strip() diff --git a/backend/models/rom.py b/backend/models/rom.py index e2232cdb8..9ff092a8c 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -7,7 +7,7 @@ import sys from collections.abc import Mapping, Sequence from dataclasses import dataclass from datetime import datetime -from functools import cached_property +from functools import cache, cached_property from typing import TYPE_CHECKING, Any, Final, NamedTuple, TypedDict from sqlalchemy import ( @@ -26,6 +26,7 @@ from sqlalchemy import ( UniqueConstraint, and_, event, + false, func, inspect, or_, @@ -97,9 +98,8 @@ ALTERNATIVE_NAME_SOURCES = ( PINNED_MEDIA_MAX_ITEMS = 100 PINNED_MEDIA_KEY_MAX_LENGTH = 1024 PINNED_MEDIA_KEY_PATTERN = r"^(scraped|file|screenshot|artwork):\S" -# Articles ignored when sorting or bucketing a title, across the languages -# No-Intro and LaunchBox name games in. Both patterns built from this are -# anchored on the right, so "la" preceding "las" costs nothing. +# Articles LaunchBox moves to the end of a title ("Boot, Das"), across the +# languages No-Intro and LaunchBox name games in. ARTICLES = ( "the", "a", @@ -118,14 +118,39 @@ ARTICLES = ( "das", "het", ) -ARTICLE_PREFIX_RE = re.compile(rf"^({'|'.join(ARTICLES)})\s+") DIGIT_RUN_RE = re.compile(r"\d+") -def compute_name_sort_key(name: str | None) -> str: - """Precompute the natural-sort key stored in `Rom.name_sort_key`""" - value = (name or "").lower() - value = ARTICLE_PREFIX_RE.sub("", value).strip() +@cache +def _article_prefix_re(articles: tuple[str, ...]) -> re.Pattern[str] | None: + if not articles: + return None + return re.compile(rf"^({'|'.join(map(re.escape, articles))})\s+") + + +def sort_articles() -> tuple[str, ...]: + """The leading words a title sorts without, from `sorting.articles`.""" + # Imported here: the config manager imports this module. + from config.config_manager import config_manager as cm + + return tuple(cm.config.SORT_ARTICLES) + + +def compute_name_sort_key( + name: str | None, *, articles: Sequence[str] | None = None +) -> str: + """Precompute the natural-sort key stored in `Rom.name_sort_key`. + + Args: + articles: Leading words to drop, the configured ones by default. An + empty sequence keeps the name as given, for a custom sort key. + """ + value = (name or "").lower().strip() + pattern = _article_prefix_re( + sort_articles() if articles is None else tuple(articles) + ) + if pattern is not None: + value = pattern.sub("", value).strip() value = DIGIT_RUN_RE.sub(lambda m: m.group(0).zfill(12), value) return value[:NAME_SORT_KEY_MAX_LENGTH] @@ -923,6 +948,10 @@ class Rom(BaseModel): name_sort_key: Mapped[str | None] = mapped_column( String(length=NAME_SORT_KEY_MAX_LENGTH), default=None ) + # Set by whoever writes a key on purpose; a derived key follows `name`. + name_sort_key_custom: Mapped[bool] = mapped_column( + default=False, server_default=false(), nullable=False + ) slug: Mapped[str | None] = mapped_column(String(length=400)) summary: Mapped[str | None] = mapped_column(Text) igdb_metadata: Mapped[dict[str, Any] | None] = mapped_column( @@ -1131,11 +1160,12 @@ class Rom(BaseModel): def _sync_name_sort_key(self, key: str, value: str | None) -> str | None: """Keep the indexed `name_sort_key` in sync with `name`""" if key == "name_sort_key": - return compute_name_sort_key(value or self.name) + # A key that is set explicitly sorts as given, leading article included. + if value: + return compute_name_sort_key(value, articles=()) + return compute_name_sort_key(self.name) - if self.name_sort_key is None or self.name_sort_key == compute_name_sort_key( - self.name - ): + if not self.name_sort_key_custom: self.name_sort_key = compute_name_sort_key(value) return value diff --git a/backend/startup.py b/backend/startup.py index 0668d35e7..9bf4a596c 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -4,8 +4,8 @@ import asyncio from typing import cast from opentelemetry import trace -from rq.exceptions import DuplicateJobError -from rq.job import Job +from rq.exceptions import DuplicateJobError, NoSuchJobError +from rq.job import Job, JobStatus from rq.utils import as_text from config import ( @@ -37,6 +37,11 @@ from handler.redis_handler import ( from handler.scan_jobs import drop_stale_scheduled_scans from logger.logger import log from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY +from models.rom import sort_articles +from tasks.manual.recompute_name_sort_keys import ( + applied_sort_articles, + articles_digest, +) from tasks.registry import enqueue_task from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE from utils.cache import conditionally_set_cache, drop_stale_cache_store @@ -46,6 +51,7 @@ from utils.sentry import init_sentry tracer = trace.get_tracer(__name__) RECOMPUTE_SAVE_HASHES_JOB_ID = "recompute_save_content_hashes_bootstrap" +RECOMPUTE_NAME_SORT_KEYS_JOB_ID = "recompute_name_sort_keys_bootstrap" CONVERT_IMAGES_TO_WEBP_JOB_ID = "convert_images_to_webp_bootstrap" UPDATE_LAUNCHBOX_METADATA_JOB_ID = "update_launchbox_metadata_bootstrap" UPDATE_SWITCH_TITLEDB_JOB_ID = "update_switch_titledb_bootstrap" @@ -88,6 +94,40 @@ def _enqueue_recompute_save_hashes_if_needed() -> None: _enqueue_backfill("recompute_save_content_hashes", RECOMPUTE_SAVE_HASHES_JOB_ID) +TERMINAL_JOB_STATUSES = frozenset( + {JobStatus.FINISHED, JobStatus.FAILED, JobStatus.STOPPED, JobStatus.CANCELED} +) + + +def _free_finished_job_id(job_id: str) -> None: + """Delete a job that has stopped running, so its id can be enqueued again.""" + try: + job = Job.fetch(job_id, connection=redis_client) + except NoSuchJobError: + return + if job.get_status() in TERMINAL_JOB_STATUSES: + job.delete() + + +def _enqueue_recompute_name_sort_keys_if_needed() -> None: + """Re-derive sort keys when `sorting.articles` differs from the stored keys'.""" + try: + articles = sort_articles() + outdated = applied_sort_articles() != articles + except Exception: + log.exception("Failed to compare the sort articles; skipping the recompute") + return + + if outdated: + # Keyed by the list; a queued or running job for it still blocks a duplicate. + job_id = f"{RECOMPUTE_NAME_SORT_KEYS_JOB_ID}_{articles_digest(articles)}" + try: + _free_finished_job_id(job_id) + except Exception: + log.exception(f"Failed to check {job_id}; enqueueing anyway") + _enqueue_backfill("recompute_name_sort_keys", job_id) + + def _enqueue_convert_images_to_webp() -> None: """Backfill .webp covers when WebP conversion is enabled. @@ -195,6 +235,7 @@ async def main() -> None: _enqueue_convert_images_to_webp() _enqueue_recompute_save_hashes_if_needed() + _enqueue_recompute_name_sort_keys_if_needed() try: await _rebuild_outdated_metadata_stores() diff --git a/backend/tasks/manual/recompute_name_sort_keys.py b/backend/tasks/manual/recompute_name_sort_keys.py new file mode 100644 index 000000000..dc8b93d12 --- /dev/null +++ b/backend/tasks/manual/recompute_name_sort_keys.py @@ -0,0 +1,55 @@ +"""Re-derive ROM sort keys when the articles `sorting.articles` names change.""" + +import hashlib +import json + +from handler.database import db_rom_handler +from handler.redis_handler import sync_cache +from logger.logger import log +from models.rom import compute_name_sort_key, sort_articles +from tasks.registry import RECOMPUTE_NAME_SORT_KEYS_SPEC +from tasks.tasks import Task + +APPLIED_SORT_ARTICLES_KEY = "romm:sort_articles" +PAGE_SIZE = 1000 + + +def articles_digest(articles: tuple[str, ...]) -> str: + """A short id for an articles list, safe in an RQ job id.""" + encoded = json.dumps(articles).encode() + return hashlib.sha1(encoded, usedforsecurity=False).hexdigest()[:12] + + +def applied_sort_articles() -> tuple[str, ...] | None: + """The articles the stored sort keys were last derived with, if recorded.""" + stored = sync_cache.get(APPLIED_SORT_ARTICLES_KEY) + return tuple(json.loads(stored)) if stored else None + + +class RecomputeNameSortKeysTask(Task): + def __init__(self) -> None: + super().__init__(RECOMPUTE_NAME_SORT_KEYS_SPEC) + + async def run(self) -> dict[str, int]: + articles = sort_articles() + # Cleared until every batch is written, so a run that fails partway is redone. + sync_cache.delete(APPLIED_SORT_ARTICLES_KEY) + scanned = replaced = 0 + last_id = 0 + while page := db_rom_handler.get_sort_keys_after_id(last_id, PAGE_SIZE): + replacements: dict[int, tuple[str | None, str]] = {} + for rom_id, name, sort_key, custom in page: + last_id = rom_id + scanned += 1 + derived = compute_name_sort_key(name, articles=articles) + if not custom and derived != sort_key: + replacements[rom_id] = (name, derived) + if replacements: + replaced += db_rom_handler.replace_derived_sort_keys(replacements) + + sync_cache.set(APPLIED_SORT_ARTICLES_KEY, json.dumps(articles)) + log.info(f"{self.spec.title} complete: scanned={scanned}, replaced={replaced}") + return {"roms_scanned": scanned, "sort_keys_replaced": replaced} + + +recompute_name_sort_keys_task = RecomputeNameSortKeysTask() diff --git a/backend/tasks/registry.py b/backend/tasks/registry.py index 0599caf82..dff89bca4 100644 --- a/backend/tasks/registry.py +++ b/backend/tasks/registry.py @@ -240,6 +240,18 @@ SYNC_FOLDER_SCAN_SPEC: Final = TaskSpec( manual_run=True, ) +RECOMPUTE_NAME_SORT_KEYS_SPEC: Final = TaskSpec( + implementation="tasks.manual.recompute_name_sort_keys.recompute_name_sort_keys_task", + title="Recompute ROM sort keys", + description=( + "Re-derive each ROM's sort key from its name with the articles " + "sorting.articles names, keeping custom sort keys." + ), + task_type=TaskType.UPDATE, + enabled=True, + manual_run=True, +) + RECOMPUTE_SAVE_CONTENT_HASHES_SPEC: Final = TaskSpec( implementation="tasks.manual.recompute_save_content_hashes.recompute_save_content_hashes_task", title="Recompute save content hashes", @@ -296,6 +308,7 @@ MANUAL_TASKS: Final[dict[str, TaskSpec]] = { "cleanup_missing_firmware": CLEANUP_MISSING_FIRMWARE_SPEC, "sync_folder_scan": SYNC_FOLDER_SCAN_SPEC, "recompute_save_content_hashes": RECOMPUTE_SAVE_CONTENT_HASHES_SPEC, + "recompute_name_sort_keys": RECOMPUTE_NAME_SORT_KEYS_SPEC, "convert_library": CONVERT_LIBRARY_SPEC, } diff --git a/backend/tests/adapters/services/test_libretro_thumbnails.py b/backend/tests/adapters/services/test_libretro_thumbnails.py index 003937844..c63d68362 100644 --- a/backend/tests/adapters/services/test_libretro_thumbnails.py +++ b/backend/tests/adapters/services/test_libretro_thumbnails.py @@ -178,7 +178,7 @@ async def libretro_server( monkeypatch: pytest.MonkeyPatch, ) -> AsyncIterator[tuple[LibretroServer, LibretroThumbnailsService]]: monkeypatch.setattr(libretro_thumbnails, "LIBRETRO_LISTING_TIMEOUT", 0.2) - monkeypatch.setattr(libretro_thumbnails, "LIBRETRO_HEAD_TIMEOUT", 0.2) + monkeypatch.setattr(libretro_thumbnails, "LIBRETRO_HEAD_TIMEOUT", 1.0) fake = LibretroServer() app = web.Application() app.router.add_route("*", "/{tail:.*}", fake.handle) diff --git a/backend/tests/adapters/services/test_sigil.py b/backend/tests/adapters/services/test_sigil.py index 73100d765..5b5ba384e 100644 --- a/backend/tests/adapters/services/test_sigil.py +++ b/backend/tests/adapters/services/test_sigil.py @@ -1,3 +1,4 @@ +import asyncio import types from pathlib import Path from unittest.mock import Mock @@ -6,6 +7,7 @@ import pytest import adapters.services.sigil as sigil_adapter from adapters.services.sigil import SigilExtractionResult, SigilService +from logger.formatter import highlight as hl from utils.platform_slugs import UniversalPlatformSlug as UPS @@ -243,3 +245,64 @@ class TestSigilService: platform="switch", filename_fallback=False, ) + + +class TestScanSummary: + @pytest.mark.asyncio + async def test_counts_encrypted_files_once_per_scan(self, monkeypatch, mocker): + extract = Mock(side_effect=FakeNeedsKeyError(-6)) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + log = mocker.patch.object(sigil_adapter, "log") + service = SigilService() + + sigil_adapter.begin_scan() + await service.extract_title_id(UPS.SWITCH, "/roms/switch/a.nsp") + await service.extract_title_id(UPS.SWITCH, "/roms/switch/a.nsp") + await service.extract_title_id(UPS.SWITCH, "/roms/switch/b.xci") + sigil_adapter.log_scan_summary() + + log.info.assert_called_once() + assert "2" in log.info.call_args.args[0] + + @pytest.mark.asyncio + async def test_new_scan_drops_the_last_count(self, monkeypatch, mocker): + extract = Mock(side_effect=FakeNeedsKeyError(-6)) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + log = mocker.patch.object(sigil_adapter, "log") + + sigil_adapter.begin_scan() + await SigilService().extract_title_id(UPS.SWITCH, "/roms/switch/a.nsp") + sigil_adapter.begin_scan() + sigil_adapter.log_scan_summary() + + log.info.assert_not_called() + + @pytest.mark.asyncio + async def test_overlapping_scans_keep_their_own_count(self, monkeypatch, mocker): + extract = Mock(side_effect=FakeNeedsKeyError(-6)) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + log = mocker.patch.object(sigil_adapter, "log") + first_scanned = asyncio.Event() + second_began = asyncio.Event() + + async def first_scan() -> None: + sigil_adapter.begin_scan() + await SigilService().extract_title_id(UPS.SWITCH, "/roms/switch/a.nsp") + first_scanned.set() + await second_began.wait() + sigil_adapter.log_scan_summary() + + async def second_scan() -> None: + await first_scanned.wait() + sigil_adapter.begin_scan() + second_began.set() + for name in ("b.nsp", "c.nsp", "d.xci"): + await SigilService().extract_title_id( + UPS.SWITCH, f"/roms/switch/{name}" + ) + sigil_adapter.log_scan_summary() + + await asyncio.gather(first_scan(), second_scan()) + + counts = sorted(call.args[0].split(" ")[0] for call in log.info.call_args_list) + assert counts == [hl("1"), hl("3")] diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index 580715e01..50d556184 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -1061,3 +1061,45 @@ def test_a_platform_named_like_a_layout_key_uses_the_default(tmp_path): config = loader.get_config() assert config.platform_structure("firmware") == (config.default_structure,) + + +def test_sorting_articles_default_to_english(tmp_path): + config_file = tmp_path / "config.yml" + config_file.write_text("{}\n") + + assert ConfigManager(str(config_file)).config.SORT_ARTICLES == ["the", "a", "an"] + + +def test_sorting_articles_are_normalized(tmp_path): + config_file = tmp_path / "config.yml" + config_file.write_text("sorting:\n articles: [' Der ', 'DIE', '', das]\n") + + assert ConfigManager(str(config_file)).config.SORT_ARTICLES == [ + "der", + "die", + "das", + ] + + +@pytest.mark.parametrize("value", ["the", "[1, 2]"]) +def test_sorting_articles_must_be_a_list_of_words(tmp_path, value): + config_file = tmp_path / "config.yml" + config_file.write_text(f"sorting:\n articles: {value}\n") + + with pytest.raises(SystemExit) as excinfo: + ConfigManager(str(config_file)) + + assert excinfo.value.code == 3 + + +def test_sorting_articles_survive_saving_another_setting(tmp_path): + config_file = tmp_path / "config.yml" + config_file.write_text("sorting:\n articles: [der, die, das]\n") + + ConfigManager(str(config_file)).add_platform_binding("gc", "ngc") + + assert ConfigManager(str(config_file)).config.SORT_ARTICLES == [ + "der", + "die", + "das", + ] diff --git a/backend/tests/config/test_env.py b/backend/tests/config/test_env.py index c43b42663..2aca47aa6 100644 --- a/backend/tests/config/test_env.py +++ b/backend/tests/config/test_env.py @@ -1,6 +1,6 @@ import pytest -from config import _get_env_list, _get_env_set +from config import _get_env_list, _get_env_set, parse_oidc_auth_params @pytest.mark.parametrize( @@ -57,3 +57,34 @@ def test_get_env_set_fallback(monkeypatch, value, expected): else: monkeypatch.setenv("ROMM_TEST_SET", value) assert _get_env_set("ROMM_TEST_SET", "win, dos") == expected + + +@pytest.mark.parametrize( + "raw,expected", + [ + ("", {}), + ('{"prompt": "select_account"}', {"prompt": "select_account"}), + ( + '{"prompt": "login", "max_age": 0, "ui_locales": "fr en"}', + {"prompt": "login", "max_age": "0", "ui_locales": "fr en"}, + ), + ], +) +def test_parse_oidc_auth_params(raw, expected): + assert parse_oidc_auth_params(raw) == expected + + +@pytest.mark.parametrize( + "raw,message", + [ + ("prompt=select_account", "not valid JSON"), + ('["prompt"]', "must be a JSON object"), + ('{"state": "fixed", "nonce": "fixed"}', "cannot set nonce, state"), + ('{"prompt": "login", "redirect_uri": "https://x"}', "cannot set redirect_uri"), + ('{"prompt": true}', "strings or integers: prompt"), + ('{"claims": {"id_token": {}}}', "strings or integers: claims"), + ], +) +def test_parse_oidc_auth_params_rejects(raw, message): + with pytest.raises(ValueError, match=message): + parse_oidc_auth_params(raw) diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index dd3fbbfa5..a47d3fb45 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -970,12 +970,25 @@ def test_update_rom( body = response.json() assert body["fs_name"] == "Metroid Prime Remastered.zip" - assert body["name_sort_key"] == compute_name_sort_key("Metroid Prime") + assert body["name_sort_key"] == compute_name_sort_key("Metroid Prime", articles=()) assert rename_fs_rom_mock.called assert get_rom_by_id_mock.called +def test_update_rom_keeps_a_custom_sort_keys_leading_article( + client: TestClient, access_token: str, rom: Rom +): + response = client.put( + f"/api/roms/{rom.id}", + headers={"Authorization": f"Bearer {access_token}"}, + data={"name_sort_key": "The Simpsons"}, + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json()["name_sort_key"] == "the simpsons" + + @patch.object(FSRomsHandler, "rename_fs_rom") @patch.object(IGDBHandler, "get_rom_by_id", return_value=IGDBRom(igdb_id=None)) def test_update_rom_reparses_tags_on_fs_name_change( diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index d99720ea4..ec4b3bcfc 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -1112,6 +1112,44 @@ def make_fs_rom(fs_name: str, fs_path: str = "test/roms") -> FSRom: } +async def test_a_rescan_keeps_the_stored_placeholder_of_an_unchanged_file(mocker): + """`keep_base_fields` reads the stored placeholder, so rebuilding the files + must not re-derive it from a file name that has not changed.""" + patch_identify_rom( + mocker, + parsed=ParsedRomFiles( + rom_files=[], crc_hash="", md5_hash="", sha1_hash="", ra_hash="" + ), + roms_fs_structure="pico/roms", + name_with_no_tags="celeste", + platform_slug="pico", + ) + platform = Platform(name="pico", slug="pico", fs_slug="pico") + platform.id = 1 + rom = Rom(fs_name="celeste.p8.png", fs_path="pico/roms", platform_id=1) + rom.id = 7 + rom.fs_name_no_tags = "celeste.p8" + scan_rom = mocker.patch.object( + scan_module, "scan_rom", AsyncMock(return_value=MagicMock(is_identified=False)) + ) + + await _identify_rom( + platform=platform, + fs_rom=make_fs_rom("celeste.p8.png", "pico/roms"), + rom=rom, + scan_type=ScanType.HASHES, + roms_ids=[], + metadata_sources=[], + launchbox_remote_enabled=False, + socket_manager=AsyncMock(), + scan_stats=AsyncMock(), + scanned_rom_ids=set(), + ) + + scanned = scan_rom.call_args.kwargs["rom"] + assert scanned.fs_name_no_tags == "celeste.p8" + + class TestIdentifyRomReassociation: """`_identify_rom` reassociates a renamed/moved file with its missing entry. diff --git a/backend/tests/handler/auth/test_oidc.py b/backend/tests/handler/auth/test_oidc.py index 91f5fa9ab..7e8352dac 100644 --- a/backend/tests/handler/auth/test_oidc.py +++ b/backend/tests/handler/auth/test_oidc.py @@ -1,10 +1,12 @@ from unittest.mock import MagicMock +from urllib.parse import parse_qs, urlsplit import pytest from authlib.integrations.starlette_client.apps import StarletteOAuth2App from fastapi import HTTPException, status from joserfc.jwt import Token +from decorators.auth import oauth from handler.auth.base_handler import OpenIDHandler from handler.database import db_user_handler from models.user import TEXT_FIELD_LENGTH, Role, User @@ -1006,3 +1008,18 @@ async def test_oidc_registration_stores_the_identity( assert user is not None assert user.oidc_sub == "sub-1" assert db_user_handler.get_user_by_oidc_identity(ISSUER, "sub-1") is not None + + +async def test_authorize_url_carries_extra_auth_params(mocker, mock_discovery): + mocker.patch.object(oauth.openid, "authorize_params", {"prompt": "select_account"}) + + first = await oauth.openid.create_authorization_url("https://romm.test/cb") + second = await oauth.openid.create_authorization_url("https://romm.test/cb") + + query = parse_qs(urlsplit(first["url"]).query) + assert query["prompt"] == ["select_account"] + assert query["code_challenge_method"] == ["S256"] + assert query["state"] == [first["state"]] + assert query["nonce"] == [first["nonce"]] + assert first["state"] != second["state"] + assert first["nonce"] != second["nonce"] diff --git a/backend/tests/handler/database/test_roms_handler.py b/backend/tests/handler/database/test_roms_handler.py index adfe9893f..0577c9d7b 100644 --- a/backend/tests/handler/database/test_roms_handler.py +++ b/backend/tests/handler/database/test_roms_handler.py @@ -101,6 +101,20 @@ class TestUpdateRomDerivedColumns: assert updated.name == "The New Name 2" assert updated.name_sort_key == "pinned" + def test_renaming_rederives_a_stale_key_that_is_not_custom(self, rom: Rom): + db_rom_handler.update_rom( + rom.id, {"name_sort_key": "hard arcade", "name_sort_key_custom": False} + ) + + updated = db_rom_handler.update_rom(rom.id, {"name": "Die Hard Trilogy"}) + + assert updated.name_sort_key == "die hard trilogy" + + def test_an_explicit_key_is_custom(self, rom: Rom): + updated = db_rom_handler.update_rom(rom.id, {"name_sort_key": "zelda"}) + + assert updated.name_sort_key_custom + def test_update_metadata_resyncs_min_age(self, rom: Rom): rated = db_rom_handler.update_rom( rom.id, diff --git a/backend/tests/handler/filesystem/test_base_handler.py b/backend/tests/handler/filesystem/test_base_handler.py index e501e204e..763d412d8 100644 --- a/backend/tests/handler/filesystem/test_base_handler.py +++ b/backend/tests/handler/filesystem/test_base_handler.py @@ -210,6 +210,18 @@ class TestFSHandler: assert handler.get_file_name_with_no_tags("game (USA) [Beta].rom") == "game" assert handler.get_file_name_with_no_tags("plain_name.rom") == "plain_name" + @pytest.mark.parametrize( + "file_name", + ["celeste.p8.png", "celeste.P8.PNG", "celeste (v1.1).p8.png", "celeste.p8"], + ) + def test_a_pico8_cart_title_drops_the_cart_extension( + self, handler: FSHandler, file_name: str + ): + assert handler.get_file_name_with_no_tags(file_name) == "celeste" + + def test_only_a_pico8_cart_loses_a_p8_suffix(self, handler: FSHandler): + assert handler.get_file_name_with_no_tags("Game.p8.zip") == "Game.p8" + def test_parse_file_extension(self, handler: FSHandler): """Test file extension parsing""" assert handler.parse_file_extension("test.txt") == "txt" diff --git a/backend/tests/handler/metadata/test_gamelist_handler.py b/backend/tests/handler/metadata/test_gamelist_handler.py index 86ac7441c..3a743fdae 100644 --- a/backend/tests/handler/metadata/test_gamelist_handler.py +++ b/backend/tests/handler/metadata/test_gamelist_handler.py @@ -869,3 +869,28 @@ class TestGamelistHandler: tags = [elem.tag for elem in handler._iter_game_elements(gamelist_path)] assert tags == ["game", "folder"] + + +def test_parse_gamelist_xml_keeps_a_sort_names_leading_article( + tmp_path: Path, platform: Platform +): + gamelist_path = tmp_path / "gamelist.xml" + gamelist_path.write_text( + """ + + + ./test-rom.zip + The Simpsons Arcade Game + The Simpsons + +""", + encoding="utf-8", + ) + + with patch( + "handler.metadata.gamelist_handler.get_preferred_media_types", + return_value=[], + ): + roms_data = GamelistHandler()._parse_gamelist_xml(gamelist_path, platform) + + assert roms_data["test-rom.zip"].get("name_sort_key") == "the simpsons" diff --git a/backend/tests/handler/test_scan_merge.py b/backend/tests/handler/test_scan_merge.py new file mode 100644 index 000000000..b5ec15ea8 --- /dev/null +++ b/backend/tests/handler/test_scan_merge.py @@ -0,0 +1,28 @@ +from tests.factories import make_rom + +from handler.scan.merge import keep_base_fields +from models.platform import Platform + + +def test_the_stored_placeholder_name_is_replaced(platform: Platform): + # The stored placeholder differs from the title derived from the filename. + rom = make_rom( + platform, + "celeste.p8", + fs_stem="celeste.p8", + fs_extension="png", + ) + rom_attrs = {"fs_name": rom.fs_name, "name": "Celeste"} + + keep_base_fields(rom_attrs, rom) + + assert rom_attrs["name"] == "Celeste" + + +def test_a_name_the_user_set_is_kept(platform: Platform): + rom = make_rom(platform, "My Celeste", fs_stem="celeste.p8", fs_extension="png") + rom_attrs = {"fs_name": rom.fs_name, "name": "Celeste"} + + keep_base_fields(rom_attrs, rom) + + assert rom_attrs["name"] == "My Celeste" diff --git a/backend/tests/handler/test_scan_sort_keys.py b/backend/tests/handler/test_scan_sort_keys.py new file mode 100644 index 000000000..37a49a925 --- /dev/null +++ b/backend/tests/handler/test_scan_sort_keys.py @@ -0,0 +1,44 @@ +from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan + +from handler.database import db_rom_handler +from handler.scan.sources import ScanType +from models.rom import Rom + + +def _with_key(rom: Rom, key: str, *, custom: bool) -> Rom: + updated = db_rom_handler.update_rom( + rom.id, {"name_sort_key": key, "name_sort_key_custom": custom} + ) + return updated + + +async def test_a_rescan_rederives_a_key_that_is_not_custom(): + platform = add_n64_platform() + rom = _with_key( + add_rom(platform, "Die Hard Arcade.z64", "Die Hard Arcade"), + "hard arcade", + custom=False, + ) + + scanned = await run_scan( + platform, rom, scan_type=ScanType.UPDATE, metadata_sources=[] + ) + + assert scanned.name_sort_key == "die hard arcade" + assert not scanned.name_sort_key_custom + + +async def test_a_rescan_keeps_a_custom_key(): + platform = add_n64_platform() + rom = _with_key( + add_rom(platform, "Die Hard Arcade.z64", "Die Hard Arcade"), + "hard arcade", + custom=True, + ) + + scanned = await run_scan( + platform, rom, scan_type=ScanType.UPDATE, metadata_sources=[] + ) + + assert scanned.name_sort_key == "hard arcade" + assert scanned.name_sort_key_custom diff --git a/backend/tests/models/test_base.py b/backend/tests/models/test_base.py index 2a782d19a..16de4ecad 100644 --- a/backend/tests/models/test_base.py +++ b/backend/tests/models/test_base.py @@ -1,5 +1,6 @@ import pytest +from config.config_manager import config_manager as cm from models.assets import Save from models.base import compute_file_name_parts from models.firmware import Firmware @@ -34,6 +35,8 @@ def test_compute_file_name_parts(file_name, no_tags, no_ext, extension): ("The Legend of Zelda 2", "legend of zelda 000000000002"), ("A Bug's Life", "bug's life"), ("Final Fantasy 10", "final fantasy 000000000010"), + ("Die Hard Arcade", "die hard arcade"), + ("Le Mans 24 Hours", "le mans 000000000024 hours"), (None, ""), ], ) @@ -41,6 +44,21 @@ def test_compute_name_sort_key(name, expected): assert compute_name_sort_key(name) == expected +def test_compute_name_sort_key_drops_the_configured_articles(mocker): + mocker.patch.object(cm.config, "SORT_ARTICLES", ["der", "die", "das"]) + + assert compute_name_sort_key("Die Siedler") == "siedler" + assert compute_name_sort_key("The Legend of Zelda") == "the legend of zelda" + + +def test_a_custom_sort_key_keeps_its_leading_article(): + assert compute_name_sort_key("The Legend", articles=()) == "the legend" + + rom = Rom(name="The Legend of Zelda", name_sort_key="The Legend") + + assert rom.name_sort_key == "the legend" + + def test_rom_validator_derives_fs_name_parts_on_construction(): rom = Rom(fs_name="The Legend of Zelda (USA) (Rev 1).z64") diff --git a/backend/tests/tasks/test_recompute_name_sort_keys.py b/backend/tests/tasks/test_recompute_name_sort_keys.py new file mode 100644 index 000000000..861c1eb4e --- /dev/null +++ b/backend/tests/tasks/test_recompute_name_sort_keys.py @@ -0,0 +1,133 @@ +import json + +import pytest +from rq.job import JOB_ID_PATTERN +from tests.factories import make_rom + +from config.config_manager import config_manager as cm +from handler.database import db_rom_handler +from handler.database.roms_handler import DBRomsHandler +from handler.redis_handler import sync_cache +from models.platform import Platform +from tasks.manual.recompute_name_sort_keys import ( + APPLIED_SORT_ARTICLES_KEY, + applied_sort_articles, + articles_digest, + recompute_name_sort_keys_task, +) + + +def stored_sort_key(rom_id: int) -> str | None: + rom = db_rom_handler.get_rom(rom_id) + assert rom is not None + return rom.name_sort_key + + +@pytest.fixture(autouse=True) +def clear_applied_articles(): + sync_cache.delete(APPLIED_SORT_ARTICLES_KEY) + yield + sync_cache.delete(APPLIED_SORT_ARTICLES_KEY) + + +def test_no_articles_are_recorded_until_a_recompute_runs(): + assert applied_sort_articles() is None + + +async def test_derived_keys_follow_the_configured_articles(platform: Platform): + rom = make_rom(platform, "Die Hard Arcade") + db_rom_handler.update_rom( + rom.id, {"name_sort_key": "hard arcade", "name_sort_key_custom": False} + ) + + stats = await recompute_name_sort_keys_task.run() + + assert stored_sort_key(rom.id) == "die hard arcade" + assert stats["sort_keys_replaced"] == 1 + applied = sync_cache.get(APPLIED_SORT_ARTICLES_KEY) + assert applied is not None + assert json.loads(applied) == ["the", "a", "an"] + + +async def test_a_custom_sort_key_is_kept(platform: Platform): + rom = make_rom(platform, "Die Hard Arcade") + db_rom_handler.update_rom(rom.id, {"name_sort_key": "hard arcade"}) + + await recompute_name_sort_keys_task.run() + + assert stored_sort_key(rom.id) == "hard arcade" + + +async def test_a_changed_articles_list_rederives_derived_keys( + platform: Platform, mocker +): + rom = make_rom(platform, "Die Siedler") + assert stored_sort_key(rom.id) == "die siedler" + mocker.patch.object(cm.config, "SORT_ARTICLES", ["der", "die", "das"]) + + await recompute_name_sort_keys_task.run() + + assert stored_sort_key(rom.id) == "siedler" + + +def test_a_key_is_not_replaced_once_its_name_changed(platform: Platform): + rom = make_rom(platform, "Die Hard Arcade") + db_rom_handler.update_rom(rom.id, {"name": "Die Hard Trilogy"}) + + replaced = db_rom_handler.replace_derived_sort_keys( + {rom.id: ("Die Hard Arcade", "die hard arcade")} + ) + + assert replaced == 0 + assert stored_sort_key(rom.id) == "die hard trilogy" + + +async def test_replacing_keys_drops_the_cached_gallery_order( + platform: Platform, mocker +): + rom = make_rom(platform, "Die Hard Arcade") + db_rom_handler.update_rom( + rom.id, {"name_sort_key": "hard arcade", "name_sort_key_custom": False} + ) + invalidate = mocker.patch.object(DBRomsHandler, "invalidate_filter_values_cache") + + await recompute_name_sort_keys_task.run() + + invalidate.assert_called_once() + + +def test_an_accent_only_rename_still_blocks_the_replacement(platform: Platform): + rom = make_rom(platform, "Die Hard Arcade") + db_rom_handler.update_rom(rom.id, {"name": "Díe Hard Arcade"}) + + replaced = db_rom_handler.replace_derived_sort_keys( + {rom.id: ("Die Hard Arcade", "die hard arcade")} + ) + + assert replaced == 0 + + +async def test_a_run_that_fails_partway_leaves_no_articles_recorded( + platform: Platform, mocker +): + rom = make_rom(platform, "Die Hard Arcade") + db_rom_handler.update_rom( + rom.id, {"name_sort_key": "hard arcade", "name_sort_key_custom": False} + ) + sync_cache.set(APPLIED_SORT_ARTICLES_KEY, json.dumps(["the", "a", "an"])) + mocker.patch.object( + DBRomsHandler, "replace_derived_sort_keys", side_effect=RuntimeError("db down") + ) + + with pytest.raises(RuntimeError): + await recompute_name_sort_keys_task.run() + + assert applied_sort_articles() is None + + +def test_each_articles_list_gets_its_own_valid_job_id(): + english = articles_digest(("the", "a", "an")) + german = articles_digest(("der", "die", "das")) + + assert english != german + assert JOB_ID_PATTERN.fullmatch(f"recompute_name_sort_keys_bootstrap_{english}") diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py index 1304d3bee..c9c08fe76 100644 --- a/backend/tests/test_migrations.py +++ b/backend/tests/test_migrations.py @@ -21,6 +21,7 @@ from sqlalchemy.sql.schema import NULL_UNSPECIFIED from tests.factories import make_platform, make_rom import models +from config.config_manager import config_manager as cm from handler.database import db_collection_handler, db_rom_handler from handler.database.base_handler import sync_engine from models.base import BaseModel @@ -258,6 +259,7 @@ def _replay(connection: sa.Connection, filename: str) -> None: ("0148_rom_age_limits.py", "permission_groups"), ("0148_rom_age_limits.py", "users"), ("0151_state_content_hash.py", "states"), + ("0157_rom_custom_sort_key_flag.py", "roms"), ], ) def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op( @@ -1412,3 +1414,50 @@ def test_the_ownerless_own_only_revision_keeps_each_rows_access(admin_user: User ("logs", "read", False, False), ("devices", "write", True, True), } + + +def test_the_custom_sort_key_revision_flags_keys_no_name_derives( + platform: Platform, +): + """0157 marks a key custom when the legacy rule would not derive it.""" + migration = _load_migration("0157_rom_custom_sort_key_flag.py") + derived = make_rom(platform, "Die Hard Arcade") + english = make_rom(platform, "Die Siedler") + custom = make_rom(platform, "Le Mans 24 Hours") + + with sync_engine.begin() as connection: + connection.execute( + sa.text("UPDATE roms SET name_sort_key = :key WHERE id = :id"), + [ + # Derived by the multilingual rule, and by 0084's English one. + {"id": derived.id, "key": "hard arcade"}, + {"id": english.id, "key": "die siedler"}, + {"id": custom.id, "key": "mans le 000000000024 hours"}, + ], + ) + with Operations.context(MigrationContext.configure(connection)): + migration.downgrade() + migration.upgrade() + + flags: dict[int, bool] = dict( + connection.execute( + sa.text( + "SELECT id, name_sort_key_custom FROM roms WHERE id IN (:a, :b, :c)" + ), + {"a": derived.id, "b": english.id, "c": custom.id}, + ).all() + ) + assert not flags[derived.id] + assert not flags[english.id] + assert flags[custom.id] + + +def test_the_sort_key_backfill_keeps_its_original_rule(mocker): + """0084 fills keys the way it always has, whatever the configured articles.""" + migration = _load_migration("0084_add_roms_search_index.py") + mocker.patch.object(cm.config, "SORT_ARTICLES", ["der", "die", "das"]) + + assert migration._sort_key("Die Hard Arcade") == "die hard arcade" + assert ( + migration._sort_key("The Legend of Zelda 2") == "legend of zelda 000000000002" + ) diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py index e7e0e6a5c..be7169861 100644 --- a/backend/tests/test_startup.py +++ b/backend/tests/test_startup.py @@ -4,12 +4,13 @@ from unittest.mock import AsyncMock import pytest import startup -from rq.exceptions import DuplicateJobError -from rq.job import JOB_ID_PATTERN +from rq.exceptions import DuplicateJobError, NoSuchJobError +from rq.job import JOB_ID_PATTERN, Job, JobStatus from handler.database import db_save_handler from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE from handler.redis_handler import default_queue, high_prio_queue, low_prio_queue +from tasks.manual.recompute_name_sort_keys import articles_digest from tasks.registry import get_task from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE from utils.cache import VersionedCacheStore @@ -47,6 +48,57 @@ def test_enqueue_recompute_fires_when_missing_hashes_present(mocker, enqueue_tas ) +@pytest.mark.parametrize( + ("applied", "queued"), + [(("the", "a", "an"), False), (("the", "die"), True), (None, True)], + ids=["unchanged", "changed", "unrecorded"], +) +def test_enqueue_recompute_name_sort_keys_when_the_articles_change( + mocker, enqueue_task, applied, queued +): + mocker.patch.object(startup, "applied_sort_articles", return_value=applied) + mocker.patch.object(startup, "sort_articles", return_value=("the", "a", "an")) + mocker.patch.object(startup, "_free_finished_job_id") + + startup._enqueue_recompute_name_sort_keys_if_needed() + + if queued: + enqueue_task.assert_called_once_with( + "recompute_name_sort_keys", + job_id=( + f"{startup.RECOMPUTE_NAME_SORT_KEYS_JOB_ID}_" + f"{articles_digest(('the', 'a', 'an'))}" + ), + unique=True, + ) + else: + enqueue_task.assert_not_called() + + +@pytest.mark.parametrize( + ("status", "freed"), + [ + (JobStatus.FINISHED, True), + (JobStatus.FAILED, True), + (JobStatus.QUEUED, False), + (JobStatus.STARTED, False), + ], +) +def test_a_stopped_job_frees_its_id_and_a_live_one_keeps_it(mocker, status, freed): + job = mocker.Mock(get_status=mocker.Mock(return_value=status)) + mocker.patch.object(Job, "fetch", return_value=job) + + startup._free_finished_job_id("recompute_name_sort_keys_bootstrap_abc") + + assert job.delete.called is freed + + +def test_a_missing_job_leaves_nothing_to_free(mocker): + mocker.patch.object(Job, "fetch", side_effect=NoSuchJobError) + + startup._free_finished_job_id("recompute_name_sort_keys_bootstrap_abc") + + def test_enqueue_convert_webp_fires_when_not_queued(enqueue_task): """No in-flight bootstrap job -> enqueue the backfill exactly once.""" startup._enqueue_convert_images_to_webp() diff --git a/backend/utils/roms_columns.py b/backend/utils/roms_columns.py index 3630ace51..e8da84cc5 100644 --- a/backend/utils/roms_columns.py +++ b/backend/utils/roms_columns.py @@ -501,6 +501,8 @@ def drop_save_target_layout_type(conn: sa.Connection) -> None: _save_target_layout_type().drop(conn, checkfirst=True) +NAME_SORT_KEY_CUSTOM_COLUMN = "name_sort_key_custom" + # The stored columns in the catalog, minus `full_path_hash`. PLAIN_COLUMNS: list[sa.Column[Any]] = [ sa.Column("is_physical", sa.Boolean(), nullable=False, server_default=sa.false()), @@ -522,6 +524,12 @@ PLAIN_COLUMNS: list[sa.Column[Any]] = [ ), sa.Column(SEARCH_TITLES_COLUMN, sa.Text()), sa.Column(MIN_AGE_COLUMN, sa.Integer()), + sa.Column( + NAME_SORT_KEY_CUSTOM_COLUMN, + sa.Boolean(), + nullable=False, + server_default=sa.false(), + ), ] diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 4b6c3a2ff..7cd5edc78 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -326,6 +326,7 @@ backend/ │ └── manual/ # On-demand tasks │ ├── cleanup_missing_roms.py # Drop DB entries for missing files │ ├── convert_library.py # Store matched ROMs in each platform's library format +│ ├── recompute_name_sort_keys.py # Re-derive sort keys after `sorting.articles` changes │ ├── cleanup_orphaned_resources.py # Remove unreferenced artwork │ └── sync_folder_scan.py # Scan sync folder for new saves │ @@ -1743,11 +1744,12 @@ Toggled via environment variables: Triggered via `POST /api/tasks/run/{task_name}`, which enqueues on `low_prio_queue` and answers 503 when no live worker is listening on it: -| Task | Description | -| ---------------------- | ------------------------------------------------------------------------------------- | -| `cleanup_missing_roms` | Remove DB entries for files no longer on disk | -| `sync_folder_scan` | Scan sync folder for new device saves | -| `convert_library` | Convert matched ROMs to `converto.platform_formats` in place, replacing the originals | +| Task | Description | +| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| `cleanup_missing_roms` | Remove DB entries for files no longer on disk | +| `sync_folder_scan` | Scan sync folder for new device saves | +| `convert_library` | Convert matched ROMs to `converto.platform_formats` in place, replacing the originals | +| `recompute_name_sort_keys` | Re-derive ROM sort keys with the articles `sorting.articles` names, keeping custom keys. Queued at startup when that list changes | A spec marked `destructive` asks for a typed confirmation before the UI runs it, and one marked `single_instance` answers 409 while a job of it is queued or running. `convert_library` is both, and runs only with `ROM_CONVERTO_ENABLED` set. @@ -1946,6 +1948,7 @@ Falls back to `FakeRedis` in test mode. | `OIDC_TLS_CACERTFILE` | | Custom CA bundle for OIDC calls | | `OIDC_RP_INITIATED_LOGOUT` | `false` | Send logout to OIDC provider | | `OIDC_END_SESSION_ENDPOINT` | | End-session URL override | +| `OIDC_AUTH_PARAMS` | | JSON of extra authorize params | #### API Keys diff --git a/env.template b/env.template index e5468b475..4f6506fc6 100644 --- a/env.template +++ b/env.template @@ -66,6 +66,7 @@ OIDC_TLS_CACERTFILE= # CA bundle file (PEM, DER or .p7b) or directory, trusted OIDC_USERNAME_ATTRIBUTE=preferred_username # Attribute on OIDC user info used as the username OIDC_RP_INITIATED_LOGOUT=false # Enable RP-initiated logout flow OIDC_END_SESSION_ENDPOINT= # OIDC end-session endpoint override URL +OIDC_AUTH_PARAMS= # JSON object of extra authorization request parameters, e.g. {"prompt":"select_account"} # Metadata Providers IGDB_CLIENT_ID= # Client ID for the IGDB API diff --git a/examples/config.example.yml b/examples/config.example.yml index fe2cfc275..02df215b2 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -93,6 +93,18 @@ # ps3: 'roms/{platform}/{category}/{game}' # snes: 'roms/{platform}/{region}/{game}' +# sorting: +# # Leading words a title sorts without, so "The Legend of Zelda" files under L. +# # Defaults to English; list your library's articles to change it. A custom +# # sort name set on a game is always used as typed. +# articles: +# - the +# - a +# - an +# - der +# - die +# - das + # scan: # # Metadata priority during scans # priority: diff --git a/frontend/src/components/Gallery/FirmwareTab.test.ts b/frontend/src/components/Gallery/FirmwareTab.test.ts index 6b2dd331e..da1fdf91030 100644 --- a/frontend/src/components/Gallery/FirmwareTab.test.ts +++ b/frontend/src/components/Gallery/FirmwareTab.test.ts @@ -106,6 +106,21 @@ describe("FirmwareTab", () => { }); }); +describe("FirmwareTab key files", () => { + it("marks Switch key files as not used by RomM", () => { + const wrapper = mountTab([ + firmware({ id: 1, file_name: "prod.keys" }), + firmware({ id: 2, file_name: "title.keys" }), + firmware({ id: 3, file_name: "BOOT0" }), + ]); + + const keyChips = wrapper + .findAllComponents({ name: "RChip" }) + .filter((c) => c.props("prependIcon") === "mdi-key-outline"); + expect(keyChips).toHaveLength(2); + }); +}); + describe("FirmwareTab selection", () => { const rows = [ firmware({ id: 1 }), diff --git a/frontend/src/components/Gallery/FirmwareTab.vue b/frontend/src/components/Gallery/FirmwareTab.vue index 346ca3c3b..d704b9204 100644 --- a/frontend/src/components/Gallery/FirmwareTab.vue +++ b/frontend/src/components/Gallery/FirmwareTab.vue @@ -50,6 +50,11 @@ const platformsStore = storePlatforms(); const galleryRoms = storeGalleryRoms(); const canWrite = useCan("platform.edit"); +// Switch key files are stored for clients and emulators; RomM never reads them. +function isKeyFile(f: FirmwareSchema): boolean { + return f.file_name.toLowerCase().endsWith(".keys"); +} + const firmwareList = computed( () => props.platform.firmware ?? [], ); @@ -392,6 +397,15 @@ async function performDelete( > {{ t("platform.firmware-verified", "Verified") }} + + {{ t("platform.firmware-keys-unused") }} +
diff --git a/frontend/src/components/Gallery/GalleryToolbar.test.ts b/frontend/src/components/Gallery/GalleryToolbar.test.ts index fbc55c539..10389caab 100644 --- a/frontend/src/components/Gallery/GalleryToolbar.test.ts +++ b/frontend/src/components/Gallery/GalleryToolbar.test.ts @@ -227,3 +227,47 @@ describe("GalleryToolbar sort axis", () => { wrapper.unmount(); }); }); + +describe("GalleryToolbar group-by control", () => { + const MANY_MODES = [ + { id: "none", icon: "mdi-view-agenda-outline", title: "Flat view" }, + { + id: "letter", + icon: "mdi-alphabetical-variant", + title: "Group by letter", + }, + { id: "family", icon: "mdi-family-tree", title: "Group by family" }, + ]; + + it("keeps the segmented slider for the default two modes", () => { + const wrapper = mountToolbar({}, RMenuPassthrough); + + expect( + wrapper + .findAllComponents({ name: "RSegmentedControl" }) + .some((c) => c.props("items")?.length === 2), + ).toBe(true); + wrapper.unmount(); + }); + + it("lists more than two modes in a labelled menu with the active one checked", () => { + const wrapper = mountToolbar( + { groupBy: "family", groupByItems: MANY_MODES }, + RMenuPassthrough, + ); + + expect( + wrapper + .findAllComponents({ name: "RSegmentedControl" }) + .some((c) => c.props("items") === MANY_MODES), + ).toBe(false); + const family = wrapper + .findAllComponents({ name: "RMenuItem" }) + .filter((item) => item.props("label") === "Group by family"); + expect(family.length).toBeGreaterThan(0); + expect(family.some((item) => item.props("variant") === "active")).toBe( + true, + ); + wrapper.unmount(); + }); +}); diff --git a/frontend/src/components/Gallery/GalleryToolbar.vue b/frontend/src/components/Gallery/GalleryToolbar.vue index f974c7c47..825497a24 100644 --- a/frontend/src/components/Gallery/GalleryToolbar.vue +++ b/frontend/src/components/Gallery/GalleryToolbar.vue @@ -228,6 +228,14 @@ const autofocusSearchField = computed( shouldAutofocusSearch(), ); +// Two modes fit a segmented slider; more read better as a labelled menu. +const groupByAsMenu = computed(() => effectiveGroupByItems.value.length > 2); +const activeGroupByIcon = computed( + () => + effectiveGroupByItems.value.find((i) => i.id === groupByValue.value) + ?.icon ?? "mdi-format-list-group", +); + function setGroupBy(value: GroupByMode) { emit("update:groupBy", value); } @@ -335,13 +343,37 @@ const { smAndUp } = useBreakpoint();