mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 18:43:23 +01:00
* feat(media): serve JPEG XL library images inline Add .jxl to the image extensions the download endpoint serves inline, with an explicit image/jxl type since mimetypes doesn't know it, and to the frontend lists that pick artwork and folder screenshots out of rom.files. AVIF was already covered; the new test pins both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs * feat(media): accept JPEG XL cover uploads through a Pillow plugin Pillow 13 reads AVIF but not JPEG XL. pillow-jxl-plugin registers a JXL codec with Pillow (imported once in utils/images, which the cover and WebP-conversion code already load). It ships musllinux wheels for the image's amd64 and arm64 builds. ROM and collection artwork uploads now accept image/jxl and store it re-encoded as PNG, since covers are served in their stored format and not every browser renders JPEG XL. Avatars, stored as uploaded, keep the PNG/JPEG/WebP/GIF allowlist. The plugin is GPL-3.0, which is compatible with RomM's AGPL-3.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs * test(roms): expect JPEG XL in the artwork rejection message Artwork uploads now also accept JPEG XL, so the rejection message lists it. The collection tests were updated with the change; this ROM one was missed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs * fix(media): list library JPEG XL images only where the browser renders them Library files are served as stored, and Chrome and Firefox render no JPEG XL, so .jxl artwork and folder screenshots showed as broken tiles there. A one-time probe decodes a 22-byte JPEG XL image and the artwork and screenshot lists only include .jxl files once it succeeds (Safari), updating reactively when the answer arrives. Chromium 153 fails the probe, so the files stay hidden there as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs * fix(media): size-check JPEG XL before decoding and keep it out of screenshot uploads pillow-jxl decodes every pixel in _open(), before Pillow's decompression-bomb check sees the size, so a small, highly compressed JXL declaring a huge canvas could exhaust memory. utils/jxl reads the width and height from the codestream SizeHeader (bare or inside a container) and runs Pillow's own bomb check on them first, then registers this guarded decoder in place of the plugin's. The decoder raises RuntimeError on a corrupt file, which escaped store_artwork as a 500. The guard turns it into SyntaxError, so Pillow reports UnidentifiedImageError and the upload takes the same path as a corrupt PNG. POST /api/screenshots validated against the library inline list, so it started accepting .jxl, but the asset endpoint serves those as attachments. Screenshot uploads now use their own list without JPEG XL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs * style(media): one-sentence jxl docstring and a narrowed mock call in the JXL test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs * style(media): one-sentence canRenderJxl doc comment Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NH5s4hx1GtQiHd7vsLCpBs --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
878 lines
28 KiB
Python
878 lines
28 KiB
Python
import json
|
|
from collections.abc import Iterable
|
|
from datetime import datetime
|
|
from io import BytesIO
|
|
from typing import Annotated, Any, TypeVar
|
|
|
|
from fastapi import Body, File, Form, HTTPException
|
|
from fastapi import Path as PathVar
|
|
from fastapi import Query, Request, UploadFile, status
|
|
from pydantic import BaseModel as PydanticBaseModel
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.collection import (
|
|
CollectionSchema,
|
|
SmartCollectionSchema,
|
|
VirtualCollectionSchema,
|
|
)
|
|
from endpoints.roms import (
|
|
refresh_affected_smart_collections,
|
|
refresh_scoped_smart_collections,
|
|
)
|
|
from exceptions.endpoint_exceptions import (
|
|
CollectionAlreadyExistsException,
|
|
CollectionNotFoundInDatabaseException,
|
|
CollectionPermissionError,
|
|
)
|
|
from handler.audit_handler import AuditTarget, changed_fields, record
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import get_rom_visibility_filter
|
|
from handler.database import db_collection_handler, db_rom_handler
|
|
from handler.database.rom_filters import RomFilterParams
|
|
from handler.filesystem import fs_resource_handler
|
|
from handler.filesystem.assets_handler import validate_image_upload
|
|
from handler.filesystem.base_handler import CoverSize
|
|
from logger.formatter import BLUE
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from models.audit_event import AuditAction
|
|
from models.collection import (
|
|
COLLECTION_NAME_MAX_LENGTH,
|
|
Collection,
|
|
SmartCollection,
|
|
VirtualCollection,
|
|
)
|
|
from models.rom import rom_id_from_resource_url
|
|
from utils.router import APIRouter
|
|
from utils.validation import ValidationError
|
|
|
|
router = APIRouter(
|
|
prefix="/collections",
|
|
tags=["collections"],
|
|
)
|
|
|
|
COLLECTION_ARTWORK_FILE = File(default=None, description="Collection artwork file.")
|
|
|
|
CollectionSchemaT = TypeVar(
|
|
"CollectionSchemaT",
|
|
CollectionSchema,
|
|
VirtualCollectionSchema,
|
|
SmartCollectionSchema,
|
|
)
|
|
|
|
|
|
def _hidden_rom_ids(request: Request, rom_ids: Iterable[int]) -> set[int]:
|
|
"""Of `rom_ids`, the ones hidden from the caller."""
|
|
ids = set(rom_ids)
|
|
visibility = get_rom_visibility_filter(request)
|
|
if not ids or visibility.is_unrestricted:
|
|
return set()
|
|
return db_rom_handler.get_hidden_rom_ids_among(list(ids), visibility)
|
|
|
|
|
|
def _hide_collection_roms(
|
|
schemas: list[CollectionSchemaT], request: Request
|
|
) -> list[CollectionSchemaT]:
|
|
"""Drop roms hidden from the caller from each collection's ids, count and covers."""
|
|
hidden = _hidden_rom_ids(request, (rid for s in schemas for rid in s.rom_ids))
|
|
if not hidden:
|
|
return schemas
|
|
for s in schemas:
|
|
s.rom_ids = set(s.rom_ids) - hidden
|
|
s.path_covers_small = _without_covers(s.path_covers_small, hidden)
|
|
s.path_covers_large = _without_covers(s.path_covers_large, hidden)
|
|
return schemas
|
|
|
|
|
|
def _hide_single_collection_roms(
|
|
schema: CollectionSchemaT, request: Request
|
|
) -> CollectionSchemaT:
|
|
return _hide_collection_roms([schema], request)[0]
|
|
|
|
|
|
def _without_covers(urls: list[str], hidden: set[int]) -> list[str]:
|
|
return [u for u in urls if rom_id_from_resource_url(u) not in hidden]
|
|
|
|
|
|
def _record_collection(
|
|
request: Request,
|
|
action: AuditAction,
|
|
collection: Collection | SmartCollection,
|
|
data: dict[str, Any] | None = None,
|
|
) -> None:
|
|
# Every heart toggle goes through the favourites collection; that's not news.
|
|
if getattr(collection, "is_favorite", False):
|
|
return
|
|
record(action, request, AuditTarget.of_collection(collection), data)
|
|
|
|
|
|
def _criteria_collection_id(criteria: object) -> int | None:
|
|
filters = RomFilterParams.from_stored_criteria(criteria)
|
|
return filters.collection_id if filters else None
|
|
|
|
|
|
def _check_criteria_collection(
|
|
criteria: object, user_id: int, kept_id: int | None = None
|
|
) -> None:
|
|
"""Refuse criteria newly scoped to a collection the owner can't see."""
|
|
collection_id = _criteria_collection_id(criteria)
|
|
if not collection_id or collection_id == kept_id:
|
|
return
|
|
collection = db_collection_handler.get_collection(collection_id)
|
|
if not collection or (collection.user_id != user_id and not collection.is_public):
|
|
raise CollectionNotFoundInDatabaseException(collection_id)
|
|
|
|
|
|
@protected_route(router.post, "", [Scope.COLLECTIONS_WRITE])
|
|
async def add_collection(
|
|
request: Request,
|
|
is_public: bool | None = None,
|
|
is_favorite: bool | None = None,
|
|
artwork: UploadFile | None = COLLECTION_ARTWORK_FILE,
|
|
name: str = Form(default="", max_length=COLLECTION_NAME_MAX_LENGTH),
|
|
description: str = Form(default=""),
|
|
url_cover: str = Form(
|
|
default="", description="Remote URL to fetch and use as cover artwork."
|
|
),
|
|
) -> CollectionSchema:
|
|
"""Create collection endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
CollectionSchema: Just created collection
|
|
"""
|
|
cleaned_data = {
|
|
"name": name,
|
|
"description": description,
|
|
"url_cover": url_cover,
|
|
"is_public": is_public or False,
|
|
"is_favorite": is_favorite or False,
|
|
"user_id": request.user.id,
|
|
}
|
|
|
|
db_collection = db_collection_handler.get_collection_by_name(
|
|
cleaned_data["name"], request.user.id
|
|
)
|
|
|
|
if db_collection:
|
|
raise CollectionAlreadyExistsException(cleaned_data["name"])
|
|
|
|
_added_collection = db_collection_handler.add_collection(Collection(**cleaned_data))
|
|
|
|
try:
|
|
if artwork is not None and artwork.filename is not None:
|
|
file_ext = validate_image_upload(
|
|
artwork, label="Artwork", allow_converted=True
|
|
)
|
|
artwork_content = BytesIO(await artwork.read())
|
|
(
|
|
path_cover_l,
|
|
path_cover_s,
|
|
) = await fs_resource_handler.store_artwork(
|
|
_added_collection, artwork_content, file_ext
|
|
)
|
|
else:
|
|
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
|
|
entity=_added_collection,
|
|
overwrite=True,
|
|
url_cover=_added_collection.url_cover,
|
|
)
|
|
except ValidationError as e:
|
|
log.error(f"Invalid cover URL in add_collection: {str(e)}")
|
|
raise HTTPException(status_code=400, detail=str(e)) from e
|
|
|
|
_added_collection.path_cover_s = path_cover_s
|
|
_added_collection.path_cover_l = path_cover_l
|
|
|
|
# Update the collection with the cover path and update database
|
|
created_collection = db_collection_handler.update_collection(
|
|
_added_collection.id,
|
|
{
|
|
"path_cover_s": path_cover_s,
|
|
"path_cover_l": path_cover_l,
|
|
},
|
|
)
|
|
|
|
_record_collection(request, AuditAction.COLLECTION_CREATE, created_collection)
|
|
return CollectionSchema.model_validate(created_collection)
|
|
|
|
|
|
@protected_route(router.post, "/smart", [Scope.COLLECTIONS_WRITE])
|
|
async def add_smart_collection(
|
|
request: Request,
|
|
is_public: bool | None = None,
|
|
name: str = Form(default="", max_length=COLLECTION_NAME_MAX_LENGTH),
|
|
description: str = Form(default=""),
|
|
filter_criteria: str = Form(
|
|
default="{}",
|
|
description="Smart collection filters as a JSON string.",
|
|
),
|
|
) -> SmartCollectionSchema:
|
|
"""Create smart collection endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
SmartCollectionSchema: Just created smart collection
|
|
"""
|
|
# Parse filter criteria from JSON string
|
|
try:
|
|
parsed_filter_criteria = json.loads(filter_criteria)
|
|
except json.JSONDecodeError as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Invalid JSON for filter_criteria field",
|
|
) from e
|
|
_check_criteria_collection(parsed_filter_criteria, request.user.id)
|
|
|
|
cleaned_data = {
|
|
"name": name,
|
|
"description": description,
|
|
"filter_criteria": parsed_filter_criteria,
|
|
"is_public": is_public if is_public is not None else False,
|
|
"user_id": request.user.id,
|
|
}
|
|
|
|
db_smart_collection = db_collection_handler.get_smart_collection_by_name(
|
|
cleaned_data["name"], request.user.id
|
|
)
|
|
|
|
if db_smart_collection:
|
|
raise CollectionAlreadyExistsException(cleaned_data["name"])
|
|
|
|
created_smart_collection = db_collection_handler.add_smart_collection(
|
|
SmartCollection(**cleaned_data)
|
|
)
|
|
|
|
smart_collection = (
|
|
db_collection_handler.refresh_smart_collection(created_smart_collection.id)
|
|
or created_smart_collection
|
|
)
|
|
_record_collection(request, AuditAction.SMART_COLLECTION_CREATE, smart_collection)
|
|
|
|
return _hide_single_collection_roms(
|
|
SmartCollectionSchema.model_validate(smart_collection), request
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.COLLECTIONS_READ])
|
|
def get_collections(
|
|
request: Request,
|
|
updated_after: Annotated[
|
|
datetime | None,
|
|
Query(
|
|
description="Filter collections updated after this datetime (ISO 8601 format with timezone information)."
|
|
),
|
|
] = None,
|
|
) -> list[CollectionSchema]:
|
|
"""Get collections endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
updated_after: Filter collections updated after this datetime
|
|
|
|
Returns:
|
|
list[CollectionSchema]: List of collections
|
|
"""
|
|
|
|
collections = db_collection_handler.get_collections(updated_after=updated_after)
|
|
|
|
return _hide_collection_roms(
|
|
CollectionSchema.for_user(request.user.id, collections), request
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "/identifiers", [Scope.COLLECTIONS_READ])
|
|
def get_collection_identifiers(
|
|
request: Request,
|
|
) -> list[int]:
|
|
"""Get collections identifiers endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
list[int]: List of collection IDs
|
|
"""
|
|
|
|
rows = db_collection_handler.get_collection_ids()
|
|
|
|
return [row.id for row in rows if row.user_id == request.user.id or row.is_public]
|
|
|
|
|
|
@protected_route(router.get, "/virtual", [Scope.COLLECTIONS_READ])
|
|
def get_virtual_collections(
|
|
request: Request,
|
|
type: str,
|
|
limit: int | None = None,
|
|
) -> list[VirtualCollectionSchema]:
|
|
"""Get virtual collections endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
list[VirtualCollectionSchema]: List of virtual collections
|
|
"""
|
|
|
|
virtual_collections = db_collection_handler.get_virtual_collections(
|
|
type=type, limit=limit
|
|
)
|
|
|
|
return _hide_collection_roms(
|
|
[VirtualCollectionSchema.model_validate(vc) for vc in virtual_collections],
|
|
request,
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "/virtual/identifiers", [Scope.COLLECTIONS_READ])
|
|
def get_virtual_collection_identifiers(
|
|
request: Request,
|
|
) -> list[str]:
|
|
"""Get virtual collections identifiers endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
list[str]: List of generated virtual collection IDs
|
|
"""
|
|
|
|
virtual_collections = db_collection_handler.get_virtual_collections(
|
|
type="all",
|
|
only_fields=[VirtualCollection.name, VirtualCollection.type],
|
|
)
|
|
|
|
return [s.id for s in virtual_collections]
|
|
|
|
|
|
@protected_route(router.get, "/smart", [Scope.COLLECTIONS_READ])
|
|
def get_smart_collections(
|
|
request: Request,
|
|
updated_after: Annotated[
|
|
datetime | None,
|
|
Query(
|
|
description="Filter smart collections updated after this datetime (ISO 8601 format with timezone information)."
|
|
),
|
|
] = None,
|
|
) -> list[SmartCollectionSchema]:
|
|
"""Get smart collections endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
updated_after: Filter smart collections updated after this datetime
|
|
|
|
Returns:
|
|
list[SmartCollectionSchema]: List of smart collections
|
|
"""
|
|
|
|
smart_collections = db_collection_handler.get_smart_collections(
|
|
request.user.id, updated_after=updated_after
|
|
)
|
|
|
|
return _hide_collection_roms(
|
|
SmartCollectionSchema.for_user(request.user.id, smart_collections), request
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "/smart/identifiers", [Scope.COLLECTIONS_READ])
|
|
def get_smart_collection_identifiers(
|
|
request: Request,
|
|
) -> list[int]:
|
|
"""Get smart collections identifiers endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
list[int]: List of smart collection IDs
|
|
"""
|
|
|
|
return db_collection_handler.get_smart_collection_ids(request.user.id)
|
|
|
|
|
|
@protected_route(router.get, "/{id}", [Scope.COLLECTIONS_READ])
|
|
def get_collection(request: Request, id: int) -> CollectionSchema:
|
|
"""Get collections endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int, optional): Collection id. Defaults to None.
|
|
|
|
Returns:
|
|
CollectionSchema: Collection
|
|
"""
|
|
|
|
collection = db_collection_handler.get_collection(id)
|
|
if not collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if collection.user_id != request.user.id and not collection.is_public:
|
|
raise CollectionPermissionError(id)
|
|
|
|
return _hide_single_collection_roms(
|
|
CollectionSchema.model_validate(collection), request
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "/virtual/{id}", [Scope.COLLECTIONS_READ])
|
|
def get_virtual_collection(request: Request, id: str) -> VirtualCollectionSchema:
|
|
"""Get virtual collections endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (str): Virtual collection id
|
|
|
|
Returns:
|
|
VirtualCollectionSchema: Virtual collection
|
|
"""
|
|
|
|
virtual_collection = db_collection_handler.get_virtual_collection(id)
|
|
if not virtual_collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
return _hide_single_collection_roms(
|
|
VirtualCollectionSchema.model_validate(virtual_collection), request
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "/smart/{id}", [Scope.COLLECTIONS_READ])
|
|
def get_smart_collection(request: Request, id: int) -> SmartCollectionSchema:
|
|
"""Get smart collection endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int): Smart collection id
|
|
|
|
Returns:
|
|
SmartCollectionSchema: Smart collection
|
|
"""
|
|
|
|
smart_collection = db_collection_handler.get_smart_collection(id)
|
|
if not smart_collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if smart_collection.user_id != request.user.id and not smart_collection.is_public:
|
|
raise CollectionPermissionError(id)
|
|
|
|
return _hide_single_collection_roms(
|
|
SmartCollectionSchema.model_validate(smart_collection), request
|
|
)
|
|
|
|
|
|
@protected_route(router.put, "/{id}", [Scope.COLLECTIONS_WRITE])
|
|
async def update_collection(
|
|
request: Request,
|
|
id: int,
|
|
remove_cover: bool = False,
|
|
is_public: bool | None = None,
|
|
artwork: UploadFile | None = COLLECTION_ARTWORK_FILE,
|
|
rom_ids: str = Form(
|
|
...,
|
|
description="Collection ROM IDs as a JSON array string (e.g. [1,2,3]).",
|
|
),
|
|
name: str | None = Form(default=None, max_length=COLLECTION_NAME_MAX_LENGTH),
|
|
description: str | None = Form(default=None),
|
|
url_cover: str | None = Form(default=None, description="Updated remote cover URL."),
|
|
) -> CollectionSchema:
|
|
"""Update collection endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
CollectionSchema: Updated collection
|
|
"""
|
|
collection = db_collection_handler.get_collection(id)
|
|
if not collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if collection.user_id != request.user.id:
|
|
raise CollectionPermissionError(id)
|
|
|
|
if name is not None:
|
|
namesake = db_collection_handler.get_collection_by_name(name, request.user.id)
|
|
if namesake and namesake.id != collection.id:
|
|
raise CollectionAlreadyExistsException(name)
|
|
|
|
try:
|
|
parsed_rom_ids = json.loads(rom_ids)
|
|
except json.JSONDecodeError as e:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail="Invalid list for rom_ids field in update collection",
|
|
) from e
|
|
# The caller can't add roms hidden from them, nor drop members they can't see.
|
|
hidden = _hidden_rom_ids(request, [*parsed_rom_ids, *collection.rom_ids])
|
|
parsed_rom_ids = [rid for rid in parsed_rom_ids if rid not in hidden] + sorted(
|
|
hidden & set(collection.rom_ids)
|
|
)
|
|
|
|
cleaned_data = {
|
|
"name": name if name is not None else collection.name,
|
|
"description": (
|
|
description if description is not None else collection.description
|
|
),
|
|
"is_public": is_public if is_public is not None else collection.is_public,
|
|
"user_id": request.user.id,
|
|
}
|
|
|
|
if remove_cover:
|
|
cleaned_data.update(await fs_resource_handler.remove_cover(collection))
|
|
cleaned_data.update({"url_cover": ""})
|
|
else:
|
|
if artwork is not None and artwork.filename is not None:
|
|
file_ext = validate_image_upload(
|
|
artwork, label="Artwork", allow_converted=True
|
|
)
|
|
artwork_content = BytesIO(await artwork.read())
|
|
(
|
|
path_cover_l,
|
|
path_cover_s,
|
|
) = await fs_resource_handler.store_artwork(
|
|
collection, artwork_content, file_ext
|
|
)
|
|
|
|
cleaned_data.update(
|
|
{
|
|
"url_cover": "",
|
|
"path_cover_s": path_cover_s,
|
|
"path_cover_l": path_cover_l,
|
|
}
|
|
)
|
|
else:
|
|
current_url_cover = (
|
|
url_cover if url_cover is not None else collection.url_cover
|
|
)
|
|
if (
|
|
current_url_cover != collection.url_cover
|
|
or not fs_resource_handler.cover_exists(collection, CoverSize.BIG)
|
|
):
|
|
try:
|
|
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
|
|
entity=collection,
|
|
overwrite=True,
|
|
url_cover=current_url_cover,
|
|
)
|
|
cleaned_data.update(
|
|
{
|
|
"url_cover": current_url_cover,
|
|
"path_cover_s": path_cover_s,
|
|
"path_cover_l": path_cover_l,
|
|
}
|
|
)
|
|
except ValidationError as e:
|
|
log.error(f"Invalid cover URL in update_collection: {str(e)}")
|
|
raise HTTPException(status_code=400, detail=str(e)) from e
|
|
|
|
updated_collection = db_collection_handler.update_collection(
|
|
id, cleaned_data, parsed_rom_ids
|
|
)
|
|
changed = changed_fields(
|
|
collection, cleaned_data, ("name", "description", "is_public")
|
|
)
|
|
if "is_public" in changed:
|
|
refresh_scoped_smart_collections(id)
|
|
new_artwork = artwork is not None and artwork.filename is not None
|
|
if (
|
|
remove_cover
|
|
or new_artwork
|
|
or changed_fields(collection, cleaned_data, ["url_cover"])
|
|
):
|
|
changed.append("cover")
|
|
before_ids, after_ids = set(collection.rom_ids), set(updated_collection.rom_ids)
|
|
if before_ids != after_ids:
|
|
refresh_affected_smart_collections(
|
|
sorted(before_ids ^ after_ids), membership_only=True
|
|
)
|
|
if changed or before_ids != after_ids:
|
|
_record_collection(
|
|
request,
|
|
AuditAction.COLLECTION_EDIT,
|
|
updated_collection,
|
|
{
|
|
"changed": changed,
|
|
"added": len(after_ids - before_ids),
|
|
"removed": len(before_ids - after_ids),
|
|
},
|
|
)
|
|
|
|
return _hide_single_collection_roms(
|
|
CollectionSchema.model_validate(updated_collection), request
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}/visibility",
|
|
[Scope.COLLECTIONS_WRITE],
|
|
responses={status.HTTP_403_FORBIDDEN: {}, status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def update_collection_visibility(
|
|
request: Request,
|
|
id: int,
|
|
is_public: Annotated[bool, Body(embed=True)],
|
|
) -> CollectionSchema:
|
|
"""Share or unshare a collection (owner only), leaving its games and cover."""
|
|
collection = db_collection_handler.get_collection(id)
|
|
if not collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if collection.user_id != request.user.id:
|
|
raise CollectionPermissionError(id)
|
|
|
|
updated_collection = db_collection_handler.update_collection(
|
|
id, {"is_public": is_public}
|
|
)
|
|
if collection.is_public != is_public:
|
|
refresh_scoped_smart_collections(id)
|
|
|
|
return _hide_single_collection_roms(
|
|
CollectionSchema.model_validate(updated_collection), request
|
|
)
|
|
|
|
|
|
class CollectionRomsPayload(PydanticBaseModel):
|
|
rom_ids: list[int]
|
|
|
|
|
|
@protected_route(router.post, "/{id}/roms", [Scope.COLLECTIONS_WRITE])
|
|
async def add_roms_to_collection(
|
|
request: Request,
|
|
id: int,
|
|
payload: CollectionRomsPayload,
|
|
) -> CollectionSchema:
|
|
"""Atomically add ROMs to a collection without replacing the full list.
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int): Collection id
|
|
payload (CollectionRomsPayload): ROM IDs to add
|
|
|
|
Returns:
|
|
CollectionSchema: Updated collection
|
|
"""
|
|
collection = db_collection_handler.get_collection(id)
|
|
if not collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if collection.user_id != request.user.id:
|
|
raise CollectionPermissionError(id)
|
|
|
|
hidden = _hidden_rom_ids(request, payload.rom_ids)
|
|
rom_ids = [rid for rid in payload.rom_ids if rid not in hidden]
|
|
before = set(collection.rom_ids)
|
|
updated_collection = db_collection_handler.add_roms_to_collection(id, rom_ids)
|
|
refresh_affected_smart_collections(rom_ids, membership_only=True)
|
|
if added := sorted(set(updated_collection.rom_ids) - before):
|
|
_record_collection(
|
|
request,
|
|
AuditAction.COLLECTION_ADD_ROMS,
|
|
collection,
|
|
{"count": len(added), "rom_ids": added},
|
|
)
|
|
return _hide_single_collection_roms(
|
|
CollectionSchema.model_validate(updated_collection), request
|
|
)
|
|
|
|
|
|
@protected_route(router.delete, "/{id}/roms", [Scope.COLLECTIONS_WRITE])
|
|
async def remove_roms_from_collection(
|
|
request: Request,
|
|
id: int,
|
|
payload: CollectionRomsPayload,
|
|
) -> CollectionSchema:
|
|
"""Atomically remove ROMs from a collection without replacing the full list.
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int): Collection id
|
|
payload (CollectionRomsPayload): ROM IDs to remove
|
|
|
|
Returns:
|
|
CollectionSchema: Updated collection
|
|
"""
|
|
collection = db_collection_handler.get_collection(id)
|
|
if not collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if collection.user_id != request.user.id:
|
|
raise CollectionPermissionError(id)
|
|
|
|
before = set(collection.rom_ids)
|
|
updated_collection = db_collection_handler.remove_roms_from_collection(
|
|
id, payload.rom_ids
|
|
)
|
|
refresh_affected_smart_collections(payload.rom_ids, membership_only=True)
|
|
if removed := sorted(before - set(updated_collection.rom_ids)):
|
|
_record_collection(
|
|
request,
|
|
AuditAction.COLLECTION_REMOVE_ROMS,
|
|
collection,
|
|
{"count": len(removed), "rom_ids": removed},
|
|
)
|
|
return _hide_single_collection_roms(
|
|
CollectionSchema.model_validate(updated_collection), request
|
|
)
|
|
|
|
|
|
@protected_route(router.put, "/smart/{id}", [Scope.COLLECTIONS_WRITE])
|
|
async def update_smart_collection(
|
|
request: Request,
|
|
id: int,
|
|
is_public: bool | None = None,
|
|
name: str | None = Form(default=None, max_length=COLLECTION_NAME_MAX_LENGTH),
|
|
description: str | None = Form(default=None),
|
|
filter_criteria: str | None = Form(
|
|
default=None,
|
|
description="Updated smart collection filters as a JSON string.",
|
|
),
|
|
) -> SmartCollectionSchema:
|
|
"""Update smart collection endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int): Smart collection id
|
|
|
|
Returns:
|
|
SmartCollectionSchema: Updated smart collection
|
|
"""
|
|
smart_collection = db_collection_handler.get_smart_collection(id)
|
|
if not smart_collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if smart_collection.user_id != request.user.id:
|
|
raise CollectionPermissionError(id)
|
|
|
|
if name is not None:
|
|
namesake = db_collection_handler.get_smart_collection_by_name(
|
|
name, request.user.id
|
|
)
|
|
if namesake and namesake.id != smart_collection.id:
|
|
raise CollectionAlreadyExistsException(name)
|
|
|
|
# Parse filter criteria if provided
|
|
parsed_filter_criteria = smart_collection.filter_criteria
|
|
if filter_criteria is not None:
|
|
try:
|
|
parsed_filter_criteria = json.loads(filter_criteria)
|
|
except json.JSONDecodeError as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Invalid JSON for filter_criteria field",
|
|
) from e
|
|
# The form resends the stored scope on every edit; the ROM filters
|
|
# already match nothing for one the owner has since lost.
|
|
_check_criteria_collection(
|
|
parsed_filter_criteria,
|
|
request.user.id,
|
|
kept_id=_criteria_collection_id(smart_collection.filter_criteria),
|
|
)
|
|
|
|
cleaned_data = {
|
|
"name": name if name is not None else smart_collection.name,
|
|
"description": (
|
|
description if description is not None else smart_collection.description
|
|
),
|
|
"filter_criteria": parsed_filter_criteria,
|
|
"is_public": is_public if is_public is not None else smart_collection.is_public,
|
|
"user_id": request.user.id,
|
|
}
|
|
|
|
updated_smart_collection = db_collection_handler.update_smart_collection(
|
|
id, cleaned_data
|
|
)
|
|
|
|
smart_collection = (
|
|
db_collection_handler.refresh_smart_collection(id) or updated_smart_collection
|
|
)
|
|
_record_collection(request, AuditAction.SMART_COLLECTION_EDIT, smart_collection)
|
|
|
|
return _hide_single_collection_roms(
|
|
SmartCollectionSchema.model_validate(smart_collection), request
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/smart/{id}/visibility",
|
|
[Scope.COLLECTIONS_WRITE],
|
|
responses={status.HTTP_403_FORBIDDEN: {}, status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def update_smart_collection_visibility(
|
|
request: Request,
|
|
id: int,
|
|
is_public: Annotated[bool, Body(embed=True)],
|
|
) -> SmartCollectionSchema:
|
|
"""Share or unshare a smart collection (owner only), leaving its filters."""
|
|
smart_collection = db_collection_handler.get_smart_collection(id)
|
|
if not smart_collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if smart_collection.user_id != request.user.id:
|
|
raise CollectionPermissionError(id)
|
|
|
|
return _hide_single_collection_roms(
|
|
SmartCollectionSchema.model_validate(
|
|
db_collection_handler.update_smart_collection(id, {"is_public": is_public})
|
|
),
|
|
request,
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/{id}",
|
|
[Scope.COLLECTIONS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
async def delete_collection(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="Collection internal id.", ge=1)],
|
|
) -> None:
|
|
"""Delete a collection by ID."""
|
|
collection = db_collection_handler.get_collection(id)
|
|
if not collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if collection.user_id != request.user.id:
|
|
raise CollectionPermissionError(id)
|
|
|
|
log.info(f"Deleting {hl(collection.name, color=BLUE)} from database")
|
|
db_collection_handler.delete_collection(id)
|
|
refresh_scoped_smart_collections(id)
|
|
_record_collection(request, AuditAction.COLLECTION_DELETE, collection)
|
|
|
|
try:
|
|
await fs_resource_handler.remove_directory(collection.fs_resources_path)
|
|
except FileNotFoundError:
|
|
log.error(
|
|
f"Couldn't find resources to delete for {hl(collection.name, color=BLUE)}"
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/smart/{id}",
|
|
[Scope.COLLECTIONS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
async def delete_smart_collection(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="Smart collection internal id.", ge=1)],
|
|
) -> None:
|
|
"""Delete a smart collection by ID."""
|
|
smart_collection = db_collection_handler.get_smart_collection(id)
|
|
if not smart_collection:
|
|
raise CollectionNotFoundInDatabaseException(id)
|
|
|
|
if smart_collection.user_id != request.user.id:
|
|
raise CollectionPermissionError(id)
|
|
|
|
log.info(f"Deleting {hl(smart_collection.name, color=BLUE)} from database")
|
|
db_collection_handler.delete_smart_collection(id)
|
|
_record_collection(request, AuditAction.SMART_COLLECTION_DELETE, smart_collection)
|