Zeige referenzierte Paperless-Dokumente zum Ansehen und Drucken.
Deploy Development / deploy (push) Successful in 22s
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:
1 parent
0108a296bc
commit
871c7d3ad5
7 files changed
+167
-14
No files matched your search
@@ -5,19 +5,21 @@ from __future__ import annotations
|
|||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends
|
||||||
|
from fastapi.responses import Response
|
||||||
from psycopg import Connection
|
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.deps import Principal, get_conn, get_principal
|
||||||
from app.api.routes import _created, _ctx_model
|
from app.api.routes import _created, _ctx_model
|
||||||
from app.api.schemas import ConnectorIn, ExternalIn
|
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.ops import create_external
|
||||||
from app.sources import (
|
from app.sources import (
|
||||||
clean_base_url,
|
clean_base_url,
|
||||||
delete_connector,
|
delete_connector,
|
||||||
imap_messages,
|
imap_messages,
|
||||||
list_connectors,
|
list_connectors,
|
||||||
|
paperless_content,
|
||||||
paperless_documents,
|
paperless_documents,
|
||||||
probe,
|
probe,
|
||||||
save_connector,
|
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)
|
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")
|
@router.get("/api/v1/sources/paperless/documents")
|
||||||
def search_paperless(q: str = "", principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
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())}
|
return {"items": paperless_documents(conn, principal.account_id, q.strip())}
|
||||||
|
|||||||
@@ -146,6 +146,68 @@ def _paperless_count(base: str, token: str) -> int:
|
|||||||
return int(payload.get("count") or 0)
|
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:
|
def _paperless_get(base: str, token: str, path: str, params: dict) -> dict:
|
||||||
url = f"{base}{path}?{urlencode(params)}"
|
url = f"{base}{path}?{urlencode(params)}"
|
||||||
request = Request(url, headers={"Authorization": f"Token {token}", "Accept": "application/json"})
|
request = Request(url, headers={"Authorization": f"Token {token}", "Accept": "application/json"})
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@ server {
|
|||||||
server_tokens off;
|
server_tokens off;
|
||||||
client_max_body_size 21m;
|
client_max_body_size 21m;
|
||||||
|
|
||||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
|
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob:; connect-src 'self'; frame-src 'self' blob:; object-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
|
||||||
add_header X-Content-Type-Options "nosniff" always;
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
add_header X-Frame-Options "DENY" always;
|
add_header X-Frame-Options "DENY" always;
|
||||||
add_header Referrer-Policy "no-referrer" always;
|
add_header Referrer-Policy "no-referrer" always;
|
||||||
|
|||||||
@@ -67,6 +67,23 @@ export async function api(path, { method = "GET", body, form } = {}) {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function fetchPaperless(elementId, context) {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (context?.kind && context?.id) {
|
||||||
|
params.set("context_kind", context.kind);
|
||||||
|
params.set("context_id", context.id);
|
||||||
|
}
|
||||||
|
const response = await fetch(`/api/v1/external-refs/${elementId}/content?${params}`, {
|
||||||
|
credentials: "include",
|
||||||
|
headers: scopeHeaders(),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const data = await response.json().catch(() => null);
|
||||||
|
throw new Error(data?.detail || "Das Paperless-Dokument ist nicht verfügbar.");
|
||||||
|
}
|
||||||
|
return response.blob();
|
||||||
|
}
|
||||||
|
|
||||||
export async function downloadFile(elementId, context, filename) {
|
export async function downloadFile(elementId, context, filename) {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (context?.kind && context?.id) {
|
if (context?.kind && context?.id) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
|
|
||||||
export function Modal({ open, title, onClose, children }) {
|
export function Modal({ open, title, onClose, wide = false, children }) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return undefined;
|
if (!open) return undefined;
|
||||||
function onKey(event) {
|
function onKey(event) {
|
||||||
@@ -18,7 +18,7 @@ export function Modal({ open, title, onClose, children }) {
|
|||||||
if (!open) return null;
|
if (!open) return null;
|
||||||
return (
|
return (
|
||||||
<div className="modal-overlay" onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
|
<div className="modal-overlay" onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
|
||||||
<div className="modal" role="dialog" aria-modal="true" aria-label={title}>
|
<div className={wide ? "modal modal--wide" : "modal"} role="dialog" aria-modal="true" aria-label={title}>
|
||||||
<header className="modal__bar">
|
<header className="modal__bar">
|
||||||
<h2>{title}</h2>
|
<h2>{title}</h2>
|
||||||
<button type="button" className="quiet" onClick={onClose}>Schließen</button>
|
<button type="button" className="quiet" onClick={onClose}>Schließen</button>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { api, documentToText, downloadFile, markDirty, textToDocument } from "../api.js";
|
import { api, documentToText, downloadFile, fetchPaperless, markDirty, textToDocument } from "../api.js";
|
||||||
|
import { Modal } from "./Modal.jsx";
|
||||||
|
|
||||||
export function ErrorNote({ error }) {
|
export function ErrorNote({ error }) {
|
||||||
if (!error) return null;
|
if (!error) return null;
|
||||||
@@ -44,6 +45,26 @@ function Binding({ binding, context, canEdit, isOwner, onChange }) {
|
|||||||
const [targetKey, setTargetKey] = useState("");
|
const [targetKey, setTargetKey] = useState("");
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [notice, setNotice] = useState("");
|
const [notice, setNotice] = useState("");
|
||||||
|
const [previewUrl, setPreviewUrl] = useState("");
|
||||||
|
const [viewing, setViewing] = useState(false);
|
||||||
|
const frameRef = useRef(null);
|
||||||
|
|
||||||
|
useEffect(() => () => {
|
||||||
|
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||||
|
}, [previewUrl]);
|
||||||
|
|
||||||
|
async function viewPaperless() {
|
||||||
|
setError("");
|
||||||
|
setViewing(true);
|
||||||
|
try {
|
||||||
|
const blob = await fetchPaperless(element.id, context);
|
||||||
|
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||||
|
setPreviewUrl(URL.createObjectURL(blob));
|
||||||
|
} catch (err) {
|
||||||
|
setViewing(false);
|
||||||
|
setError(err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function saveNote(event) {
|
async function saveNote(event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -189,17 +210,32 @@ function Binding({ binding, context, canEdit, isOwner, onChange }) {
|
|||||||
)
|
)
|
||||||
) : null}
|
) : null}
|
||||||
{element.kind === "external_ref" && element.external ? (
|
{element.kind === "external_ref" && element.external ? (
|
||||||
<p className="ref">
|
<div className="ref">
|
||||||
{element.external.source === "paperless" ? "Paperless" : element.external.source === "imap" ? "E-Mail" : "Externe Adresse"}
|
<p>
|
||||||
{element.external.detail?.correspondent ? ` · ${element.external.detail.correspondent}` : ""}
|
{element.external.source === "paperless" ? "Paperless" : element.external.source === "imap" ? "E-Mail" : "Externe Adresse"}
|
||||||
{element.external.detail?.message_from ? ` · ${element.external.detail.message_from}` : ""}
|
{element.external.detail?.correspondent ? ` · ${element.external.detail.correspondent}` : ""}
|
||||||
{element.external.detail?.open_url ? (
|
{element.external.detail?.message_from ? ` · ${element.external.detail.message_from}` : ""}
|
||||||
<a href={element.external.detail.open_url} target="_blank" rel="noreferrer">In Paperless öffnen</a>
|
</p>
|
||||||
|
{element.external.source === "paperless" ? (
|
||||||
|
<button type="button" onClick={viewPaperless}>Ansehen</button>
|
||||||
) : (
|
) : (
|
||||||
<span>Verknüpft, ohne die Quelle zu kopieren.</span>
|
<span>Verknüpft, ohne die Quelle zu kopieren.</span>
|
||||||
)}
|
)}
|
||||||
</p>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
<Modal
|
||||||
|
open={viewing}
|
||||||
|
wide
|
||||||
|
title={element.title}
|
||||||
|
onClose={() => setViewing(false)}
|
||||||
|
>
|
||||||
|
<div className="viewer">
|
||||||
|
{previewUrl ? <iframe ref={frameRef} title={element.title} src={previewUrl} /> : <p className="muted">Dokument wird geladen …</p>}
|
||||||
|
<div className="row">
|
||||||
|
<button type="button" onClick={() => frameRef.current?.contentWindow?.print()} disabled={!previewUrl}>Drucken</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
{binding.rights.share && context ? (
|
{binding.rights.share && context ? (
|
||||||
<form onSubmit={bindElsewhere} className="inline" onFocus={loadTargets}>
|
<form onSubmit={bindElsewhere} className="inline" onFocus={loadTargets}>
|
||||||
<select value={targetKey} onChange={(event) => setTargetKey(event.target.value)} onFocus={loadTargets}>
|
<select value={targetKey} onChange={(event) => setTargetKey(event.target.value)} onFocus={loadTargets}>
|
||||||
|
|||||||
@@ -335,6 +335,8 @@ label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(-
|
|||||||
padding: 16px;
|
padding: 16px;
|
||||||
background: rgba(28, 27, 24, 0.45);
|
background: rgba(28, 27, 24, 0.45);
|
||||||
}
|
}
|
||||||
|
.viewer { display: grid; gap: 12px; }
|
||||||
|
.viewer iframe { width: 100%; height: 72vh; border: 0; background: #fff; border-radius: 8px; }
|
||||||
.modal {
|
.modal {
|
||||||
width: min(520px, 100%);
|
width: min(520px, 100%);
|
||||||
max-height: min(86vh, 760px);
|
max-height: min(86vh, 760px);
|
||||||
@@ -346,6 +348,7 @@ label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(-
|
|||||||
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.18);
|
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.18);
|
||||||
}
|
}
|
||||||
.modal__bar { display: flex; justify-content: space-between; gap: 12px; align-items: center; margin-bottom: 14px; }
|
.modal__bar { display: flex; justify-content: space-between; gap: 12px; align-items: center; margin-bottom: 14px; }
|
||||||
|
.modal.modal--wide { width: min(960px, 100%); }
|
||||||
.modal h2 { font-size: 18px; color: var(--text1); text-transform: none; letter-spacing: 0; margin: 0; }
|
.modal h2 { font-size: 18px; color: var(--text1); text-transform: none; letter-spacing: 0; margin: 0; }
|
||||||
.modal h3 { font-size: 13px; }
|
.modal h3 { font-size: 13px; }
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user