54 lines
2.4 KiB
Python
54 lines
2.4 KiB
Python
"""The Conversations page: the LibreDesk conversations, pumped read-only by ~/aimsight-libredesk (link libredesk/,
|
|||
|
|
conversations/pompage.py, called as it is; its key stays in its .env) into labeling/auto/conversations/<reference>/
|
||
|
|
(conversation.json, messages.json, attachments/, transcript.md). The app lists them and shows a transcript safely: the text
|
||
|
|
escaped before Markdown (a client's <script> stays text), served with a strict CSP (no script, no remote image), the
|
||
|
|
attachments other than plain images as downloads.
|
||
|
|
"""
|
||
|
|
import html
|
||
|
|
import json
|
||
|
|
import sys
|
||
|
|
|
||
|
|
import analysis
|
||
|
|
import station
|
||
|
|
|
||
|
|
FOLDER = station.LABELS / "auto" / "conversations"
|
||
|
|
LIBREDESK = station.ROOT / "libredesk"
|
||
|
|
sys.path.insert(0, str(LIBREDESK / "conversations"))
|
||
|
|
import pompage # noqa: E402
|
||
|
|
|
||
|
|
INLINE = {".png", ".jpg", ".jpeg", ".gif", ".webp"} # shown in the page; any other attachment is downloaded
|
||
|
|
|
||
|
|
|
||
|
|
def pump_state():
|
||
|
|
return {"running": pompage.running(), "log": pompage.log()}
|
||
|
|
|
||
|
|
|
||
|
|
def pump(body):
|
||
|
|
try:
|
||
|
|
pompage.start(body.get("start") or "", body.get("end") or "", str(FOLDER))
|
||
|
|
except ValueError as e:
|
||
|
|
raise station.Refusal(str(e)) from e
|
||
|
|
return pump_state()
|
||
|
|
|
||
|
|
|
||
|
|
def list_conversations():
|
||
|
|
"""Each pumped conversation, the most recent message first."""
|
||
|
|
out = []
|
||
|
|
for f in FOLDER.glob("*/conversation.json"):
|
||
|
|
c = json.loads(f.read_text(encoding="utf-8"))
|
||
|
|
m = f.with_name("messages.json")
|
||
|
|
messages = json.loads(m.read_text(encoding="utf-8")) if m.exists() else []
|
||
|
|
contact = c.get("contact") or {}
|
||
|
|
out.append({"reference": f.parent.name, "subject": c.get("subject") or "", "status": c.get("status") or "",
|
||
|
|
"contact": " ".join(x for x in (contact.get("first_name"), contact.get("last_name")) if x)
|
||
|
|
or contact.get("email") or "",
|
||
|
|
"last": max((x["created_at"] for x in messages), default=c.get("updated_at") or ""),
|
||
|
|
"messages": sum(x.get("type") != "activity" for x in messages),
|
||
|
|
"attachments": sum(len(x.get("attachments") or []) for x in messages)})
|
||
|
|
return sorted(out, key=lambda c: c["last"], reverse=True)
|
||
|
|
|
||
|
|
|
||
|
|
def transcript(reference, dark):
|
||
|
|
"""transcript.md in HTML, escaped first: what a client wrote is shown, never run."""
|
||
|
|
text = analysis.file(reference, "transcript.md", FOLDER).read_text(encoding="utf-8")
|
||
|
|
return analysis._page(html.escape(text, quote=False), reference, dark)
|