mock_chat.py 26 KB

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