Files
romm/backend/models/base.py
Sam Dornan 5c43a97687 feat(gallery): pick a game's default version by region priority
The group_by_meta_id dedup window ordered each sibling group by
is_main_sibling then fs_name_no_ext, so absent a manual override the
gallery entry went to whichever filename sorted first: "(Demo)" beat
"(Europe)" beat "(USA)".

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

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

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

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

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

Closes #1528

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 11:55:07 -05:00

84 lines
2.6 KiB
Python

import re
from datetime import datetime, timezone
from typing import NamedTuple
from sqlalchemy import TIMESTAMP
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
FILE_NAME_MAX_LENGTH = 450
FILE_PATH_MAX_LENGTH = 1000
FILE_EXTENSION_MAX_LENGTH = 100
# Matches parenthesised/bracketed tag groups, e.g. " (USA)" or " [!]", or " (USA) (Rev 1) [!]"
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+)$")
# 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)".
PRERELEASE_FILENAME_TAGS = (
"demo",
"beta",
"proto",
"sample",
"kiosk",
"preview",
)
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def compute_file_name_no_ext(file_name: str) -> str:
"""Strip the trailing extension from a file name."""
return EXTENSION_REGEX.sub("", file_name).strip()
def compute_file_name_no_tags(file_name: str) -> str:
"""Strip the extension and any trailing tag groups from a file name.
Only tag groups at the end are removed (repeatedly), so a title that
legitimately contains parentheses/brackets mid-name is not truncated.
"""
name = compute_file_name_no_ext(file_name)
return TAG_GROUP_REGEX.sub("", name).strip()
def compute_file_extension(file_name: str) -> str:
"""Return the file's extension (without the leading dot), or ""."""
match = EXTENSION_REGEX.search(file_name)
return match.group(1) if match else ""
class FileNameParts(NamedTuple):
no_tags: str
no_ext: str
extension: str
def compute_file_name_parts(file_name: str) -> FileNameParts:
"""Precompute the derived columns stored alongside a file name.
These mirror the `*_no_tags` / `*_no_ext` / `*_extension` columns on
`Rom`, the asset models, and `Firmware`, which are kept in sync via a
`@validates` hook on the source name column.
"""
return FileNameParts(
no_tags=compute_file_name_no_tags(file_name),
no_ext=compute_file_name_no_ext(file_name),
extension=compute_file_extension(file_name),
)
class BaseModel(DeclarativeBase):
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True), default=utc_now
)
updated_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
onupdate=utc_now,
)