"""Etherpad-shaped live extras for Nomadro pads (presence + chat). In-memory — low load; survives process restart by re-joining. No iframe / upstream Etherpad. """ from __future__ import annotations import time from typing import Any # author -> color (classic Etherpad palette + amber accent) AUTHOR_COLORS = ( "#e11d48", "#f59e0b", "#84cc16", "#14b8a6", "#3b82f6", "#8b5cf6", "#ec4899", "#06b6d4", "#f97316", "#22c55e", "#a855f7", "#ef4444", ) PRESENCE_TTL_SEC = 25.0 # pad_id -> { author_key: {author, color, at, sid} } _presence: dict[str, dict[str, dict[str, Any]]] = {} # pad_id -> [{id, author, color, text, at}] _chat: dict[str, list[dict[str, Any]]] = {} def author_color(name: str) -> str: s = (name or "guest").strip().lower() or "guest" h = 0 for ch in s: h = (h * 31 + ord(ch)) & 0xFFFFFFFF return AUTHOR_COLORS[h % len(AUTHOR_COLORS)] def _purge(pad_id: str) -> None: now = time.time() bucket = _presence.get(pad_id) or {} dead = [k for k, v in bucket.items() if now - float(v.get("at") or 0) > PRESENCE_TTL_SEC] for k in dead: bucket.pop(k, None) if not bucket: _presence.pop(pad_id, None) else: _presence[pad_id] = bucket def heartbeat( pad_id: str, *, author: str, sid: str = "", ) -> list[dict[str, Any]]: pid = (pad_id or "").strip() if not pid: return [] name = (author or "guest").strip()[:80] or "guest" key = (sid or name).strip()[:64] or name bucket = _presence.setdefault(pid, {}) bucket[key] = { "author": name, "color": author_color(name), "at": time.time(), "sid": key, } _purge(pid) return list_presence(pid) def list_presence(pad_id: str) -> list[dict[str, Any]]: _purge(pad_id) rows = list((_presence.get(pad_id) or {}).values()) rows.sort(key=lambda r: str(r.get("author") or "").lower()) return [ { "author": r.get("author"), "color": r.get("color"), "sid": r.get("sid"), "at": r.get("at"), } for r in rows ] def list_chat(pad_id: str, limit: int = 80) -> list[dict[str, Any]]: rows = list(_chat.get(pad_id) or []) return rows[-max(1, min(limit, 200)) :] def post_chat(pad_id: str, *, author: str, text: str) -> dict[str, Any] | None: body = (text or "").strip()[:500] if not body or not pad_id: return None name = (author or "guest").strip()[:80] or "guest" msg = { "id": f"msg_{int(time.time() * 1000)}_{len(_chat.get(pad_id) or [])}", "author": name, "color": author_color(name), "text": body, "at": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()), } bucket = _chat.setdefault(pad_id, []) bucket.append(msg) if len(bucket) > 200: del bucket[:-200] return msg