Files
lan-clipboard/backend/app/api/files.py
T
dbildhauerandClaude Opus 5.5 d3a52c25a7 feat: projekte mit anderen benutzern teilen (backend)
Mitglieder mit Rolle "bearbeiten" oder "lesen"; nur der Besitzer
verwaltet das Projekt. Sichtbar sind eigene Clips und alle Clips in
eigenen oder geteilten Projekten, zentral in services/access.py. Beim
Entfernen oder Verlassen landen die eigenen Clips wieder bei "ohne
Projekt". Live-Ereignisse gehen an alle, die einen Clip sehen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 14:36:56 +01:00

110 lines
3.7 KiB
Python

from typing import Annotated
from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, Request, status
from fastapi.responses import FileResponse
from pydantic import BaseModel
from app.api.deps import CurrentUser, DbSession
from app.api.notify import notify
from app.config import get_settings
from app.schemas.clips import ClipOut
from app.services import clips as clip_service
from app.services import files as file_service
from app.services.access import clip_audience
router = APIRouter(prefix="/files", tags=["files"])
UPLOAD_PATH = "/api/files"
# A downloaded file must never run as a page of this origin
_DOWNLOAD_CSP = "default-src 'none'; sandbox"
class Usage(BaseModel):
used_bytes: int
quota_bytes: int
max_file_bytes: int
class ExpiryUpdate(BaseModel):
expires_days: int
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
async def upload(
request: Request,
user: CurrentUser,
db: DbSession,
background: BackgroundTasks,
name: Annotated[str, Query(max_length=1000)],
expires_days: int = 7,
project_id: int | None = None,
title: Annotated[str | None, Query(max_length=1000)] = None,
):
"""Raw file body (not multipart), streamed to disk; metadata in the query string."""
length = request.headers.get("content-length", "")
if not length.isdigit():
raise HTTPException(status.HTTP_411_LENGTH_REQUIRED, "Content-Length fehlt.")
clip = await file_service.store_upload(
db,
user.id,
request.stream(),
name=name,
size=int(length),
content_type=request.headers.get("content-type"),
expires_days=expires_days,
project_id=project_id,
title=title,
)
out = ClipOut.model_validate(clip)
audience = clip_audience(db, clip.user_id, clip.project_id)
notify(background, audience, "clip.created", out.model_dump(mode="json"))
return out
@router.get("/usage", response_model=Usage)
def usage(user: CurrentUser, db: DbSession) -> Usage:
settings = get_settings()
return Usage(
used_bytes=file_service.used_bytes(db, user.id),
quota_bytes=settings.file_quota_bytes,
max_file_bytes=settings.file_max_bytes,
)
@router.get("/{clip_id}")
def download(clip_id: int, user: CurrentUser, db: DbSession, inline: bool = False):
stored = file_service.get_file(db, user.id, clip_id)
# Stored under the uploader, who may be another member of a shared project
path = None if stored is None else file_service.file_path(stored.user_id, stored.storage_name)
if stored is None or path is None or not path.is_file():
raise HTTPException(status.HTTP_404_NOT_FOUND, "Datei nicht gefunden.")
# Only verified images may be shown in the browser; everything else is a download
show_inline = inline and stored.previewable
return FileResponse(
path,
media_type=stored.content_type,
headers={
"Content-Disposition": file_service.content_disposition(stored.name, show_inline),
"Content-Security-Policy": _DOWNLOAD_CSP,
"Cache-Control": "private, no-cache",
},
)
@router.patch("/{clip_id}", response_model=ClipOut)
def update_expiry(
clip_id: int,
body: ExpiryUpdate,
user: CurrentUser,
db: DbSession,
background: BackgroundTasks,
):
clip = clip_service.get_clip(db, user.id, clip_id)
if clip is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
clip = file_service.set_expiry(db, user.id, clip, body.expires_days)
out = ClipOut.model_validate(clip)
audience = clip_audience(db, clip.user_id, clip.project_id)
notify(background, audience, "clip.updated", out.model_dump(mode="json"))
return out