585 lines
21 KiB
React
585 lines
21 KiB
React
import { useEffect, useState } from "react";
|
|
import { Link } from "react-router-dom";
|
|
import { api } from "../api.js";
|
|
import { TargetLine, formatDate } from "./content.jsx";
|
|
import { NavIcon } from "./icons.jsx";
|
|
import { ErrorNote } from "./widgets.jsx";
|
|
|
|
export function Sources() {
|
|
const [items, setItems] = useState([]);
|
|
const [error, setError] = useState("");
|
|
const [notice, setNotice] = useState("");
|
|
|
|
async function load() {
|
|
const data = await api("/api/v1/connectors");
|
|
setItems(data.items);
|
|
}
|
|
|
|
useEffect(() => {
|
|
load().catch((err) => setError(err.message));
|
|
}, []);
|
|
|
|
return (
|
|
<main className="page">
|
|
<header className="page-head">
|
|
<div>
|
|
<h1>Quellen</h1>
|
|
<p className="muted">Paperless und E-Mail-Konten bleiben bei dir. Eine Verknüpfung zeigt in der Akte nur Titel und Herkunft.</p>
|
|
</div>
|
|
</header>
|
|
<ErrorNote error={error} />
|
|
{notice ? <p className="notice">{notice}</p> : null}
|
|
<div className="tiles">
|
|
{items.map((item) => (
|
|
<article key={item.id} className="tile">
|
|
<span className="tile__kind">{item.kind === "paperless" ? "Paperless" : "IMAP"}</span>
|
|
<strong>{item.name}</strong>
|
|
<span>{item.kind === "paperless" ? item.settings.base_url : item.settings.username}</span>
|
|
<div className="row">
|
|
<button type="button" className="quiet" onClick={() => probe(item.id, setNotice, setError)}>Prüfen</button>
|
|
<button type="button" className="danger" onClick={() => remove(item.id, load, setError)}>Entfernen</button>
|
|
</div>
|
|
</article>
|
|
))}
|
|
</div>
|
|
<section className="card">
|
|
<h2>Paperless</h2>
|
|
<PaperlessForm onSaved={load} onError={setError} />
|
|
</section>
|
|
<section className="card">
|
|
<h2>E-Mail-Konto</h2>
|
|
<MailForm onSaved={load} onError={setError} />
|
|
</section>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
function PaperlessForm({ onSaved, onError }) {
|
|
const [name, setName] = useState("Paperless");
|
|
const [baseUrl, setBaseUrl] = useState("");
|
|
const [token, setToken] = useState("");
|
|
|
|
async function submit(event) {
|
|
event.preventDefault();
|
|
onError("");
|
|
try {
|
|
await api("/api/v1/connectors", {
|
|
method: "POST",
|
|
body: { kind: "paperless", name, base_url: baseUrl, token },
|
|
});
|
|
setToken("");
|
|
await onSaved();
|
|
} catch (err) {
|
|
onError(err.message);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<form onSubmit={submit} className="stack">
|
|
<label>Name <input value={name} onChange={(event) => setName(event.target.value)} required /></label>
|
|
<label>Adresse <input value={baseUrl} onChange={(event) => setBaseUrl(event.target.value)} placeholder="https://paperless.example" required /></label>
|
|
<label>API-Schlüssel <input type="password" value={token} onChange={(event) => setToken(event.target.value)} autoComplete="off" required /></label>
|
|
<button type="submit">Paperless verbinden</button>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
function MailForm({ onSaved, onError }) {
|
|
const [name, setName] = useState("");
|
|
const [host, setHost] = useState("");
|
|
const [port, setPort] = useState("993");
|
|
const [username, setUsername] = useState("");
|
|
const [password, setPassword] = useState("");
|
|
const [security, setSecurity] = useState("ssl");
|
|
|
|
async function submit(event) {
|
|
event.preventDefault();
|
|
onError("");
|
|
try {
|
|
await api("/api/v1/connectors", {
|
|
method: "POST",
|
|
body: {
|
|
kind: "imap",
|
|
name: name || username,
|
|
host,
|
|
port: Number(port),
|
|
username,
|
|
password,
|
|
security,
|
|
mailbox: "INBOX",
|
|
},
|
|
});
|
|
setPassword("");
|
|
await onSaved();
|
|
} catch (err) {
|
|
onError(err.message);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<form onSubmit={submit} className="stack">
|
|
<label>Name <input value={name} onChange={(event) => setName(event.target.value)} placeholder="Postfach" /></label>
|
|
<label>Server <input value={host} onChange={(event) => setHost(event.target.value)} placeholder="imap.example" required /></label>
|
|
<label>Port <input value={port} onChange={(event) => setPort(event.target.value)} required /></label>
|
|
<label>
|
|
Verbindung
|
|
<select value={security} onChange={(event) => setSecurity(event.target.value)}>
|
|
<option value="ssl">SSL</option>
|
|
<option value="starttls">STARTTLS</option>
|
|
</select>
|
|
</label>
|
|
<label>Benutzername <input value={username} onChange={(event) => setUsername(event.target.value)} required /></label>
|
|
<label>Passwort <input type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete="off" required /></label>
|
|
<button type="submit">Konto hinzufügen</button>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
export function PaperlessPicker({ context, placement, chapterId = "", chapterTitle = "", targetLabel = "", onDone }) {
|
|
const [query, setQuery] = useState("");
|
|
const [items, setItems] = useState([]);
|
|
const [error, setError] = useState("");
|
|
|
|
async function search(event) {
|
|
event.preventDefault();
|
|
setError("");
|
|
try {
|
|
const data = await api(`/api/v1/sources/paperless/documents?q=${encodeURIComponent(query)}`);
|
|
setItems(data.items);
|
|
} catch (err) {
|
|
setError(err.message);
|
|
}
|
|
}
|
|
|
|
async function link(item) {
|
|
setError("");
|
|
try {
|
|
await api("/api/v1/external-refs", {
|
|
method: "POST",
|
|
body: {
|
|
title: item.title,
|
|
source: "paperless",
|
|
external_id: item.id,
|
|
context,
|
|
...(placement ? { placement } : {}),
|
|
...(chapterId ? { chapter_id: chapterId } : {}),
|
|
...(item.document_on || item.correspondent || item.open_url
|
|
? {
|
|
dates: { document_on: item.document_on || null, sent_on: null, received_on: null },
|
|
detail: {
|
|
...(item.correspondent ? { correspondent: item.correspondent } : {}),
|
|
...(item.open_url ? { open_url: item.open_url } : {}),
|
|
},
|
|
}
|
|
: {}),
|
|
},
|
|
});
|
|
onDone();
|
|
} catch (err) {
|
|
setError(err.message);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="stack">
|
|
<TargetLine label={targetLabel} chapterId={chapterId} chapterTitle={chapterTitle} />
|
|
<form onSubmit={search} className="inline">
|
|
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Titel oder Stichwort" />
|
|
<button type="submit">Suchen</button>
|
|
</form>
|
|
<ErrorNote error={error} />
|
|
<p className="muted">Die Verbindung richtest du unter <Link to="/sources">Quellen</Link> ein.</p>
|
|
<div className="stack">
|
|
{items.map((item) => (
|
|
<button key={item.id} type="button" className="quiet" onClick={() => link(item)}>{item.title}</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function folderTree(folders) {
|
|
const roots = [];
|
|
const stack = [];
|
|
for (const folder of folders) {
|
|
const node = { ...folder, children: [] };
|
|
while (stack.length && stack[stack.length - 1].depth >= folder.depth) stack.pop();
|
|
if (stack.length) stack[stack.length - 1].node.children.push(node);
|
|
else roots.push(node);
|
|
stack.push({ depth: folder.depth, node });
|
|
}
|
|
return roots;
|
|
}
|
|
|
|
function ancestorNames(folders, name) {
|
|
const folder = folders.find((item) => item.name === name);
|
|
if (!folder?.delimiter || !name.includes(folder.delimiter)) return [];
|
|
const parts = name.split(folder.delimiter);
|
|
const names = [];
|
|
for (let index = 1; index < parts.length; index += 1) names.push(parts.slice(0, index).join(folder.delimiter));
|
|
return names;
|
|
}
|
|
|
|
function FolderBranch({ node, mailbox, path, expanded, onToggle, onSelect }) {
|
|
const open = expanded.has(node.name);
|
|
const current = node.name === mailbox;
|
|
const onPath = path.has(node.name);
|
|
const rowClass = current ? "folder-row is-current" : onPath ? "folder-row is-ancestor" : "folder-row";
|
|
return (
|
|
<li>
|
|
<div className={rowClass}>
|
|
{node.children.length ? (
|
|
<button type="button" className="folder-twist" aria-expanded={open} aria-label={open ? `${node.label} zuklappen` : `${node.label} aufklappen`} onClick={() => onToggle(node.name)}>
|
|
{open ? "▾" : "▸"}
|
|
</button>
|
|
) : <span className="folder-twist" aria-hidden="true" />}
|
|
{node.selectable ? (
|
|
<button type="button" className="folder-name" aria-current={current ? "true" : undefined} onClick={() => onSelect(node.name)}>
|
|
<NavIcon name="folder" />
|
|
<span>{node.label}</span>
|
|
</button>
|
|
) : (
|
|
<span className="folder-name"><NavIcon name="folder" /><span>{node.label}</span></span>
|
|
)}
|
|
</div>
|
|
{node.children.length && open ? (
|
|
<ul>
|
|
{node.children.map((child) => (
|
|
<FolderBranch key={child.name} node={child} mailbox={mailbox} path={path} expanded={expanded} onToggle={onToggle} onSelect={onSelect} />
|
|
))}
|
|
</ul>
|
|
) : null}
|
|
</li>
|
|
);
|
|
}
|
|
|
|
function MailFiles({ files }) {
|
|
if (!files?.length) return <p className="muted">Keine Anhänge.</p>;
|
|
return (
|
|
<ul className="mail-files">
|
|
{files.map((file) => <li key={file.filename}>{file.filename}</li>)}
|
|
</ul>
|
|
);
|
|
}
|
|
|
|
function FolderTree({ folders, mailbox, onSelect }) {
|
|
const [expanded, setExpanded] = useState(() => new Set());
|
|
useEffect(() => {
|
|
setExpanded((current) => {
|
|
const next = new Set(current);
|
|
for (const name of ancestorNames(folders, mailbox)) next.add(name);
|
|
return next;
|
|
});
|
|
}, [folders, mailbox]);
|
|
const roots = folderTree(folders);
|
|
const path = new Set([mailbox, ...ancestorNames(folders, mailbox)]);
|
|
function toggle(name) {
|
|
setExpanded((current) => {
|
|
const next = new Set(current);
|
|
if (next.has(name)) next.delete(name);
|
|
else next.add(name);
|
|
return next;
|
|
});
|
|
}
|
|
if (!roots.length) return <p className="muted">Keine Fächer.</p>;
|
|
return (
|
|
<nav className="mailbox__folders" aria-label="Fächer">
|
|
<ul className="folder-tree">
|
|
{roots.map((node) => (
|
|
<FolderBranch key={node.name} node={node} mailbox={mailbox} path={path} expanded={expanded} onToggle={toggle} onSelect={onSelect} />
|
|
))}
|
|
</ul>
|
|
</nav>
|
|
);
|
|
}
|
|
|
|
export function MailPicker({ context, placement, chapterId = "", chapterTitle = "", targetLabel = "", onDone }) {
|
|
const [accounts, setAccounts] = useState([]);
|
|
const [accountId, setAccountId] = useState("");
|
|
const [folders, setFolders] = useState([]);
|
|
const [mailbox, setMailbox] = useState("");
|
|
const [draft, setDraft] = useState("");
|
|
const [query, setQuery] = useState("");
|
|
const [items, setItems] = useState([]);
|
|
const [nextBefore, setNextBefore] = useState(null);
|
|
const [selectedKey, setSelectedKey] = useState("");
|
|
const [preview, setPreview] = useState(null);
|
|
const [previewError, setPreviewError] = useState("");
|
|
const [adopting, setAdopting] = useState(false);
|
|
const [loading, setLoading] = useState("");
|
|
const [error, setError] = useState("");
|
|
|
|
useEffect(() => {
|
|
api("/api/v1/connectors")
|
|
.then((data) => {
|
|
const mail = data.items.filter((item) => item.kind === "imap");
|
|
setAccounts(mail);
|
|
if (mail[0]) setAccountId(mail[0].id);
|
|
})
|
|
.catch((err) => setError(err.message));
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!accountId) return undefined;
|
|
let alive = true;
|
|
setFolders([]);
|
|
setMailbox("");
|
|
setItems([]);
|
|
setError("");
|
|
setLoading("Fächer werden gelesen …");
|
|
api(`/api/v1/sources/imap/mailboxes?connector_id=${accountId}`)
|
|
.then((data) => {
|
|
if (!alive) return;
|
|
const list = data.items || [];
|
|
setFolders(list);
|
|
const preferred = list.find((item) => item.selectable && item.name.toUpperCase() === "INBOX")
|
|
|| list.find((item) => item.selectable);
|
|
setMailbox(preferred ? preferred.name : "");
|
|
if (!preferred) setLoading("");
|
|
})
|
|
.catch((err) => {
|
|
if (!alive) return;
|
|
setLoading("");
|
|
setError(err.message);
|
|
});
|
|
return () => {
|
|
alive = false;
|
|
};
|
|
}, [accountId]);
|
|
|
|
useEffect(() => {
|
|
if (!accountId || !mailbox) return undefined;
|
|
let alive = true;
|
|
setQuery("");
|
|
setDraft("");
|
|
setItems([]);
|
|
setNextBefore(null);
|
|
setSelectedKey("");
|
|
setPreview(null);
|
|
setPreviewError("");
|
|
setError("");
|
|
setLoading("Nachrichten werden gelesen …");
|
|
const params = new URLSearchParams({ connector_id: accountId, mailbox });
|
|
api(`/api/v1/sources/imap/messages?${params}`)
|
|
.then((data) => {
|
|
if (!alive) return;
|
|
setItems(data.items || []);
|
|
setNextBefore(data.next_before ?? null);
|
|
setLoading("");
|
|
})
|
|
.catch((err) => {
|
|
if (!alive) return;
|
|
setLoading("");
|
|
setError(err.message);
|
|
});
|
|
return () => {
|
|
alive = false;
|
|
};
|
|
}, [accountId, mailbox]);
|
|
|
|
async function search(event) {
|
|
event.preventDefault();
|
|
if (!accountId || !mailbox) return;
|
|
setError("");
|
|
setLoading("Nachrichten werden gelesen …");
|
|
const params = new URLSearchParams({ connector_id: accountId, mailbox });
|
|
if (draft.trim()) params.set("q", draft.trim());
|
|
try {
|
|
const data = await api(`/api/v1/sources/imap/messages?${params}`);
|
|
setQuery(draft.trim());
|
|
setItems(data.items || []);
|
|
setNextBefore(data.next_before ?? null);
|
|
setSelectedKey("");
|
|
setPreview(null);
|
|
setPreviewError("");
|
|
} catch (err) {
|
|
setError(err.message);
|
|
} finally {
|
|
setLoading("");
|
|
}
|
|
}
|
|
|
|
async function older() {
|
|
if (!nextBefore) return;
|
|
setError("");
|
|
setLoading("Ältere Nachrichten werden gelesen …");
|
|
const params = new URLSearchParams({ connector_id: accountId, mailbox, before: String(nextBefore) });
|
|
if (query) params.set("q", query);
|
|
try {
|
|
const data = await api(`/api/v1/sources/imap/messages?${params}`);
|
|
setItems((current) => [...current, ...(data.items || [])]);
|
|
setNextBefore(data.next_before ?? null);
|
|
} catch (err) {
|
|
setError(err.message);
|
|
} finally {
|
|
setLoading("");
|
|
}
|
|
}
|
|
|
|
function choose(item) {
|
|
const key = `${mailbox}:${item.uid || item.id}`;
|
|
setSelectedKey(key);
|
|
setPreview(null);
|
|
setPreviewError("");
|
|
if (!item.uid) {
|
|
setPreviewError("Diese Nachricht lässt sich nicht öffnen.");
|
|
return;
|
|
}
|
|
const params = new URLSearchParams({ connector_id: accountId, mailbox, uid: String(item.uid) });
|
|
api(`/api/v1/sources/imap/message?${params}`)
|
|
.then((data) => {
|
|
setPreview(data);
|
|
})
|
|
.catch((err) => setPreviewError(err.message));
|
|
}
|
|
|
|
async function link(item) {
|
|
if (adopting) return;
|
|
setError("");
|
|
setAdopting(true);
|
|
const letter = preview && preview.uid === item.uid ? preview : null;
|
|
const known = letter?.direction || item.direction;
|
|
const direction = known === "out" || known === "in" ? known : null;
|
|
const attachments = (letter?.attachments || item.attachments || [])
|
|
.filter((file) => file?.filename)
|
|
.map((file) => ({
|
|
filename: file.filename,
|
|
...(file.content_type ? { content_type: file.content_type } : {}),
|
|
}));
|
|
const detail = {
|
|
direction,
|
|
mailbox,
|
|
connector_id: accountId,
|
|
uid: item.uid,
|
|
};
|
|
const from = letter?.message_from || item.message_from;
|
|
const to = letter?.message_to || item.message_to;
|
|
const cc = letter?.message_cc || item.message_cc;
|
|
if (from) detail.message_from = from;
|
|
if (to) detail.message_to = to;
|
|
if (cc) detail.message_cc = cc;
|
|
if (attachments.length) detail.attachments = attachments;
|
|
try {
|
|
await api("/api/v1/external-refs", {
|
|
method: "POST",
|
|
body: {
|
|
title: item.title,
|
|
source: "imap",
|
|
external_id: item.id,
|
|
context,
|
|
...(placement ? { placement } : {}),
|
|
...(chapterId ? { chapter_id: chapterId } : {}),
|
|
...(item.document_on ? {
|
|
dates: {
|
|
document_on: item.document_on,
|
|
sent_on: direction === "out" ? item.document_on : null,
|
|
received_on: direction === "in" ? item.document_on : null,
|
|
},
|
|
} : {}),
|
|
detail,
|
|
},
|
|
});
|
|
onDone();
|
|
} catch (err) {
|
|
setError(err.message);
|
|
} finally {
|
|
setAdopting(false);
|
|
}
|
|
}
|
|
|
|
const selected = items.find((item) => `${mailbox}:${item.uid || item.id}` === selectedKey) || null;
|
|
|
|
return (
|
|
<div className="stack">
|
|
<TargetLine label={targetLabel} chapterId={chapterId} chapterTitle={chapterTitle} />
|
|
<label>
|
|
Konto
|
|
<select value={accountId} onChange={(event) => setAccountId(event.target.value)}>
|
|
{accounts.length ? null : <option value="">Kein Konto</option>}
|
|
{accounts.map((item) => (
|
|
<option key={item.id} value={item.id}>{item.name}</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
{!accounts.length ? <p className="muted">Lege zuerst ein E-Mail-Konto unter <Link to="/sources">Quellen</Link> an.</p> : null}
|
|
<div className="mailbox mailbox--read">
|
|
<FolderTree folders={folders} mailbox={mailbox} onSelect={setMailbox} />
|
|
<div className="mailbox__messages">
|
|
<form onSubmit={search} className="inline">
|
|
<input value={draft} onChange={(event) => setDraft(event.target.value)} placeholder="Im gewählten Fach suchen" aria-label="Im gewählten Fach suchen" />
|
|
<button type="submit" className="quiet" disabled={!mailbox || !!loading}>Suchen</button>
|
|
</form>
|
|
<ErrorNote error={error} />
|
|
{accountId && !loading && !mailbox && !error ? <p className="muted">Dieses Konto hat keine lesbaren Fächer.</p> : null}
|
|
{loading ? <p className="muted">{loading}</p> : null}
|
|
{!loading && mailbox && !items.length ? (
|
|
<p className="muted">{query ? "In diesem Fach gibt es dazu keine Nachricht." : "In diesem Fach gibt es keine Nachricht."}</p>
|
|
) : null}
|
|
<div className="mail-list">
|
|
{items.map((item) => {
|
|
const key = `${mailbox}:${item.uid || item.id}`;
|
|
const outgoing = item.direction === "out";
|
|
const incoming = item.direction === "in";
|
|
const who = outgoing ? (item.message_to ? `an ${item.message_to}` : "") : (item.message_from || "");
|
|
const way = outgoing ? "Ausgang" : incoming ? "Eingang" : "";
|
|
const files = item.attachments?.length || 0;
|
|
return (
|
|
<button key={key} type="button" className={key === selectedKey ? "mail-row is-current" : "mail-row"} aria-current={key === selectedKey ? "true" : undefined} onClick={() => choose(item)}>
|
|
<span className="mail-row__date">{formatDate(item.document_on)}</span>
|
|
<span className="mail-row__main">
|
|
<strong>{item.title}</strong>
|
|
<span>{[way, who].filter(Boolean).join(" · ")}</span>
|
|
</span>
|
|
{files ? <span className="mail-row__files" aria-label={`${files} ${files === 1 ? "Anhang" : "Anhänge"}`}>{files}</span> : null}
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
{nextBefore ? <button type="button" className="quiet" onClick={older} disabled={!!loading}>Ältere laden</button> : null}
|
|
</div>
|
|
<aside className="mail-preview" aria-label="E-Mail-Vorschau">
|
|
{!selected ? <p className="muted">Wähle eine Nachricht, um Absender, Empfänger und Inhalt zu prüfen.</p> : (
|
|
<>
|
|
<h3>{preview?.title || selected.title}</h3>
|
|
<p className="mail-preview__party">{(preview?.direction || selected.direction) === "out" ? "Ausgang" : (preview?.direction || selected.direction) === "in" ? "Eingang" : "Richtung nicht bekannt"}</p>
|
|
<p><span>Von</span> {preview?.message_from || selected.message_from || "Ohne Absender"}</p>
|
|
<p><span>An</span> {preview?.message_to || selected.message_to || "Ohne Empfänger"}</p>
|
|
{(preview?.message_cc || selected.message_cc) ? <p><span>Kopie</span> {preview?.message_cc || selected.message_cc}</p> : null}
|
|
<p><span>Datum</span> {formatDate(preview?.document_on || selected.document_on)}</p>
|
|
<MailFiles files={preview?.attachments || selected.attachments || []} />
|
|
{previewError ? <p className="error">{previewError}</p> : null}
|
|
{selected && !preview && !previewError ? <p className="muted">Vorschau wird geladen …</p> : null}
|
|
{preview?.text ? <pre className="mail-letter__body">{preview.text}</pre> : null}
|
|
{preview?.text_truncated ? <p className="muted">Der Text ist gekürzt, weil die Nachricht sehr groß ist.</p> : null}
|
|
{preview && !preview.text ? <p className="muted">Diese Nachricht hat keinen lesbaren Text.</p> : null}
|
|
<ErrorNote error={error} />
|
|
<button type="button" onClick={() => link(selected)} disabled={!selected.uid || adopting}>{adopting ? "Wird übernommen …" : "Übernehmen"}</button>
|
|
</>
|
|
)}
|
|
</aside>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
async function probe(id, setNotice, setError) {
|
|
setError("");
|
|
setNotice("");
|
|
try {
|
|
const data = await api(`/api/v1/connectors/${id}/probe`, { method: "POST" });
|
|
setNotice(data.detail);
|
|
} catch (err) {
|
|
setError(err.message);
|
|
}
|
|
}
|
|
|
|
async function remove(id, load, setError) {
|
|
setError("");
|
|
try {
|
|
await api(`/api/v1/connectors/${id}`, { method: "DELETE" });
|
|
await load();
|
|
} catch (err) {
|
|
setError(err.message);
|
|
}
|
|
}
|