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>
This commit is contained in:
1 parent
d0f09830bb
commit
cd239a3ab8
5 files changed
+164
-26
No files matched your search
@@ -242,13 +242,18 @@ def download_mail_attachment(
|
||||
if index < 0 or index >= len(parsed.attachments):
|
||||
raise not_found()
|
||||
item = parsed.attachments[index]
|
||||
return _mail_bytes(item.data, item.media_type or "application/octet-stream", item.filename, inline=True)
|
||||
name = item.display_name or item.filename or "anlage"
|
||||
media = (item.media_type or "application/octet-stream").split(";", 1)[0].strip()
|
||||
if item.data[:1024].lstrip(b"\xef\xbb\xbf\r\n\t ").startswith(b"%PDF"):
|
||||
media = "application/pdf"
|
||||
if not name.lower().endswith(".pdf"):
|
||||
leaf = name.replace("\\", "/").split("/")[-1]
|
||||
name = name if "." in leaf else f"{name}.pdf"
|
||||
return _mail_bytes(item.data, media or "application/octet-stream", name, inline=True)
|
||||
|
||||
|
||||
def _mail_bytes(data: bytes, media_type: str, filename: str, inline: bool = False) -> Response:
|
||||
disposition = content_disposition(filename)
|
||||
if inline:
|
||||
disposition = disposition.replace("attachment;", "inline;", 1)
|
||||
disposition = content_disposition(filename, inline=inline)
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=media_type,
|
||||
|
||||
+47
-3
@@ -6,6 +6,7 @@ The same tree feeds preview, reading, attachment download and export.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import html
|
||||
import re
|
||||
@@ -164,9 +165,13 @@ def parse_mail(raw: bytes) -> ParsedMail:
|
||||
missing.append(label or f"Anlage {index}")
|
||||
notices.append(f"Die Anlage {label or index} ließ sich nicht vollständig lesen.")
|
||||
continue
|
||||
data = _unwrap_pdf_payload(data, media, label)
|
||||
if _is_pdf(data):
|
||||
media = "application/pdf"
|
||||
label = _pdf_filename(label)
|
||||
name = _unique_filename(label or f"anlage-{index}.bin", used)
|
||||
inline = disposition == "inline" or bool(content_id)
|
||||
attachments.append(_attachment(part, name, label or name, data, inline=inline))
|
||||
attachments.append(_attachment(part, name, label or name, data, inline=inline, media=media))
|
||||
simplified = "\n".join(chunk for chunk in plain if chunk).strip()
|
||||
rendered = ""
|
||||
if html_parts:
|
||||
@@ -410,10 +415,49 @@ def _content_id(part: EmailMessage) -> str:
|
||||
return token
|
||||
|
||||
|
||||
def _attachment(part: EmailMessage, filename: str, label: str, data: bytes, inline: bool) -> AttachmentBytes:
|
||||
def _is_pdf(data: bytes) -> bool:
|
||||
return data[:1024].lstrip(b"\xef\xbb\xbf\r\n\t ").startswith(b"%PDF")
|
||||
|
||||
|
||||
def _unwrap_pdf_payload(data: bytes, media: str, name: str) -> bytes:
|
||||
"""A PDF that arrived as undecoded Base64 is still the PDF, not the transfer text."""
|
||||
if _is_pdf(data):
|
||||
return data
|
||||
declared = (media or "").split(";", 1)[0].strip().lower()
|
||||
hinted = "pdf" in declared or (name or "").lower().endswith(".pdf") or declared in {
|
||||
"application/octet-stream",
|
||||
"application/x-octet-stream",
|
||||
"binary/octet-stream",
|
||||
}
|
||||
if not hinted:
|
||||
return data
|
||||
stripped = b"".join(data.split())
|
||||
if len(stripped) < 16 or re.fullmatch(rb"[A-Za-z0-9+/=]+", stripped) is None:
|
||||
return data
|
||||
try:
|
||||
decoded = base64.b64decode(stripped, validate=True)
|
||||
except Exception:
|
||||
return data
|
||||
return decoded if _is_pdf(decoded) else data
|
||||
|
||||
|
||||
def _pdf_filename(name: str) -> str:
|
||||
text = (name or "").strip() or "anlage"
|
||||
if text.lower().endswith(".pdf"):
|
||||
return text
|
||||
if text.lower().endswith(".bin"):
|
||||
text = text[:-4].rstrip(" .") or "anlage"
|
||||
leaf = text.replace("\\", "/").split("/")[-1]
|
||||
if "." in leaf:
|
||||
return text
|
||||
return f"{text}.pdf"
|
||||
|
||||
|
||||
def _attachment(part: EmailMessage, filename: str, label: str, data: bytes, inline: bool, media: str | None = None) -> AttachmentBytes:
|
||||
resolved = (media or part.get_content_type() or "application/octet-stream").split(";", 1)[0].strip()
|
||||
return AttachmentBytes(
|
||||
filename=filename,
|
||||
media_type=(part.get_content_type() or "application/octet-stream")[:120],
|
||||
media_type=(resolved or "application/octet-stream")[:120],
|
||||
data=data,
|
||||
sha256=hashlib.sha256(data).hexdigest(),
|
||||
display_name=label or filename,
|
||||
|
||||
@@ -4,6 +4,7 @@ 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
|
||||
@@ -66,10 +67,17 @@ def display_filename(name: str) -> str:
|
||||
return text[:240]
|
||||
|
||||
|
||||
def content_disposition(filename: str) -> str:
|
||||
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."""
|
||||
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='')}"
|
||||
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='')}"
|
||||
@@ -104,6 +104,40 @@ def test_parse_mail_keeps_names_html_and_attached_messages():
|
||||
assert named.attachments[0].data == b"pdf"
|
||||
|
||||
|
||||
def test_an_undecoded_pdf_stays_a_named_pdf():
|
||||
import base64
|
||||
from app.media.storage import content_disposition
|
||||
|
||||
pdf = b"%PDF-1.4\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF\n"
|
||||
raw = (
|
||||
b"Subject: Scan\r\n"
|
||||
b"MIME-Version: 1.0\r\n"
|
||||
b"Content-Type: multipart/mixed; boundary=bound\r\n"
|
||||
b"\r\n"
|
||||
b"--bound\r\n"
|
||||
b"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
b"\r\n"
|
||||
b"text\r\n"
|
||||
b"--bound\r\n"
|
||||
b"Content-Type: application/octet-stream\r\n"
|
||||
b"Content-Transfer-Encoding: 8bit\r\n"
|
||||
b"Content-Disposition: attachment; filename=\"scan-7f3a9c\"\r\n"
|
||||
b"\r\n"
|
||||
+ base64.b64encode(pdf) + b"\r\n"
|
||||
b"--bound--\r\n"
|
||||
)
|
||||
item = parse_mail(raw).attachments[0]
|
||||
assert item.data.startswith(b"%PDF")
|
||||
assert item.media_type == "application/pdf"
|
||||
assert item.display_name == "scan-7f3a9c.pdf"
|
||||
header = content_disposition("\u00dcbergabe.pdf", inline=True)
|
||||
assert header.startswith("inline;")
|
||||
header.encode("ascii")
|
||||
assert ".pdf" in header
|
||||
assert "filename*=UTF-8''" in header
|
||||
assert "%C3%9Cbergabe.pdf" in header
|
||||
|
||||
|
||||
class QuotedIMAP:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.untagged_responses = {}
|
||||
|
||||
Reference in new issue
Block a user