Files
romm/backend/endpoints/responses/assets.py
zurdi ecaa883400 refactor(v2): apply the simplify pass
The folding rule was written three times in two phrasings: as a filter,
as its own inverse inside the auto-open check, and as an arithmetic
difference for the chevron count. A slot band now partitions into
`pinned` and `hidden` once where it is built, so the rule has one home
and the filter stops re-running per render.

Also:
- A band carries its newest asset instead of the id, so ranking no
  longer scans the band to find it again inside a sort comparator.
- `HIDDEN_ASSET_ANNOTATIONS` derives from `AssetAnnotations`, so a third
  annotation field cannot be added without also being masked.
- `normalize_asset_labels` keys the dedupe off a dict, folding each label
  once, and rejects an oversized set as soon as it crosses the cap
  instead of after walking the whole body.
- The clear button's absolute placement moved onto the stage that wants
  it, so the inline variant no longer un-sets it.
- Two duplicated label ternaries became computeds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016bZ7R3xC73MZu1vTNuatPK
2026-09-23 00:16:32 +02:00

130 lines
3.6 KiB
Python

from typing import Any
from pydantic import ConfigDict, field_validator, model_validator
from sqlalchemy import inspect
from sqlalchemy.exc import InvalidRequestError
from .base import BaseModel, UTCDatetime
from .device import DeviceSyncSchema
class BaseAsset(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
rom_id: int
user_id: int
file_name: str
file_name_no_tags: str
file_name_no_ext: str
file_extension: str
file_path: str
file_size_bytes: int
full_path: str
download_path: str
missing_from_fs: bool
created_at: UTCDatetime
updated_at: UTCDatetime
class AssetAnnotations(BaseModel):
"""The owner-only annotations saves and states share."""
is_favorite: bool = False
labels: list[str] = []
@field_validator("labels", mode="before")
@classmethod
def _labels_never_null(cls, value: Any) -> Any:
# The column is nullable, so rows predating the migration read NULL.
return value or []
# A shared save or state shows its author's name, never their annotations:
# a label names a run for its owner and is not part of what sharing offers.
# Derived from the model so a field added there is masked without a second edit.
HIDDEN_ASSET_ANNOTATIONS: dict[str, Any] = AssetAnnotations().model_dump()
class ScreenshotSchema(BaseAsset):
is_gallery: bool = False
is_public: bool = False
class UserScreenshotSchema(ScreenshotSchema):
"""A gallery screenshot enriched with its owner's username, for the
community (My / Community) view. Mirrors UserNoteSchema."""
username: str
# Author identity for rendering an avatar next to community screenshots.
user_avatar_path: str = ""
user_updated_at: UTCDatetime | None = None
class SaveSchema(BaseAsset, AssetAnnotations):
emulator: str | None
slot: str | None = None
content_hash: str | None = None
is_public: bool = False
screenshot: ScreenshotSchema | None
origin_device_id: str | None = None
device_syncs: list[DeviceSyncSchema] = []
@model_validator(mode="before")
@classmethod
def handle_lazy_relationships(cls, data: Any) -> Any:
if isinstance(data, dict):
return data
try:
state = inspect(data)
except Exception:
return data
result = {}
for field_name in cls.model_fields:
if field_name in state.unloaded:
continue
try:
result[field_name] = getattr(data, field_name)
except InvalidRequestError:
continue
return result
class UserSaveSchema(SaveSchema):
"""A save enriched with its owner's username, for the community (My /
Community) view. Mirrors UserScreenshotSchema."""
username: str
# Author identity for rendering an avatar next to community saves.
user_avatar_path: str = ""
user_updated_at: UTCDatetime | None = None
class SlotSummarySchema(BaseModel):
slot: str | None
count: int
latest: SaveSchema
class SaveSummarySchema(BaseModel):
total_count: int
slots: list[SlotSummarySchema]
class StateSchema(BaseAsset, AssetAnnotations):
emulator: str | None
is_public: bool = False
screenshot: ScreenshotSchema | None
class UserStateSchema(StateSchema):
"""A state enriched with its owner's username, for the community (My /
Community) view. Mirrors UserScreenshotSchema."""
username: str
# Author identity for rendering an avatar next to community states.
user_avatar_path: str = ""
user_updated_at: UTCDatetime | None = None