"""Centrifugo publish + connection JWT for 游民社区聊天.""" from __future__ import annotations import logging import time from typing import Any import httpx import jwt from social_svc.config import ( CENTRIFUGO_API_KEY, CENTRIFUGO_API_URL, CENTRIFUGO_ENABLED, CENTRIFUGO_TOKEN_SECRET, CENTRIFUGO_WS_URL, ) log = logging.getLogger("social_svc.realtime") _http: httpx.AsyncClient | None = None def _client() -> httpx.AsyncClient: global _http if _http is None or _http.is_closed: _http = httpx.AsyncClient(timeout=3.0) return _http def channel_name(channel_id: str) -> str: cid = (channel_id or "").strip() or "lobby" return f"social:{cid}" def issue_connection_token(guest_id: str, channel_id: str | None = None) -> dict[str, Any]: """Return client connection info. Disabled → ok=false (前端降级轮询).""" if not CENTRIFUGO_ENABLED or not CENTRIFUGO_TOKEN_SECRET: return { "ok": False, "enabled": False, "wsUrl": CENTRIFUGO_WS_URL, "token": "", "channel": channel_name(channel_id or "lobby"), } now = int(time.time()) payload: dict[str, Any] = { "sub": guest_id[:80], "iat": now, "exp": now + 60 * 60 * 12, } token = jwt.encode(payload, CENTRIFUGO_TOKEN_SECRET, algorithm="HS256") if isinstance(token, bytes): token = token.decode("utf-8") return { "ok": True, "enabled": True, "wsUrl": CENTRIFUGO_WS_URL, "token": token, "channel": channel_name(channel_id or "lobby"), } async def _publish(channel_id: str, data: dict[str, Any]) -> bool: if not CENTRIFUGO_ENABLED or not CENTRIFUGO_API_KEY: return False url = CENTRIFUGO_API_URL.rstrip("/") + "/publish" body = {"channel": channel_name(channel_id), "data": data} try: res = await _client().post( url, headers={"X-API-Key": CENTRIFUGO_API_KEY, "Content-Type": "application/json"}, json=body, ) if res.status_code >= 400: log.warning("centrifugo publish %s: %s", res.status_code, res.text[:200]) return False return True except Exception as e: # pragma: no cover log.warning("centrifugo publish failed: %s", e) return False async def publish_chat_message(channel_id: str, message: dict[str, Any]) -> bool: return await _publish(channel_id, {"type": "chat.message", "message": message}) async def publish_chat_note( channel_id: str, *, what: str, seq: int, guest_id: str, ) -> bool: """Tinode-like {note}: recv / read / kp (typing).""" from social_svc.im import note_event return await _publish(channel_id, note_event(what, seq, guest_id)) async def publish_live_event(channel_id: str, event: str, payload: dict[str, Any]) -> bool: return await _publish(channel_id, {"type": f"live.{event}", **payload})