128 lines
7.7 KiB
Python
128 lines
7.7 KiB
Python
"""Phase 0 sur l'instance LibreDesk de test (127.0.0.1:9100, SMTP = Mailpit 127.0.0.1:9125). Rien ne sort."""
|
|||
|
|
import http.cookiejar, json, sys, time, urllib.error, urllib.parse, urllib.request
|
||
|
|
|
||
|
|
B, MP = "http://127.0.0.1:9100", "http://127.0.0.1:9125"
|
||
|
|
jar = http.cookiejar.CookieJar()
|
||
|
|
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||
|
|
|
||
|
|
|
||
|
|
def req(m, p, body=None, auth=None, quiet=False):
|
||
|
|
r = urllib.request.Request(B + p, method=m, data=json.dumps(body).encode() if body is not None else None,
|
||
|
|
headers={"Content-Type": "application/json"})
|
||
|
|
if auth:
|
||
|
|
r.add_header("Authorization", f"token {auth}")
|
||
|
|
else:
|
||
|
|
csrf = next((c.value for c in jar if c.name == "csrf_token"), None)
|
||
|
|
if csrf:
|
||
|
|
r.add_header("X-CSRFTOKEN", csrf)
|
||
|
|
try:
|
||
|
|
with (urllib.request.urlopen(r) if auth else op.open(r)) as x:
|
||
|
|
return x.status, json.loads(x.read() or b"{}").get("data")
|
||
|
|
except urllib.error.HTTPError as e:
|
||
|
|
t = e.read().decode()
|
||
|
|
return e.code, (json.loads(t).get("message") if t.startswith("{") else t[:200])
|
||
|
|
|
||
|
|
|
||
|
|
def mailpit():
|
||
|
|
return json.load(urllib.request.urlopen(MP + "/api/v1/messages"))["messages_count"]
|
||
|
|
|
||
|
|
|
||
|
|
def ok(nom, cond, detail=""):
|
||
|
|
print(("OK " if cond else "ÉCHEC ") + nom + (f" [{detail}]" if detail else ""))
|
||
|
|
|
||
|
|
|
||
|
|
print("login", req("POST", "/api/v1/auth/login", {"email": "System", "password": sys.argv[1]})[0])
|
||
|
|
for c in jar:
|
||
|
|
c.secure = False # cookies Secure : http local
|
||
|
|
jar.set_cookie(http.cookiejar.Cookie(0, "csrf_token", "t0k3n", None, False, "127.0.0.1", False, False, "/", True,
|
||
|
|
False, None, False, None, None, {})) # le serveur compare cookie et en-tête
|
||
|
|
|
||
|
|
# boîte e-mail, SMTP = Mailpit
|
||
|
|
s, inbox = req("POST", "/api/v1/inboxes", {"name": "Test", "channel": "email", "enabled": True, "csat_enabled": False, "from": "Support <support@example.com>",
|
||
|
|
"config": {"auth_type": "password", "from": "Support <support@example.com>",
|
||
|
|
"smtp": [{"enabled": True, "host": "mailpit", "port": 1025, "username": "", "password": "",
|
||
|
|
"auth_protocol": "none", "tls_type": "none", "max_conns": 1, "max_msg_retries": 0,
|
||
|
|
"idle_timeout": "5s", "pool_wait_timeout": "5s", "hello_hostname": ""}],
|
||
|
|
"imap": [{"host": "127.0.0.1", "port": 1, "username": "x", "password": "x", "mailbox": "INBOX",
|
||
|
|
"read_interval": "1h", "scan_inbox_since": "1h", "tls_type": "none"}]}})
|
||
|
|
print("inbox", s, inbox if s != 200 else inbox["id"])
|
||
|
|
inbox_id = inbox["id"]
|
||
|
|
|
||
|
|
# étiquettes : caractères
|
||
|
|
for nom in ["tri:diagnostic", "diag-fait", "diag-en-cours", "tri-diagnostic", "Brouillon IA 🤖"]:
|
||
|
|
s, d = req("POST", "/api/v1/tags", {"name": nom})
|
||
|
|
ok(f"créer l'étiquette « {nom} »", s == 200, d if s != 200 else "")
|
||
|
|
tags = {t["name"]: t["id"] for t in req("GET", "/api/v1/tags")[1]}
|
||
|
|
|
||
|
|
# rôle restreint + agent IA + clé
|
||
|
|
perms = ["conversations:read", "conversations:read_all", "messages:read", "messages:write_private", "conversations:update_tags"]
|
||
|
|
s, role = req("POST", "/api/v1/roles", {"name": "Agent IA", "description": "notes privées seulement", "permissions": perms})
|
||
|
|
print("role", s, role if s != 200 else perms)
|
||
|
|
s, ag = req("POST", "/api/v1/agents", {"first_name": "Agent", "last_name": "IA", "email": "agent-ia@example.com",
|
||
|
|
"roles": ["Agent IA"], "send_welcome_email": False, "enabled": True})
|
||
|
|
print("agent", s, ag if s != 200 else ag["id"])
|
||
|
|
s, k = req("POST", f"/api/v1/agents/{ag['id']}/api-key")
|
||
|
|
print("api-key", s, list(k) if s == 200 else k)
|
||
|
|
KEY = f"{k['api_key']}:{k['api_secret']}"
|
||
|
|
|
||
|
|
# une conversation : un mail « client » (créée par l'admin, ce qui envoie un premier mail sortant vers Mailpit)
|
||
|
|
s, conv = req("POST", "/api/v1/conversations", {"inbox_id": inbox_id, "contact_email": "client@example.com",
|
||
|
|
"first_name": "Client", "last_name": "Test", "initiator": "contact", "subject": "Courbes bizarres", "content": "<p>amorce</p>"})
|
||
|
|
print("conversation", s, conv if s != 200 else conv["uuid"])
|
||
|
|
cu = conv["uuid"]
|
||
|
|
time.sleep(5)
|
||
|
|
m0 = mailpit()
|
||
|
|
|
||
|
|
# 1. note privée par la clé restreinte
|
||
|
|
s, n = req("POST", f"/api/v1/conversations/{cu}/messages", {"message": "<p>🤖 BROUILLON IA</p>", "private": True,
|
||
|
|
"sender_type": "agent"}, auth=KEY)
|
||
|
|
ok("note privée (clé restreinte)", s == 200 and n.get("private") is True, f"{s} private={n.get('private') if s == 200 else n}")
|
||
|
|
# 2. réponse au client par la clé restreinte : doit être refusée
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/messages", {"message": "<p>réponse</p>", "private": False,
|
||
|
|
"sender_type": "agent"}, auth=KEY)
|
||
|
|
ok("réponse refusée sans messages:write", s == 403, f"{s} {d}")
|
||
|
|
# 3. sans le champ private (défaut), clé restreinte
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/messages", {"message": "<p>défaut</p>", "sender_type": "agent"}, auth=KEY)
|
||
|
|
ok("sans « private » : refusé aussi (défaut = réponse)", s == 403, f"{s} {d}")
|
||
|
|
# 4. sans sender_type
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/messages", {"message": "<p>x</p>", "private": True}, auth=KEY)
|
||
|
|
print("note sans sender_type :", s, d if s != 200 else "acceptée")
|
||
|
|
time.sleep(5)
|
||
|
|
ok("aucun mail de plus dans Mailpit", mailpit() == m0, f"{m0} → {mailpit()}")
|
||
|
|
|
||
|
|
# 5. même appel sans private avec l'admin : part-il ? (instance de test seulement)
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/messages", {"message": "<p>admin défaut</p>", "sender_type": "agent",
|
||
|
|
"to": ["client@example.com"]})
|
||
|
|
time.sleep(8)
|
||
|
|
print("admin sans private :", s, "type", d.get("type") if s == 200 else d, "| Mailpit", m0, "→", mailpit())
|
||
|
|
|
||
|
|
# étiquettes : add / remove, étiquette inconnue, set par défaut
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/tags", {"tags": ["tri:diagnostic"], "action": "add_tags"}, auth=KEY)
|
||
|
|
ok("add_tags", s == 200, f"{s} {d}")
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/tags", {"tags": ["diag-en-cours"], "action": "add_tags"}, auth=KEY)
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/tags", {"tags": ["inconnue"], "action": "add_tags"}, auth=KEY)
|
||
|
|
print("add_tags d'une étiquette inexistante :", s, d)
|
||
|
|
s, c = req("GET", f"/api/v1/conversations/{cu}", auth=KEY)
|
||
|
|
print("étiquettes :", c.get("tags"))
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/tags", {"tags": ["diag-en-cours"], "action": "remove_tags"}, auth=KEY)
|
||
|
|
print("remove_tags →", req("GET", f"/api/v1/conversations/{cu}", auth=KEY)[1].get("tags"))
|
||
|
|
|
||
|
|
# filtre par étiquette
|
||
|
|
for f in ([{"model": "conversations", "field": "tags", "operator": "contains", "value": json.dumps([tags["tri:diagnostic"]])}],
|
||
|
|
[{"model": "conversations", "field": "tags", "operator": "not contains", "value": json.dumps([tags["diag-fait"]])}]):
|
||
|
|
s, d = req("GET", "/api/v1/conversations/all?page_size=50&filters=" + urllib.parse.quote(json.dumps(f)), auth=KEY)
|
||
|
|
print("filtre", f[0]["operator"], s, [x["uuid"] == cu for x in d["results"]] if s == 200 else d)
|
||
|
|
|
||
|
|
# brouillon : visible par qui ?
|
||
|
|
s, d = req("POST", f"/api/v1/conversations/{cu}/draft", {"content": "<p>brouillon IA</p>", "type": "reply"}, auth=KEY)
|
||
|
|
print("brouillon par la clé :", s)
|
||
|
|
s, d = req("GET", "/api/v1/drafts")
|
||
|
|
print("brouillons vus par l'admin :", s, len(d or []))
|
||
|
|
|
||
|
|
# suppression de sa propre note
|
||
|
|
s, d = req("DELETE", f"/api/v1/conversations/{cu}/messages/{n['uuid']}", auth=KEY)
|
||
|
|
ok("supprimer sa note privée", s == 200, f"{s} {d}")
|
||
|
|
|
||
|
|
# suggestion d'étiquettes par clé API (sans fournisseur IA configuré : on regarde seulement l'accès)
|
||
|
|
s, d = req("POST", "/api/v1/ai/suggest-tags", {"conversation_uuid": cu}, auth=KEY)
|
||
|
|
print("suggest-tags par clé :", s, d)
|