Files
romm/backend/endpoints/activity.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

131 lines
4.4 KiB
Python

from fastapi import HTTPException, Query, Request, status
from pydantic import Field
from decorators.auth import protected_route
from endpoints.responses.activity import ActivityEntrySchema
from endpoints.responses.base import BaseModel
from handler.activity_handler import ActivityEntry, activity_handler
from handler.auth.constants import Scope
from handler.auth.dependencies import get_permissions
from handler.database import db_device_handler, db_rom_handler
from utils.auth import require_device, require_token_device
from utils.router import APIRouter, RomIdPath
router = APIRouter(
prefix="/activity",
tags=["activity"],
)
def _visible_activity(
request: Request, entries: list[ActivityEntry]
) -> list[ActivityEntrySchema]:
"""Drop sessions whose ROM is hidden from the caller (platform or rom hide)."""
visibility = get_permissions(request).rom_visibility
if not visibility.is_unrestricted:
hidden = db_rom_handler.get_hidden_rom_ids_among(
[e["rom_id"] for e in entries], visibility
)
entries = [e for e in entries if e["rom_id"] not in hidden]
return [ActivityEntrySchema(**e) for e in entries]
def _is_hidden(request: Request, rom_id: int) -> bool:
"""Whether the caller's visibility rules hide the ROM."""
visibility = get_permissions(request).rom_visibility
if visibility.is_unrestricted:
return False
return rom_id in db_rom_handler.get_hidden_rom_ids_among([rom_id], visibility)
class DeviceHeartbeatPayload(BaseModel):
rom_id: int = Field(ge=1)
device_id: str = Field(min_length=1, max_length=255)
@protected_route(router.get, "", [Scope.ROMS_USER_READ])
async def get_all_activity(request: Request) -> list[ActivityEntrySchema]:
"""Return every currently active play session across all users."""
entries = await activity_handler.get_all_active()
return _visible_activity(request, entries)
@protected_route(router.get, "/rom/{rom_id}", [Scope.ROMS_USER_READ])
async def get_rom_activity(
request: Request,
rom_id: RomIdPath,
) -> list[ActivityEntrySchema]:
"""Return all active play sessions for a specific ROM."""
entries = await activity_handler.get_active_for_rom(rom_id)
return _visible_activity(request, entries)
@protected_route(
router.post,
"/heartbeat",
[Scope.ROMS_USER_WRITE],
responses={
status.HTTP_404_NOT_FOUND: {
"description": (
"The caller has no device with this ID that it can see, or no rom"
" the caller can see has this ID."
)
}
},
)
async def device_heartbeat(
request: Request, payload: DeviceHeartbeatPayload
) -> ActivityEntrySchema:
"""Heartbeat endpoint for external devices (muOS, Android, etc.).
Called periodically by devices while the user is playing a game. Writes
activity state to Redis and sends an ``activity:update`` event to the
users who can see the ROM.
"""
device = require_device(request, payload.device_id)
# build_entry does the ROM lookup; None back from it is a missing ROM, and a
# hidden one answers the same 404.
entry = None
if not _is_hidden(request, payload.rom_id):
entry = await activity_handler.build_entry(
user_id=request.user.id,
device_id=device.id,
rom_id=payload.rom_id,
preserve_started_at=True,
device_type=device.client or "unknown",
)
if entry is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"ROM {payload.rom_id} not found",
)
await activity_handler.publish_active(entry)
# Update the device last_seen as a side-effect (mirrors play session ingest).
db_device_handler.update_last_seen(device_id=device.id, user_id=request.user.id)
return ActivityEntrySchema(**entry)
@protected_route(
router.delete,
"/heartbeat",
[Scope.ROMS_USER_WRITE],
status_code=status.HTTP_204_NO_CONTENT,
responses={
status.HTTP_404_NOT_FOUND: {
"description": "The caller uses a token bound to a different device."
}
},
)
async def clear_device_activity(
request: Request,
device_id: str = Query(),
) -> None:
"""Immediately clear an active session for a device (e.g. on graceful exit)."""
require_token_device(request, device_id)
await activity_handler.publish_clear(request.user.id, device_id)
return None