Files
LarsandCursor cd239a3ab8
Deploy Development / deploy (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 6m16s
Test Suite / smoke-dev (push) Successful in 1s
Test Suite / frontend-build (push) Successful in 22s
Zeige PDF-Anlagen in der Mail-Ansicht, damit der Browser sie nicht unter einem zufälligen Namen speichert.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:59:07 +02:00

84 lines
2.6 KiB
Python

"""Sniff uploads and keep client names out of the storage path."""
from __future__ import annotations
import hashlib
from pathlib import Path
from urllib.parse import quote
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, *, inline: bool = False) -> str:
"""The real name goes along in UTF-8 (RFC 5987), with a plain ASCII fallback for old clients."""
name = display_filename(filename)
kind = "inline" if inline else "attachment"
suffix = ""
leaf = name.rsplit(".", 1)
if len(leaf) == 2 and leaf[1].isascii() and leaf[1].isalnum():
suffix = f".{leaf[1]}"
fallback = name.encode("ascii", "replace").decode("ascii").replace("?", "_").replace('"', "").replace("\\", "_").replace(";", "_")
fallback = " ".join(fallback.split())
if suffix and not fallback.lower().endswith(suffix.lower()):
fallback = f"{fallback}{suffix}".strip()
fallback = fallback or f"datei{suffix}"
return f"{kind}; filename=\"{fallback}\"; filename*=UTF-8''{quote(name, safe='')}"