Files
romm/backend/models/base.py
zurdi 980a7887c6 simplify: give collections a visibility route and derive name columns in the handlers
- PUT /collections/{id}/visibility and /collections/smart/{id}/visibility
  flip is_public alone. The settings switch used the full update, which
  rewrote membership from the client's rom_ids and ran the cover branch.
- update_save, update_state and update_screenshot derive the file-name
  columns from file_name, like update_rom does for fs_name, so the rename
  path hands them a name instead of building the columns itself.
- Name fields use notBlank, AssetEditDialog picks its own title from its
  type, ScreenshotEditDialog shares one canSubmit, the collection tile and
  row drop a virtual guard their callers already cover, and PublicBadge
  uses the pill radius token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 16:10:42 +02:00

98 lines
3.0 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),
)
def with_file_name_parts(data: dict) -> dict:
"""`data` plus the columns derived from its `file_name`, which a bulk
update() must write itself since it skips the `@validates` hook."""
if "file_name" not in data:
return data
parts = compute_file_name_parts(data["file_name"])
return {
**data,
"file_name_no_tags": parts.no_tags,
"file_name_no_ext": parts.no_ext,
"file_extension": parts.extension,
}
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,
)