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

+37 -2
View File
@@ -5,19 +5,21 @@ from __future__ import annotations
from uuid import UUID
from fastapi import APIRouter, Depends
from fastapi.responses import Response
from psycopg import Connection
from app.access.policy import Ctx
from app.access.policy import Ctx, element_rights, get_element, parse_query_context
from app.api.deps import Principal, get_conn, get_principal
from app.api.routes import _created, _ctx_model
from app.api.schemas import ConnectorIn, ExternalIn
from app.core.errors import unprocessable
from app.core.errors import not_found, unprocessable
from app.ops import create_external
from app.sources import (
clean_base_url,
delete_connector,
imap_messages,
list_connectors,
paperless_content,
paperless_documents,
probe,
save_connector,
@@ -48,6 +50,39 @@ def probe_connector(connector_id: UUID, principal: Principal = Depends(get_princ
return probe(conn, principal.account_id, connector_id)
@router.get("/api/v1/external-refs/{element_id}/content")
def view_paperless(
element_id: UUID,
context_kind: str | None = None,
context_id: str | None = None,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
element = get_element(conn, element_id)
if element is None or element["kind"] != "external_ref":
raise not_found()
rights = element_rights(conn, principal.account_id, element, parse_query_context(context_kind, context_id))
if not rights.read:
raise not_found()
ref = conn.execute(
"SELECT source, external_id FROM external_references WHERE element_id = %s",
(element_id,),
).fetchone()
if ref is None or ref["source"] != "paperless":
raise unprocessable("Nur ein Paperless-Dokument lässt sich hier ansehen.")
data, media_type, filename = paperless_content(conn, principal.account_id, ref["external_id"])
safe_name = (filename or f"paperless-{ref['external_id']}.pdf").replace('"', "")
return Response(
content=data,
media_type=media_type,
headers={
"Content-Disposition": f'inline; filename="{safe_name}"',
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, no-store",
},
)
@router.get("/api/v1/sources/paperless/documents")
def search_paperless(q: str = "", principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
return {"items": paperless_documents(conn, principal.account_id, q.strip())}
+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"})