79 lines
3.9 KiB
Python
79 lines
3.9 KiB
Python
"""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}
|