mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 02:24:09 +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>
215 lines
7.1 KiB
Python
215 lines
7.1 KiB
Python
from typing import Annotated
|
|
|
|
from fastapi import Body, File, HTTPException
|
|
from fastapi import Path as PathVar
|
|
from fastapi import Request, UploadFile, status
|
|
from fastapi.responses import FileResponse, Response
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.assets import ScreenshotSchema
|
|
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import assert_rom_visible
|
|
from handler.database import db_rom_handler, db_screenshot_handler
|
|
from handler.filesystem import fs_asset_handler
|
|
from handler.filesystem.assets_handler import build_asset_file_response
|
|
from handler.scan_handler import scan_screenshot
|
|
from logger.formatter import BLUE
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from utils.media_types import (
|
|
SCREENSHOT_UPLOAD_EXTENSIONS,
|
|
is_allowed_screenshot_upload,
|
|
)
|
|
from utils.router import APIRouter
|
|
from utils.uploads import check_asset_upload_size, sanitize_asset_filename
|
|
|
|
router = APIRouter(
|
|
prefix="/screenshots",
|
|
tags=["screenshots"],
|
|
)
|
|
|
|
SCREENSHOT_FILE_UPLOAD = File(..., description="Screenshot file to upload.")
|
|
|
|
|
|
@protected_route(router.post, "", [Scope.ASSETS_WRITE])
|
|
async def add_screenshot(
|
|
request: Request,
|
|
rom_id: int,
|
|
screenshotFile: UploadFile = SCREENSHOT_FILE_UPLOAD,
|
|
) -> ScreenshotSchema:
|
|
"""Upload a per-user gallery screenshot for a ROM.
|
|
|
|
Stored under the user's asset folder (not the ROM folder) and flagged
|
|
`is_gallery=True` so it surfaces in the gallery; `is_public=False` so it
|
|
stays private until the owner shares it.
|
|
"""
|
|
check_asset_upload_size(screenshotFile, "Screenshot file")
|
|
|
|
rom = db_rom_handler.get_rom(id=rom_id)
|
|
if not rom:
|
|
raise RomNotFoundInDatabaseException(rom_id)
|
|
|
|
assert_rom_visible(request, rom)
|
|
|
|
current_user = request.user
|
|
log.info(f"Uploading screenshot to {hl(str(rom.name), color=BLUE)}")
|
|
|
|
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
|
user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id
|
|
)
|
|
|
|
if not screenshotFile.filename:
|
|
log.error("Screenshot file has no filename")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Screenshot file has no filename",
|
|
)
|
|
|
|
sanitized_screenshot_filename = sanitize_asset_filename(
|
|
screenshotFile.filename, "screenshot"
|
|
)
|
|
|
|
if not is_allowed_screenshot_upload(sanitized_screenshot_filename):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=(
|
|
f"Unsupported image file type. Allowed: "
|
|
f"{', '.join(sorted(SCREENSHOT_UPLOAD_EXTENSIONS))}"
|
|
),
|
|
)
|
|
|
|
await fs_asset_handler.write_file(
|
|
file=screenshotFile,
|
|
path=screenshots_path,
|
|
filename=sanitized_screenshot_filename,
|
|
)
|
|
|
|
# Scan or update screenshot
|
|
scanned_screenshot = await scan_screenshot(
|
|
file_name=sanitized_screenshot_filename,
|
|
user=request.user,
|
|
platform_fs_slug=rom.platform_slug,
|
|
rom_id=rom.id,
|
|
)
|
|
db_screenshot = db_screenshot_handler.get_screenshot(
|
|
file_name=sanitized_screenshot_filename,
|
|
rom_id=rom.id,
|
|
user_id=current_user.id,
|
|
)
|
|
if db_screenshot:
|
|
db_screenshot = db_screenshot_handler.update_screenshot(
|
|
db_screenshot.id,
|
|
{
|
|
"file_size_bytes": scanned_screenshot.file_size_bytes,
|
|
"is_gallery": True,
|
|
"missing_from_fs": False,
|
|
},
|
|
)
|
|
else:
|
|
scanned_screenshot.rom_id = rom.id
|
|
scanned_screenshot.user_id = current_user.id
|
|
scanned_screenshot.is_gallery = True
|
|
db_screenshot = db_screenshot_handler.add_screenshot(
|
|
screenshot=scanned_screenshot
|
|
)
|
|
|
|
return ScreenshotSchema.model_validate(db_screenshot)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{id}/content",
|
|
[Scope.ASSETS_READ],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def download_screenshot(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="Screenshot internal id.", ge=1)],
|
|
) -> FileResponse:
|
|
"""Download a screenshot file. Owner can download any of their screenshots;
|
|
everyone else only public ones."""
|
|
screenshot = db_screenshot_handler.get_screenshot_by_id(id)
|
|
if not screenshot or (
|
|
screenshot.user_id != request.user.id and not screenshot.is_public
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Screenshot not found",
|
|
)
|
|
|
|
# Sharing must not override the hidden-ROM/platform policy: a screenshot on a
|
|
# ROM hidden from the caller stays 404-masked, just like the ROM itself.
|
|
assert_rom_visible(request, screenshot.rom, not_found_detail="Screenshot not found")
|
|
|
|
try:
|
|
file_path = fs_asset_handler.validate_path(screenshot.full_path)
|
|
except ValueError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Screenshot not found",
|
|
) from None
|
|
|
|
if not file_path.exists() or not file_path.is_file():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Screenshot file not found on disk",
|
|
)
|
|
|
|
return build_asset_file_response(file_path, filename=screenshot.file_name)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
async def update_screenshot(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="Screenshot internal id.", ge=1)],
|
|
is_public: Annotated[bool, Body(embed=True)],
|
|
) -> ScreenshotSchema:
|
|
"""Toggle a gallery screenshot's public/private visibility (owner only)."""
|
|
screenshot = db_screenshot_handler.get_screenshot_by_id(id)
|
|
if not screenshot or screenshot.user_id != request.user.id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Screenshot not found",
|
|
)
|
|
|
|
updated = db_screenshot_handler.update_screenshot(id, {"is_public": is_public})
|
|
return ScreenshotSchema.model_validate(updated)
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/{id}",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
async def delete_screenshot(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="Screenshot internal id.", ge=1)],
|
|
) -> Response:
|
|
"""Delete a gallery screenshot — its file and DB row (owner only)."""
|
|
screenshot = db_screenshot_handler.get_screenshot_by_id(id)
|
|
if not screenshot or screenshot.user_id != request.user.id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Screenshot not found",
|
|
)
|
|
|
|
try:
|
|
await fs_asset_handler.remove_file(file_path=screenshot.full_path)
|
|
except FileNotFoundError:
|
|
log.warning(
|
|
f"Screenshot file {hl(screenshot.full_path)} not found on disk; "
|
|
f"removing DB row anyway"
|
|
)
|
|
|
|
db_screenshot_handler.delete_screenshot(screenshot.id)
|
|
log.info(f"Deleted screenshot {hl(screenshot.file_name)}")
|
|
|
|
return Response()
|