Lies Paperless-Dateien aus dem Ablageordner, wenn die Vorschau keine anzeigbare Datei liefert.
Deploy Development / deploy (push) Failing after 39s

Eine unbekannte Dokumentnummer wird als solche gemeldet.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-17 07:12:35 +02:00
1 parent 4420790707
commit b328385561
6 files changed
+114 -5

No files matched your search

+86 -4
View File
@@ -7,6 +7,7 @@ import json
import ssl
from email.header import decode_header
from email.parser import BytesParser
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlparse
from urllib.request import Request, urlopen
@@ -14,7 +15,9 @@ from uuid import UUID
from psycopg.types.json import Json
from app.core.errors import not_found, unprocessable
from app.core.errors import Problem, not_found, unprocessable
from app.core.settings import get_settings
from app.media.storage import sniff
def save_connector(conn, owner_id: UUID, kind: str, name: str, settings: dict, secret: str) -> dict:
@@ -161,13 +164,22 @@ def paperless_content(conn, owner_id: UUID, document_id: str) -> tuple[bytes, st
raise unprocessable("Paperless ist für dieses Konto nicht verbunden.")
base = row["settings"]["base_url"].rstrip("/")
token = row["secret"]
misses = 0
for suffix in ("preview", "download"):
fetched = _paperless_file(base, token, f"/api/documents/{document_id}/{suffix}/")
if fetched is None:
misses += 1
continue
data, media, name = fetched
if media.startswith("application/pdf") or media.startswith("image/"):
return data, media, name or f"paperless-{document_id}.pdf"
viewable = _viewable(fetched[0], fetched[1], fetched[2], document_id)
if viewable is not None:
return viewable
meta = _paperless_metadata(base, token, document_id)
if meta is None and misses == 2:
raise unprocessable("Dieses Dokument gibt es in Paperless nicht.")
if meta is not None:
local = _paperless_from_disk(document_id, meta)
if local is not None:
return local
raise unprocessable("Paperless stellt diese Datei nicht zum Ansehen bereit.")
@@ -197,6 +209,76 @@ def _paperless_file(base: str, token: str, path: str) -> tuple[bytes, str, str]
raise unprocessable("Paperless ist nicht erreichbar.") from exc
def _viewable(data: bytes, media: str, name: str, document_id: str) -> tuple[bytes, str, str] | None:
media = media.split(";")[0].strip().lower()
if not (media.startswith("application/pdf") or media.startswith("image/")):
try:
media = sniff(data)
except Problem:
return None
if media.startswith("application/pdf") or media.startswith("image/"):
return data, media, name or f"paperless-{document_id}.pdf"
return None
def _paperless_metadata(base: str, token: str, document_id: str) -> dict | None:
request = Request(
f"{base}/api/documents/{document_id}/metadata/",
headers={"Authorization": f"Token {token}", "Accept": "application/json"},
)
try:
with urlopen(request, timeout=20) as response:
payload = json.loads(response.read().decode("utf-8"))
except HTTPError as exc:
if exc.code == 404:
return None
if exc.code in {401, 403}:
raise unprocessable("Paperless hat den Schlüssel abgelehnt.") from exc
raise unprocessable("Paperless hat die Datei nicht bereitgestellt.") from exc
except (URLError, TimeoutError, json.JSONDecodeError) as exc:
raise unprocessable("Paperless ist nicht erreichbar.") from exc
return payload if isinstance(payload, dict) else None
def _paperless_from_disk(document_id: str, meta: dict) -> tuple[bytes, str, str] | None:
root = get_settings().paperless_media_root.strip()
if not root:
return None
candidates: list[tuple[str, str]] = []
archive_name = meta.get("archive_media_filename")
if meta.get("has_archive_version") and isinstance(archive_name, str) and archive_name.strip():
candidates.append(("archive", archive_name))
original_name = meta.get("media_filename")
if isinstance(original_name, str) and original_name.strip():
candidates.append(("originals", original_name))
for kind, relative in candidates:
data = read_paperless_file(root, kind, relative)
if data is None:
continue
viewable = _viewable(data, "application/octet-stream", Path(relative).name, document_id)
if viewable is not None:
return viewable
return None
def read_paperless_file(media_root: str, kind: str, relative: str) -> bytes | None:
if kind not in {"archive", "originals"}:
return None
raw = relative.replace("\\", "/").strip()
if not raw or raw.startswith("/") or ".." in Path(raw).parts:
return None
base = (Path(media_root) / "documents" / kind).resolve()
target = (base / raw).resolve()
if target != base and base not in target.parents:
return None
if not target.is_file():
return None
data = target.read_bytes()
if len(data) > 40 * 1024 * 1024:
raise unprocessable("Die Datei ist zum Ansehen in Tsumugu zu groß.")
return data
def _filename(disposition: str | None) -> str:
if not disposition:
return ""