Files
lan-clipboard/backend/app/api/clips.py
T
dbildhauerandClaude Opus 5.5 ff2860f7be feat: projekte und suche im backend
Projekte pro Benutzer mit Name und Farbe, Clips optional einem Projekt
zugeordnet. Löschen eines Projekts verschiebt seine Clips nach "ohne
Projekt". Clip-Liste filtert nach Projekt und sucht Teiltexte in Titel
und Inhalt, unabhängig von Groß-/Kleinschreibung (auch Umlaute).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 13:15:05 +01:00

101 lines
3.7 KiB
Python

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", "project_id"}
# "none" or a project id
_PROJECT_FILTER = r"^(none|[1-9][0-9]{0,17})$"
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,
project: Annotated[str | None, Query(pattern=_PROJECT_FILTER)] = None,
q: Annotated[str | None, Query(max_length=clip_service.SEARCH_MAX_LENGTH)] = None,
) -> ClipList:
project_filter = project if project in (None, clip_service.NO_PROJECT) else int(project)
items, total = clip_service.list_clips(
db, user.id, limit, offset, project=project_filter, query=q
)
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})