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):
|
if index < 0 or index >= len(parsed.attachments):
|
||||||
raise not_found()
|
raise not_found()
|
||||||
item = parsed.attachments[index]
|
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:
|
def _mail_bytes(data: bytes, media_type: str, filename: str, inline: bool = False) -> Response:
|
||||||
disposition = content_disposition(filename)
|
disposition = content_disposition(filename, inline=inline)
|
||||||
if inline:
|
|
||||||
disposition = disposition.replace("attachment;", "inline;", 1)
|
|
||||||
return Response(
|
return Response(
|
||||||
content=data,
|
content=data,
|
||||||
media_type=media_type,
|
media_type=media_type,
|
||||||
|
|||||||
+47
-3
@@ -6,6 +6,7 @@ The same tree feeds preview, reading, attachment download and export.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
import hashlib
|
import hashlib
|
||||||
import html
|
import html
|
||||||
import re
|
import re
|
||||||
@@ -164,9 +165,13 @@ def parse_mail(raw: bytes) -> ParsedMail:
|
|||||||
missing.append(label or f"Anlage {index}")
|
missing.append(label or f"Anlage {index}")
|
||||||
notices.append(f"Die Anlage {label or index} ließ sich nicht vollständig lesen.")
|
notices.append(f"Die Anlage {label or index} ließ sich nicht vollständig lesen.")
|
||||||
continue
|
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)
|
name = _unique_filename(label or f"anlage-{index}.bin", used)
|
||||||
inline = disposition == "inline" or bool(content_id)
|
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()
|
simplified = "\n".join(chunk for chunk in plain if chunk).strip()
|
||||||
rendered = ""
|
rendered = ""
|
||||||
if html_parts:
|
if html_parts:
|
||||||
@@ -410,10 +415,49 @@ def _content_id(part: EmailMessage) -> str:
|
|||||||
return token
|
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(
|
return AttachmentBytes(
|
||||||
filename=filename,
|
filename=filename,
|
||||||
media_type=(part.get_content_type() or "application/octet-stream")[:120],
|
media_type=(resolved or "application/octet-stream")[:120],
|
||||||
data=data,
|
data=data,
|
||||||
sha256=hashlib.sha256(data).hexdigest(),
|
sha256=hashlib.sha256(data).hexdigest(),
|
||||||
display_name=label or filename,
|
display_name=label or filename,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from urllib.parse import quote
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from app.core.errors import storage_unavailable, unprocessable
|
from app.core.errors import storage_unavailable, unprocessable
|
||||||
@@ -66,10 +67,17 @@ def display_filename(name: str) -> str:
|
|||||||
return text[:240]
|
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."""
|
"""The real name goes along in UTF-8 (RFC 5987), with a plain ASCII fallback for old clients."""
|
||||||
from urllib.parse import quote
|
name = display_filename(filename)
|
||||||
|
kind = "inline" if inline else "attachment"
|
||||||
safe = display_filename(filename).replace('"', "")
|
suffix = ""
|
||||||
fallback = safe.encode("ascii", "replace").decode("ascii").replace("?", "_")
|
leaf = name.rsplit(".", 1)
|
||||||
return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(safe, safe='')}"
|
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"
|
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:
|
class QuotedIMAP:
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
self.untagged_responses = {}
|
self.untagged_responses = {}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { DocumentView } from "../pages/DocumentView.jsx";
|
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { api, documentToText, downloadMailPart, fetchExternal, fetchMailPart, markDirty, textToDocument } from "../api.js";
|
import { api, documentToText, downloadMailPart, fetchExternal, fetchMailPart, markDirty, textToDocument } from "../api.js";
|
||||||
import { MailAttachments, MailBody } from "../mail-view.jsx";
|
import { MailAttachments, MailBody } from "../mail-view.jsx";
|
||||||
@@ -17,6 +16,18 @@ function previewKind(type, filename) {
|
|||||||
return "other";
|
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 }) {
|
export function NoteStage({ element, context, binding, onReload }) {
|
||||||
const editor = editors.note;
|
const editor = editors.note;
|
||||||
const [text, setText] = useState(() => documentToText(element.document));
|
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]);
|
}, [element.id, element.external?.source, context?.kind, context?.id]);
|
||||||
|
|
||||||
useEffect(() => {
|
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);
|
const file = (letter?.attachments || []).find((item) => item.index === shownIndex);
|
||||||
if (!file) return undefined;
|
if (!file) return undefined;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
setPhase("loading");
|
setPhase("loading");
|
||||||
|
setPdf(null);
|
||||||
|
setPages(0);
|
||||||
|
setPage(1);
|
||||||
|
setMedia("");
|
||||||
fetchMailPart(element.id, context, `attachments/${file.index}`).then(async (blob) => {
|
fetchMailPart(element.id, context, `attachments/${file.index}`).then(async (blob) => {
|
||||||
if (!alive) return;
|
if (!alive) return;
|
||||||
if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
|
const buffer = await blob.arrayBuffer();
|
||||||
const url = URL.createObjectURL(blob);
|
if (!alive) return;
|
||||||
objectUrl.current = url;
|
const declared = previewKind(blob.type || file.content_type, file.filename);
|
||||||
setBlobUrl(url);
|
const kind = isPdfBytes(buffer) ? "pdf" : declared;
|
||||||
const kind = previewKind(blob.type || file.content_type, file.filename);
|
if (objectUrl.current) {
|
||||||
|
URL.revokeObjectURL(objectUrl.current);
|
||||||
|
objectUrl.current = "";
|
||||||
|
}
|
||||||
|
setBlobUrl("");
|
||||||
if (kind === "image") {
|
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");
|
setMedia("image");
|
||||||
setPhase("ready");
|
setPhase("ready");
|
||||||
return;
|
return;
|
||||||
@@ -182,10 +215,9 @@ export function MailStage({ element, context, binding, shownDirection }) {
|
|||||||
if (kind === "pdf") {
|
if (kind === "pdf") {
|
||||||
setMedia("pdf");
|
setMedia("pdf");
|
||||||
try {
|
try {
|
||||||
const bytes = await blob.arrayBuffer();
|
|
||||||
const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
|
const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
|
||||||
pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
|
pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
|
||||||
const doc = await pdfjs.getDocument({ data: bytes }).promise;
|
const doc = await pdfjs.getDocument({ data: new Uint8Array(buffer) }).promise;
|
||||||
if (!alive) {
|
if (!alive) {
|
||||||
doc.destroy();
|
doc.destroy();
|
||||||
return;
|
return;
|
||||||
@@ -195,16 +227,17 @@ export function MailStage({ element, context, binding, shownDirection }) {
|
|||||||
setPhase("ready");
|
setPhase("ready");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!alive) return;
|
if (!alive) return;
|
||||||
setMedia("pdf-frame");
|
setPdf(null);
|
||||||
setPhase("ready");
|
setPhase("ready");
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setMedia("other");
|
setMedia("file");
|
||||||
setPhase("ready");
|
setPhase("ready");
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
if (!alive) return;
|
if (!alive) return;
|
||||||
setPhase("ready");
|
setPhase("ready");
|
||||||
|
setMedia("");
|
||||||
setError(err.message || "Die Anlage ist nicht verfügbar.");
|
setError(err.message || "Die Anlage ist nicht verfügbar.");
|
||||||
});
|
});
|
||||||
return () => {
|
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 (
|
return (
|
||||||
<article className="mail-letter">
|
<article className="mail-letter">
|
||||||
<p className="mail-letter__way"><DirectionColumn direction={shownDirection} />{directionWord(shownDirection) ? <span>{directionWord(shownDirection)}</span> : null}</p>
|
<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}
|
{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 === "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" && pdf ? <canvas ref={canvasRef} className="reader-canvas" /> : null}
|
||||||
{media === "pdf-frame" && blobUrl ? <DocumentView title={shownFile?.filename || element.title} url={blobUrl} /> : null}
|
{shownFile && phase === "ready" && binding?.rights?.download && (media === "file" || (media === "pdf" && !pdf)) ? (
|
||||||
{media === "other" && blobUrl && binding?.rights?.download ? <a href={blobUrl} target="_blank" rel="noreferrer">Anlage öffnen</a> : null}
|
<p className="muted">
|
||||||
|
<button type="button" onClick={saveAttachment}>{downloadName(shownFile, media === "pdf")} herunterladen</button>
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
{pages > 1 ? (
|
{pages > 1 ? (
|
||||||
<div className="reader-pages">
|
<div className="reader-pages">
|
||||||
<button type="button" disabled={page <= 1} onClick={() => setPage((current) => Math.max(1, current - 1))}>Vorherige Seite</button>
|
<button type="button" disabled={page <= 1} onClick={() => setPage((current) => Math.max(1, current - 1))}>Vorherige Seite</button>
|
||||||
|
|||||||
Reference in new issue
Block a user