mock_chat.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. #!/usr/bin/env python3
  2. """Mock Cloudron Chat server + Cloudron OIDC login for the NebOS chat client.
  3. Two plain-HTTP origins on the host, reachable from a QEMU slirp guest as
  4. 10.0.2.2:
  5. chat (default port 18080): /auth/login, /auth/callback, /auth/return,
  6. /auth/logout and the /api/* routes the client uses, including
  7. /api/avatars/<uid>, /api/attachments/<id> and /api/previews/p1 for
  8. pictures
  9. login (default port 18081): /openid/auth, /openid/interaction/<uid>
  10. (login page with cloudron-config JSON, consent page as a bare
  11. auto-submit form), POST .../login and .../confirm
  12. Accounts (password "test"):
  13. test plain login
  14. totp needs the TOTP code 123456
  15. passkey passkey-only (the client must fall back to the cookie screen)
  16. consent login is followed by a consent interaction (auto-confirmed)
  17. Debug endpoints on the chat port (no auth):
  18. GET /debug/state JSON dump (messages, reads, joins)
  19. POST /debug/inject {"channel","body","user"} message from another user
  20. POST /debug/presence {"user","presence"}
  21. Usage: tools/mock_chat.py [--host 0.0.0.0] [--chat-port 18080]
  22. [--login-port 18081] [--public-host 10.0.2.2] [--messages N]
  23. """
  24. import argparse
  25. import datetime
  26. import json
  27. import secrets
  28. import struct
  29. import threading
  30. import zlib
  31. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  32. from urllib.parse import parse_qs, urlparse
  33. LOCK = threading.Lock()
  34. STATE = {
  35. "users": {
  36. "u-test": {"id": "u-test", "username": "test", "name": "Test User",
  37. "picture": ""},
  38. "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example",
  39. "picture": "/api/avatars/u-alice"},
  40. "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm",
  41. "picture": "/api/avatars/u-bob"},
  42. "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol",
  43. "picture": ""},
  44. "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User",
  45. "picture": ""},
  46. "u-consent": {"id": "u-consent", "username": "consent",
  47. "name": "Consent User", "picture": ""},
  48. },
  49. "channels": {}, # id -> {id,name,type,members:set,description}
  50. "messages": {}, # channel id -> [msg]
  51. "reads": {}, # (channel, user) -> last read message id
  52. "presence": {"u-alice": "online", "u-bob": "away", "u-carol": "offline"},
  53. "sessions": {}, # connect.sid -> user id (or None = pre-login)
  54. "interactions": {}, # uid -> {"pre": sid, "user": None, "consent": bool}
  55. "log": [],
  56. }
  57. SEQ = [0]
  58. ARGS = None
  59. def png_chunk(tag, data):
  60. return (struct.pack(">I", len(data)) + tag + data +
  61. struct.pack(">I", zlib.crc32(tag + data) & 0xffffffff))
  62. def png_rgb(w, h, pixel):
  63. raw = bytearray()
  64. for y in range(h):
  65. raw.append(0)
  66. for x in range(w):
  67. raw.extend(pixel(x, y))
  68. return (b"\x89PNG\r\n\x1a\n" +
  69. png_chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) +
  70. png_chunk(b"IDAT", zlib.compress(bytes(raw), 6)) +
  71. png_chunk(b"IEND", b""))
  72. AVATAR_PNGS = {}
  73. def avatar_png(uid):
  74. if uid in AVATAR_PNGS:
  75. return AVATAR_PNGS[uid]
  76. h = sum(ord(c) for c in uid)
  77. colors = [(208, 90, 90), (90, 154, 208), (90, 176, 112),
  78. (192, 138, 58), (154, 106, 200), (58, 168, 168)]
  79. r, g, b = colors[h % len(colors)]
  80. def pixel(x, y):
  81. # A coloured disc with a lighter centre, so the screenshot shows a
  82. # real avatar rather than the initial fallback.
  83. dx, dy = x - 15.5, y - 15.5
  84. if dx * dx + dy * dy > 15.5 * 15.5:
  85. return (32, 34, 38)
  86. if 8 <= x <= 23 and 12 <= y <= 19:
  87. return (245, 245, 245)
  88. return (r, g, b)
  89. AVATAR_PNGS[uid] = png_rgb(32, 32, pixel)
  90. return AVATAR_PNGS[uid]
  91. def attachment_png():
  92. def pixel(x, y):
  93. if (x // 8 + y // 8) % 2:
  94. return (240, 150, 40)
  95. return (40, 90, 160)
  96. return png_rgb(96, 64, pixel)
  97. ATTACHMENT_PNG = attachment_png()
  98. def preview_png():
  99. def pixel(x, y):
  100. if (x // 16 + y // 16) % 2:
  101. return (68, 132, 220)
  102. return (30, 36, 52)
  103. return png_rgb(160, 100, pixel)
  104. PREVIEW_PNG = preview_png()
  105. def note(line):
  106. STATE["log"].append(line)
  107. if ARGS and ARGS.verbose:
  108. print(line, flush=True)
  109. def now_iso():
  110. SEQ[0] += 1
  111. t = datetime.datetime(2026, 11, 9, 9, 0, 0) + datetime.timedelta(seconds=37 * SEQ[0])
  112. return t.strftime("%Y-%m-%dT%H:%M:%S.") + "%03dZ" % (SEQ[0] % 1000)
  113. def add_channel(cid, name, ctype, members, description=""):
  114. STATE["channels"][cid] = {"id": cid, "name": name, "type": ctype,
  115. "members": set(members), "description": description}
  116. STATE["messages"][cid] = []
  117. def add_message(cid, uid, body, client_id=None, reply_to=None, extra=None):
  118. msgs = STATE["messages"][cid]
  119. m = {"id": "m%05d" % (SEQ[0] + 1), "clientId": client_id, "channelId": cid,
  120. "userId": uid, "authorName": STATE["users"][uid]["name"],
  121. "authorUsername": STATE["users"][uid]["username"],
  122. "authorPicture": STATE["users"][uid].get("picture", ""),
  123. "body": body,
  124. "type": None, "parentId": None, "replyToId": reply_to, "replyTo": None,
  125. "createdAt": now_iso(), "deleted": False, "reactions": [],
  126. "attachments": [], "threadCount": 0, "readBy": [], "pinned": False}
  127. if reply_to:
  128. target = next((x for x in msgs if x["id"] == reply_to), None)
  129. if target:
  130. m["replyTo"] = {"id": target["id"], "authorName": target["authorName"],
  131. "body": target["body"], "deleted": False}
  132. if extra:
  133. m.update(extra)
  134. msgs.append(m)
  135. return m
  136. def seed(n_general):
  137. add_channel("c-general", "general", "public",
  138. ["u-test", "u-alice", "u-bob", "u-carol", "u-totp", "u-consent"],
  139. "Company-wide")
  140. add_channel("c-random", "random", "public", ["u-alice", "u-bob"], "Off topic")
  141. add_channel("c-design", "design", "public", ["u-alice"], "Design talk")
  142. add_channel("c-secret", "secret", "private", ["u-test", "u-alice"])
  143. add_channel("d-alice", None, "dm", ["u-test", "u-alice"])
  144. who = ["u-alice", "u-bob", "u-carol"]
  145. for i in range(n_general):
  146. add_message("c-general", who[i % 3],
  147. "History message %d – “quoted” café \U0001F44D" % (i + 1))
  148. first = STATE["messages"]["c-general"][-1]["id"] if n_general else None
  149. add_message("c-general", "u-bob",
  150. "A longer message that should wrap over several lines in the "
  151. "NebOS chat timeline, because it keeps going and going with "
  152. "plenty of words to test the greedy word wrapper.\nAnd a "
  153. "second paragraph.", reply_to=first,
  154. extra={
  155. "attachments": [
  156. {"id": "a1", "filename": "notes.txt",
  157. "mime": "text/plain", "size": 12},
  158. {"id": "a2", "filename": "neb.png",
  159. "mime": "image/png", "size": len(ATTACHMENT_PNG),
  160. "url": "/api/attachments/a2"}],
  161. "threadCount": 2,
  162. "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
  163. add_message("c-general", "u-carol",
  164. "Release notes: https://cloudron.io/blog/",
  165. extra={
  166. "preview": {
  167. "url": "https://cloudron.io/blog/",
  168. "title": "Cloudron release notes",
  169. "description": "What changed in the latest release, "
  170. "including new app versions.",
  171. "siteName": "Cloudron",
  172. "image": "/api/previews/p1",
  173. "favicon": "/api/avatars/u-carol",
  174. "type": "website"}})
  175. add_message("c-secret", "u-alice", "Private channel, only us two.")
  176. add_message("d-alice", "u-alice", "Hi Test, this is a direct message!")
  177. # test has read general up to the history; the rest is unread
  178. msgs = STATE["messages"]["c-general"]
  179. if len(msgs) > 1:
  180. STATE["reads"][("c-general", "u-test")] = msgs[-2]["id"]
  181. def unread(cid, uid):
  182. msgs = [m for m in STATE["messages"][cid] if not m["deleted"]]
  183. last = STATE["reads"].get((cid, uid))
  184. if last is None:
  185. return len([m for m in msgs if m["userId"] != uid])
  186. idx = next((i for i, m in enumerate(msgs) if m["id"] == last), -1)
  187. return len([m for m in msgs[idx + 1:] if m["userId"] != uid])
  188. def last_message(cid):
  189. msgs = [m for m in STATE["messages"][cid] if not m["deleted"]]
  190. if not msgs:
  191. return None
  192. m = msgs[-1]
  193. return {"id": m["id"], "body": m["body"][:160], "createdAt": m["createdAt"],
  194. "userId": m["userId"], "authorName": m["authorName"],
  195. "authorPicture": m.get("authorPicture", "")}
  196. def channel_json(c, uid):
  197. return {"id": c["id"], "name": c["name"], "type": c["type"],
  198. "description": c["description"], "archived": False,
  199. "memberCount": len(c["members"]), "isSelf": False,
  200. "unreadCount": unread(c["id"], uid), "lastMessage": last_message(c["id"])}
  201. def dm_json(c, uid):
  202. other = next((m for m in c["members"] if m != uid), None)
  203. u = STATE["users"].get(other)
  204. return {"id": c["id"], "type": "dm", "isSelf": other is None,
  205. "otherUser": dict(u, active=True) if u else None,
  206. "otherUserId": other, "unreadCount": unread(c["id"], uid),
  207. "lastMessage": last_message(c["id"]),
  208. "presence": STATE["presence"].get(other, "offline")}
  209. class Base(BaseHTTPRequestHandler):
  210. protocol_version = "HTTP/1.1"
  211. server_version = "MockChat/1.0"
  212. def log_message(self, fmt, *a):
  213. note("%s %s" % (self.server.label, fmt % a))
  214. def cookies(self):
  215. out = {}
  216. for part in (self.headers.get("Cookie") or "").split(";"):
  217. if "=" in part:
  218. k, v = part.strip().split("=", 1)
  219. out[k] = v
  220. return out
  221. def body_json(self):
  222. n = int(self.headers.get("Content-Length") or 0)
  223. raw = self.rfile.read(n) if n else b""
  224. if not raw:
  225. return {}
  226. try:
  227. return json.loads(raw.decode())
  228. except ValueError:
  229. return None
  230. def send(self, status, body=b"", ctype="application/json",
  231. headers=None):
  232. if isinstance(body, (dict, list)):
  233. body = json.dumps(body).encode()
  234. elif isinstance(body, str):
  235. body = body.encode()
  236. self.send_response(status)
  237. for k, v in (headers or []):
  238. self.send_header(k, v)
  239. if status not in (204, 304):
  240. self.send_header("Content-Type", ctype)
  241. self.send_header("Content-Length", str(len(body)))
  242. self.end_headers()
  243. if status not in (204, 304):
  244. self.wfile.write(body)
  245. def redirect(self, status, location, headers=None):
  246. self.send(status, "Redirecting to " + location, "text/plain",
  247. [("Location", location)] + (headers or []))
  248. def chat_origin(self):
  249. return "http://%s:%d" % (ARGS.public_host, ARGS.chat_port)
  250. def login_origin(self):
  251. return "http://%s:%d" % (ARGS.public_host, ARGS.login_port)
  252. LOGIN_PAGE = """<!DOCTYPE html>
  253. <html><head><title>Login</title>
  254. <script id="cloudron-config" type="application/json">
  255. %s
  256. </script>
  257. <script type="module" crossorigin src="/assets/oidc_login.js"></script>
  258. </head><body><div id="app"></div></body></html>
  259. """
  260. # The real Cloudron consent page (dashboard/oidc_interaction_confirm.html) is
  261. # a bare auto-submit form, not the login SPA: no cloudron-config JSON.
  262. CONSENT_PAGE = """<!DOCTYPE html>
  263. <html lang="en">
  264. <head>
  265. <title>Authorize chat</title>
  266. </head>
  267. <body>
  268. <form id="submitForm" method="post" action="/openid/interaction/%s/confirm">
  269. <!-- <button type="submit"></button> -->
  270. </form>
  271. <script type="module" src="/src/oidcinteractionconfirm.js"></script>
  272. </body>
  273. </html>
  274. """
  275. class LoginHandler(Base):
  276. def do_GET(self):
  277. u = urlparse(self.path)
  278. parts = u.path.strip("/").split("/")
  279. with LOCK:
  280. if u.path == "/openid/auth":
  281. q = parse_qs(u.query)
  282. uid = secrets.token_urlsafe(12)
  283. STATE["interactions"][uid] = {"pre": q.get("state", [""])[0],
  284. "user": None, "consent": False,
  285. "icookie": secrets.token_hex(8)}
  286. it = STATE["interactions"][uid]
  287. return self.redirect(303, "/openid/interaction/" + uid, [
  288. ("Set-Cookie", "_interaction=%s; path=/openid/interaction/%s; "
  289. "expires=Mon, 09 Nov 2026 20:00:00 GMT; samesite=lax; httponly"
  290. % (it["icookie"], uid)),
  291. ("Set-Cookie", "_interaction_resume=%s; path=/openid/auth/%s; "
  292. "httponly" % (it["icookie"], uid))])
  293. if len(parts) == 3 and parts[:2] == ["openid", "interaction"]:
  294. uid = parts[2]
  295. it = STATE["interactions"].get(uid)
  296. if not it or self.cookies().get("_interaction") != it["icookie"]:
  297. return self.send(400, {"message": "interaction cookie missing"})
  298. if it["user"] and it["consent"]:
  299. return self.send(200, CONSENT_PAGE % uid, "text/html")
  300. cfg = {"iconUrl": "/icon", "name": "chat", "note": "",
  301. "submitUrl": "/openid/interaction/%s/login" % uid,
  302. "passkeyLoginUrl": "/openid/interaction/%s/passkey_login" % uid,
  303. "footer": "&copy; mock", "language": None}
  304. return self.send(200, LOGIN_PAGE % json.dumps(cfg), "text/html")
  305. if len(parts) == 3 and parts[:2] == ["openid", "auth"]:
  306. uid = parts[2]
  307. it = STATE["interactions"].get(uid)
  308. if not it or self.cookies().get("_interaction_resume") != it["icookie"]:
  309. return self.send(400, {"message": "resume cookie missing"})
  310. if not it["user"]:
  311. return self.redirect(303, "/openid/interaction/" + uid)
  312. if it["consent"] and not it.get("confirmed"):
  313. return self.redirect(303, "/openid/interaction/" + uid)
  314. code = secrets.token_hex(8)
  315. STATE["interactions"][uid]["code"] = code
  316. return self.redirect(303, "%s/auth/callback?code=%s&state=%s"
  317. % (self.chat_origin(), code, it["pre"]))
  318. self.send(404, {"message": "not found"})
  319. def do_POST(self):
  320. u = urlparse(self.path)
  321. parts = u.path.strip("/").split("/")
  322. body = self.body_json()
  323. with LOCK:
  324. if len(parts) == 4 and parts[:2] == ["openid", "interaction"]:
  325. uid = parts[2]
  326. it = STATE["interactions"].get(uid)
  327. if not it or self.cookies().get("_interaction") != it["icookie"]:
  328. return self.send(400, {"message": "interaction cookie missing"})
  329. if body is None:
  330. return self.send(400, {"message": "bad JSON"})
  331. if parts[3] == "login":
  332. note("login attempt user=%r totp=%r"
  333. % (body.get("username"), body.get("totpToken")))
  334. user, pw = body.get("username"), body.get("password")
  335. if pw != "test" or user not in ("test", "totp", "passkey", "consent"):
  336. return self.send(401, {"status": "Unauthorized",
  337. "message": "Username and password does not match"})
  338. if user == "passkey":
  339. return self.send(200, {"twoFactorRequired": True,
  340. "totpRequired": False,
  341. "passkeyOptions": {}})
  342. if user == "totp":
  343. tok = body.get("totpToken") or ""
  344. if not tok:
  345. return self.send(200, {"twoFactorRequired": True,
  346. "totpRequired": True,
  347. "passkeyOptions": None})
  348. if tok != "123456":
  349. return self.send(401, {"status": "Unauthorized",
  350. "message": "Invalid totpToken"})
  351. it["user"] = "u-" + user
  352. it["consent"] = user == "consent"
  353. return self.send(200, {"redirectTo": "%s/openid/auth/%s"
  354. % (self.login_origin(), uid)})
  355. if parts[3] == "confirm":
  356. if not it["user"]:
  357. return self.send(400, {"message": "not logged in"})
  358. it["confirmed"] = True
  359. return self.redirect(303, "/openid/auth/" + uid)
  360. self.send(404, {"message": "not found"})
  361. class ChatHandler(Base):
  362. def user(self):
  363. return STATE["sessions"].get(self.cookies().get("connect.sid"))
  364. def do_GET(self):
  365. u = urlparse(self.path)
  366. q = parse_qs(u.query)
  367. p = u.path
  368. with LOCK:
  369. if p == "/auth/login":
  370. sid = "pre-" + secrets.token_hex(8)
  371. STATE["sessions"][sid] = None
  372. return self.redirect(302, "%s/openid/auth?client_id=chat&state=%s"
  373. % (self.login_origin(), sid),
  374. [("Set-Cookie", "connect.sid=%s; Path=/; "
  375. "Expires=Mon, 23 Nov 2026 18:03:29 GMT; HttpOnly; SameSite=Lax" % sid)])
  376. if p == "/auth/callback":
  377. sid = self.cookies().get("connect.sid")
  378. state = q.get("state", [""])[0]
  379. code = q.get("code", [""])[0]
  380. it = next((i for i in STATE["interactions"].values()
  381. if i.get("code") == code), None)
  382. if not sid or sid != state or sid not in STATE["sessions"] or not it:
  383. return self.redirect(302, "/?error=auth_failed")
  384. new = "s%3A" + it["user"] + "." + secrets.token_hex(8)
  385. del STATE["sessions"][sid]
  386. STATE["sessions"][new] = it["user"]
  387. return self.redirect(302, "/auth/return", [
  388. ("Set-Cookie", "connect.sid=%s; Path=/; HttpOnly" % new)])
  389. if p == "/auth/return":
  390. return self.redirect(302, "/")
  391. if p == "/auth/logout":
  392. STATE["sessions"].pop(self.cookies().get("connect.sid"), None)
  393. return self.redirect(302, "/", [
  394. ("Set-Cookie", "connect.sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT")])
  395. if p == "/":
  396. return self.send(200, "<!DOCTYPE html><html><body>chat SPA</body></html>",
  397. "text/html")
  398. if p == "/debug/state":
  399. st = {"messages": STATE["messages"],
  400. "reads": {"%s|%s" % k: v for k, v in STATE["reads"].items()},
  401. "channels": {k: dict(v, members=sorted(v["members"]))
  402. for k, v in STATE["channels"].items()},
  403. "sessions": STATE["sessions"], "log": STATE["log"][-200:]}
  404. return self.send(200, st)
  405. if p == "/api/config":
  406. return self.send(200, {"providerName": "Mock", "gifEnabled": False})
  407. uid = self.user()
  408. if not uid:
  409. return self.send(401, {"error": "Unauthorized"})
  410. if p == "/api/me":
  411. return self.send(200, dict(STATE["users"][uid], email="",
  412. active=True))
  413. if p == "/api/channels":
  414. return self.send(200, [channel_json(c, uid) for c in STATE["channels"].values()
  415. if c["type"] != "dm" and uid in c["members"]])
  416. if p == "/api/channels/public":
  417. return self.send(200, [channel_json(c, uid) for c in
  418. sorted(STATE["channels"].values(),
  419. key=lambda c: c["name"] or "")
  420. if c["type"] == "public" and uid not in c["members"]])
  421. if p == "/api/dms":
  422. return self.send(200, [dm_json(c, uid) for c in STATE["channels"].values()
  423. if c["type"] == "dm" and uid in c["members"]])
  424. if p == "/api/users":
  425. return self.send(200, [dict(x, email="", active=True)
  426. for x in STATE["users"].values()])
  427. parts = p.strip("/").split("/")
  428. if len(parts) == 3 and parts[:2] == ["api", "avatars"]:
  429. if parts[2] in STATE["users"]:
  430. return self.send(200, avatar_png(parts[2]), "image/png")
  431. if len(parts) == 3 and parts[:2] == ["api", "attachments"]:
  432. if parts[2] == "a2":
  433. return self.send(200, ATTACHMENT_PNG, "image/png")
  434. if len(parts) == 3 and parts[:2] == ["api", "previews"]:
  435. if parts[2] == "p1":
  436. return self.send(200, PREVIEW_PNG, "image/png")
  437. if len(parts) == 4 and parts[:2] == ["api", "channels"] and parts[3] == "messages":
  438. c = STATE["channels"].get(parts[2])
  439. if not c or uid not in c["members"]:
  440. return self.send(403, {"error": "Not a member"})
  441. limit = min(int(q.get("limit", ["50"])[0]), 200)
  442. msgs = STATE["messages"][c["id"]]
  443. ids = [m["id"] for m in msgs]
  444. if "after" in q:
  445. a = q["after"][0]
  446. if a not in ids:
  447. return self.send(404, {"error": "Message not found"})
  448. rows = msgs[ids.index(a) + 1:][:limit]
  449. return self.send(200, list(reversed(rows)))
  450. end = len(msgs)
  451. if "before" in q:
  452. b = q["before"][0]
  453. if b not in ids:
  454. return self.send(404, {"error": "Message not found"})
  455. end = ids.index(b)
  456. rows = msgs[max(0, end - limit):end]
  457. return self.send(200, list(reversed(rows)))
  458. self.send(404, {"error": "Not found"})
  459. def do_POST(self):
  460. u = urlparse(self.path)
  461. p = u.path
  462. body = self.body_json()
  463. with LOCK:
  464. if p == "/debug/inject":
  465. m = add_message(body["channel"], body.get("user", "u-alice"), body["body"])
  466. return self.send(201, m)
  467. if p == "/debug/presence":
  468. STATE["presence"][body["user"]] = body["presence"]
  469. return self.send(200, {})
  470. uid = self.user()
  471. if not uid:
  472. return self.send(401, {"error": "Unauthorized"})
  473. if body is None:
  474. return self.send(400, {"error": "bad JSON"})
  475. parts = p.strip("/").split("/")
  476. if p == "/api/dms":
  477. other = body.get("userId")
  478. if other not in STATE["users"]:
  479. return self.send(400, {"error": "Unknown user"})
  480. for c in STATE["channels"].values():
  481. if c["type"] == "dm" and c["members"] == {uid, other}:
  482. return self.send(200, dm_json(c, uid))
  483. cid = "d-" + secrets.token_hex(4)
  484. add_channel(cid, None, "dm", [uid, other])
  485. return self.send(201, dm_json(STATE["channels"][cid], uid))
  486. if len(parts) == 4 and parts[:2] == ["api", "channels"]:
  487. c = STATE["channels"].get(parts[2])
  488. if not c:
  489. return self.send(404, {"error": "Channel not found"})
  490. if parts[3] == "join":
  491. if c["type"] != "public":
  492. return self.send(403, {"error": "Forbidden"})
  493. c["members"].add(uid)
  494. return self.send(200, channel_json(c, uid))
  495. if uid not in c["members"]:
  496. return self.send(403, {"error": "Not a member"})
  497. if parts[3] == "read":
  498. msgs = STATE["messages"][c["id"]]
  499. if msgs:
  500. STATE["reads"][(c["id"], uid)] = msgs[-1]["id"]
  501. return self.send(200, {"unreadCount": 0})
  502. if parts[3] == "messages":
  503. text = (body.get("body") or "").strip()
  504. if not text:
  505. return self.send(400, {"error": "Message must not be empty"})
  506. cid_ = body.get("clientId")
  507. for m in STATE["messages"][c["id"]]:
  508. if cid_ and m["clientId"] == cid_:
  509. return self.send(201, m)
  510. m = add_message(c["id"], uid, text, client_id=cid_)
  511. STATE["reads"][(c["id"], uid)] = m["id"]
  512. return self.send(201, m)
  513. self.send(404, {"error": "Not found"})
  514. def serve(handler, port, label):
  515. srv = ThreadingHTTPServer((ARGS.host, port), handler)
  516. srv.label = label
  517. srv.daemon_threads = True
  518. threading.Thread(target=srv.serve_forever, daemon=True).start()
  519. return srv
  520. def main():
  521. global ARGS
  522. ap = argparse.ArgumentParser(description=__doc__,
  523. formatter_class=argparse.RawDescriptionHelpFormatter)
  524. ap.add_argument("--host", default="0.0.0.0")
  525. ap.add_argument("--chat-port", type=int, default=18080)
  526. ap.add_argument("--login-port", type=int, default=18081)
  527. ap.add_argument("--public-host", default="10.0.2.2",
  528. help="address the guest uses to reach this host")
  529. ap.add_argument("--messages", type=int, default=120,
  530. help="history messages seeded into #general")
  531. ap.add_argument("-v", "--verbose", action="store_true")
  532. ARGS = ap.parse_args()
  533. seed(ARGS.messages)
  534. serve(ChatHandler, ARGS.chat_port, "chat")
  535. serve(LoginHandler, ARGS.login_port, "login")
  536. print("mock chat on :%d, login on :%d (guest: http://%s:%d)"
  537. % (ARGS.chat_port, ARGS.login_port, ARGS.public_host, ARGS.chat_port),
  538. flush=True)
  539. try:
  540. threading.Event().wait()
  541. except KeyboardInterrupt:
  542. pass
  543. if __name__ == "__main__":
  544. main()