"""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: """The real name goes along in UTF-8 (RFC 5987), with a plain ASCII fallback for old clients.""" from urllib.parse import quote safe = display_filename(filename).replace('"', "") fallback = safe.encode("ascii", "replace").decode("ascii").replace("?", "_") return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(safe, safe='')}"