"""Polls the LibreDesk conversations into Supabase (docs/superpowers/specs/2026-11-24-conversations-supabase-design.md): the tables conversations and messages (LibreDesk's response kept as is in raw, private notes included), the attachments in the private bucket attachments, under /. LibreDesk is only read, through conversations.pomper.Lecteur (GET only, its key goes only to LibreDesk). Supabase is written through its REST API (PostgREST, Storage), with the service_role key, which goes only to Supabase. A run: the conversations updated since the checkpoint of the last complete run (table checkpoints) minus MARGE, the most recent first; everything the first time. Each conversation and its messages are upserted: running again never makes a duplicate. The checkpoint is written only at the end of a complete run: an interrupted run is taken up by the next one. LIBREDESK_URL=… LIBREDESK_API_KEY=… LIBREDESK_API_SECRET=… SUPABASE_CONVERSATIONS_URL=… SUPABASE_CONVERSATIONS_KEY=… python3 -m poller.poll [--every SECONDS] """ import argparse import json import os import sys import time import urllib.error import urllib.parse import urllib.request from datetime import datetime, timezone from typing import Callable from conversations.pomper import MARGE, PERDUE, Lecteur, _date, recentes BUCKET = "attachments" CHECKPOINT = "conversations" REFUSED = {400, 413} # an attachment Storage refuses (too big, for example): skipped, noted, never blocks the next runs KEYS = {"checkpoints": "name"} # the primary key of each table; uuid by default class Supabase: """The client of Supabase, restricted to its REST API (tables and Storage).""" def __init__(self, url: str, key: str): self.url, self._key = url.rstrip("/"), key def _request(self, method: str, path: str, body: bytes | None = None, headers: dict | None = None) -> bytes: if not path.startswith(("/rest/v1/", "/storage/v1/")): raise ValueError(f"not a Supabase path: {path}") r = urllib.request.Request(self.url + path, data=body, method=method) r.add_header("apikey", self._key) if self._key.startswith("eyJ"): # an old JWT key; a new sb_secret_ key goes only in apikey r.add_header("Authorization", f"Bearer {self._key}") for k, v in ({"Content-Type": "application/json"} | (headers or {})).items(): r.add_header(k, v) with urllib.request.urlopen(r, timeout=60) as answer: return answer.read() def checkpoint(self) -> datetime | None: rows = json.loads(self._request("GET", f"/rest/v1/checkpoints?name=eq.{CHECKPOINT}&select=until")) return _date(rows[0]["until"]) if rows else None def write_checkpoint(self, t: datetime) -> None: self.upsert("checkpoints", [{"name": CHECKPOINT, "until": t.isoformat()}]) def upsert(self, table: str, rows: list[dict]) -> None: self._request("POST", f"/rest/v1/{table}?on_conflict={KEYS.get(table, 'uuid')}", json.dumps(rows, ensure_ascii=False).encode(), {"Prefer": "resolution=merge-duplicates,return=minimal"}) def objects(self, folder: str) -> set[str]: """The names of the files under / in the bucket.""" body = json.dumps({"prefix": f"{folder}/", "limit": 1000}).encode() return {o["name"] for o in json.loads(self._request("POST", f"/storage/v1/object/list/{BUCKET}", body))} def put(self, key: str, content: bytes, type_: str) -> None: self._request("POST", f"/storage/v1/object/{BUCKET}/{urllib.parse.quote(key)}", content, {"Content-Type": type_, "x-upsert": "true"}) def _save_attachments(reader: Lecteur, supabase: Supabase, conv_uuid: str, messages: list[dict], log) -> int: """Uploads the attachments missing from the bucket; each one's url (signed, it expires) becomes its key.""" present, n = supabase.objects(conv_uuid), 0 for m in messages: for i, a in enumerate(m.get("attachments") or []): name = a.get("uuid") or f"{m['uuid']}-{i}" key, url = f"{conv_uuid}/{name}", a.get("url") or "" if url and name not in present: try: supabase.put(key, reader.lire(url), a.get("content_type") or "application/octet-stream") except urllib.error.HTTPError as e: e.close() if e.code not in (REFUSED if e.url.startswith(supabase.url) else PERDUE): raise # a passing failure: the run stops, the next one takes it up log(f" attachment {key} skipped: {e.code}") a["url"], a["absent"] = "", True continue if url: m["content"] = (m.get("content") or "").replace(url.replace("&", "&"), url).replace(url, key) a["url"] = key n += 1 return n def poll_once(reader: Lecteur, supabase: Supabase, log=print) -> int: """One run; returns the number of conversations saved.""" start, checkpoint, n = datetime.now(timezone.utc), supabase.checkpoint(), 0 for c in recentes(reader, checkpoint - MARGE if checkpoint else None): messages = reader.messages(c["uuid"]) n_attachments = _save_attachments(reader, supabase, c["uuid"], messages, log) raw = {k: v for k, v in c.items() if k != "previous_conversations"} ref = c.get("reference_number") supabase.upsert("conversations", [{ "uuid": c["uuid"], "reference_number": None if ref is None else str(ref), "subject": c.get("subject"), "status": c.get("status"), "inbox_name": c.get("inbox_name"), "contact_email": (c.get("contact") or {}).get("email"), "created_at": c.get("created_at"), "updated_at": c["updated_at"], "raw": raw}]) if messages: supabase.upsert("messages", [{ "uuid": m["uuid"], "conversation_uuid": c["uuid"], "type": m.get("type"), "sender_type": m.get("sender_type"), "private": m.get("private"), "created_at": m.get("created_at"), "raw": m} for m in messages]) log(f"#{ref} {c.get('subject') or ''}: {len(messages)} messages, {n_attachments} attachments") n += 1 supabase.write_checkpoint(start) # only after a complete run log(f"{n} conversation(s) saved") return n def _describe(e: Exception) -> str: """An error for the log, without the signature of an attachment URL.""" if isinstance(e, urllib.error.HTTPError): return f"{e.code} on {e.url.split('?')[0]}" if isinstance(e, urllib.error.URLError): return f"unreachable: {e.reason}" return f"{type(e).__name__}: {e}".split("?")[0] def loop(run: Callable[[], int], every: int, log=print, sleep=time.sleep) -> None: """run() forever, every `every` seconds; a failed run is noted and the next one starts again.""" while True: try: run() except Exception as e: # noqa: BLE001 — the poller must outlive a failed run log(f"run failed: {_describe(e)}") if isinstance(e, urllib.error.HTTPError): e.close() sleep(every) def main(): p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) p.add_argument("--every", type=int, help="seconds between two runs; without it, a single run") a = p.parse_args() names = ("LIBREDESK_API_KEY", "LIBREDESK_API_SECRET", "SUPABASE_CONVERSATIONS_URL", "SUPABASE_CONVERSATIONS_KEY") missing = [n for n in names if not os.environ.get(n)] if missing: sys.exit("missing variables: " + ", ".join(missing)) reader = Lecteur(os.environ.get("LIBREDESK_URL", "https://helpdesk.sensima.ch"), os.environ["LIBREDESK_API_KEY"], os.environ["LIBREDESK_API_SECRET"]) supabase = Supabase(os.environ["SUPABASE_CONVERSATIONS_URL"], os.environ["SUPABASE_CONVERSATIONS_KEY"]) log = lambda line: print(line, flush=True) # noqa: E731 if a.every: loop(lambda: poll_once(reader, supabase, log), a.every, log) try: poll_once(reader, supabase, log) except Exception as e: # noqa: BLE001 sys.exit(_describe(e)) if __name__ == "__main__": main()