mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* 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>
266 lines
8.3 KiB
Python
266 lines
8.3 KiB
Python
import uuid
|
|
from datetime import datetime, timezone
|
|
from typing import Annotated, Any
|
|
|
|
from fastapi import HTTPException, Request, Response, status
|
|
from pydantic import (
|
|
Field,
|
|
StrictBool,
|
|
StringConstraints,
|
|
model_validator,
|
|
)
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.base import BaseModel
|
|
from endpoints.responses.device import DeviceCreateResponse, DeviceSchema
|
|
from handler.auth.constants import Scope
|
|
from handler.database import (
|
|
db_client_token_handler,
|
|
db_device_handler,
|
|
db_device_save_sync_handler,
|
|
)
|
|
from handler.device_install import device_install_handler
|
|
from handler.filesystem import get_fs_sync_handler
|
|
from handler.socket_handler import close_client_token_sockets
|
|
from logger.logger import log
|
|
from models.audit_event import AuditAction
|
|
from models.device import Device, SyncMode
|
|
from utils.auth import require_device, token_reaches_device
|
|
from utils.client_tokens import record_token_event
|
|
from utils.router import APIRouter
|
|
|
|
from .install import router as install_router
|
|
|
|
router = APIRouter(
|
|
prefix="/devices",
|
|
tags=["devices"],
|
|
)
|
|
|
|
router.include_router(install_router)
|
|
|
|
# Flags a device reports about itself, such as {"remote_install": true}.
|
|
DeviceCapabilities = Annotated[
|
|
dict[Annotated[str, StringConstraints(min_length=1, max_length=64)], StrictBool],
|
|
Field(max_length=32),
|
|
]
|
|
|
|
|
|
class DeviceCreatePayload(BaseModel):
|
|
name: str | None = None
|
|
platform: str | None = None
|
|
client: str | None = None
|
|
client_version: str | None = None
|
|
ip_address: str | None = None
|
|
mac_address: str | None = None
|
|
hostname: str | None = None
|
|
sync_mode: SyncMode | None = None
|
|
sync_config: dict[str, Any] | None = None
|
|
capabilities: DeviceCapabilities | None = None
|
|
allow_existing: bool = True
|
|
allow_duplicate: bool = False
|
|
reset_syncs: bool = False
|
|
|
|
@model_validator(mode="after")
|
|
def _duplicate_disables_existing(self) -> "DeviceCreatePayload":
|
|
if self.allow_duplicate:
|
|
self.allow_existing = False
|
|
return self
|
|
|
|
|
|
class DeviceUpdatePayload(BaseModel):
|
|
name: str | None = None
|
|
platform: str | None = None
|
|
client: str | None = None
|
|
client_version: str | None = None
|
|
ip_address: str | None = None
|
|
mac_address: str | None = None
|
|
hostname: str | None = None
|
|
sync_enabled: bool | None = None
|
|
sync_mode: SyncMode | None = None
|
|
sync_config: dict[str, Any] | None = None
|
|
capabilities: DeviceCapabilities | None = None
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"",
|
|
[Scope.DEVICES_WRITE],
|
|
responses={
|
|
status.HTTP_409_CONFLICT: {
|
|
"description": (
|
|
"The caller already has a device with the same MAC address,"
|
|
" hostname and platform, and neither `allow_existing` nor"
|
|
" `allow_duplicate` is set."
|
|
)
|
|
}
|
|
},
|
|
)
|
|
def register_device(
|
|
request: Request,
|
|
response: Response,
|
|
payload: DeviceCreatePayload,
|
|
) -> DeviceCreateResponse:
|
|
"""Register a device and return its ID."""
|
|
existing_device = None
|
|
if not payload.allow_duplicate:
|
|
existing_device = db_device_handler.get_device_by_fingerprint(
|
|
user_id=request.user.id,
|
|
mac_address=payload.mac_address,
|
|
hostname=payload.hostname,
|
|
platform=payload.platform,
|
|
)
|
|
if existing_device and not token_reaches_device(request, existing_device.id):
|
|
existing_device = None
|
|
|
|
if existing_device:
|
|
if not payload.allow_existing:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail={
|
|
"error": "device_exists",
|
|
"message": "A device with this fingerprint already exists",
|
|
"device_id": existing_device.id,
|
|
},
|
|
)
|
|
|
|
if payload.reset_syncs:
|
|
db_device_save_sync_handler.delete_syncs_for_device(
|
|
device_id=existing_device.id
|
|
)
|
|
|
|
db_device_handler.update_last_seen(
|
|
device_id=existing_device.id, user_id=request.user.id
|
|
)
|
|
if payload.capabilities is not None:
|
|
db_device_handler.update_device(
|
|
device_id=existing_device.id,
|
|
user_id=request.user.id,
|
|
data={"capabilities": payload.capabilities},
|
|
)
|
|
log.info(
|
|
f"Returned existing device {existing_device.id} for user {request.user.username}"
|
|
)
|
|
|
|
response.status_code = status.HTTP_200_OK
|
|
return DeviceCreateResponse(
|
|
device_id=existing_device.id,
|
|
name=existing_device.name,
|
|
created_at=existing_device.created_at,
|
|
)
|
|
|
|
response.status_code = status.HTTP_201_CREATED
|
|
device_id = str(uuid.uuid4())
|
|
now = datetime.now(timezone.utc)
|
|
|
|
device = Device(
|
|
id=device_id,
|
|
user_id=request.user.id,
|
|
name=payload.name,
|
|
platform=payload.platform,
|
|
client=payload.client,
|
|
client_version=payload.client_version,
|
|
ip_address=payload.ip_address,
|
|
mac_address=payload.mac_address,
|
|
hostname=payload.hostname,
|
|
sync_mode=payload.sync_mode,
|
|
sync_config=payload.sync_config,
|
|
capabilities=payload.capabilities,
|
|
last_seen=now,
|
|
)
|
|
|
|
db_device = db_device_handler.add_device(device)
|
|
log.info(f"Registered device {device_id} for user {request.user.username}")
|
|
|
|
# Auto-create sync folders for file_transfer devices
|
|
if payload.sync_mode == SyncMode.FILE_TRANSFER:
|
|
try:
|
|
get_fs_sync_handler().ensure_device_directories(device_id)
|
|
except Exception:
|
|
log.warning(f"Failed to create sync directories for device {device_id}")
|
|
|
|
return DeviceCreateResponse(
|
|
device_id=db_device.id,
|
|
name=db_device.name,
|
|
created_at=db_device.created_at,
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.DEVICES_READ])
|
|
def get_devices(request: Request) -> list[DeviceSchema]:
|
|
"""List the caller's devices that the client token has access to."""
|
|
devices = db_device_handler.get_devices(user_id=request.user.id)
|
|
return [
|
|
DeviceSchema.model_validate(device)
|
|
for device in devices
|
|
if token_reaches_device(request, device.id)
|
|
]
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{device_id}",
|
|
[Scope.DEVICES_READ],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The caller has no device with this ID that it can see."
|
|
}
|
|
},
|
|
)
|
|
def get_device(request: Request, device_id: str) -> DeviceSchema:
|
|
"""Get one of the caller's devices."""
|
|
device = require_device(request, device_id)
|
|
return DeviceSchema.model_validate(device)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{device_id}",
|
|
[Scope.DEVICES_WRITE],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The caller has no device with this ID that it can see."
|
|
}
|
|
},
|
|
)
|
|
def update_device(
|
|
request: Request,
|
|
device_id: str,
|
|
payload: DeviceUpdatePayload,
|
|
) -> DeviceSchema:
|
|
"""Update a device. Fields left out of the request keep their current values."""
|
|
device: Device | None = require_device(request, device_id)
|
|
|
|
update_data = payload.model_dump(exclude_unset=True)
|
|
if update_data:
|
|
device = db_device_handler.update_device(
|
|
device_id=device_id,
|
|
user_id=request.user.id,
|
|
data=update_data,
|
|
)
|
|
|
|
return DeviceSchema.model_validate(device)
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/{device_id}",
|
|
[Scope.DEVICES_WRITE],
|
|
status_code=status.HTTP_204_NO_CONTENT,
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The caller has no device with this ID that it can see."
|
|
}
|
|
},
|
|
)
|
|
async def delete_device(request: Request, device_id: str) -> None:
|
|
"""Delete a device and the client tokens bound to it."""
|
|
require_device(request, device_id)
|
|
|
|
tokens = db_client_token_handler.get_tokens_by_device(device_id)
|
|
db_device_handler.delete_device(device_id=device_id, user_id=request.user.id)
|
|
log.info(f"Deleted device {device_id} for user {request.user.username}")
|
|
for token in tokens:
|
|
record_token_event(request, AuditAction.CLIENT_TOKEN_REVOKE, token)
|
|
await close_client_token_sockets([token.id for token in tokens])
|
|
await device_install_handler.discard_for_device(device_id)
|