Files
member-portal/loomio_inbound.py
T

128 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""Relay Loomio reply-by-email messages from Cloudron mail into Loomio.
Loomio's notification Reply-To addresses look like
d=<discussion>&u=<user>&k=<email_api_key>@forum-reply.inference.coop
Cloudron's Loomio package has no inbound mail receiver (upstream Haraka needs
port 25, which Cloudron cannot expose), so this job polls the catch-all mailbox
and hands each raw message to Loomio's ActionMailbox relay endpoint.
Runs from the Cloudron scheduler addon. Env comes from the portal app's launch
environment (same secrets the app process sees).
"""
import base64
import imaplib
import os
import ssl
import sys
from datetime import datetime, timedelta, timezone
from urllib.error import HTTPError
from urllib.request import Request, urlopen
def required(name: str) -> str:
value = os.environ.get(name)
if not value:
raise SystemExit(f"loomio-inbound: {name} is not set")
return value
IMAP_HOST = os.environ.get("LOOMIO_INBOUND_IMAP_HOST", "my.inference.coop")
IMAP_PORT = int(os.environ.get("LOOMIO_INBOUND_IMAP_PORT", "993"))
IMAP_USER = required("LOOMIO_INBOUND_IMAP_USERNAME")
IMAP_PASSWORD = required("LOOMIO_INBOUND_IMAP_PASSWORD")
RELAY_URL = os.environ.get(
"LOOMIO_INBOUND_RELAY_URL",
"https://forum.inference.coop/rails/action_mailbox/relay/inbound_emails",
)
RELAY_PASSWORD = required("LOOMIO_INBOUND_RELAY_PASSWORD")
MAX_PER_RUN = int(os.environ.get("LOOMIO_INBOUND_MAX", "50"))
KEEP_DAYS = int(os.environ.get("LOOMIO_INBOUND_KEEP_DAYS", "30"))
def relay(raw: bytes) -> int:
auth = base64.b64encode(f"actionmailbox:{RELAY_PASSWORD}".encode()).decode()
req = Request(
RELAY_URL,
data=raw,
method="POST",
headers={
"Authorization": f"Basic {auth}",
"Content-Type": "message/rfc822",
},
)
with urlopen(req, timeout=60) as resp:
return resp.status
def fetch_raw(imap: imaplib.IMAP4_SSL, uid: str) -> bytes:
typ, data = imap.uid("FETCH", uid, "(BODY.PEEK[])")
if typ != "OK":
raise RuntimeError(f"FETCH failed: {typ}")
for item in data or []:
if isinstance(item, tuple) and len(item) >= 2 and isinstance(item[1], (bytes, bytearray)):
return bytes(item[1])
raise RuntimeError("FETCH returned no message body")
def main() -> int:
ctx = ssl.create_default_context()
imap = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, ssl_context=ctx)
try:
imap.login(IMAP_USER, IMAP_PASSWORD)
typ, data = imap.select("INBOX")
if typ != "OK":
raise RuntimeError(f"SELECT INBOX failed: {typ}")
typ, data = imap.uid("SEARCH", "UNSEEN")
if typ != "OK":
raise RuntimeError(f"SEARCH UNSEEN failed: {typ}")
uids = (data[0].split() if data and data[0] else [])[:MAX_PER_RUN]
print(f"loomio-inbound: {len(uids)} unseen message(s)")
relayed = 0
for uid in uids:
try:
raw = fetch_raw(imap, uid.decode())
status = relay(raw)
imap.uid("STORE", uid.decode(), "+FLAGS", "(\\Seen)")
relayed += 1
print(f"loomio-inbound: uid {uid.decode()} relayed ({status}, {len(raw)} bytes)")
except HTTPError as exc:
print(
f"loomio-inbound: uid {uid.decode()} relay HTTP {exc.code}",
file=sys.stderr,
)
if exc.code in (401, 403):
return 1
except Exception as exc: # keep the message unseen for the next tick
print(
f"loomio-inbound: uid {uid.decode()} failed: "
f"{type(exc).__name__}: {exc}",
file=sys.stderr,
)
try:
cutoff = (datetime.now(timezone.utc) - timedelta(days=KEEP_DAYS)).strftime("%d-%b-%Y")
typ, data = imap.uid("SEARCH", f"SEEN BEFORE {cutoff}")
old = data[0].split() if typ == "OK" and data and data[0] else []
for uid in old:
imap.uid("STORE", uid.decode(), "+FLAGS", "(\\Deleted)")
if old:
imap.expunge()
print(f"loomio-inbound: relayed={relayed} purged={len(old)}")
except Exception as exc:
print(f"loomio-inbound: purge skipped: {type(exc).__name__}: {exc}", file=sys.stderr)
return 0
finally:
try:
imap.logout()
except Exception:
pass
if __name__ == "__main__":
sys.exit(main())