app/: the Support page reads client mails from LibreDesk (read-only)

Menu « Depuis LibreDesk » : the 50 latest conversations; choosing one fills the
mail (thread newest first, no private notes, decoded subjects) and its images
over 10 kB. Settings LIBREDESK_* in API/.env; check_libredesk in check.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-05 16:30:38 +01:00
1 parent 67a1d71c57
commit b475da0acc
6 files changed
+148 -4

No files matched your search

+29 -1
View File
@@ -109,7 +109,35 @@ def check_station():
station.ETIQUETTES = avant
CHECKS = [check_serveur, check_station]
def check_libredesk():
# le fil et ses images depuis de fausses réponses de l'API : ordre, notes privées, logos écartés
import base64
import libredesk
png = b"\x89PNG" + b"x" * libredesk.TAILLE_MIN
msgs = [{"created_at": "2026-11-04T08:00Z", "type": "incoming", "private": False, "text_content": "Bonjour, trou ?",
"author": {"first_name": "David", "email": "d@x.ch"}, "meta": {"subject": "Crissier"},
"attachments": [{"name": "c.png", "content_type": "image/png", "size": len(png), "url": "/uploads/a"},
{"name": "logo.png", "content_type": "image/png", "size": 900, "url": "/uploads/b"}]},
{"created_at": "2026-11-04T09:00Z", "type": "outgoing", "private": True, "text_content": "note interne"},
{"created_at": "2026-11-05T08:00Z", "type": "outgoing", "private": False, "text_content": "Hello David",
"author": {"first_name": "Marc"}}]
avant = libredesk._requete
libredesk._requete = lambda c: json.dumps({"data": {"results": msgs}}).encode() if "/messages" in c else png
try:
c = libredesk.conversation("0b1c-2d")
finally:
libredesk._requete = avant
assert c["mail"].index("Hello David") < c["mail"].index("Bonjour, trou ?") and "note interne" not in c["mail"], c["mail"]
assert "De: David <d@x.ch>" in c["mail"] and "Objet: Crissier" in c["mail"], c["mail"]
assert [i["nom"] for i in c["images"]] == ["c.png"] and base64.b64decode(c["images"][0]["base64"]) == png
try:
libredesk.conversation("../x")
raise AssertionError("uuid ../x accepté")
except ValueError:
pass
CHECKS = [check_serveur, check_station, check_libredesk]
if __name__ == "__main__":
nom = sys.argv[1] if len(sys.argv) > 1 else None
+79
View File
@@ -0,0 +1,79 @@
"""Les mails des clients depuis le LibreDesk de l'entreprise, en lecture seule (API REST v1, https://docs.libredesk.io).
Réglages, dans API/.env (chargé par seance.py) : LIBREDESK_URL (ex. https://support.aimsight.ch), LIBREDESK_API_KEY,
LIBREDESK_API_SECRET (Admin → Teammates → Agents → Generate API key ; permissions conversations:read_all, messages:read).
"""
import base64
import email.header
import json
import os
import urllib.parse
import urllib.request
TYPES_IMAGE = {"image/png", "image/jpeg", "image/gif", "image/webp"} # ceux que lit la séance (seance.TYPES_IMAGE)
TAILLE_MIN = 10_000 # ponytail: octets ; écarte les logos des signatures, à revoir si une vraie capture est plus petite
class Absent(Exception):
"""LibreDesk n'est pas configuré dans API/.env."""
def _requete(chemin: str) -> bytes:
base, cle, secret = (os.environ.get(k, "") for k in ("LIBREDESK_URL", "LIBREDESK_API_KEY", "LIBREDESK_API_SECRET"))
if not (base and cle and secret):
raise Absent("LibreDesk non configuré : LIBREDESK_URL, LIBREDESK_API_KEY, LIBREDESK_API_SECRET dans API/.env")
r = urllib.request.Request(urllib.parse.urljoin(base.rstrip("/") + "/", chemin.lstrip("/")))
r.add_unredirected_header("Authorization", f"token {cle}:{secret}") # pas vers S3 si /uploads redirige
with urllib.request.urlopen(r, timeout=30) as rep:
return rep.read()
def _objet(s: str | None) -> str:
"""Un objet de mail encodé (=?Windows-1252?Q?…?=, RFC 2047) en clair ; tel quel s'il ne se décode pas."""
try:
return str(email.header.make_header(email.header.decode_header(s or "")))
except (LookupError, ValueError, UnicodeDecodeError):
return s or ""
def _json(chemin: str) -> dict:
return json.loads(_requete(chemin))["data"]
def conversations() -> list[dict]:
"""Les 50 conversations au dernier message le plus récent."""
d = _json("/api/v1/conversations/all?page_size=50&order_by=conversations.last_message_at&order=desc")
return [{"uuid": c["uuid"], "reference": c["reference_number"], "sujet": _objet(c.get("subject")) or "(sans objet)",
"contact": " ".join(filter(None, [(c.get("contact") or {}).get(k) for k in ("first_name", "last_name")])),
"date": c.get("last_message_at"), "statut": c.get("status")} for c in d["results"]]
def mail(messages: list[dict]) -> str:
"""Le fil en texte, le plus récent en tête comme un mail collé ; ni notes privées ni activités."""
blocs = []
for m in sorted(messages, key=lambda m: m["created_at"], reverse=True):
if m.get("private") or m.get("type") not in ("incoming", "outgoing"):
continue
a, meta = m.get("author") or {}, m.get("meta") or {}
qui = " ".join(filter(None, [a.get("first_name"), a.get("last_name")])) or ", ".join(meta.get("from") or [])
tete = [f"De: {qui}" + (f" <{a['email']}>" if a.get("email") else ""), f"Date: {m['created_at']}"]
if meta.get("subject"):
tete.append(f"Objet: {_objet(meta['subject'])}")
blocs.append("\n".join(tete) + "\n\n" + (m.get("text_content") or m.get("content") or "").strip())
return "\n\n---\n\n".join(blocs)
def conversation(uuid: str) -> dict:
"""Le mail et ses images (base64, comme les captures collées dans la page Support)."""
if not uuid.replace("-", "").isalnum():
raise ValueError("uuid invalide")
msgs = _json(f"/api/v1/conversations/{uuid}/messages?page_size=500&type=incoming&type=outgoing")["results"]
images = []
for m in msgs:
if m.get("private"):
continue
for p in m.get("attachments") or []:
if p.get("content_type") in TYPES_IMAGE and (p.get("size") or 0) >= TAILLE_MIN and p.get("url"):
images.append({"nom": p.get("name") or "piece", "type": p["content_type"],
"base64": base64.b64encode(_requete(p["url"])).decode()})
return {"mail": mail(msgs), "images": images}
+19
View File
@@ -21,6 +21,7 @@ import uvicorn
from fastapi import FastAPI, Query, Request
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
import libredesk
import station
from fastapi.staticfiles import StaticFiles
@@ -138,6 +139,24 @@ def message(corps: dict):
return {}
# --- les mails de LibreDesk (libredesk.py), pour remplir la page Support
@app.get("/api/libredesk")
def libredesk_liste():
try:
return libredesk.conversations()
except Exception as e: # noqa: BLE001 — non configuré ou injoignable : le dire dans la page
return erreur(502, f"LibreDesk : {e}")
@app.get("/api/libredesk/{uuid}")
def libredesk_conversation(uuid: str):
try:
return libredesk.conversation(uuid)
except Exception as e: # noqa: BLE001
return erreur(502, f"LibreDesk : {e}")
# --- les pages Images et Data (station.py)
@app.exception_handler(station.Refus)