From 59552659c527bddc0697a78f6e1085c557e67fea Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Mon, 5 Oct 2026 02:57:31 +0000 Subject: [PATCH] feat(sources): route a shared inbox's mail to namespaces with rules An email watch can carry routing rules: conditions on sender, recipient (To, Cc, Delivered-To), subject, list or mailbox send matching messages to another namespace, or skip them. No rules: everything goes to the watch's namespace, as before. A preview endpoint shows where the latest messages would go before saving. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01V3JT2ET8A1tXFMdidgek2S --- docs/processing.md | 10 + fastapi_backend/app/api/v1/routes/sources.py | 14 + fastapi_backend/app/domain/feeds.py | 34 +- fastapi_backend/app/domain/mail_routes.py | 110 ++++++ fastapi_backend/app/domain/sources.py | 79 ++++- fastapi_backend/app/schemas/sources.py | 44 +++ fastapi_backend/tests/api/test_mail_routes.py | 160 +++++++++ fastapi_backend/tests/fake_imap.py | 5 +- nextjs-frontend/app/openapi-client/index.ts | 9 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 21 ++ .../app/openapi-client/types.gen.ts | 165 +++++++++ nextjs-frontend/openapi.json | 312 ++++++++++++++++++ 12 files changed, 950 insertions(+), 13 deletions(-) create mode 100644 fastapi_backend/app/domain/mail_routes.py create mode 100644 fastapi_backend/tests/api/test_mail_routes.py diff --git a/docs/processing.md b/docs/processing.md index 0c1fa6b90..69e294a51 100644 --- a/docs/processing.md +++ b/docs/processing.md @@ -254,6 +254,16 @@ importing chosen ones and watching work as above. Important), and a message several mailboxes show (one Message-ID) becomes one resource. A watch remembers the last message it saw in each mailbox and asks only for newer ones. Lens only reads: mailboxes are opened read-only and messages fetched without marking them read. +- **Routing rules** (email watches only): a shared inbox can feed several namespaces. Each rule has conditions on who + sent a message (`from`), who it was for (`to`: To, Cc, and the address the inbox received it at, so mail to an alias + like support@ is told apart), its `subject`, its mailing list (`list`, the List-Id) or its `mailbox`, and sends + matching messages to a namespace, or skips them. Rules are tried in order and the first whose conditions all match + decides; a message no rule matches goes to the watch's own namespace, as it does with no rules. Patterns ignore case; + one without `*` or `?` matches anywhere in the text (`acme.com`), one with them must match all of it + (`*@acme.com`), and a condition can list several patterns, any of which may match. A rule names a namespace that + exists (rules never create one); mail for a namespace deleted since goes to the watch's. Rules apply to messages that + arrive after they're saved. `POST /api/v1/watches/routes/preview` shows where the latest messages would go before + saving, and a scan's stats count the messages `routed` elsewhere. - **Calendar feed (iCal)**: the calendar's iCal address (`https://` or `webcal://`; a user and password if it asks for one). The address is kept encrypted like a password and never shown again, since a private calendar's address is all it takes to read it. It is fetched the way web pages are captured: public addresses only (and the networks in diff --git a/fastapi_backend/app/api/v1/routes/sources.py b/fastapi_backend/app/api/v1/routes/sources.py index be953948b..ea7d36bdc 100644 --- a/fastapi_backend/app/api/v1/routes/sources.py +++ b/fastapi_backend/app/api/v1/routes/sources.py @@ -15,6 +15,8 @@ from app.schemas.sources import ( Backend, BrowseEntry, + RoutedMessage, + RoutePreviewRequest, Source, SourceCreate, SourceCreated, @@ -147,6 +149,18 @@ def preview_watch(body: WatchPreviewRequest, user: AdminWriter, db: Db, cfg: Cfg ) +@router.post("/watches/routes/preview") +def preview_routes(body: RoutePreviewRequest, user: AdminWriter, db: Db, cfg: Cfg) -> list[RoutedMessage]: + """Where the latest messages of an email account would go under these routing rules, before saving them.""" + try: + rows = sources.preview_routes(db, cfg, body.source, body.path, [r.model_dump() for r in body.routes], body.namespace) + except KeyError: + raise HTTPException(400, "no such source") from None + except (ValueError, RuntimeError) as e: + raise HTTPException(400, str(e)) from None + return [RoutedMessage(**r) for r in rows] + + @router.patch("/watches/{wid}") def update_watch(wid: int, body: WatchUpdate, user: AdminWriter, db: Db) -> Ok: _watch(db, wid) diff --git a/fastapi_backend/app/domain/feeds.py b/fastapi_backend/app/domain/feeds.py index c0705b3e6..c5313cb5b 100644 --- a/fastapi_backend/app/domain/feeds.py +++ b/fastapi_backend/app/domain/feeds.py @@ -24,6 +24,7 @@ import contextlib import datetime as dt import email +import email.utils import imaplib import re import ssl @@ -51,6 +52,8 @@ # not taken when a whole account is watched: what can't be opened, the bin, junk and drafts, and the mailboxes that # only show messages kept elsewhere (Gmail's All Mail, Starred and Important) SKIP_MAILBOXES = {"\\noselect", "\\nonexistent", "\\trash", "\\junk", "\\drafts", "\\all", "\\flagged", "\\important"} +# read with each message's listing (headers only): enough to name it, place it, and route it +HEADERS = ("SUBJECT", "DATE", "MESSAGE-ID", "FROM", "TO", "CC", "DELIVERED-TO", "X-ORIGINAL-TO", "LIST-ID") MAX_CALENDAR = 50 * 1024 * 1024 FEED_SECONDS = 60 # a calendar fetched for a listing is reused this long (a scan reads each of its events) _FEEDS: dict = {} @@ -191,7 +194,7 @@ def _messages(conn, mailbox, base, after=None): if not count: return [] last = int(after["uid"]) if after and int(after.get("validity") or -1) == validity else 0 - typ, data = conn.uid("FETCH", f"{last + 1}:*", "(UID RFC822.SIZE INTERNALDATE BODY.PEEK[HEADER.FIELDS (SUBJECT DATE MESSAGE-ID)])") + typ, data = conn.uid("FETCH", f"{last + 1}:*", f"(UID RFC822.SIZE INTERNALDATE BODY.PEEK[HEADER.FIELDS ({' '.join(HEADERS)})])") data = _ok(typ, data, f"reading {mailbox}") out, i = [], 0 while i < len(data): @@ -231,11 +234,40 @@ def _messages(conn, mailbox, base, after=None): sent or arrived, key=f"message-id:{msgid}" if msgid else None, cursor={"mailbox": mailbox, "validity": validity, "uid": int(uid.group(1))}, + mail=_addressing(h, subject, mailbox), ) ) return sorted(out, key=lambda e: e["modified"] or "", reverse=True) +def _addresses(h, *names): + """The addresses in these headers, lowercased, each once (Delivered-To and the like are read as plain text).""" + out = [] + for n in names: + try: + values = [str(v) for v in h.get_all(n) or []] + except (TypeError, ValueError): # a header too broken to read gives no addresses + continue + out += [a.strip().lower() for _, a in email.utils.getaddresses(values) if "@" in a] + return list(dict.fromkeys(out)) + + +def _addressing(h, subject, mailbox): + """What routing rules (mail_routes.py) look at: who sent it, who it was for (To, Cc, and the address a shared + inbox received it at), its subject, mailing list and mailbox.""" + try: + listed = str(h.get("list-id") or "").strip() + except (ValueError, TypeError): + listed = "" + return { + "from": _addresses(h, "from"), + "to": _addresses(h, "to", "cc", "delivered-to", "x-original-to"), + "subject": subject, + "list": listed, + "mailbox": mailbox, + } + + MESSAGE_RX = re.compile(r"^(?P.+)/(?P\d+)-(?P\d+)\.eml$") diff --git a/fastapi_backend/app/domain/mail_routes.py b/fastapi_backend/app/domain/mail_routes.py new file mode 100644 index 000000000..e0ca08697 --- /dev/null +++ b/fastapi_backend/app/domain/mail_routes.py @@ -0,0 +1,110 @@ +"""Routing rules for a watched email account: which namespace each new message goes to. + +A shared inbox (support@, info@, a family address) often carries mail for several namespaces. A watch on an IMAP +source can carry rules, tried in order; the first whose conditions all match a message decides where it goes: into +another namespace, or nowhere (skipped). A message no rule matches goes to the watch's own namespace, as it does with +no rules at all, and so does one whose rule names a namespace that has since been deleted. + +A condition looks at one part of the message (FIELDS) and holds one or more patterns, any of which may match. Patterns +ignore case; one without * or ? matches anywhere in the text (`acme.com` matches `ana@acme.com`), one with them must +match all of it (`*@acme.com`). `to` covers To, Cc and the address the inbox received the message at (Delivered-To, +X-Original-To), which is how mail sent to an alias of a shared inbox is told apart. + +Rules are kept on the watch with namespace ids (a renamed namespace keeps its mail), and shown with names. +""" + +from __future__ import annotations + +import fnmatch + +from . import store + +FIELDS = { + "from": "who sent it", + "to": "who it was for: To, Cc, or the address the inbox received it at", + "subject": "its subject", + "list": "its mailing list (List-Id)", + "mailbox": "the mailbox it is in", +} +MAX_RULES = 100 +MAX_PATTERNS = 50 + + +def _patterns(field, value): + vals = [value] if isinstance(value, str) else value + if not isinstance(vals, list) or not all(isinstance(v, str) for v in vals): + raise ValueError(f"{field} is a pattern or a list of patterns") + vals = [v.strip() for v in vals if v.strip()] + if not vals or len(vals) > MAX_PATTERNS: + raise ValueError(f"{field} needs between 1 and {MAX_PATTERNS} patterns") + return vals + + +def check(db, rules): + """Rules as the API takes them ({match: {field: patterns}, namespace} or {match, skip: true}), checked, with + namespace ids in place of names. A namespace must exist already: a rule never creates one.""" + if rules is None: + return [] + if not isinstance(rules, list) or len(rules) > MAX_RULES: + raise ValueError(f"routes is a list of at most {MAX_RULES} rules") + out = [] + for i, r in enumerate(rules, 1): + if not isinstance(r, dict): + raise ValueError(f"rule {i} isn't a rule") + match = r.get("match") or {} + if not isinstance(match, dict) or not match: + raise ValueError(f"rule {i} needs at least one condition: {', '.join(FIELDS)}") + if set(match) - set(FIELDS): + raise ValueError(f"rule {i}: conditions are on {', '.join(FIELDS)}") + rule = {"match": {f: _patterns(f, v) for f, v in match.items()}} + if r.get("skip"): + if r.get("namespace"): + raise ValueError(f"rule {i} either skips messages or sends them to a namespace, not both") + rule["skip"] = True + elif r.get("namespace"): + try: + rule["space"] = store.ns_id(db, r["namespace"], create=False) + except KeyError: + raise ValueError(f"rule {i}: there's no namespace {r['namespace']}") from None + else: + raise ValueError(f"rule {i} needs a namespace, or skip") + if r.get("name"): + rule["name"] = str(r["name"]).strip()[:100] + out.append(rule) + return out + + +def view(rules, names): + """Stored rules as the API shows them: namespaces by name (None for one deleted since).""" + out = [] + for r in rules or []: + shown = {"match": r["match"], "skip": bool(r.get("skip")), "namespace": None if r.get("skip") else names.get(r.get("space"))} + out.append({**shown, "name": r["name"]} if r.get("name") else shown) + return out + + +def _hit(pattern, text): + p, t = pattern.lower(), (text or "").lower() + return fnmatch.fnmatchcase(t, p) if any(c in p for c in "*?[") else p in t + + +def matches(rule, mail): + for field, patterns in rule["match"].items(): + got = mail.get(field) + texts = got if isinstance(got, list) else [got or ""] + if not any(_hit(p, t) for p in patterns for t in texts): + return False + return True + + +def route(rules, mail, home, spaces): + """Where a message goes: (namespace id, or None to skip it; the number of the rule that decided, or None). + `home` is the watch's namespace; `spaces` the namespace ids that exist.""" + if not mail: + return home, None + for i, r in enumerate(rules or [], 1): + if matches(r, mail): + if r.get("skip"): + return None, i + return (r["space"], i) if r.get("space") in spaces else (home, i) + return home, None diff --git a/fastapi_backend/app/domain/sources.py b/fastapi_backend/app/domain/sources.py index ae98d3e2a..30a597a47 100644 --- a/fastapi_backend/app/domain/sources.py +++ b/fastapi_backend/app/domain/sources.py @@ -4,7 +4,8 @@ this machine (only inside sources.local_roots); or, without rclone, an email account (IMAP) or a calendar feed (iCal), whose messages and events are shown as files (feeds.py). A watch maps a folder on a source to a namespace: new audio, video, documents (PDFs) and images become resources queued for the whole pipeline, their files staying on the source; new -transcripts are imported and queued for analysis. Credentials are stored encrypted and handed to rclone in a private +transcripts are imported and queued for analysis. A watch on an email account can carry routing rules that send some +messages to other namespaces, or skip them (mail_routes.py). Credentials are stored encrypted and handed to rclone in a private temporary config file per call; OAuth tokens rclone refreshes are saved. """ @@ -21,7 +22,7 @@ import subprocess import tempfile -from . import convert, deletion, feeds, ingest, jobs, settings, store +from . import convert, deletion, feeds, ingest, jobs, mail_routes, settings, store R = store.R BACKENDS = { @@ -70,6 +71,7 @@ "steps": None, "pipeline": None, "enabled": True, + "routes": [], # an email watch's routing rules (mail_routes.py); none: everything goes to its namespace } @@ -367,7 +369,7 @@ def list_sources(db): # ---------- watched folders ---------- def _check_watch(opts): - out = {k: opts[k] for k in WATCH if k in opts} + out = {k: opts[k] for k in WATCH if k in opts and k != "routes"} if out.get("kinds", WATCH["kinds"]) not in TAKES: raise ValueError(f"kinds is one of: {', '.join(TAKES)}") if not isinstance(out.get("poll_minutes", 5), int) or out.get("poll_minutes", 5) < 1: @@ -384,9 +386,20 @@ def _check_watch(opts): return out +def _routes(db, src, opts): + """The routing rules in `opts`, checked, as the watch keeps them ({} when they aren't being set).""" + if "routes" not in opts: + return {} + routes = mail_routes.check(db, opts["routes"]) + if routes and src["type"] != "imap": + raise ValueError("routing rules are for watches on an email account") + return {"routes": routes} + + def create_watch(db, cfg, sid, path, space, user=None, **opts): src = get(db, sid) p = check_path(cfg, src, path) + routes = _routes(db, src, opts) wid = db.next_id("watch_path") db.q( "CREATE $r CONTENT $d", @@ -395,6 +408,7 @@ def create_watch(db, cfg, sid, path, space, user=None, **opts): { **WATCH, **_check_watch(opts), + **routes, "source": sid, "path": p, "space": space, @@ -408,7 +422,9 @@ def create_watch(db, cfg, sid, path, space, user=None, **opts): def update_watch(db, wid, **opts): - db.q("UPDATE $r MERGE $d", r=R("watch_path", wid), d=_check_watch(opts)) + w = db.one("SELECT source FROM $r", r=R("watch_path", wid)) + routes = _routes(db, get(db, w["source"]), opts) if w else {} + db.q("UPDATE $r MERGE $d", r=R("watch_path", wid), d={**_check_watch(opts), **routes}) if {"kinds", "include", "exclude"} & set(opts): # what it takes changed: look through the mailboxes again db.q("UPDATE $r SET cursor = NONE", r=R("watch_path", wid)) @@ -419,12 +435,44 @@ def remove_watch(db, wid): def list_watches(db, spaces=None): q = ( - "SELECT record::id(id) AS id, source, path, space, kinds, poll_minutes, stable_seconds, backfill, include, exclude, steps, enabled, " + "SELECT record::id(id) AS id, source, path, space, kinds, poll_minutes, stable_seconds, backfill, include, exclude, steps, enabled, routes, " "last_scan_at, next_scan_at, last_stats, last_error FROM watch_path" ) rows = db.rows(q + (" WHERE space IN $sp" if spaces is not None else ""), sp=sorted(spaces or [])) names, srcs = store.space_names(db), {s["id"]: s["name"] for s in db.rows("SELECT record::id(id) AS id, name FROM storage_source")} - return [{**r, "namespace": names.get(r["space"]), "source_name": srcs.get(r["source"])} for r in rows] + return [ + {**r, "namespace": names.get(r["space"]), "source_name": srcs.get(r["source"]), "routes": mail_routes.view(r.get("routes"), names)} + for r in rows + ] + + +def preview_routes(db, cfg, sid, path, routes, home, limit=50): + """Where the latest messages of an email watch would go under these rules (as the API takes them), before + they're saved: one row per message, newest first, with the namespace (None: skipped) and the rule that decided. + `home` is the name of the watch's namespace, which may not exist yet.""" + src = get(db, sid) + if src["type"] != "imap": + raise ValueError("routing rules are for watches on an email account") + rules = _routes(db, src, {"routes": routes})["routes"] + names = store.space_names(db) + files = sorted(list_files(db, cfg, src, path), key=lambda f: f.get("modified") or "", reverse=True)[:limit] + out = [] + for f in files: + to, rule = mail_routes.route(rules, f.get("mail"), "", set(names)) # "": the watch's own namespace, `home` + mail = f.get("mail") or {} + out.append( + { + "path": f["path"], + "title": f.get("title"), + "when": f.get("when"), + "from": mail.get("from", []), + "to": mail.get("to", []), + "namespace": home if to == "" else names.get(to), + "skipped": to is None, + "rule": rule, + } + ) + return out def _when(s): @@ -533,14 +581,18 @@ def kind_of(cfg, w, f): def poll_watch(db, cfg, wid, log=print): w = db.one( "SELECT record::id(id) AS id, source, path, space, kinds, poll_minutes, stable_seconds, backfill, include, exclude, steps, pipeline, last_scan_at, " - "cursor FROM $r", + "cursor, routes FROM $r", r=R("watch_path", wid), ) src = get(db, w["source"]) first, now = not w.get("last_scan_at"), dt.datetime.now(dt.timezone.utc) known = {r["path"]: r for r in db.rows("SELECT path, size, modified, status FROM remote_file WHERE watch = $w", w=wid)} - gone = deletion.gone_remote(db, w["space"]) # recordings someone deleted stay deleted + gone = {w["space"]: deletion.gone_remote(db, w["space"])} # recordings someone deleted stay deleted stats = {"seen": 0, "new": 0, "waiting": 0, "skipped": 0, "errors": 0} + routes = w.get("routes") or [] + spaces = set(store.space_names(db)) if routes else set() + if routes: + stats["routed"] = 0 files, held = list_files(db, cfg, src, w["path"], w.get("cursor")), set() for f in files: kind = kind_of(cfg, w, f) @@ -552,7 +604,12 @@ def poll_watch(db, cfg, wid, log=print): continue key = R("remote_file", f"{wid}-{hashlib.sha1(f['path'].encode()).hexdigest()[:20]}") row = {"watch": wid, "path": f["path"], "size": f["size"], "modified": f["modified"], "seen_at": store.now()} - if (first and not w.get("backfill")) or (src["id"], f["path"]) in gone: + space, rule = mail_routes.route(routes, f.get("mail"), w["space"], spaces) if routes else (w["space"], None) + if rule: + row.update(rule=rule, space=space) + if space is not None and space not in gone: + gone[space] = deletion.gone_remote(db, space) + if space is None or (first and not w.get("backfill")) or (src["id"], f["path"]) in gone[space]: db.q("UPSERT $k CONTENT $d", k=key, d={**row, "status": "skipped"}) stats["skipped"] += 1 elif (now - _when(f["modified"])).total_seconds() < (w.get("stable_seconds") or 0): @@ -561,9 +618,11 @@ def poll_watch(db, cfg, wid, log=print): held.add(f["path"]) else: try: - rid, _job = _ingest(db, cfg, src, f, kind, w["space"], f"watch:{wid}", w.get("steps"), w.get("pipeline")) + rid, _job = _ingest(db, cfg, src, f, kind, space, f"watch:{wid}", w.get("steps"), w.get("pipeline")) db.q("UPSERT $k CONTENT $d", k=key, d={**row, "status": "queued", "recording": rid}) stats["new"] += 1 + if space != w["space"]: + stats["routed"] += 1 except Exception as e: # noqa: BLE001 - one bad file must not stop the scan db.q("UPSERT $k CONTENT $d", k=key, d={**row, "status": "error", "error": f"{type(e).__name__}: {e}"[:300]}) stats["errors"] += 1 diff --git a/fastapi_backend/app/schemas/sources.py b/fastapi_backend/app/schemas/sources.py index 619fc1e11..965bce852 100644 --- a/fastapi_backend/app/schemas/sources.py +++ b/fastapi_backend/app/schemas/sources.py @@ -85,6 +85,30 @@ class BrowseEntry(ResponseModel): imported: list[ImportedAs] = Field(default_factory=list, description="the recordings this file already is, and where") +RouteField = Literal["from", "to", "subject", "list", "mailbox"] +ROUTES_HELP = ( + "an email watch's routing rules, tried in order: the first whose conditions all match a new message sends it to its " + "namespace (or skips it); a message no rule matches goes to the watch's namespace. Patterns ignore case; without " + "* or ? they match anywhere in the text. `to` covers To, Cc and the address the inbox received it at." +) + + +class Route(RequestModel): + match: dict[RouteField, str | list[str]] = Field( + description="conditions, all of which must match; each holds patterns, any of which may" + ) + namespace: str | None = Field(default=None, description="where matching messages go (a namespace that exists)") + skip: bool = Field(default=False, description="matching messages aren't imported at all") + name: str | None = Field(default=None, max_length=100) + + +class RouteView(ResponseModel): + match: dict[str, list[str]] + namespace: str | None = Field(default=None, description="None when skipped, or the namespace was deleted") + skip: bool = False + name: str | None = None + + class WatchOptions(RequestModel): kinds: WatchKinds | None = Field(default=None, description=KINDS_HELP) poll_minutes: int | None = Field(default=None, ge=1) @@ -95,6 +119,7 @@ class WatchOptions(RequestModel): steps: list[str] | None = None pipeline: int | None = None enabled: bool | None = None + routes: list[Route] | None = Field(default=None, description=ROUTES_HELP) class WatchCreate(WatchOptions): @@ -138,7 +163,26 @@ class Watch(ResponseModel): exclude: list[str] | None = None steps: list[str] | None = None enabled: bool | None = None + routes: list[RouteView] = [] last_scan_at: str | None = None next_scan_at: str | None = None last_stats: dict[str, Any] | None = None last_error: str | None = None + + +class RoutePreviewRequest(RequestModel): + source: int + path: str = "" + namespace: str = Field(description="the watch's own namespace, for messages no rule matches") + routes: list[Route] = [] + + +class RoutedMessage(ResponseModel): + path: str + title: str | None = None + when: str | None = None + from_: list[str] = Field(default=[], alias="from") + to: list[str] = [] + namespace: str | None = None + skipped: bool = False + rule: int | None = Field(default=None, description="the rule that decided, counted from 1; None: no rule matched") diff --git a/fastapi_backend/tests/api/test_mail_routes.py b/fastapi_backend/tests/api/test_mail_routes.py new file mode 100644 index 000000000..ce8963ec7 --- /dev/null +++ b/fastapi_backend/tests/api/test_mail_routes.py @@ -0,0 +1,160 @@ +"""Routing rules on a watched email account: a shared inbox's messages sent to different namespaces, or skipped, by +who sent them, who they were for, their subject, list or mailbox. Runs against the fake IMAP server.""" + +from __future__ import annotations + +from email.message import EmailMessage + +import pytest + +from app.domain import convert, mail_routes, sources, store +from tests import fake_imap +from tests.helpers import login, make_user + +R = store.R + + +def _mail(subject, sender, to, uid, *, cc=None, delivered=None, listed=None): + m = EmailMessage() + m["Subject"], m["From"], m["To"], m["Date"] = subject, sender, to, "Tue, 29 Sep 2026 09:30:00 +0100" + m["Message-ID"] = f"<{uid}@example.org>" + if cc: + m["Cc"] = cc + if delivered: + m["Delivered-To"] = delivered + if listed: + m["List-Id"] = listed + m.set_content(f"Message {uid}.") + return (uid, m.as_bytes(), f"{uid:02d}-Sep-2026 09:31:02 +0100") + + +def _inbox(): + return { + "INBOX": [ + _mail("Invoice 2231", "Billing ", "info@harbour.org", 1), + _mail("Ticket: lamp broken", "Ana ", "Help Desk ", 2), + _mail("Lunch?", "Tom ", "info@harbour.org", 3, cc="Mara "), + _mail("Weekly digest", "news@lists.example", "info@harbour.org", 4, listed="Harbour news "), + _mail("Forwarded", "Ana ", "someone@else.org", 5, delivered="support@harbour.org"), + ], + "Archive": [_mail("Old invoice", "billing@acme.com", "info@harbour.org", 6)], + } + + +@pytest.fixture +def imap(): + srv = fake_imap.start(_inbox()) + yield srv + srv.shutdown() + + +@pytest.fixture +def admin(client, db): + make_user(db, "root@x.io", "root password 1", admin=True) + return login(client, "root@x.io", "root password 1") + + +@pytest.fixture +def mail(client, db, admin, imap, monkeypatch): + monkeypatch.setattr(convert, "soffice", lambda cfg: None) # no converters: emails are read as text + monkeypatch.setattr(convert, "chromium", lambda cfg: None) + params = {"host": "127.0.0.1", "port": str(imap.port), "security": "none", "user": "lens"} + r = client.post( + "/api/v1/sources", headers=admin, json={"name": "shared", "type": "imap", "params": params, "secrets": {"pass": "mail password 1"}} + ) + assert r.status_code == 200, r.text + for ns in ("finance", "support", "family"): + store.ns_id(db, ns) + return r.json()["id"] + + +RULES = [ + {"name": "Bills", "match": {"from": "*@acme.com"}, "namespace": "finance"}, + {"match": {"to": "support@"}, "namespace": "support"}, + {"match": {"list": "news.lists.example"}, "skip": True}, +] + + +def _where(db): + names = store.space_names(db) + return {r["title"]: names[r["space"]] for r in db.rows("SELECT title, space FROM recording")} + + +def test_a_shared_inbox_routed_to_namespaces(client, db, cfg, admin, mail, imap): + h = admin + # before saving: the latest messages, and where each would go + r = client.post( + "/api/v1/watches/routes/preview", headers=h, json={"source": mail, "path": "INBOX", "namespace": "family", "routes": RULES} + ) + assert r.status_code == 200, r.text + shown = {m["title"]: (m["namespace"], m["skipped"], m["rule"]) for m in r.json()} + assert shown == { + "Invoice 2231": ("finance", False, 1), + "Ticket: lamp broken": ("support", False, 2), + "Lunch?": ("family", False, None), # no rule: the watch's namespace + "Weekly digest": (None, True, 3), + "Forwarded": ("support", False, 2), # received at the shared alias + } + lunch = next(m for m in r.json() if m["title"] == "Lunch?") + assert lunch["from"] == ["tom@harbour.org"] and lunch["to"] == ["info@harbour.org", "mara@harbour.org"] + + r = client.post( + "/api/v1/watches", + headers=h, + json={"source": mail, "path": "INBOX", "namespace": "family", "stable_seconds": 0, "backfill": True, "routes": RULES}, + ) + assert r.status_code == 200, r.text + wid = r.json()["id"] + watch = next(w for w in client.get("/api/v1/watches", headers=h).json() if w["id"] == wid) + assert watch["routes"][0] == {"name": "Bills", "match": {"from": ["*@acme.com"]}, "namespace": "finance", "skip": False} + assert watch["routes"][2]["skip"] and watch["routes"][2]["namespace"] is None + + assert sources.poll_watch(db, cfg, wid) == {"seen": 5, "new": 4, "waiting": 0, "skipped": 1, "errors": 0, "routed": 3} + assert _where(db) == {"Invoice 2231": "finance", "Ticket: lamp broken": "support", "Lunch?": "family", "Forwarded": "support"} + skipped = db.one("SELECT status, rule FROM remote_file WHERE path = 'INBOX/7-4.eml'") + assert skipped == {"status": "skipped", "rule": 3} + + # rules apply to mail that comes after a change; a namespace deleted since sends its mail home + r = client.patch( + f"/api/v1/watches/{wid}", headers=h, json={"routes": [{"match": {"subject": ["door", "window"]}, "namespace": "finance"}]} + ) + assert r.status_code == 200, r.text + imap.mailboxes["INBOX"].append(_mail("Ticket: door", "x@y.org", "info@harbour.org", 7)) + imap.mailboxes["INBOX"].append(_mail("Invoice 9", "billing@acme.com", "info@harbour.org", 8)) + assert sources.poll_watch(db, cfg, wid)["routed"] == 1 + assert _where(db)["Ticket: door"] == "finance" and _where(db)["Invoice 9"] == "family" + + +def test_rules_are_checked(client, admin, mail): + h = admin + base = {"source": mail, "path": "INBOX", "namespace": "family"} + for routes, said in [ + ([{"match": {}, "namespace": "finance"}], "at least one condition"), + ([{"match": {"from": "a"}}], "needs a namespace, or skip"), + ([{"match": {"from": "a"}, "namespace": "nowhere"}], "no namespace nowhere"), # rules never create namespaces + ([{"match": {"from": "a"}, "namespace": "finance", "skip": True}], "not both"), + ([{"match": {"from": [" "]}, "namespace": "finance"}], "between 1 and"), + ]: + r = client.post("/api/v1/watches", headers=h, json={**base, "routes": routes}) + assert r.status_code == 400 and said in r.json()["detail"], (routes, r.text) + r = client.post("/api/v1/watches", headers=h, json={**base, "routes": [{"match": {"sender": "a"}, "namespace": "finance"}]}) + assert r.status_code == 422 # not a field rules look at + + +def test_rules_only_on_email_watches(db): + store.ns_id(db, "finance") + with pytest.raises(ValueError, match="email account"): + sources._routes(db, {"type": "local"}, {"routes": [{"match": {"from": "a"}, "namespace": "finance"}]}) + assert sources._routes(db, {"type": "local"}, {"routes": []}) == {"routes": []} # none is fine anywhere + + +def test_matching(): + rule = {"match": {"from": ["*@acme.com", "boss@"], "subject": ["invoice"]}} + mail = {"from": ["billing@ACME.com"], "to": [], "subject": "Your Invoice", "list": "", "mailbox": "INBOX"} + assert mail_routes.matches(rule, mail) + assert not mail_routes.matches(rule, {**mail, "subject": "Hello"}) # every condition must match + assert mail_routes.matches(rule, {**mail, "from": ["boss@harbour.org"]}) # any pattern of one may + assert not mail_routes.matches(rule, {**mail, "from": ["billing@acme.com.evil.io"]}) # a pattern with * matches whole + assert mail_routes.route([], mail, 5, {5}) == (5, None) + assert mail_routes.route([{**rule, "space": 9}], mail, 5, {5}) == (5, 1) # namespace deleted: home + assert mail_routes.route([{**rule, "space": 9}], None, 5, {5, 9}) == (5, None) # not an email: home diff --git a/fastapi_backend/tests/fake_imap.py b/fastapi_backend/tests/fake_imap.py index a672d1685..a74c12e49 100644 --- a/fastapi_backend/tests/fake_imap.py +++ b/fastapi_backend/tests/fake_imap.py @@ -101,10 +101,11 @@ def uid(self, tag, args, messages): self.send(f"* {seq} FETCH (UID {uid} BODY[] {{{len(raw)}}}\r\n".encode() + raw + b")\r\n") continue msg = email.message_from_bytes(raw, policy=policy.default) - head = "".join(f"{k}: {msg[k]}\r\n" for k in ("Subject", "Date", "Message-ID") if msg[k] is not None).encode() + b"\r\n" + fields = re.search(r"HEADER\.FIELDS \(([^)]*)\)", items).group(1) + head = "".join(f"{k}: {v}\r\n" for k in fields.split() for v in msg.get_all(k) or []).encode() + b"\r\n" self.send( f'* {seq} FETCH (UID {uid} RFC822.SIZE {len(raw)} INTERNALDATE "{arrived}" ' - f"BODY[HEADER.FIELDS (SUBJECT DATE MESSAGE-ID)] {{{len(head)}}}\r\n".encode() + f"BODY[HEADER.FIELDS ({fields})] {{{len(head)}}}\r\n".encode() + head + b")\r\n" ) diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 91a05e1b4..d0cab4602 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -1779,6 +1779,11 @@ export type { PreviewImportResponse, PreviewImportResponses, PreviewLine, + PreviewRoutesData, + PreviewRoutesError, + PreviewRoutesErrors, + PreviewRoutesResponse, + PreviewRoutesResponses, PreviewScheduleData, PreviewScheduleError, PreviewScheduleErrors, @@ -2051,6 +2056,10 @@ export type { RotateNotifySecretErrors, RotateNotifySecretResponse, RotateNotifySecretResponses, + Route, + RoutedMessage, + RoutePreviewRequest, + RouteView, Routine, RoutineCatalog, RoutineCreate, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 852367a54..81dd57f07 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -883,6 +883,9 @@ import type { PreviewImportData, PreviewImportErrors, PreviewImportResponses, + PreviewRoutesData, + PreviewRoutesErrors, + PreviewRoutesResponses, PreviewScheduleData, PreviewScheduleErrors, PreviewScheduleResponses, @@ -6661,6 +6664,24 @@ export class Sources { }); } + /** + * Preview Routes + * + * Where the latest messages of an email account would go under these routing rules, before saving them. + */ + public static previewRoutes( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/watches/routes/preview", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + /** * Delete Watch */ diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 95b8c829a..725c2bdc9 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -11154,6 +11154,128 @@ export type RollbackAsk = { dry_run?: boolean; }; +/** + * Route + */ +export type Route = { + /** + * Match + * + * conditions, all of which must match; each holds patterns, any of which may + */ + match: { + [key: string]: string | Array; + }; + /** + * Namespace + * + * where matching messages go (a namespace that exists) + */ + namespace?: string | null; + /** + * Skip + * + * matching messages aren't imported at all + */ + skip?: boolean; + /** + * Name + */ + name?: string | null; +}; + +/** + * RoutePreviewRequest + */ +export type RoutePreviewRequest = { + /** + * Source + */ + source: number; + /** + * Path + */ + path?: string; + /** + * Namespace + * + * the watch's own namespace, for messages no rule matches + */ + namespace: string; + /** + * Routes + */ + routes?: Array; +}; + +/** + * RouteView + */ +export type RouteView = { + /** + * Match + */ + match: { + [key: string]: Array; + }; + /** + * Namespace + * + * None when skipped, or the namespace was deleted + */ + namespace?: string | null; + /** + * Skip + */ + skip?: boolean; + /** + * Name + */ + name?: string | null; + [key: string]: unknown; +}; + +/** + * RoutedMessage + */ +export type RoutedMessage = { + /** + * Path + */ + path: string; + /** + * Title + */ + title?: string | null; + /** + * When + */ + when?: string | null; + /** + * From + */ + from?: Array; + /** + * To + */ + to?: Array; + /** + * Namespace + */ + namespace?: string | null; + /** + * Skipped + */ + skipped?: boolean; + /** + * Rule + * + * the rule that decided, counted from 1; None: no rule matched + */ + rule?: number | null; + [key: string]: unknown; +}; + /** * Routine */ @@ -15306,6 +15428,10 @@ export type Watch = { * Enabled */ enabled?: boolean | null; + /** + * Routes + */ + routes?: Array; /** * Last Scan At */ @@ -15371,6 +15497,12 @@ export type WatchCreate = { * Enabled */ enabled?: boolean | null; + /** + * Routes + * + * an email watch's routing rules, tried in order: the first whose conditions all match a new message sends it to its namespace (or skips it); a message no rule matches goes to the watch's namespace. Patterns ignore case; without * or ? they match anywhere in the text. `to` covers To, Cc and the address the inbox received it at. + */ + routes?: Array | null; /** * Source */ @@ -15486,6 +15618,12 @@ export type WatchUpdate = { * Enabled */ enabled?: boolean | null; + /** + * Routes + * + * an email watch's routing rules, tried in order: the first whose conditions all match a new message sends it to its namespace (or skips it); a message no rule matches goes to the watch's namespace. Patterns ignore case; without * or ? they match anywhere in the text. `to` covers To, Cc and the address the inbox received it at. + */ + routes?: Array | null; }; /** @@ -26105,6 +26243,33 @@ export type PreviewWatchResponses = { export type PreviewWatchResponse = PreviewWatchResponses[keyof PreviewWatchResponses]; +export type PreviewRoutesData = { + body: RoutePreviewRequest; + path?: never; + query?: never; + url: "/api/v1/watches/routes/preview"; +}; + +export type PreviewRoutesErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type PreviewRoutesError = PreviewRoutesErrors[keyof PreviewRoutesErrors]; + +export type PreviewRoutesResponses = { + /** + * Response Sources-Preview Routes + * + * Successful Response + */ + 200: Array; +}; + +export type PreviewRoutesResponse = PreviewRoutesResponses[keyof PreviewRoutesResponses]; + export type DeleteWatchData = { body?: never; path: { diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 6b28eb2ee..55874e71c 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -16681,6 +16681,52 @@ } } }, + "/api/v1/watches/routes/preview": { + "post": { + "tags": [ + "sources" + ], + "summary": "Preview Routes", + "description": "Where the latest messages of an email account would go under these routing rules, before saving them.", + "operationId": "preview_routes", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RoutePreviewRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/RoutedMessage" + }, + "type": "array", + "title": "Response Sources-Preview Routes" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/watches/{wid}": { "patch": { "tags": [ @@ -41785,6 +41831,234 @@ ], "title": "RollbackAsk" }, + "Route": { + "properties": { + "match": { + "additionalProperties": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ] + }, + "propertyNames": { + "enum": [ + "from", + "to", + "subject", + "list", + "mailbox" + ] + }, + "type": "object", + "title": "Match", + "description": "conditions, all of which must match; each holds patterns, any of which may" + }, + "namespace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Namespace", + "description": "where matching messages go (a namespace that exists)" + }, + "skip": { + "type": "boolean", + "title": "Skip", + "description": "matching messages aren't imported at all", + "default": false + }, + "name": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ], + "title": "Name" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "match" + ], + "title": "Route" + }, + "RoutePreviewRequest": { + "properties": { + "source": { + "type": "integer", + "title": "Source" + }, + "path": { + "type": "string", + "title": "Path", + "default": "" + }, + "namespace": { + "type": "string", + "title": "Namespace", + "description": "the watch's own namespace, for messages no rule matches" + }, + "routes": { + "items": { + "$ref": "#/components/schemas/Route" + }, + "type": "array", + "title": "Routes", + "default": [] + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "source", + "namespace" + ], + "title": "RoutePreviewRequest" + }, + "RouteView": { + "properties": { + "match": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object", + "title": "Match" + }, + "namespace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Namespace", + "description": "None when skipped, or the namespace was deleted" + }, + "skip": { + "type": "boolean", + "title": "Skip", + "default": false + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "match" + ], + "title": "RouteView" + }, + "RoutedMessage": { + "properties": { + "path": { + "type": "string", + "title": "Path" + }, + "title": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Title" + }, + "when": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "When" + }, + "from": { + "items": { + "type": "string" + }, + "type": "array", + "title": "From", + "default": [] + }, + "to": { + "items": { + "type": "string" + }, + "type": "array", + "title": "To", + "default": [] + }, + "namespace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Namespace" + }, + "skipped": { + "type": "boolean", + "title": "Skipped", + "default": false + }, + "rule": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Rule", + "description": "the rule that decided, counted from 1; None: no rule matched" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "path" + ], + "title": "RoutedMessage" + }, "Routine": { "properties": { "id": { @@ -49044,6 +49318,14 @@ ], "title": "Enabled" }, + "routes": { + "items": { + "$ref": "#/components/schemas/RouteView" + }, + "type": "array", + "title": "Routes", + "default": [] + }, "last_scan_at": { "anyOf": [ { @@ -49221,6 +49503,21 @@ ], "title": "Enabled" }, + "routes": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/Route" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Routes", + "description": "an email watch's routing rules, tried in order: the first whose conditions all match a new message sends it to its namespace (or skips it); a message no rule matches goes to the watch's namespace. Patterns ignore case; without * or ? they match anywhere in the text. `to` covers To, Cc and the address the inbox received it at." + }, "source": { "type": "integer", "title": "Source" @@ -49464,6 +49761,21 @@ } ], "title": "Enabled" + }, + "routes": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/Route" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Routes", + "description": "an email watch's routing rules, tried in order: the first whose conditions all match a new message sends it to its namespace (or skips it); a message no rule matches goes to the watch's namespace. Patterns ignore case; without * or ? they match anywhere in the text. `to` covers To, Cc and the address the inbox received it at." } }, "additionalProperties": false,