Files
romm/backend/endpoints/screenshots.py
Georges-Antoine Assi 4159710e79 docs(api): document the error responses routes raise (#5693)
* docs(api): document error responses for roms routes

Describe every 4xx and 5xx the rom routes and their helpers raise in each
decorator's responses=, so the OpenAPI schema lists them. A hidden rom,
platform or file is described like a missing one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for saves routes

Describe every 4xx/5xx the saves, states, screenshots, snapshots,
play-sessions and sync routes raise in their responses=, and rewrite the
states identifiers docstring that carried Args/Returns blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for devices routes

Describe the 4xx/5xx statuses that the device, device auth, install,
client token, notification, notification channel, sync channel and
heartbeat routes raise, and fill the empty install route entries.
Rewrite the setup and heartbeat docstrings that published Args and
Returns blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for streaming routes

Describe the 4xx and 5xx statuses the streaming, memory card and netplay routes raise in their responses= declarations, and replace the Args: blocks in route docstrings that FastAPI published verbatim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for admin routes

Describe the 4xx and 5xx statuses the config, permissions, user, auth,
tasks, logs, activity and export routes raise, and rewrite their
Args/Returns docstrings as plain operation descriptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for library routes

Describe the 400/403/404/409/500 statuses the collection, feed, firmware,
platform, music, playlist and search routes raise, and replace route
docstrings that carried Args/Returns blocks with plain sentences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): describe private collections and playlists as missing

Matches #5686, where another user's private collection or playlist
answers 404 and a play session on a hidden rom answers like a missing
one. The read routes drop their 403, and the write 403 now covers only
a public resource another user owns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): address Greptile review on route error docs

Fold the nine multi-paragraph route docstrings into one line, and keep
the device-scope 403 descriptions in utils/auth.py next to
resolve_device, which raises them, instead of in both saves.py and
states.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): plain-prose pass on route error descriptions

Spell out clipped error descriptions, replace internal slang (picked,
taken, live, moved past), name the parameter an ID comes from, and split
the long save conversion 400s into sentences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:11:20 -05:00

244 lines
7.7 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 handler.auth.constants import Scope
from handler.auth.dependencies import (
assert_rom_visible,
owned_rom_asset_or_404,
visible_rom_or_404,
)
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, RomIdQuery
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],
responses={
status.HTTP_400_BAD_REQUEST: {
"description": (
"The screenshot file has no name, its name is not valid, or it is"
" not a supported image type."
)
},
status.HTTP_404_NOT_FOUND: {
"description": "No rom the caller can see has this ID."
},
status.HTTP_413_CONTENT_TOO_LARGE: {
"description": "The screenshot is larger than the server allows."
},
},
)
async def add_screenshot(
request: Request,
rom_id: RomIdQuery,
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 = visible_rom_or_404(request, db_rom_handler.get_rom(id=rom_id), rom_id)
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: {
"description": (
"No screenshot the caller can read has this ID, or the screenshot's"
" file is missing."
)
}
},
)
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: {
"description": "The caller has no screenshot with this ID that it can see."
}
},
)
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)."""
owned_rom_asset_or_404(
request, db_screenshot_handler.get_screenshot_by_id(id), "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: {
"description": "The caller has no screenshot with this ID that it can see."
}
},
)
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 = owned_rom_asset_or_404(
request, db_screenshot_handler.get_screenshot_by_id(id), "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()