Files
tsumugu/backend/app/media/storage.py
T
LarsandCursor 2558239bfd
Deploy Development / deploy (push) Successful in 23s
Stelle den ersten nutzbaren Ablauf zum Organisieren und Nachverfolgen bereit.
Anmeldung, Datenraeume, Akten, Vorgaenge, gemeinsame Notizen, Dateien, manuelle Paperless-Referenzen, Aufgaben und unabhaengige Fristen laufen damit in der Entwicklungsumgebung.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 22:09:08 +02:00

72 lines
1.9 KiB
Python

"""Sniff uploads and keep client names out of the storage path."""
from __future__ import annotations
import hashlib
from pathlib import Path
from uuid import UUID
from app.core.errors import storage_unavailable, unprocessable
ALLOWED = {
"application/pdf": "pdf",
"image/png": "png",
"image/jpeg": "jpg",
"image/webp": "webp",
}
def sniff(data: bytes) -> str:
if data.startswith(b"%PDF"):
return "application/pdf"
if data.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
if data.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return "image/webp"
raise unprocessable("Erlaubt sind PDF, PNG, JPEG und WebP.")
def asset_path(media_root: str, asset_id: UUID) -> Path:
root = Path(media_root).resolve()
root.mkdir(parents=True, exist_ok=True)
target = (root / str(asset_id)).resolve()
if target.parent != root:
raise unprocessable("Ungültiger Speicherpfad.")
return target
def write_bytes(path: Path, data: bytes) -> None:
try:
path.write_bytes(data)
except OSError as exc:
raise storage_unavailable() from exc
def read_bytes(path: Path) -> bytes:
try:
if not path.is_file():
raise storage_unavailable()
return path.read_bytes()
except OSError as exc:
raise storage_unavailable() from exc
def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def display_filename(name: str) -> str:
cleaned = []
for char in name.replace("\\", "/").split("/")[-1]:
if char.isprintable() and char not in {'"', "\r", "\n", ":"}:
cleaned.append(char)
text = "".join(cleaned).strip() or "datei"
return text[:240]
def content_disposition(filename: str) -> str:
safe = display_filename(filename).replace('"', "")
return f'attachment; filename="{safe}"'