Lade eine uebernommene E-Mail bei Bedarf vollstaendig, damit Anzeige und Export nicht an der Vorschau haengen.
Deploy Development / deploy (push) Successful in 27s
Test Suite / pytest-backend (push) Failing after 1m10s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 10s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-17 18:59:18 +02:00
1 parent 17a3b3a736
commit 7626c56f3d
7 files changed
+740 -19

No files matched your search

+133 -5
View File
@@ -20,6 +20,7 @@ from psycopg.types.json import Json
from app.core.errors import Problem, not_found, unprocessable
from app.core.settings import get_settings
from app.mailpack import MailIdentityError, choose_message, identities_match, header_message_id
from app.media.storage import sniff
@@ -227,7 +228,12 @@ def paperless_content(conn, owner_id: UUID, document_id: str) -> tuple[bytes, st
raise unprocessable("Paperless stellt diese Datei nicht zum Ansehen bereit.")
def _paperless_file(base: str, token: str, path: str) -> tuple[bytes, str, str] | None:
def _paperless_file(
base: str,
token: str,
path: str,
max_bytes: int = 40 * 1024 * 1024,
) -> tuple[bytes, str, str] | None:
request = Request(
f"{base}{path}",
headers={"Authorization": f"Token {token}", "Accept": "application/pdf, image/*, */*"},
@@ -238,8 +244,10 @@ def _paperless_file(base: str, token: str, path: str) -> tuple[bytes, str, str]
allowed = urlparse(base)
if final.scheme not in {"http", "https"} or final.netloc != allowed.netloc:
raise unprocessable("Paperless hat auf eine fremde Adresse verwiesen.")
data = response.read(40 * 1024 * 1024 + 1)
if len(data) > 40 * 1024 * 1024:
data = response.read(max_bytes + 1)
if len(data) > max_bytes:
if max_bytes > 40 * 1024 * 1024:
raise unprocessable("Die Originaldatei ist für den Export zu groß.")
raise unprocessable("Die Datei ist zum Ansehen in Tsumugu zu groß.")
media = (response.headers.get("Content-Type") or "application/octet-stream").split(";")[0].strip()
return data, media, _filename(response.headers.get("Content-Disposition"))
@@ -305,7 +313,12 @@ def _paperless_from_disk(document_id: str, meta: dict) -> tuple[bytes, str, str]
return None
def read_paperless_file(media_root: str, kind: str, relative: str) -> bytes | None:
def read_paperless_file(
media_root: str,
kind: str,
relative: str,
max_bytes: int = 40 * 1024 * 1024,
) -> bytes | None:
if kind not in {"archive", "originals"}:
return None
raw = relative.replace("\\", "/").strip()
@@ -318,7 +331,9 @@ def read_paperless_file(media_root: str, kind: str, relative: str) -> bytes | No
if not target.is_file():
return None
data = target.read_bytes()
if len(data) > 40 * 1024 * 1024:
if len(data) > max_bytes:
if max_bytes > 40 * 1024 * 1024:
raise unprocessable("Die Originaldatei ist für den Export zu groß.")
raise unprocessable("Die Datei ist zum Ansehen in Tsumugu zu groß.")
return data
@@ -748,3 +763,116 @@ def _decode(value: str | None) -> str:
else:
parts.append(text)
return "".join(parts).strip()
def pull_paperless_original(base: str, token: str, document_id: str, max_bytes: int) -> tuple[bytes, str, str]:
"""Original download only. A preview is never returned in its place."""
if not document_id.isdigit() or len(document_id) > 12:
raise unprocessable("Die Paperless-Nummer ist ungültig.")
fetched = _paperless_file(base, token, f"/api/documents/{document_id}/download/", max_bytes)
if fetched is not None:
data, media, name = fetched
return data, media or "application/octet-stream", name or f"paperless-{document_id}"
meta = _paperless_metadata(base, token, document_id)
if meta is None:
raise unprocessable("Dieses Dokument gibt es in Paperless nicht.")
local = _paperless_original_from_disk(meta, max_bytes)
if local is None:
raise unprocessable(
"Das Paperless-Original ist nicht verfügbar. Eine Vorschau wird nicht als Original übernommen."
)
return local
def _paperless_original_from_disk(meta: dict, max_bytes: int) -> tuple[bytes, str, str] | None:
root = get_settings().paperless_media_root.strip()
original_name = meta.get("media_filename")
if not root or not isinstance(original_name, str) or not original_name.strip():
return None
data = read_paperless_file(root, "originals", original_name, max_bytes)
if data is None:
return None
return data, "application/octet-stream", Path(original_name).name
COMPLETE_MAIL_LIMIT = 80 * 1024 * 1024
def load_imap_original(conn, owner_id: UUID, connector_id: UUID, mailbox: str, uid: int, expected_id: str) -> bytes:
"""The referenced message in full. A preview is not returned in its place."""
row = _owned(conn, owner_id, connector_id)
if row["kind"] != "imap":
raise unprocessable("Das ist kein E-Mail-Konto.")
return pull_rfc822(row["settings"], row["secret"], mailbox, uid, expected_id, COMPLETE_MAIL_LIMIT)
def pull_rfc822(settings: dict, secret: str, mailbox: str, uid: int, expected_id: str, max_bytes: int) -> bytes:
"""Fetch the referenced message. A different message at the old UID is not returned."""
client = _imap_login(settings, secret)
try:
_select_mailbox(client, mailbox)
candidate = _fetch_rfc822(client, uid)
if candidate is not None and len(candidate) > max_bytes:
raise unprocessable(
"Die vollständige Nachricht überschreitet die Exportgrenze. "
"Eine gekürzte Vorschau wird nicht als Original übernommen."
)
alternates: list[bytes] = []
if candidate is None or not identities_match(header_message_id(candidate), expected_id):
alternates = _search_rfc822(client, expected_id, max_bytes)
try:
chosen = choose_message(candidate, alternates, expected_id)
except MailIdentityError as exc:
raise unprocessable(exc.message) from exc
if len(chosen) > max_bytes:
raise unprocessable(
"Die vollständige Nachricht überschreitet die Exportgrenze. "
"Eine gekürzte Vorschau wird nicht als Original übernommen."
)
return chosen
finally:
_imap_logout(client)
def _fetch_rfc822(client: imaplib.IMAP4, uid: int) -> bytes | None:
try:
status, fetched = client.uid("FETCH", str(uid), "(BODY.PEEK[])")
except imaplib.IMAP4.error:
return None
if status != "OK":
return None
return _literal(fetched)
def _search_rfc822(client: imaplib.IMAP4, expected_id: str, max_bytes: int) -> list[bytes]:
token = (expected_id or "").strip()
if not token or token.casefold().startswith("uid:"):
return []
found: list[bytes] = []
for folder in _imap_mailboxes(client):
if not folder["selectable"]:
continue
try:
_select_mailbox(client, folder["name"])
status, data = client.uid("SEARCH", "HEADER", "Message-ID", token)
except (imaplib.IMAP4.error, Problem):
continue
if status != "OK" or not data or not data[0]:
continue
for raw_uid in data[0].split():
try:
uid = int(raw_uid)
except ValueError:
continue
blob = _fetch_rfc822(client, uid)
if blob is None:
continue
if len(blob) > max_bytes:
raise unprocessable(
"Die vollständige Nachricht überschreitet die Exportgrenze. "
"Eine gekürzte Vorschau wird nicht als Original übernommen."
)
found.append(blob)
if len(found) > 5:
return found
return found