Lass E-Mails ueber die Faecher finden und halte Kapitel sowie das Menue in der Akte an ihrem Ort.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3465ed57f6
commit
67d48378c9
11 files changed
+696
-160
No files matched your search
@@ -17,6 +17,7 @@ from app.ops import create_external
|
||||
from app.sources import (
|
||||
clean_base_url,
|
||||
delete_connector,
|
||||
imap_mailboxes,
|
||||
imap_messages,
|
||||
list_connectors,
|
||||
paperless_content,
|
||||
@@ -88,14 +89,27 @@ def search_paperless(q: str = "", principal: Principal = Depends(get_principal),
|
||||
return {"items": paperless_documents(conn, principal.account_id, q.strip())}
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/imap/mailboxes")
|
||||
def list_mailboxes(
|
||||
connector_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return {"items": imap_mailboxes(conn, principal.account_id, connector_id)}
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/imap/messages")
|
||||
def search_mail(
|
||||
connector_id: UUID,
|
||||
q: str = "",
|
||||
mailbox: str = "",
|
||||
before: int | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return {"items": imap_messages(conn, principal.account_id, connector_id, q.strip())}
|
||||
if before is not None and before < 1:
|
||||
raise unprocessable("Die Seitenangabe ist ungültig.")
|
||||
return imap_messages(conn, principal.account_id, connector_id, q.strip(), mailbox.strip(), before)
|
||||
|
||||
|
||||
@router.post("/api/v1/sources/link", status_code=201)
|
||||
|
||||
+49
-28
@@ -358,6 +358,32 @@ def matter_placements(conn, actor: UUID, matter_id: UUID, context: Ctx | None) -
|
||||
return items
|
||||
|
||||
|
||||
def _contained_group(conn, actor: UUID, matter: dict, context: Ctx) -> dict | None:
|
||||
matter_right = matter_rights(conn, actor, matter, context)
|
||||
if not matter_right.read:
|
||||
return None
|
||||
return {
|
||||
"matter_id": str(matter["id"]),
|
||||
"title": matter["title"],
|
||||
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
|
||||
"parent_title": matter_title_if_readable(conn, actor, matter["parent_matter_id"]),
|
||||
"version": matter["version"],
|
||||
"rights": matter_right.as_dict(),
|
||||
"chapters": _chapters(conn, "matter", matter["id"]),
|
||||
"content_order": matter.get("content_order") or "position",
|
||||
"content_order_dir": matter.get("content_order_dir") or "asc",
|
||||
"bindings": _ordered_bindings(
|
||||
conn,
|
||||
actor,
|
||||
"matter",
|
||||
matter["id"],
|
||||
context,
|
||||
matter.get("content_order") or "position",
|
||||
matter.get("content_order_dir") or "asc",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _matter_node(row: dict) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
@@ -461,7 +487,8 @@ def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
|
||||
conn, actor, "case", case["id"], context, payload["content_order"], payload["content_order_dir"]
|
||||
)
|
||||
contained = []
|
||||
for link in conn.execute(
|
||||
seen_matters: set[UUID] = set()
|
||||
linked_matters = conn.execute(
|
||||
"""
|
||||
SELECT m.*
|
||||
FROM matter_case_links l
|
||||
@@ -470,33 +497,27 @@ def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
|
||||
ORDER BY m.title, m.id
|
||||
""",
|
||||
(case["id"],),
|
||||
).fetchall():
|
||||
matter_right = matter_rights(conn, actor, link, context)
|
||||
if not matter_right.read:
|
||||
continue
|
||||
items = _ordered_bindings(
|
||||
conn,
|
||||
actor,
|
||||
"matter",
|
||||
link["id"],
|
||||
context,
|
||||
link.get("content_order") or "position",
|
||||
link.get("content_order_dir") or "asc",
|
||||
)
|
||||
if not items:
|
||||
continue
|
||||
contained.append(
|
||||
{
|
||||
"matter_id": str(link["id"]),
|
||||
"title": link["title"],
|
||||
"version": link["version"],
|
||||
"rights": matter_right.as_dict(),
|
||||
"chapters": _chapters(conn, "matter", link["id"]),
|
||||
"content_order": link.get("content_order") or "position",
|
||||
"content_order_dir": link.get("content_order_dir") or "asc",
|
||||
"bindings": items,
|
||||
}
|
||||
)
|
||||
).fetchall()
|
||||
for link in linked_matters:
|
||||
block = [link]
|
||||
if not link["parent_matter_id"]:
|
||||
block.extend(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT * FROM matters
|
||||
WHERE parent_matter_id = %s AND deleted_at IS NULL
|
||||
ORDER BY title, id
|
||||
""",
|
||||
(link["id"],),
|
||||
).fetchall()
|
||||
)
|
||||
for matter in block:
|
||||
if matter["id"] in seen_matters:
|
||||
continue
|
||||
seen_matters.add(matter["id"])
|
||||
group = _contained_group(conn, actor, matter, context)
|
||||
if group is not None:
|
||||
contained.append(group)
|
||||
payload["contained"] = contained
|
||||
payload["tasks"] = []
|
||||
payload["deadlines"] = []
|
||||
|
||||
+189
-38
@@ -2,11 +2,14 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import imaplib
|
||||
import json
|
||||
import re
|
||||
import ssl
|
||||
from email.header import decode_header
|
||||
from email.parser import BytesParser
|
||||
from email.utils import parsedate_to_datetime
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode, urlparse
|
||||
@@ -107,11 +110,37 @@ def paperless_documents(conn, owner_id: UUID, query: str) -> list[dict]:
|
||||
return items
|
||||
|
||||
|
||||
def imap_messages(conn, owner_id: UUID, connector_id: UUID, query: str) -> list[dict]:
|
||||
def imap_mailboxes(conn, owner_id: UUID, connector_id: UUID) -> list[dict]:
|
||||
row = _owned(conn, owner_id, connector_id)
|
||||
if row["kind"] != "imap":
|
||||
raise unprocessable("Das ist kein E-Mail-Konto.")
|
||||
return _imap_list(row["settings"], row["secret"], query)
|
||||
client = _imap_login(row["settings"], row["secret"])
|
||||
try:
|
||||
return _imap_mailboxes(client)
|
||||
finally:
|
||||
_imap_logout(client)
|
||||
|
||||
|
||||
def imap_messages(
|
||||
conn,
|
||||
owner_id: UUID,
|
||||
connector_id: UUID,
|
||||
query: str,
|
||||
mailbox: str,
|
||||
before: int | None,
|
||||
) -> dict:
|
||||
row = _owned(conn, owner_id, connector_id)
|
||||
if row["kind"] != "imap":
|
||||
raise unprocessable("Das ist kein E-Mail-Konto.")
|
||||
if any(char in mailbox for char in "\r\n\x00"):
|
||||
raise unprocessable("Der Fachname ist ungültig.")
|
||||
if len(query) > 200:
|
||||
raise unprocessable("Die Suche ist zu lang.")
|
||||
client = _imap_login(row["settings"], row["secret"])
|
||||
try:
|
||||
return _imap_page(client, mailbox, query, before)
|
||||
finally:
|
||||
_imap_logout(client)
|
||||
|
||||
|
||||
def _owned(conn, owner_id: UUID, connector_id: UUID) -> dict:
|
||||
@@ -329,43 +358,165 @@ def _imap_login(settings: dict, secret: str) -> imaplib.IMAP4:
|
||||
raise unprocessable("Das Postfach ist nicht erreichbar.") from exc
|
||||
|
||||
|
||||
def _imap_list(settings: dict, secret: str, query: str) -> list[dict]:
|
||||
client = _imap_login(settings, secret)
|
||||
PAGE_SIZE = 30
|
||||
_LIST_LINE = re.compile(
|
||||
r'^\((?P<flags>[^)]*)\)\s+(?P<delim>"(?:\\.|[^"])*"|NIL)\s+(?P<name>"(?:\\.|[^"])*"|\S+)\s*$'
|
||||
)
|
||||
|
||||
|
||||
def _imap_logout(client: imaplib.IMAP4) -> None:
|
||||
try:
|
||||
mailbox = settings.get("mailbox") or "INBOX"
|
||||
status, _ = client.select(mailbox, readonly=True)
|
||||
if status != "OK":
|
||||
raise unprocessable("Das Postfach enthält dieses Fach nicht.")
|
||||
status, data = client.search(None, "ALL")
|
||||
if status != "OK" or not data or not data[0]:
|
||||
return []
|
||||
ids = data[0].split()[-25:]
|
||||
needle = query.strip().lower()
|
||||
items = []
|
||||
for mid in reversed(ids):
|
||||
status, fetched = client.fetch(mid, "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE MESSAGE-ID)])")
|
||||
if status != "OK" or not fetched or not isinstance(fetched[0], tuple):
|
||||
continue
|
||||
header = BytesParser().parsebytes(fetched[0][1])
|
||||
subject = _decode(header.get("Subject")) or "(ohne Betreff)"
|
||||
sender = _decode(header.get("From"))
|
||||
if needle and needle not in subject.lower() and needle not in sender.lower():
|
||||
continue
|
||||
message_id = (header.get("Message-ID") or f"uid:{mid.decode()}").strip()
|
||||
items.append(
|
||||
{
|
||||
"id": message_id[:200],
|
||||
"title": subject[:200],
|
||||
"message_from": sender[:200],
|
||||
"date": _decode(header.get("Date"))[:80],
|
||||
}
|
||||
)
|
||||
return items
|
||||
finally:
|
||||
try:
|
||||
client.logout()
|
||||
except imaplib.IMAP4.error:
|
||||
pass
|
||||
client.logout()
|
||||
except imaplib.IMAP4.error:
|
||||
pass
|
||||
|
||||
|
||||
def _imap_mailboxes(client: imaplib.IMAP4) -> list[dict]:
|
||||
try:
|
||||
status, data = client.list()
|
||||
except imaplib.IMAP4.error as exc:
|
||||
raise unprocessable("Die Fächer konnten nicht gelesen werden.") from exc
|
||||
if status != "OK":
|
||||
raise unprocessable("Die Fächer konnten nicht gelesen werden.")
|
||||
items = []
|
||||
seen: set[str] = set()
|
||||
for raw in data or []:
|
||||
parsed = _parse_list_line(raw)
|
||||
if parsed is None or parsed["name"] in seen:
|
||||
continue
|
||||
seen.add(parsed["name"])
|
||||
items.append(parsed)
|
||||
items.sort(key=lambda item: (0 if item["name"].upper() == "INBOX" else 1, item["label"].casefold()))
|
||||
return items
|
||||
|
||||
|
||||
def _imap_page(client: imaplib.IMAP4, mailbox: str, query: str, before: int | None) -> dict:
|
||||
folders = _imap_mailboxes(client)
|
||||
chosen = mailbox or "INBOX"
|
||||
match = next((item for item in folders if item["name"] == chosen), None)
|
||||
if match is None or not match["selectable"]:
|
||||
raise unprocessable("Dieses Fach gibt es in dem Konto nicht.")
|
||||
try:
|
||||
status, _ = client.select(chosen, readonly=True)
|
||||
except imaplib.IMAP4.error as exc:
|
||||
raise unprocessable("Dieses Fach lässt sich nicht öffnen.") from exc
|
||||
if status != "OK":
|
||||
raise unprocessable("Dieses Fach lässt sich nicht öffnen.")
|
||||
status, data = _uid_search(client, query)
|
||||
if status != "OK" or not data or not data[0]:
|
||||
return {"mailbox": chosen, "items": [], "next_before": None}
|
||||
uids = sorted(int(part) for part in data[0].split() if part.isdigit())
|
||||
if before is not None:
|
||||
uids = [uid for uid in uids if uid < before]
|
||||
page = uids[-PAGE_SIZE:]
|
||||
next_before = page[0] if len(uids) > PAGE_SIZE else None
|
||||
items = []
|
||||
for uid in reversed(page):
|
||||
item = _fetch_header(client, uid, chosen)
|
||||
if item is not None:
|
||||
items.append(item)
|
||||
return {"mailbox": chosen, "items": items, "next_before": next_before}
|
||||
|
||||
|
||||
def _uid_search(client: imaplib.IMAP4, query: str):
|
||||
needle = " ".join(query.split())
|
||||
if not needle:
|
||||
return client.uid("SEARCH", None, "ALL")
|
||||
quoted = '"' + needle.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
||||
try:
|
||||
if needle.isascii():
|
||||
return client.uid("SEARCH", None, "OR", "SUBJECT", quoted, "FROM", quoted)
|
||||
encoded = quoted.encode("utf-8")
|
||||
return client.uid("SEARCH", "CHARSET", "UTF-8", "OR", "SUBJECT", encoded, "FROM", encoded)
|
||||
except imaplib.IMAP4.error as exc:
|
||||
raise unprocessable("Das Postfach kann diese Suche nicht ausführen. Blättere im Fach oder kürze den Suchtext.") from exc
|
||||
|
||||
|
||||
def _fetch_header(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict | None:
|
||||
try:
|
||||
status, fetched = client.uid("FETCH", str(uid), "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE MESSAGE-ID)])")
|
||||
except imaplib.IMAP4.error:
|
||||
return None
|
||||
if status != "OK" or not fetched or not isinstance(fetched[0], tuple):
|
||||
return None
|
||||
header = BytesParser().parsebytes(fetched[0][1])
|
||||
subject = _decode(header.get("Subject")) or "(ohne Betreff)"
|
||||
sender = _decode(header.get("From"))
|
||||
message_id = (header.get("Message-ID") or f"uid:{mailbox}:{uid}").strip()
|
||||
return {
|
||||
"id": message_id[:200],
|
||||
"uid": uid,
|
||||
"title": subject[:200],
|
||||
"message_from": sender[:200],
|
||||
"document_on": _mail_date(header.get("Date")),
|
||||
}
|
||||
|
||||
|
||||
def _parse_list_line(raw) -> dict | None:
|
||||
if not isinstance(raw, (bytes, str)) or not raw:
|
||||
return None
|
||||
text = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else raw
|
||||
match = _LIST_LINE.match(text.strip())
|
||||
if match is None:
|
||||
return None
|
||||
flags = {flag.lstrip("\\").casefold() for flag in match.group("flags").split() if flag}
|
||||
delimiter = _unquote(match.group("delim"))
|
||||
name = _unquote(match.group("name"))
|
||||
if not name:
|
||||
return None
|
||||
label = "Posteingang" if name.upper() == "INBOX" else _decode_utf7(name)
|
||||
depth = 0 if not delimiter or name.upper() == "INBOX" else name.count(delimiter)
|
||||
return {
|
||||
"name": name,
|
||||
"label": label,
|
||||
"delimiter": delimiter,
|
||||
"depth": depth,
|
||||
"selectable": "noselect" not in flags,
|
||||
}
|
||||
|
||||
|
||||
def _unquote(token: str) -> str:
|
||||
if token == "NIL":
|
||||
return ""
|
||||
if len(token) >= 2 and token.startswith('"') and token.endswith('"'):
|
||||
return token[1:-1].replace(r"\"", '"').replace(r"\\", "\\")
|
||||
return token
|
||||
|
||||
|
||||
def _decode_utf7(value: str) -> str:
|
||||
if "&" not in value:
|
||||
return value
|
||||
parts: list[str] = []
|
||||
index = 0
|
||||
while index < len(value):
|
||||
if value[index] != "&":
|
||||
parts.append(value[index])
|
||||
index += 1
|
||||
continue
|
||||
end = value.find("-", index)
|
||||
if end < 0:
|
||||
parts.append(value[index:])
|
||||
break
|
||||
if end == index + 1:
|
||||
parts.append("&")
|
||||
else:
|
||||
chunk = value[index + 1:end].replace(",", "/")
|
||||
padding = "=" * ((4 - len(chunk) % 4) % 4)
|
||||
try:
|
||||
parts.append(base64.b64decode(chunk + padding).decode("utf-16-be"))
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
parts.append(value[index:end + 1])
|
||||
index = end + 1
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _mail_date(value: str | None) -> str | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return parsedate_to_datetime(value).date().isoformat()
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def _decode(value: str | None) -> str:
|
||||
|
||||
Reference in new issue
Block a user