Files
romm/backend/endpoints/channels.py
Georges-Antoine Assi 3b14dddd88 chore(prose): fix the prose-check findings on master (#5826)
The scheduled Trunk Check (all files) run fails on 79 prose-check issues
that predate the linter: clipped 'X, else Y' chains, 'internal id' in
API descriptions, and clipped 'Left out, ...' conditionals.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 08:17:01 -05:00

269 lines
8.7 KiB
Python

import uuid
from typing import Annotated
from fastapi import HTTPException, Query, Request, status
from pydantic import Field
from decorators.auth import protected_route
from endpoints.responses.base import BaseModel
from endpoints.responses.snapshots import (
ChannelSchema,
build_channel_schema,
build_channel_schemas,
)
from endpoints.snapshots import (
FEED_DEVICE_DESCRIPTION,
channels_on_files,
readable_channel_or_404,
request_device,
required_device,
visible_rom_file,
)
from handler.auth.constants import Scope
from handler.database import db_snapshot_handler
from handler.snapshots import retention
from handler.snapshots.file_key import FileKey
from models.channel import CHANNEL_LABEL_MAX_LENGTH, Channel
from utils.router import APIRouter
router = APIRouter(prefix="/channels", tags=["channels"])
Label = Annotated[str, Field(min_length=1, max_length=CHANNEL_LABEL_MAX_LENGTH)]
class ChannelCreatePayload(BaseModel):
rom_file_id: int
label: Label
# A client may mint the id itself, so a channel it made offline keeps it.
id: uuid.UUID | None = None
class ChannelUpdatePayload(BaseModel):
label: Label | None = None
is_public: bool | None = None
class ChannelAttachPayload(BaseModel):
rom_file_id: int
@protected_route(
router.get,
"",
[Scope.ASSETS_READ],
responses={
status.HTTP_403_FORBIDDEN: {
"description": (
"The `device_id` is not the client token's device, and the caller"
" lacks the `devices.write` scope."
)
},
status.HTTP_404_NOT_FOUND: {
"description": (
"No rom file the caller can see has the ID in `rom_file_id`, no"
" channel the caller can read has the ID in `channel_id`, or the caller"
" has no device with the ID in `device_id`."
)
},
},
)
def get_channels(
request: Request,
rom_file_id: Annotated[
list[int] | None,
Query(
description=(
"The ID of a rom file whose channels to list. Repeat the"
" parameter for several files. A file that is unknown or hidden"
" returns 404."
)
),
] = None,
channel_id: Annotated[
list[uuid.UUID] | None,
Query(
description=(
"The ID of a channel to include. Repeat the parameter for"
" several channels. A channel you cannot read returns 404."
)
),
] = None,
detached_platform_id: Annotated[
int | None,
Query(description="Your channels on this platform whose ROM was removed."),
] = None,
device_id: Annotated[str | None, Query(description=FEED_DEVICE_DESCRIPTION)] = None,
) -> list[ChannelSchema]:
"""List your channels on the named files, empty ones included, plus public channels named by id, each with its current snapshot or null."""
viewer = request.user
device = request_device(request, device_id)
channels: dict[uuid.UUID, Channel] = {}
fed = channels_on_files(request, rom_file_id or [], channel_id or [])
if detached_platform_id is not None:
for channel in db_snapshot_handler.get_detached_channels(
viewer.id, detached_platform_id
):
channels[channel.id] = channel
channels.update(fed)
if device is not None:
db_snapshot_handler.record_device_seen(
device.id, {c.id: c.current_snapshot_id for c in fed.values()}
)
return build_channel_schemas(list(channels.values()), viewer)
@protected_route(
router.post,
"",
[Scope.ASSETS_WRITE],
status_code=status.HTTP_201_CREATED,
responses={
status.HTTP_404_NOT_FOUND: {
"description": "No rom file the caller can see has the ID in `rom_file_id`."
},
status.HTTP_409_CONFLICT: {
"description": "A channel with the requested `id` already exists."
},
},
)
def create_channel(request: Request, payload: ChannelCreatePayload) -> ChannelSchema:
"""Create an empty channel on a ROM file. A device's first push into an
unknown channel id creates it too; creating it first is recommended."""
viewer = request.user
rom_file, rom = visible_rom_file(request, payload.rom_file_id)
if payload.id is not None and db_snapshot_handler.get_channel(payload.id):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail="That channel id is taken"
)
channel = FileKey.of_file(rom_file).new_channel(
viewer.id, rom.id, rom.platform_id, payload.label, id=payload.id
)
return build_channel_schema(db_snapshot_handler.add_channel(channel), viewer)
@protected_route(
router.patch,
"/{id}",
[Scope.ASSETS_WRITE],
responses={
status.HTTP_404_NOT_FOUND: {
"description": "No channel the caller owns and can see has this ID."
}
},
)
def update_channel(
request: Request,
id: uuid.UUID,
payload: ChannelUpdatePayload,
) -> ChannelSchema:
"""Rename a channel or open it to every user. Owner only."""
channel = readable_channel_or_404(request, id, owner_only=True)
changes = payload.model_dump(exclude_none=True)
if changes:
channel = db_snapshot_handler.update_channel(channel.id, changes)
return build_channel_schema(channel, request.user)
@protected_route(
router.post,
"/{id}/attach",
[Scope.ASSETS_WRITE],
responses={
status.HTTP_404_NOT_FOUND: {
"description": (
"No channel the caller owns and can see has this ID, or no rom"
" file the caller can see has the ID in `rom_file_id`."
)
},
status.HTTP_409_CONFLICT: {
"description": "The channel is already attached to a rom."
},
},
)
def attach_channel(
request: Request,
id: uuid.UUID,
payload: ChannelAttachPayload,
) -> ChannelSchema:
"""Attach a channel whose ROM was removed to a file of the same platform.
Owner only."""
channel = readable_channel_or_404(request, id, owner_only=True)
if channel.rom_id is not None:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="The channel is already attached to a ROM",
)
rom_file, rom = visible_rom_file(request, payload.rom_file_id)
if rom.platform_id != channel.platform_id:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="The file is on another platform than the channel",
)
attached = db_snapshot_handler.attach_channel(channel.id, rom_file)
return build_channel_schema(attached, request.user)
@protected_route(
router.delete,
"/{id}/held",
[Scope.ASSETS_READ],
status_code=status.HTTP_204_NO_CONTENT,
responses={
status.HTTP_400_BAD_REQUEST: {
"description": (
"The request has no `device_id`, and the client token is not bound"
" to a device."
)
},
status.HTTP_403_FORBIDDEN: {
"description": (
"The `device_id` is not the client token's device, and the caller"
" lacks the `devices.write` scope."
)
},
status.HTTP_404_NOT_FOUND: {
"description": (
"No channel the caller can read has this ID, or the caller has no"
" device with the ID in `device_id`."
)
},
},
)
def clear_held(
request: Request,
id: uuid.UUID,
device_id: Annotated[
str | None,
Query(
description="The device to clear, which requires `devices.write`. Defaults to the client token's device."
),
] = None,
) -> None:
"""Forget what the device holds in the channel and the current it knows,
so its next push without `expected_current_id` expects its parent."""
device = required_device(request, device_id)
channel = readable_channel_or_404(request, id)
db_snapshot_handler.clear_device_sync(device.id, channel.id)
@protected_route(
router.delete,
"/{id}",
[Scope.ASSETS_WRITE],
status_code=status.HTTP_204_NO_CONTENT,
responses={
status.HTTP_404_NOT_FOUND: {
"description": "No channel the caller owns and can see has this ID."
}
},
)
async def delete_channel(
request: Request,
id: uuid.UUID,
) -> None:
"""Delete a channel. Its current and pinned snapshots stay as archival backups,
except on a detached channel, whose ROM is gone, which keeps nothing."""
channel = readable_channel_or_404(request, id, owner_only=True)
released = db_snapshot_handler.delete_channel(channel.id)
await retention.discard_content(released)