from typing import Annotated from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, status from fastapi.responses import JSONResponse from app.api.deps import CurrentUser, DbSession from app.models import Clip from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate from app.services import clips as clip_service from app.ws.hub import hub router = APIRouter(prefix="/clips", tags=["clips"]) # Fields that may be null on purpose (clearing them); all others are ignored when null _NULLABLE_FIELDS = {"title", "language"} def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None: """Tell all devices of the user about a change, after the response is sent.""" background.add_task(hub.broadcast, user_id, {"type": event, "data": data}) def _clip_data(clip: Clip) -> dict: return ClipOut.model_validate(clip).model_dump(mode="json") def _get_own_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip: # Foreign and missing clips look the same, so ids of other users are not revealed clip = clip_service.get_clip(db, user.id, clip_id) if clip is None: raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.") return clip @router.get("", response_model=ClipList) def list_clips( user: CurrentUser, db: DbSession, limit: Annotated[int, Query(ge=1, le=100)] = 50, offset: Annotated[int, Query(ge=0)] = 0, ) -> ClipList: items, total = clip_service.list_clips(db, user.id, limit, offset) return ClipList(items=[ClipOut.model_validate(c) for c in items], total=total) @router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED) def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks): clip = clip_service.create_clip(db, user.id, **body.model_dump()) _notify(background, user.id, "clip.created", _clip_data(clip)) return clip @router.get("/{clip_id}", response_model=ClipOut) def get_clip(clip_id: int, user: CurrentUser, db: DbSession): return _get_own_clip(db, user, clip_id) @router.patch("/{clip_id}", response_model=ClipOut) def update_clip( clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession, background: BackgroundTasks, ): clip = _get_own_clip(db, user, clip_id) changes = { field: getattr(body, field) for field in body.model_fields_set - {"version"} if getattr(body, field) is not None or field in _NULLABLE_FIELDS } try: clip = clip_service.update_clip(db, user.id, clip, changes, body.version) except clip_service.ClipConflict as exc: return JSONResponse( status_code=status.HTTP_409_CONFLICT, content={ "detail": "Der Clip wurde inzwischen auf einem anderen Gerät geändert.", "current": _clip_data(exc.current), }, ) _notify(background, user.id, "clip.updated", _clip_data(clip)) return clip @router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_clip( clip_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks ) -> None: if not clip_service.delete_clip(db, user.id, clip_id): raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.") _notify(background, user.id, "clip.deleted", {"id": clip_id})