loomio: relay reply-by-email messages from Cloudron mail into ActionMailbox

This commit is contained in:
inference-bot committed 2026-12-03 19:14:11 +00:00
1 parent bbd8115058
commit 3db67e54f3
4 files changed
+135 -3

No files matched your search

+4
View File
@@ -29,6 +29,10 @@
"credit_cycle_close": {
"schedule": "*/10 * * * *",
"command": "/app/code/credit_cycle_close.sh"
},
"loomio_inbound": {
"schedule": "*/2 * * * *",
"command": "/app/code/loomio_inbound.py"
}
}
},
+2 -1
View File
@@ -12,7 +12,8 @@ COPY sweep.sh /app/code/sweep.sh
COPY service_sync.sh /app/code/service_sync.sh
COPY credit_cycle_close.sh /app/code/credit_cycle_close.sh
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/credit_cycle_close.sh /app/code/metrics_snapshot.py
COPY loomio_inbound.py /app/code/loomio_inbound.py
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/credit_cycle_close.sh /app/code/metrics_snapshot.py /app/code/loomio_inbound.py
# Run as root (the base image default). Cloudron's sandboxing (read-only
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
+2 -2
View File
@@ -180,7 +180,7 @@ points. Remaining work before production:
## Scheduled tasks (scheduler addon)
Four jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
Five jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
- **membership_sweep** (`0 3,11,19 * * *` UTC — three times a day) — `sweep.sh`
calls the portal's own `/admin/sweep` (auth: the `X-Admin-Token` header with
@@ -316,7 +316,7 @@ Four jobs run inside the container via `CloudronManifest.json` → `addons.sched
Methodology: [Energy and carbon metrics](docs/energy-metrics.md).
Verify after any manifest change: the deploy log must show
`setupAddons: ... scheduler ...` listing all four tasks, and each script must
`setupAddons: ... scheduler ...` listing all five tasks, and each script must
succeed when run manually inside the container.
### Allowance renewal (payment-driven, join-day anchored)
+127
View File
@@ -0,0 +1,127 @@
#!/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())