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 = {}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { DocumentView } from "../pages/DocumentView.jsx";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { api, documentToText, downloadMailPart, fetchExternal, fetchMailPart, markDirty, textToDocument } from "../api.js";
|
||||
import { MailAttachments, MailBody } from "../mail-view.jsx";
|
||||
@@ -17,6 +16,18 @@ function previewKind(type, filename) {
|
||||
return "other";
|
||||
}
|
||||
|
||||
function isPdfBytes(buffer) {
|
||||
const sample = new TextDecoder("iso-8859-1").decode(buffer.slice(0, 1024)).trim();
|
||||
return sample.startsWith("%PDF");
|
||||
}
|
||||
|
||||
function downloadName(file, pdf) {
|
||||
const name = file?.filename || "anlage";
|
||||
if (!pdf || name.toLowerCase().endsWith(".pdf")) return name;
|
||||
const stem = name.toLowerCase().endsWith(".bin") ? name.slice(0, -4).trim() : name;
|
||||
return `${stem || "anlage"}.pdf`;
|
||||
}
|
||||
|
||||
export function NoteStage({ element, context, binding, onReload }) {
|
||||
const editor = editors.note;
|
||||
const [text, setText] = useState(() => documentToText(element.document));
|
||||
@@ -162,19 +173,41 @@ export function MailStage({ element, context, binding, shownDirection }) {
|
||||
}, [element.id, element.external?.source, context?.kind, context?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (shownIndex === null) return undefined;
|
||||
if (shownIndex === null) {
|
||||
setMedia("");
|
||||
setPdf(null);
|
||||
setPages(0);
|
||||
setPhase("idle");
|
||||
if (objectUrl.current) {
|
||||
URL.revokeObjectURL(objectUrl.current);
|
||||
objectUrl.current = "";
|
||||
}
|
||||
setBlobUrl("");
|
||||
return undefined;
|
||||
}
|
||||
const file = (letter?.attachments || []).find((item) => item.index === shownIndex);
|
||||
if (!file) return undefined;
|
||||
let alive = true;
|
||||
setPhase("loading");
|
||||
setPdf(null);
|
||||
setPages(0);
|
||||
setPage(1);
|
||||
setMedia("");
|
||||
fetchMailPart(element.id, context, `attachments/${file.index}`).then(async (blob) => {
|
||||
if (!alive) return;
|
||||
if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
|
||||
const url = URL.createObjectURL(blob);
|
||||
objectUrl.current = url;
|
||||
setBlobUrl(url);
|
||||
const kind = previewKind(blob.type || file.content_type, file.filename);
|
||||
const buffer = await blob.arrayBuffer();
|
||||
if (!alive) return;
|
||||
const declared = previewKind(blob.type || file.content_type, file.filename);
|
||||
const kind = isPdfBytes(buffer) ? "pdf" : declared;
|
||||
if (objectUrl.current) {
|
||||
URL.revokeObjectURL(objectUrl.current);
|
||||
objectUrl.current = "";
|
||||
}
|
||||
setBlobUrl("");
|
||||
if (kind === "image") {
|
||||
const url = URL.createObjectURL(new Blob([buffer], { type: blob.type || file.content_type || "application/octet-stream" }));
|
||||
objectUrl.current = url;
|
||||
setBlobUrl(url);
|
||||
setMedia("image");
|
||||
setPhase("ready");
|
||||
return;
|
||||
@@ -182,10 +215,9 @@ export function MailStage({ element, context, binding, shownDirection }) {
|
||||
if (kind === "pdf") {
|
||||
setMedia("pdf");
|
||||
try {
|
||||
const bytes = await blob.arrayBuffer();
|
||||
const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
|
||||
const doc = await pdfjs.getDocument({ data: bytes }).promise;
|
||||
const doc = await pdfjs.getDocument({ data: new Uint8Array(buffer) }).promise;
|
||||
if (!alive) {
|
||||
doc.destroy();
|
||||
return;
|
||||
@@ -195,16 +227,17 @@ export function MailStage({ element, context, binding, shownDirection }) {
|
||||
setPhase("ready");
|
||||
} catch (err) {
|
||||
if (!alive) return;
|
||||
setMedia("pdf-frame");
|
||||
setPdf(null);
|
||||
setPhase("ready");
|
||||
}
|
||||
return;
|
||||
}
|
||||
setMedia("other");
|
||||
setMedia("file");
|
||||
setPhase("ready");
|
||||
}).catch((err) => {
|
||||
if (!alive) return;
|
||||
setPhase("ready");
|
||||
setMedia("");
|
||||
setError(err.message || "Die Anlage ist nicht verfügbar.");
|
||||
});
|
||||
return () => {
|
||||
@@ -243,6 +276,17 @@ export function MailStage({ element, context, binding, shownDirection }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function saveAttachment() {
|
||||
if (!shownFile) return;
|
||||
setError("");
|
||||
const namedPdf = media === "pdf" || (shownFile.content_type || "").toLowerCase().includes("pdf") || (shownFile.filename || "").toLowerCase().endsWith(".pdf");
|
||||
try {
|
||||
await downloadMailPart(element.id, context, `attachments/${shownFile.index}`, downloadName(shownFile, namedPdf));
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="mail-letter">
|
||||
<p className="mail-letter__way"><DirectionColumn direction={shownDirection} />{directionWord(shownDirection) ? <span>{directionWord(shownDirection)}</span> : null}</p>
|
||||
@@ -262,8 +306,11 @@ export function MailStage({ element, context, binding, shownDirection }) {
|
||||
{shownFile && phase === "loading" ? <p className="muted">Die Anlage wird geladen …</p> : null}
|
||||
{media === "image" && blobUrl ? <img className="reader-image" alt={shownFile?.filename || element.title} src={blobUrl} /> : null}
|
||||
{media === "pdf" && pdf ? <canvas ref={canvasRef} className="reader-canvas" /> : null}
|
||||
{media === "pdf-frame" && blobUrl ? <DocumentView title={shownFile?.filename || element.title} url={blobUrl} /> : null}
|
||||
{media === "other" && blobUrl && binding?.rights?.download ? <a href={blobUrl} target="_blank" rel="noreferrer">Anlage öffnen</a> : null}
|
||||
{shownFile && phase === "ready" && binding?.rights?.download && (media === "file" || (media === "pdf" && !pdf)) ? (
|
||||
<p className="muted">
|
||||
<button type="button" onClick={saveAttachment}>{downloadName(shownFile, media === "pdf")} herunterladen</button>
|
||||
</p>
|
||||
) : null}
|
||||
{pages > 1 ? (
|
||||
<div className="reader-pages">
|
||||
<button type="button" disabled={page <= 1} onClick={() => setPage((current) => Math.max(1, current - 1))}>Vorherige Seite</button>
|
||||
|
||||
Reference in new issue
Block a user