mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* test(api): check that routes document the error statuses they raise protected_route now documents the scope guard's 401 and 403 on every route that declares scopes, appending to a route's own description when it has one. tools/route_errors.py follows each route's calls through imports, handler instances, custom exception classes and HTTPException subclasses to the statuses it can raise. test_raised_statuses_are_documented fails on a status the route's responses= leaves out, against a baseline of existing gaps that can only shrink. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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> * fix(api): answer like a missing resource for hidden play sessions and private collections DELETE /play-sessions/{id} deleted the caller's session even on a rom hidden from them, so 204 versus 404 showed the session existed. The handler now takes the caller's rom visibility. Another user's private collection, smart collection or playlist answered 403, which showed it existed. It now answers 404 on every route; a public one the caller does not own still answers 403 on write. 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(collections): use #5693's docstrings on the routes this PR touches 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> * test(api): follow route dependencies in the status analyzer Addresses Greptile's review: route_errors now follows the callable in Depends(...) and Security(...), whether it is a parameter default or inside an Annotated alias, and the module docstring is one line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): tighten wording of route error descriptions Give clipped responses descriptions and helper docstrings their missing subjects and verbs, use 'the caller lacks' and 'is not allowed to' consistently, and replace 'picked' with 'chosen'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(api): drop the route error baseline Every status left in the baseline was one a client cannot get: - The export routes' empty platform list check is dead, since FastAPI answers a missing required list query with 422. Removed. - get_save_layouts went through _restore_error, whose 500 fallback it cannot reach. It raises its 400 and 503 directly now. - The notification test and confirm routes only catch ChannelError, since the cooldown and email errors come from other actions. - The analyzer now skips asyncio.gather(..., return_exceptions=True), which covers search_rom. - A '# route-errors: ignore' marker, with its reason, skips code whose errors never reach the client: the metadata heartbeat probe, the force-release teardowns, and the legacy save adoption. The check now fails on any undocumented status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
157 lines
5.2 KiB
Python
157 lines
5.2 KiB
Python
from typing import Annotated, List
|
|
|
|
from fastapi import HTTPException, Query, Request, status
|
|
from fastapi.responses import Response
|
|
|
|
from decorators.auth import protected_route
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import visible_platform_or_404
|
|
from handler.database import db_platform_handler
|
|
from logger.formatter import BLUE
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from utils.gamelist_exporter import GamelistExporter
|
|
from utils.pegasus_exporter import PegasusExporter
|
|
from utils.router import APIRouter
|
|
|
|
router = APIRouter(
|
|
prefix="/export",
|
|
tags=["export"],
|
|
)
|
|
|
|
|
|
def _assert_platforms_exportable(request: Request, platform_ids: List[int]) -> None:
|
|
"""Reject the whole request before anything is written to disk.
|
|
|
|
A platform hidden from the caller 404s exactly like a missing one, so the
|
|
response never reveals that the platform exists.
|
|
"""
|
|
for platform_id in platform_ids:
|
|
visible_platform_or_404(
|
|
request, db_platform_handler.get_platform(platform_id), platform_id
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/gamelist-xml",
|
|
[Scope.PLATFORMS_WRITE],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "No platform the caller can see has one of these IDs."
|
|
},
|
|
status.HTTP_500_INTERNAL_SERVER_ERROR: {
|
|
"description": "The export failed, or no file could be written."
|
|
},
|
|
},
|
|
)
|
|
async def export_gamelist_xml(
|
|
request: Request,
|
|
platform_ids: Annotated[
|
|
List[int], Query(description="List of platform IDs to export")
|
|
],
|
|
local_export: Annotated[
|
|
bool, Query(description="Use local paths instead of URLs")
|
|
] = False,
|
|
) -> Response:
|
|
"""Export platforms/ROMs to gamelist.xml format and write to platform directories"""
|
|
_assert_platforms_exportable(request, platform_ids)
|
|
|
|
try:
|
|
exporter = GamelistExporter(local_export=local_export)
|
|
files_written = []
|
|
|
|
for platform_id in platform_ids:
|
|
success = await exporter.export_platform_to_file(
|
|
platform_id,
|
|
request,
|
|
)
|
|
if success:
|
|
files_written.append(f"gamelist_{platform_id}.xml")
|
|
else:
|
|
log.warning(f"Failed to write gamelist for platform {platform_id}")
|
|
|
|
if not files_written:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Failed to write any gamelist files",
|
|
)
|
|
|
|
log.info(
|
|
f"Exported gamelist for {hl(str(len(files_written)), color=BLUE)} platform(s):"
|
|
)
|
|
for file in files_written:
|
|
log.info(f"\t• {file}")
|
|
return Response(status_code=status.HTTP_200_OK)
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) from e
|
|
except Exception as e:
|
|
log.error(f"Failed to export gamelist: {e}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Failed to export gamelist",
|
|
) from e
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/pegasus",
|
|
[Scope.PLATFORMS_WRITE],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "No platform the caller can see has one of these IDs."
|
|
},
|
|
status.HTTP_500_INTERNAL_SERVER_ERROR: {
|
|
"description": "The export failed, or no file could be written."
|
|
},
|
|
},
|
|
)
|
|
async def export_pegasus(
|
|
request: Request,
|
|
platform_ids: Annotated[
|
|
List[int], Query(description="List of platform IDs to export")
|
|
],
|
|
local_export: Annotated[
|
|
bool, Query(description="Use local paths instead of URLs")
|
|
] = False,
|
|
) -> Response:
|
|
"""Export platforms/ROMs to Pegasus metadata.pegasus.txt format and write to platform directories"""
|
|
_assert_platforms_exportable(request, platform_ids)
|
|
|
|
try:
|
|
exporter = PegasusExporter(local_export=local_export)
|
|
files_written = []
|
|
|
|
for platform_id in platform_ids:
|
|
success = await exporter.export_platform_to_file(
|
|
platform_id,
|
|
request,
|
|
)
|
|
if success:
|
|
files_written.append(f"metadata_pegasus_{platform_id}.txt")
|
|
else:
|
|
log.warning(
|
|
f"Failed to write Pegasus metadata for platform {platform_id}"
|
|
)
|
|
|
|
if not files_written:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Failed to write any Pegasus metadata files",
|
|
)
|
|
|
|
log.info(
|
|
f"Exported Pegasus metadata for {hl(str(len(files_written)), color=BLUE)} platform(s):"
|
|
)
|
|
for file in files_written:
|
|
log.info(f"\t• {file}")
|
|
return Response(status_code=status.HTTP_200_OK)
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) from e
|
|
except Exception as e:
|
|
log.error(f"Failed to export Pegasus metadata: {e}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Failed to export Pegasus metadata",
|
|
) from e
|