Speichere die neue Position einer verschobenen IMAP-Nachricht, damit der nächste Aufruf sie direkt öffnet.
Test Suite / pytest-backend (push) Canceled after 0s
Test Suite / smoke-dev (push) Canceled after 0s
Test Suite / frontend-build (push) Canceled after 0s
Deploy Development / deploy (push) Successful in 43s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-23 13:00:25 +02:00
1 parent cd239a3ab8
commit 7a1206b18c
4 files changed
+299 -19

No files matched your search

+1 -1
View File
@@ -44,7 +44,7 @@ def load_external(conn, actor_id: UUID, element_id: UUID, assigned: UUID | None)
ref = conn.execute(
"""
SELECT source, external_id, detail, connector_id, resolution
SELECT element_id, source, external_id, detail, connector_id, resolution
FROM external_references WHERE element_id = %s
""",
(element_id,),
+39
View File
@@ -217,3 +217,42 @@ def assign_reference(conn, actor_id: UUID, element_id: UUID, connector_id: UUID)
detail = dict(ref["detail"] or {})
detail["connector_id"] = str(connector_id)
_set_binding(conn, element_id, connector_id, "bound", detail)
def remember_imap_location(
conn,
element_id: UUID,
external_id: str,
previous_mailbox: str,
previous_uid: int,
mailbox: str,
uid: int,
) -> None:
"""Store the folder and UID of a message found at a new place.
Only the previous place is replaced. The message identity, the connector
and an adopted direction stay as they were.
"""
if (
not mailbox
or any(char in mailbox for char in "\r\n\x00")
or uid < 1
or (mailbox == previous_mailbox and uid == previous_uid)
):
return
conn.execute(
"""
UPDATE external_references
SET detail = jsonb_set(
jsonb_set(detail, '{mailbox}', to_jsonb(%s::text)),
'{uid}',
to_jsonb(%s::bigint)
)
WHERE element_id = %s
AND source = 'imap'
AND external_id = %s
AND detail->>'mailbox' = %s
AND detail->>'uid' = %s
""",
(mailbox, uid, element_id, external_id, previous_mailbox, str(previous_uid)),
)
+67 -18
View File
@@ -7,6 +7,7 @@ import imaplib
import json
import re
import ssl
from dataclasses import dataclass
from email.header import decode_header
from email.parser import BytesParser
from email.utils import parsedate_to_datetime
@@ -33,7 +34,7 @@ from app.mailpack import (
simplified_text,
)
from app.media.storage import sniff
from app.sourcebind import resolve_for_read
from app.sourcebind import remember_imap_location, resolve_for_read
from app.sourceaccess import (
ORIGINAL_UNAVAILABLE,
assert_still_owned,
@@ -509,7 +510,8 @@ def read_linked_mail(conn, actor_id: UUID, element: dict, context: Ctx | None, r
def fetch(row):
return pull_rfc822(row["settings"], row["secret"], mailbox, uid, external_id, COMPLETE_MAIL_LIMIT)
return complete_borrow(conn, borrowed, fetch)
found = complete_borrow(conn, borrowed, fetch)
return _keep_moved_mail(conn, element["id"], external_id, mailbox, uid, found)
def _uuid(value) -> UUID | None:
@@ -1470,11 +1472,33 @@ def load_imap_original(conn, owner_id: UUID, connector_id: UUID, mailbox: str, u
row = _owned(conn, owner_id, connector_id)
if row["kind"] != "imap":
raise unprocessable("Das ist kein E-Mail-Konto.")
return pull_rfc822(row["settings"], row["secret"], mailbox, uid, expected_id, COMPLETE_MAIL_LIMIT)
found = pull_rfc822(row["settings"], row["secret"], mailbox, uid, expected_id, COMPLETE_MAIL_LIMIT)
return found.raw if isinstance(found, LocatedMail) else found
def pull_rfc822(settings: dict, secret: str, mailbox: str, uid: int, expected_id: str, max_bytes: int) -> bytes:
"""Fetch the referenced message. A different message at the old UID is not returned."""
@dataclass(frozen=True)
class LocatedMail:
"""Bytes plus the folder they were read from. `relocated` is a complete, unique hit."""
raw: bytes
mailbox: str
uid: int
relocated: bool = False
@dataclass(frozen=True)
class _MailHit:
raw: bytes
mailbox: str
uid: int
def pull_rfc822(settings: dict, secret: str, mailbox: str, uid: int, expected_id: str, max_bytes: int) -> LocatedMail:
"""Fetch the referenced message. A different message at the old UID is not returned.
The stored folder is tried first. A single Message-ID hit elsewhere comes back
marked relocated; the caller stores that place after the access check.
"""
client = _imap_login(settings, secret)
try:
_select_mailbox(client, mailbox)
@@ -1484,23 +1508,45 @@ def pull_rfc822(settings: dict, secret: str, mailbox: str, uid: int, expected_id
"Die vollständige Nachricht überschreitet die Exportgrenze. "
"Eine gekürzte Vorschau wird nicht als Original übernommen."
)
alternates: list[bytes] = []
if candidate is None or not identities_match(header_message_id(candidate), expected_id):
alternates = _search_rfc822(client, expected_id, max_bytes)
if candidate is not None and identities_match(header_message_id(candidate), expected_id):
return LocatedMail(candidate, mailbox, uid, relocated=False)
hits, capped = _search_rfc822(client, expected_id, max_bytes)
try:
chosen = choose_message(candidate, alternates, expected_id)
chosen = choose_message(None, [hit.raw for hit in hits], expected_id)
except MailIdentityError as exc:
raise unprocessable(exc.message) from exc
if len(chosen) > max_bytes:
match = next(
hit for hit in hits
if hit.raw == chosen and identities_match(header_message_id(hit.raw), expected_id)
)
if len(match.raw) > max_bytes:
raise unprocessable(
"Die vollständige Nachricht überschreitet die Exportgrenze. "
"Eine gekürzte Vorschau wird nicht als Original übernommen."
)
return chosen
moved = not capped and (match.mailbox != mailbox or match.uid != uid)
return LocatedMail(match.raw, match.mailbox, match.uid, relocated=moved)
finally:
_imap_logout(client)
def _keep_moved_mail(conn, element_id, external_id: str, mailbox: str, uid: int | None, found) -> bytes:
"""Return the bytes. A unique new place is written only after the fetch has finished."""
if not isinstance(found, LocatedMail):
return found
if found.relocated and element_id is not None and uid is not None:
remember_imap_location(
conn,
element_id,
external_id,
mailbox,
uid,
found.mailbox,
found.uid,
)
return found.raw
def _fetch_rfc822(client: imaplib.IMAP4, uid: int) -> bytes | None:
try:
status, fetched = client.uid("FETCH", str(uid), "(BODY.PEEK[])")
@@ -1511,11 +1557,12 @@ def _fetch_rfc822(client: imaplib.IMAP4, uid: int) -> bytes | None:
return _literal(fetched)
def _search_rfc822(client: imaplib.IMAP4, expected_id: str, max_bytes: int) -> list[bytes]:
def _search_rfc822(client: imaplib.IMAP4, expected_id: str, max_bytes: int) -> tuple[list[_MailHit], bool]:
"""Search every selectable folder. The second value is true when the scan stopped early."""
token = (expected_id or "").strip()
if not token or token.casefold().startswith("uid:"):
return []
found: list[bytes] = []
return [], False
found: list[_MailHit] = []
for folder in _imap_mailboxes(client):
if not folder["selectable"]:
continue
@@ -1539,10 +1586,10 @@ def _search_rfc822(client: imaplib.IMAP4, expected_id: str, max_bytes: int) -> l
"Die vollständige Nachricht überschreitet die Exportgrenze. "
"Eine gekürzte Vorschau wird nicht als Original übernommen."
)
found.append(blob)
found.append(_MailHit(blob, folder["name"], uid))
if len(found) > 5:
return found
return found
return found, True
return found, False
PAPERLESS_FIELDS = (
@@ -1667,13 +1714,15 @@ def _export_imap(conn, actor_id: UUID, external_id: str, detail: dict, assigned:
owner_id = resolved.row["owner_id"]
release_for_external(conn)
try:
raw = pull_rfc822(settings, secret, mailbox, uid, str(external_id), EXPORT_BYTE_LIMIT)
found = pull_rfc822(settings, secret, mailbox, uid, str(external_id), EXPORT_BYTE_LIMIT)
except Problem as exc:
return failure_from_problem(exc)
try:
assert_still_owned(conn, connector_id, owner_id)
except Problem as exc:
return failure_from_problem(exc)
element_id = ref["element_id"] if ref is not None and "element_id" in ref.keys() else None
raw = _keep_moved_mail(conn, element_id, str(external_id), mailbox, uid, found)
if len(raw) > EXPORT_BYTE_LIMIT:
return RetrievalFailure(
"too_large",