feat: dateiaustausch im backend
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>
This commit is contained in:
1 parent
ae334d2248
commit
52a8fd019f
12 files changed
+1027
-11
No files matched your search
@@ -0,0 +1,109 @@
|
||||
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
|
||||
@@ -30,6 +30,11 @@ class Settings(BaseSettings):
|
||||
|
||||
clip_max_chars: int = 200_000
|
||||
|
||||
file_max_bytes: int = 100 * 1024 * 1024
|
||||
file_quota_bytes: int = 1024 * 1024 * 1024
|
||||
# Uploads are refused when the disk would drop below this; the server is shared
|
||||
file_min_free_bytes: int = 2 * 1024 * 1024 * 1024
|
||||
|
||||
initial_admin_username: str | None = None
|
||||
initial_admin_password: str | None = None
|
||||
|
||||
@@ -37,6 +42,10 @@ class Settings(BaseSettings):
|
||||
def database_url(self) -> str:
|
||||
return f"sqlite:///{self.data_dir / 'app.db'}"
|
||||
|
||||
@property
|
||||
def files_dir(self) -> Path:
|
||||
return self.data_dir / "files"
|
||||
|
||||
@property
|
||||
def allowed_origin_list(self) -> list[str]:
|
||||
return [o.strip().rstrip("/") for o in self.allowed_origins.split(",") if o.strip()]
|
||||
|
||||
+28
-6
@@ -9,7 +9,7 @@ from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from app import __version__
|
||||
from app.api import admin, auth, clips, health, projects, ws
|
||||
from app.api import admin, auth, clips, files, health, projects, ws
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import (
|
||||
@@ -17,28 +17,41 @@ from app.middleware import (
|
||||
OriginCheckMiddleware,
|
||||
SecurityHeadersMiddleware,
|
||||
)
|
||||
from app.services import files as file_service
|
||||
from app.services.auth import delete_old_login_attempts
|
||||
from app.services.projects import ProjectNotFound
|
||||
from app.services.sessions import delete_expired_sessions
|
||||
from app.services.users import UserError, bootstrap_initial_admin
|
||||
from app.ws.hub import hub
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CLEANUP_INTERVAL_SECONDS = 3600
|
||||
|
||||
|
||||
def _cleanup() -> None:
|
||||
def _cleanup() -> list[tuple[int, int]]:
|
||||
"""Hourly housekeeping; returns (user_id, clip_id) of expired file clips."""
|
||||
with _session_factory()() as db:
|
||||
sessions = delete_expired_sessions(db)
|
||||
attempts = delete_old_login_attempts(db)
|
||||
if sessions or attempts:
|
||||
logger.info("Cleanup: %d sessions, %d login attempts removed", sessions, attempts)
|
||||
expired = file_service.delete_expired(db)
|
||||
orphans = file_service.remove_orphans(db)
|
||||
if sessions or attempts or expired or orphans:
|
||||
logger.info(
|
||||
"Cleanup: %d sessions, %d login attempts, %d expired files, %d orphans removed",
|
||||
sessions,
|
||||
attempts,
|
||||
len(expired),
|
||||
orphans,
|
||||
)
|
||||
return expired
|
||||
|
||||
|
||||
async def _cleanup_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
await run_in_threadpool(_cleanup)
|
||||
for user_id, clip_id in await run_in_threadpool(_cleanup):
|
||||
await hub.broadcast(user_id, {"type": "clip.deleted", "data": {"id": clip_id}})
|
||||
except Exception:
|
||||
logger.exception("Cleanup failed")
|
||||
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
|
||||
@@ -124,19 +137,28 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
# Last added runs first: security headers wrap every response, including rejections
|
||||
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||
app.add_middleware(BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes)
|
||||
app.add_middleware(
|
||||
BodySizeLimitMiddleware,
|
||||
max_bytes=settings.max_request_bytes,
|
||||
exempt=frozenset({("POST", files.UPLOAD_PATH)}),
|
||||
)
|
||||
app.add_middleware(SecurityHeadersMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(admin.router, prefix="/api")
|
||||
app.include_router(clips.router, prefix="/api")
|
||||
app.include_router(projects.router, prefix="/api")
|
||||
app.include_router(files.router, prefix="/api")
|
||||
app.include_router(ws.router, prefix="/api")
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@app.exception_handler(file_service.FileRejected)
|
||||
def file_rejected_handler(_request: Request, exc: file_service.FileRejected) -> JSONResponse:
|
||||
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
|
||||
|
||||
@app.exception_handler(ProjectNotFound)
|
||||
def project_not_found_handler(_request: Request, _exc: ProjectNotFound) -> JSONResponse:
|
||||
# Same answer for foreign and missing projects, so ids of other users are not revealed
|
||||
|
||||
@@ -90,13 +90,25 @@ class BodySizeLimitMiddleware:
|
||||
When a stream exceeds the limit, the 413 is sent here and the app sees a disconnect.
|
||||
"""
|
||||
|
||||
def __init__(self, app: ASGIApp, max_bytes: int, path_prefix: str = "/api/") -> None:
|
||||
def __init__(
|
||||
self,
|
||||
app: ASGIApp,
|
||||
max_bytes: int,
|
||||
path_prefix: str = "/api/",
|
||||
exempt: frozenset[tuple[str, str]] = frozenset(),
|
||||
) -> None:
|
||||
self.app = app
|
||||
self.max_bytes = max_bytes
|
||||
self.path_prefix = path_prefix
|
||||
# (method, path) pairs that enforce their own, larger limit (file uploads)
|
||||
self.exempt = exempt
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http" or not scope["path"].startswith(self.path_prefix):
|
||||
if (
|
||||
scope["type"] != "http"
|
||||
or not scope["path"].startswith(self.path_prefix)
|
||||
or (scope["method"], scope["path"]) in self.exempt
|
||||
):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
from app.models.clip import Clip, ClipKind
|
||||
from app.models.file import StoredFile
|
||||
from app.models.login_attempt import LoginAttempt
|
||||
from app.models.project import PROJECT_COLORS, Project
|
||||
from app.models.session import UserSession
|
||||
@@ -13,6 +14,7 @@ __all__ = [
|
||||
"PROJECT_COLORS",
|
||||
"Project",
|
||||
"Role",
|
||||
"StoredFile",
|
||||
"UTCDateTime",
|
||||
"User",
|
||||
"UserSession",
|
||||
|
||||
@@ -2,16 +2,22 @@ from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import Enum, ForeignKey, Index, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.file import StoredFile
|
||||
|
||||
|
||||
class ClipKind(enum.StrEnum):
|
||||
TEXT = "text"
|
||||
CODE = "code"
|
||||
# Uploaded file; content holds the file name so search finds it
|
||||
FILE = "file"
|
||||
|
||||
|
||||
class Clip(Base):
|
||||
@@ -37,3 +43,7 @@ class Clip(Base):
|
||||
version: Mapped[int] = mapped_column(default=1)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
|
||||
file: Mapped[StoredFile | None] = relationship(
|
||||
back_populates="clip", lazy="selectin", passive_deletes=True
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import BigInteger, ForeignKey, Index, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.clip import Clip
|
||||
|
||||
|
||||
class StoredFile(Base):
|
||||
"""An uploaded file; belongs to exactly one clip of kind "file"."""
|
||||
|
||||
__tablename__ = "files"
|
||||
__table_args__ = (
|
||||
Index("ix_files_user", "user_id"),
|
||||
Index("ix_files_expires_at", "expires_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
clip_id: Mapped[int] = mapped_column(ForeignKey("clips.id", ondelete="CASCADE"), unique=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
# Random name on disk; the original name never touches the file system
|
||||
storage_name: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
content_type: Mapped[str] = mapped_column(String(127))
|
||||
size: Mapped[int] = mapped_column(BigInteger)
|
||||
sha256: Mapped[str] = mapped_column(String(64))
|
||||
# Only set when the content really is a JPEG/PNG/GIF/WebP image (checked on upload)
|
||||
previewable: Mapped[bool] = mapped_column(default=False)
|
||||
expires_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
|
||||
clip: Mapped[Clip] = relationship(back_populates="file")
|
||||
@@ -29,6 +29,16 @@ class ClipUpdate(BaseModel):
|
||||
version: int | None = Field(default=None, description="Expected version for conflict check")
|
||||
|
||||
|
||||
class FileOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
name: str
|
||||
content_type: str
|
||||
size: int
|
||||
previewable: bool
|
||||
expires_at: datetime | None
|
||||
|
||||
|
||||
class ClipOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@@ -39,6 +49,7 @@ class ClipOut(BaseModel):
|
||||
language: str | None
|
||||
pinned: bool
|
||||
project_id: int | None
|
||||
file: FileOut | None = None
|
||||
version: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -5,13 +5,17 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.languages import LANGUAGES
|
||||
from app.models import Clip, ClipKind, utcnow
|
||||
from app.models import Clip, ClipKind, StoredFile, utcnow
|
||||
from app.services.files import remove_from_disk
|
||||
from app.services.projects import require_project
|
||||
from app.services.users import UserError
|
||||
|
||||
# Changing only these fields does not count as an edit (no new updated_at)
|
||||
_META_FIELDS = frozenset({"pinned", "project_id"})
|
||||
|
||||
# Fixed for file clips: content is the file name
|
||||
_CONTENT_FIELDS = frozenset({"kind", "content", "language"})
|
||||
|
||||
# Filter value for clips without a project
|
||||
NO_PROJECT = "none"
|
||||
SEARCH_MAX_LENGTH = 200
|
||||
@@ -36,7 +40,7 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
|
||||
title = (title or "").strip() or None
|
||||
if title is not None and len(title) > 200:
|
||||
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
|
||||
if kind == ClipKind.TEXT:
|
||||
if kind != ClipKind.CODE:
|
||||
language = None
|
||||
else:
|
||||
language = language or "plaintext"
|
||||
@@ -100,6 +104,8 @@ def create_clip(
|
||||
pinned: bool = False,
|
||||
project_id: int | None = None,
|
||||
) -> Clip:
|
||||
if kind == ClipKind.FILE:
|
||||
raise UserError("Dateien werden über den Upload angelegt.")
|
||||
title, language = _normalize(kind, title, content, language)
|
||||
if project_id is not None:
|
||||
require_project(db, user_id, project_id)
|
||||
@@ -128,6 +134,10 @@ def update_clip(
|
||||
# Early check so a stale client gets the conflict, not a follow-up validation error
|
||||
if expected_version is not None and clip.version != expected_version:
|
||||
raise ClipConflict(clip)
|
||||
if clip.kind == ClipKind.FILE and set(changes) & _CONTENT_FIELDS:
|
||||
raise UserError("Bei Dateien lassen sich nur Titel, Projekt und Anheften ändern.")
|
||||
if changes.get("kind") == ClipKind.FILE and clip.kind != ClipKind.FILE:
|
||||
raise UserError("Ein Clip lässt sich nicht in eine Datei umwandeln.")
|
||||
kind = changes.get("kind", clip.kind)
|
||||
title = changes.get("title", clip.title)
|
||||
content = changes.get("content", clip.content)
|
||||
@@ -164,6 +174,13 @@ def update_clip(
|
||||
|
||||
|
||||
def delete_clip(db: Session, user_id: int, clip_id: int) -> bool:
|
||||
storage_name = db.scalar(
|
||||
select(StoredFile.storage_name).where(
|
||||
StoredFile.clip_id == clip_id, StoredFile.user_id == user_id
|
||||
)
|
||||
)
|
||||
result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||
db.commit()
|
||||
if storage_name is not None:
|
||||
remove_from_disk(user_id, storage_name)
|
||||
return result.rowcount > 0
|
||||
@@ -0,0 +1,277 @@
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import unicodedata
|
||||
import uuid
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.models import Clip, ClipKind, StoredFile, utcnow
|
||||
from app.services.projects import require_project
|
||||
from app.services.users import UserError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Allowed lifetimes in days; 0 means the file is kept until deleted
|
||||
EXPIRY_CHOICES = frozenset({0, 1, 7, 30})
|
||||
NAME_MAX_LENGTH = 255
|
||||
FALLBACK_NAME = "datei"
|
||||
TMP_DIR_NAME = "tmp"
|
||||
# Files on disk without database row are only removed after this age, so an upload
|
||||
# that is just being committed is never touched
|
||||
ORPHAN_MIN_AGE_SECONDS = 3600
|
||||
STALE_UPLOAD_SECONDS = 6 * 3600
|
||||
|
||||
_CONTENT_TYPE = re.compile(r"^[a-z0-9][a-z0-9!#$&^_.+-]{0,62}/[a-z0-9][a-z0-9!#$&^_.+-]{0,62}$")
|
||||
# Magic bytes of the image formats every browser displays safely (no SVG: it can run script)
|
||||
_IMAGE_SIGNATURES = (
|
||||
(b"\xff\xd8\xff", "image/jpeg"),
|
||||
(b"\x89PNG\r\n\x1a\n", "image/png"),
|
||||
(b"GIF87a", "image/gif"),
|
||||
(b"GIF89a", "image/gif"),
|
||||
)
|
||||
|
||||
|
||||
class FileRejected(Exception):
|
||||
"""Upload refused; status code and message go to the client unchanged."""
|
||||
|
||||
def __init__(self, status_code: int, detail: str) -> None:
|
||||
super().__init__(detail)
|
||||
self.status_code = status_code
|
||||
self.detail = detail
|
||||
|
||||
|
||||
def format_bytes(size: int) -> str:
|
||||
for unit, factor in (("GB", 1024**3), ("MB", 1024**2), ("KB", 1024)):
|
||||
if size >= factor:
|
||||
return f"{size / factor:.1f}".rstrip("0").rstrip(".").replace(".", ",") + f" {unit}"
|
||||
return f"{size} B"
|
||||
|
||||
|
||||
def sanitize_name(name: str) -> str:
|
||||
"""Keep only the base name, without control characters, at most 255 characters."""
|
||||
name = unicodedata.normalize("NFC", name)
|
||||
name = re.split(r"[/\\]", name)[-1]
|
||||
name = "".join(ch for ch in name if not unicodedata.category(ch).startswith("C"))
|
||||
name = name.strip()
|
||||
if name in ("", ".", ".."):
|
||||
return FALLBACK_NAME
|
||||
if len(name) > NAME_MAX_LENGTH:
|
||||
stem, dot, ext = name.rpartition(".")
|
||||
if dot and stem and len(ext) <= 20:
|
||||
name = stem[: NAME_MAX_LENGTH - len(ext) - 1] + "." + ext
|
||||
else:
|
||||
name = name[:NAME_MAX_LENGTH]
|
||||
return name
|
||||
|
||||
|
||||
def sanitize_content_type(value: str | None) -> str:
|
||||
value = (value or "").split(";")[0].strip().lower()
|
||||
return value if _CONTENT_TYPE.fullmatch(value) else "application/octet-stream"
|
||||
|
||||
|
||||
def sniff_image(head: bytes) -> str | None:
|
||||
"""Image type from the first bytes, or None if it is not a previewable image."""
|
||||
for signature, content_type in _IMAGE_SIGNATURES:
|
||||
if head.startswith(signature):
|
||||
return content_type
|
||||
if len(head) >= 12 and head[:4] == b"RIFF" and head[8:12] == b"WEBP":
|
||||
return "image/webp"
|
||||
return None
|
||||
|
||||
|
||||
def content_disposition(name: str, inline: bool = False) -> str:
|
||||
"""RFC 6266 header with ASCII fallback; quotes and line breaks cannot break out."""
|
||||
fallback = "".join(ch if 32 <= ord(ch) < 127 and ch not in '"\\' else "_" for ch in name)
|
||||
kind = "inline" if inline else "attachment"
|
||||
return f"{kind}; filename=\"{fallback}\"; filename*=UTF-8''{quote(name, safe='')}"
|
||||
|
||||
|
||||
def file_path(user_id: int, storage_name: str) -> Path:
|
||||
return get_settings().files_dir / str(user_id) / storage_name
|
||||
|
||||
|
||||
def remove_from_disk(user_id: int, storage_name: str) -> None:
|
||||
try:
|
||||
file_path(user_id, storage_name).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
logger.exception("Could not remove file %s of user %d", storage_name, user_id)
|
||||
|
||||
|
||||
def used_bytes(db: Session, user_id: int) -> int:
|
||||
total = db.scalar(select(func.sum(StoredFile.size)).where(StoredFile.user_id == user_id))
|
||||
return int(total or 0)
|
||||
|
||||
|
||||
def _expires_at(days: int):
|
||||
if days not in EXPIRY_CHOICES:
|
||||
raise UserError("Ungültige Ablaufzeit.")
|
||||
return utcnow() + timedelta(days=days) if days else None
|
||||
|
||||
|
||||
def _check_limits(db: Session, user_id: int, size: int) -> None:
|
||||
settings = get_settings()
|
||||
if size <= 0:
|
||||
raise FileRejected(400, "Die Datei ist leer.")
|
||||
if size > settings.file_max_bytes:
|
||||
raise FileRejected(
|
||||
413, f"Die Datei ist zu groß (höchstens {format_bytes(settings.file_max_bytes)})."
|
||||
)
|
||||
used = used_bytes(db, user_id)
|
||||
if used + size > settings.file_quota_bytes:
|
||||
free = max(settings.file_quota_bytes - used, 0)
|
||||
raise FileRejected(
|
||||
413,
|
||||
f"Nicht genug Speicherplatz: noch {format_bytes(free)} von "
|
||||
f"{format_bytes(settings.file_quota_bytes)} frei.",
|
||||
)
|
||||
settings.files_dir.mkdir(parents=True, exist_ok=True)
|
||||
if shutil.disk_usage(settings.files_dir).free - size < settings.file_min_free_bytes:
|
||||
raise FileRejected(507, "Auf dem Server ist gerade nicht genug Speicherplatz frei.")
|
||||
|
||||
|
||||
async def store_upload(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
chunks: AsyncIterator[bytes],
|
||||
*,
|
||||
name: str,
|
||||
size: int,
|
||||
content_type: str | None = None,
|
||||
expires_days: int = 7,
|
||||
project_id: int | None = None,
|
||||
title: str | None = None,
|
||||
) -> Clip:
|
||||
"""Stream an upload to disk and create its clip. size is the announced Content-Length."""
|
||||
name = sanitize_name(name)
|
||||
expires_at = _expires_at(expires_days)
|
||||
title = (title or "").strip() or None
|
||||
if title is not None and len(title) > 200:
|
||||
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
|
||||
if project_id is not None:
|
||||
require_project(db, user_id, project_id)
|
||||
_check_limits(db, user_id, size)
|
||||
|
||||
settings = get_settings()
|
||||
tmp_dir = settings.files_dir / TMP_DIR_NAME
|
||||
tmp_dir.mkdir(parents=True, exist_ok=True)
|
||||
storage_name = uuid.uuid4().hex
|
||||
tmp_path = tmp_dir / f"{storage_name}.part"
|
||||
final_path = file_path(user_id, storage_name)
|
||||
digest = hashlib.sha256()
|
||||
received = 0
|
||||
head = b""
|
||||
try:
|
||||
with tmp_path.open("xb") as out:
|
||||
async for chunk in chunks:
|
||||
received += len(chunk)
|
||||
if received > size:
|
||||
raise FileRejected(400, "Die Datei ist größer als angekündigt.")
|
||||
if len(head) < 16:
|
||||
head = (head + chunk)[:16]
|
||||
digest.update(chunk)
|
||||
out.write(chunk)
|
||||
if received != size:
|
||||
raise FileRejected(400, "Die Übertragung wurde unterbrochen.")
|
||||
|
||||
image_type = sniff_image(head)
|
||||
final_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(tmp_path, final_path)
|
||||
|
||||
clip = Clip(
|
||||
user_id=user_id,
|
||||
project_id=project_id,
|
||||
kind=ClipKind.FILE,
|
||||
title=title,
|
||||
content=name,
|
||||
)
|
||||
clip.file = StoredFile(
|
||||
user_id=user_id,
|
||||
storage_name=storage_name,
|
||||
name=name,
|
||||
content_type=image_type or sanitize_content_type(content_type),
|
||||
size=size,
|
||||
sha256=digest.hexdigest(),
|
||||
previewable=image_type is not None,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
db.add(clip)
|
||||
db.commit()
|
||||
return clip
|
||||
except BaseException:
|
||||
db.rollback()
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
final_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def get_file(db: Session, user_id: int, clip_id: int) -> StoredFile | None:
|
||||
"""The file of a clip of this user, unless it has expired."""
|
||||
stored = db.scalar(
|
||||
select(StoredFile).where(StoredFile.clip_id == clip_id, StoredFile.user_id == user_id)
|
||||
)
|
||||
if stored is None or (stored.expires_at is not None and stored.expires_at <= utcnow()):
|
||||
return None
|
||||
return stored
|
||||
|
||||
|
||||
def set_expiry(db: Session, user_id: int, clip: Clip, expires_days: int) -> Clip:
|
||||
"""Change how long a file is kept; counts as a change of the clip, not as an edit."""
|
||||
if clip.file is None:
|
||||
raise UserError("Dieser Clip ist keine Datei.")
|
||||
clip.file.expires_at = _expires_at(expires_days)
|
||||
db.execute(
|
||||
update(Clip)
|
||||
.where(Clip.id == clip.id, Clip.user_id == user_id)
|
||||
.values(version=Clip.version + 1)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(clip)
|
||||
return clip
|
||||
|
||||
|
||||
def delete_expired(db: Session) -> list[tuple[int, int]]:
|
||||
"""Delete clips whose file has expired; returns (user_id, clip_id) for notifications."""
|
||||
rows = db.execute(
|
||||
select(StoredFile.user_id, StoredFile.clip_id, StoredFile.storage_name).where(
|
||||
StoredFile.expires_at.is_not(None), StoredFile.expires_at <= utcnow()
|
||||
)
|
||||
).all()
|
||||
if not rows:
|
||||
return []
|
||||
db.execute(delete(Clip).where(Clip.id.in_([row.clip_id for row in rows])))
|
||||
db.commit()
|
||||
for row in rows:
|
||||
remove_from_disk(row.user_id, row.storage_name)
|
||||
return [(row.user_id, row.clip_id) for row in rows]
|
||||
|
||||
|
||||
def remove_orphans(db: Session) -> int:
|
||||
"""Remove files without database row (e.g. of deleted users) and stale partial uploads."""
|
||||
files_dir = get_settings().files_dir
|
||||
if not files_dir.is_dir():
|
||||
return 0
|
||||
known = set(db.scalars(select(StoredFile.storage_name)))
|
||||
now = time.time()
|
||||
removed = 0
|
||||
for path in files_dir.glob("*/*"):
|
||||
if not path.is_file():
|
||||
continue
|
||||
if path.parent.name == TMP_DIR_NAME:
|
||||
stale = now - path.stat().st_mtime > STALE_UPLOAD_SECONDS
|
||||
else:
|
||||
stale = path.name not in known and now - path.stat().st_mtime > ORPHAN_MIN_AGE_SECONDS
|
||||
if stale:
|
||||
path.unlink(missing_ok=True)
|
||||
removed += 1
|
||||
return removed
|
||||
Reference in new issue
Block a user