Conversations: pump LibreDesk through aimsight-libredesk, list and show the transcripts safely
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ca2f66ce3d
commit
3544f29d85
6 files changed
+449
-2
No files matched your search
+37
-1
@@ -377,7 +377,43 @@ def check_support():
|
||||
support.supports.clear()
|
||||
|
||||
|
||||
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support]
|
||||
def check_conversations():
|
||||
# the Conversations page (conversations.py): the list, the transcript rendered safely, the files, the pumping refused
|
||||
# on a bad range; without LibreDesk (the pumping is libredesk/conversations/, tested there)
|
||||
import conversations
|
||||
root, before = temp_folder(), conversations.FOLDER
|
||||
conversations.FOLDER = root
|
||||
try:
|
||||
c = root / "42"
|
||||
(c / "attachments").mkdir(parents=True)
|
||||
(c / "conversation.json").write_text(json.dumps({"reference_number": "42", "subject": "A jump", "status": "Open",
|
||||
"updated_at": "2026-11-18T09:00:00Z", "contact": {"first_name": "Jean", "last_name": "", "email": "j@x.ch"}}))
|
||||
(c / "messages.json").write_text(json.dumps([
|
||||
{"type": "incoming", "created_at": "2026-11-18T08:00:00Z", "attachments": [{"url": "attachments/p.png"}]},
|
||||
{"type": "activity", "created_at": "2026-11-18T08:05:00Z", "attachments": []},
|
||||
{"type": "outgoing", "created_at": "2026-11-18T08:10:00Z", "attachments": [{"url": "attachments/x.svg"}]}]))
|
||||
(c / "transcript.md").write_text("# A jump\n\n<script>alert(1)</script>\n\n\n")
|
||||
(c / "attachments" / "p.png").write_bytes(b"png")
|
||||
(c / "attachments" / "x.svg").write_text("<svg onload='alert(1)'/>")
|
||||
(root / "pumped.json").write_text("{}") # not a conversation
|
||||
assert conversations.list_conversations() == [{"reference": "42", "subject": "A jump", "contact": "Jean",
|
||||
"status": "Open", "last": "2026-11-18T08:10:00Z", "messages": 2, "attachments": 2}], conversations.list_conversations()
|
||||
page = conversations.transcript("42", False)
|
||||
assert "<script>" not in page and "<script>" in page and '<img alt="p" src="attachments/p.png"' in page, page
|
||||
assert server.conversation_file("42", "attachments/x.svg").headers["content-disposition"].startswith("attachment")
|
||||
png = server.conversation_file("42", "attachments/p.png").headers
|
||||
assert "content-disposition" not in png and png["x-content-type-options"] == "nosniff"
|
||||
assert "img-src 'self'" in server.conversation_transcript("42").headers["content-security-policy"]
|
||||
refuses(conversations.transcript, "../analyses", False)
|
||||
refuses(server.conversation_file, "42", "../../etc/passwd")
|
||||
assert "From and To" in refuses(conversations.pump, {"start": "2026-11-01"})
|
||||
assert set(conversations.pump_state()) == {"running", "log"}
|
||||
finally:
|
||||
conversations.FOLDER = before
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support, check_conversations]
|
||||
|
||||
if __name__ == "__main__":
|
||||
name = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""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)
|
||||
+37
-1
@@ -2,7 +2,8 @@
|
||||
|
||||
The FastAPI server serves the built React page (app/web/dist, `npm run build` in app/web) and the API under /api.
|
||||
The Data page reads data/ and the labels of labeling/ (station.py); its Analysis tab launches the analyst, and the
|
||||
optimization of the detectors (analysis.py); its Support tab, the support (support.py).
|
||||
optimization of the detectors (analysis.py); its Support tab, the support (support.py). The Conversations page, the
|
||||
LibreDesk conversations pumped by ~/aimsight-libredesk (conversations.py).
|
||||
Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770).
|
||||
"""
|
||||
import json
|
||||
@@ -19,6 +20,7 @@ from fastapi import FastAPI, Query, Request
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
|
||||
import analysis
|
||||
import conversations
|
||||
import station
|
||||
import support
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -200,6 +202,40 @@ def support_file(name: str, path: str):
|
||||
return FileResponse(analysis.file(name, path, support.FOLDER))
|
||||
|
||||
|
||||
# --- the Conversations page (conversations.py): the LibreDesk conversations, pumped read-only, and their transcripts
|
||||
|
||||
CSP = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'" # a client's mail: no script, no remote image
|
||||
|
||||
|
||||
@app.get("/api/conversations/pump")
|
||||
def conversations_pump_state():
|
||||
return conversations.pump_state()
|
||||
|
||||
|
||||
@app.post("/api/conversations/pump")
|
||||
def conversations_pump(body: dict):
|
||||
return conversations.pump(body)
|
||||
|
||||
|
||||
@app.get("/api/conversations")
|
||||
def conversations_list():
|
||||
return conversations.list_conversations()
|
||||
|
||||
|
||||
@app.get("/api/conversations/{reference}/report.html")
|
||||
def conversation_transcript(reference: str, dark: bool = False):
|
||||
return HTMLResponse(conversations.transcript(reference, dark), headers={"Content-Security-Policy": CSP})
|
||||
|
||||
|
||||
@app.get("/api/conversations/{reference}/{path:path}")
|
||||
def conversation_file(reference: str, path: str):
|
||||
"""A plain image inline; any other attachment (an .html, an .svg) as a download: it never runs at the app's address."""
|
||||
f = analysis.file(reference, path, conversations.FOLDER)
|
||||
headers = {"X-Content-Type-Options": "nosniff", "Content-Security-Policy": CSP}
|
||||
return FileResponse(f, headers=headers) if f.suffix.lower() in conversations.INLINE \
|
||||
else FileResponse(f, filename=f.name, headers=headers)
|
||||
|
||||
|
||||
if PAGE.is_dir():
|
||||
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
|
||||
else:
|
||||
|
||||
Reference in new issue
Block a user