Files
romm/backend/endpoints/platform.py
zurdi d9d65d8b56 refactor(audit): apply the pr-ready simplify pass
- record() takes the request as its actor, and a target can be a
  function: the lookups that name it now run inside the recorder's error
  handling, and for downloads only once the dedupe lets them record.
  That also restores the minimal visibility query on the file route.
- One changed_fields/change pair for rom, user, collection and platform
  edits, one collection helper, AuditActor.anonymous, a shared
  count_in_window and current_device_id, one test helper for recorded
  events and one fixture for audit events.
- The describers share simple/counted/visibility builders and the
  eventData readers with notifications, join lists per locale, and treat
  any *.delete as unlinked.
- EventLog builds one item list with the phase folded in, keeps each
  event's sentence across pages, formats days once, and loads users
  through the users store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:45:12 +02:00

217 lines
6.3 KiB
Python

from datetime import datetime
from typing import Annotated
from fastapi import Body
from fastapi import Path as PathVar
from fastapi import Query, Request, status
from decorators.auth import protected_route
from endpoints.responses.platform import PlatformSchema
from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException
from exceptions.fs_exceptions import PlatformAlreadyExistsException
from handler.audit_handler import AuditTarget, changed_fields, record
from handler.auth.constants import Scope
from handler.auth.dependencies import (
assert_can,
assert_platform_visible,
get_permissions,
)
from handler.database import db_platform_handler
from handler.filesystem import fs_platform_handler
from handler.scan_handler import scan_platform
from logger.formatter import BLUE
from logger.formatter import highlight as hl
from logger.logger import log
from models.audit_event import AuditAction
from models.permission import PermAction, PermEntity
from models.platform import (
CUSTOM_NAME_MAX_LENGTH,
DESCRIPTION_MAX_LENGTH,
)
from utils.platforms import get_filesystem_platforms, get_supported_platforms
from utils.router import APIRouter
router = APIRouter(
prefix="/platforms",
tags=["platforms"],
)
@protected_route(
router.post,
"",
[Scope.PLATFORMS_WRITE],
status_code=status.HTTP_201_CREATED,
)
async def add_platform(
request: Request,
fs_slug: Annotated[str, Body(description="Platform slug.", embed=True)],
) -> PlatformSchema:
"""Create a platform."""
try:
await fs_platform_handler.add_platform(fs_slug=fs_slug)
except PlatformAlreadyExistsException:
log.info(f"Detected platform: {hl(fs_slug)}")
scanned_platform = await scan_platform(fs_slug, [fs_slug])
platform = db_platform_handler.add_platform(scanned_platform)
record(
AuditAction.PLATFORM_CREATE,
request,
AuditTarget.of_platform(platform),
{"fs_slug": fs_slug},
)
return PlatformSchema.model_validate(platform)
@protected_route(router.get, "", [Scope.PLATFORMS_READ])
def get_platforms(
request: Request,
updated_after: Annotated[
datetime | None,
Query(
description="Filter platforms updated after this datetime (ISO 8601 format with timezone information)."
),
] = None,
) -> list[PlatformSchema]:
"""Retrieve platforms."""
perms = get_permissions(request)
return [
PlatformSchema.model_validate(p)
for p in db_platform_handler.get_platforms(
updated_after=updated_after,
hidden_platform_ids=perms.hidden_platform_ids,
)
]
@protected_route(router.get, "/identifiers", [Scope.PLATFORMS_READ])
def get_platform_identifiers(
request: Request,
) -> list[int]:
"""Retrieve platform identifiers."""
perms = get_permissions(request)
return db_platform_handler.get_platform_ids(
hidden_platform_ids=perms.hidden_platform_ids,
)
@protected_route(router.get, "/supported", [Scope.PLATFORMS_READ])
def get_supported_platforms_endpoint(request: Request) -> list[PlatformSchema]:
"""Retrieve the list of supported platforms."""
return get_supported_platforms()
@protected_route(router.get, "/filesystem", [Scope.PLATFORMS_READ])
async def get_filesystem_platforms_endpoint(request: Request) -> list[PlatformSchema]:
"""Retrieve platform folders on disk that have no database row yet."""
return await get_filesystem_platforms()
@protected_route(
router.get,
"/{id}",
[Scope.PLATFORMS_READ],
responses={status.HTTP_404_NOT_FOUND: {}},
)
def get_platform(
request: Request,
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
) -> PlatformSchema:
"""Retrieve a platform by ID."""
platform = db_platform_handler.get_platform(id)
if not platform:
raise PlatformNotFoundInDatabaseException(id)
assert_platform_visible(request, platform)
return PlatformSchema.model_validate(platform)
@protected_route(
router.put,
"/{id}",
[Scope.PLATFORMS_WRITE],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def update_platform(
request: Request,
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
custom_name: Annotated[
str | None,
Body(
embed=True,
max_length=CUSTOM_NAME_MAX_LENGTH,
description="Custom platform name.",
),
] = None,
description: Annotated[
str | None,
Body(
embed=True,
max_length=DESCRIPTION_MAX_LENGTH,
description="Custom platform description.",
),
] = None,
) -> PlatformSchema:
"""Update a platform."""
platform_db = db_platform_handler.get_platform(id)
if not platform_db:
raise PlatformNotFoundInDatabaseException(id)
assert_platform_visible(request, platform_db)
submitted = {"custom_name": custom_name, "description": description}
changed = changed_fields(
platform_db, {k: v for k, v in submitted.items() if v is not None}, submitted
)
if custom_name is not None:
platform_db.custom_name = custom_name
if description is not None:
platform_db.description = description
platform_db = db_platform_handler.add_platform(platform_db)
if changed:
record(
AuditAction.PLATFORM_EDIT,
request,
AuditTarget.of_platform(platform_db),
{"changed": changed},
)
return PlatformSchema.model_validate(platform_db)
@protected_route(
router.delete,
"/{id}",
[Scope.PLATFORMS_WRITE],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def delete_platform(
request: Request,
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
) -> None:
"""Delete a platform by ID."""
perms = get_permissions(request)
platform = db_platform_handler.get_platform(id)
if not platform:
raise PlatformNotFoundInDatabaseException(id)
assert_platform_visible(request, platform)
assert_can(perms, PermEntity.PLATFORMS, PermAction.DELETE)
log.info(
f"Deleting {hl(platform.name, color=BLUE)} [{hl(platform.fs_slug)}] from database"
)
db_platform_handler.delete_platform(id)
record(
AuditAction.PLATFORM_DELETE,
request,
AuditTarget.of_platform(platform),
{"fs_slug": platform.fs_slug},
)