Zeige referenzierte Paperless-Dokumente zum Ansehen und Drucken.
Deploy Development / deploy (push) Successful in 22s

Die Datei bleibt in Paperless. Tsumugu laedt sie nur fuer die Ansicht und speichert keine Kopie.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-16 22:42:24 +02:00
1 parent 0108a296bc
commit 871c7d3ad5
7 files changed
+167 -14

No files matched your search

+62
View File
@@ -146,6 +146,68 @@ def _paperless_count(base: str, token: str) -> int:
return int(payload.get("count") or 0)
def paperless_content(conn, owner_id: UUID, document_id: str) -> tuple[bytes, str, str]:
if not document_id.isdigit() or len(document_id) > 12:
raise unprocessable("Die Paperless-Nummer ist ungültig.")
row = conn.execute(
"""
SELECT settings, secret FROM connectors
WHERE owner_id = %s AND kind = 'paperless'
ORDER BY created_at DESC LIMIT 1
""",
(owner_id,),
).fetchone()
if row is None:
raise unprocessable("Paperless ist für dieses Konto nicht verbunden.")
base = row["settings"]["base_url"].rstrip("/")
token = row["secret"]
for suffix in ("preview", "download"):
fetched = _paperless_file(base, token, f"/api/documents/{document_id}/{suffix}/")
if fetched is None:
continue
data, media, name = fetched
if media.startswith("application/pdf") or media.startswith("image/"):
return data, media, name or f"paperless-{document_id}.pdf"
raise unprocessable("Paperless stellt diese Datei nicht zum Ansehen bereit.")
def _paperless_file(base: str, token: str, path: str) -> tuple[bytes, str, str] | None:
request = Request(
f"{base}{path}",
headers={"Authorization": f"Token {token}", "Accept": "application/pdf, image/*, */*"},
)
try:
with urlopen(request, timeout=30) as response:
final = urlparse(response.geturl())
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:
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"))
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) as exc:
raise unprocessable("Paperless ist nicht erreichbar.") from exc
def _filename(disposition: str | None) -> str:
if not disposition:
return ""
marker = "filename="
lower = disposition.lower()
if marker not in lower:
return ""
value = disposition[lower.index(marker) + len(marker):].split(";")[0].strip().strip('"')
return value.replace("\\", "").replace("/", "")[:180]
def _paperless_get(base: str, token: str, path: str, params: dict) -> dict:
url = f"{base}{path}?{urlencode(params)}"
request = Request(url, headers={"Authorization": f"Token {token}", "Accept": "application/json"})