Dateien als Clip-Art "file": gestreamter Upload mit Größengrenze, Kontingent pro Benutzer und Mindestreserve an freiem Speicher. Download immer als Anhang mit sandbox-CSP, Vorschau nur für geprüfte JPEG/PNG/GIF/WebP. Ablauf nach 1/7/30 Tagen oder nie; der Aufräumjob löscht abgelaufene und verwaiste Dateien. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
110 lines
3.6 KiB
Python
110 lines
3.6 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.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.ws.hub import hub
|
|
|
|
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
|
|
|
|
|
|
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
|
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
|
|
|
|
|
@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)
|
|
_notify(background, user.id, "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)
|
|
path = None if stored is None else file_service.file_path(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)
|
|
_notify(background, user.id, "clip.updated", out.model_dump(mode="json"))
|
|
return out
|