"""Le transcript lisible d'une conversation pompée (transcript.md) : du texte seul, jamais le HTML d'un mail ; les images en ligne, les autres pièces jointes en lien, vers attachments/. Les messages sont déjà sous leur forme locale (pomper.py).""" import re import urllib.parse from datetime import datetime, timezone from html.parser import HTMLParser BLOCS = {"p", "div", "li", "tr", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6"} class _Texte(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.morceaux, self._cache = [], 0 def handle_starttag(self, tag, attrs): if tag in ("script", "style"): self._cache += 1 elif tag == "br": self.morceaux.append("\n") elif tag in BLOCS: self.morceaux.append("\n\n") def handle_endtag(self, tag): if tag in ("script", "style"): self._cache = max(0, self._cache - 1) elif tag in BLOCS: self.morceaux.append("\n\n") def handle_data(self, data): if not self._cache: self.morceaux.append(data) def texte(contenu_html: str) -> str: """Le HTML d'un message en texte : balises retirées, entités décodées, paragraphes gardés.""" p = _Texte() p.feed(contenu_html or "") p.close() t = re.sub(r"[ \t]*\n[ \t]*", "\n", "".join(p.morceaux)) return re.sub(r"\n{3,}", "\n\n", t).strip() def _heure(t: str) -> str: return datetime.fromisoformat(t).astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M") + " UTC" def _nom(personne: dict | None) -> str: return " ".join(x for x in ((personne or {}).get("first_name"), (personne or {}).get("last_name")) if x) def _pieces(pieces: list[dict]) -> list[str]: lignes = [] for a in pieces: cible = urllib.parse.quote(a.get("url") or "") image = (a.get("content_type") or "").startswith("image/") and a.get("content_type") != "image/svg+xml" lignes.append(f"{'!' * image}[{a.get('name')}]({cible})") return lignes def transcript(conversation: dict, messages: list[dict]) -> str: c = conversation.get("contact") or {} contact = " ".join(x for x in (_nom(c), c.get("email")) if x) morceaux = [f"# {conversation.get('subject') or '(sans sujet)'} (#{conversation.get('reference_number')})", f"Contact : {contact} · Boîte : {conversation.get('inbox_name')} · Statut : {conversation.get('status')}" f" · Créée : {_heure(conversation['created_at'])}"] for m in messages: corps = (m.get("text_content") or "").strip() or texte(m.get("content")) if m.get("type") == "activity": morceaux.append(f"*{_heure(m['created_at'])} — {corps}*") continue client = m.get("sender_type") == "contact" role = "note privée" if m.get("private") else "client" if client else "agent" auteur = _nom(m.get("author")) or ("Client" if client else "Agent") morceaux.append(f"## {_heure(m['created_at'])} — {auteur} ({role})") if corps: morceaux.append(corps) if lignes := _pieces(m.get("attachments") or []): morceaux.append("\n".join(lignes)) return "\n\n".join(morceaux) + "\n"