messaging_relay.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Team Gateway account linking for the Channels surfaces (dashboard and Desktop).
  2. On a relay-fronted instance the shared bot is the only way to reach Telegram, Discord and Slack;
  3. these routes let the user link their chat account to it from the instance (#141546). Codes are
  4. minted by the running gateway, which alone holds the per-gateway relay secret, through its
  5. ``relay-link`` control-socket verb (``gateway/relay/link.py``).
  6. """
  7. import asyncio
  8. from typing import Any
  9. from fastapi import APIRouter, HTTPException
  10. router = APIRouter()
  11. # Connector answers that mean "the instance is not ready yet" rather than "this cannot work".
  12. _NOT_READY = frozenset({"relay_not_provisioned", "connector_unreachable", "connector_unavailable"})
  13. def _ask_gateway(params: dict[str, Any]) -> dict[str, Any]:
  14. from gateway.control_socket import query_gateway_control
  15. from gateway.relay.link import CONTROL_TIMEOUT_S
  16. from hermes_constants import get_process_hermes_home
  17. answer = query_gateway_control(get_process_hermes_home(), "relay-link", params=params,
  18. timeout=CONTROL_TIMEOUT_S)
  19. if answer is None:
  20. raise HTTPException(status_code=503, detail={
  21. # No answer covers a stopped gateway, one too old for the verb, and a timeout alike.
  22. "code": "gateway_not_answering",
  23. "message": "The gateway did not answer. Make sure it is running and up to date: it holds the "
  24. "Team Gateway connection."})
  25. if not answer.get("ok"):
  26. code = str(answer.get("error") or "connector_refused")
  27. raise HTTPException(status_code=503 if code in _NOT_READY else 409,
  28. detail={"code": code, "message": answer.get("message") or code})
  29. return {k: v for k, v in answer.items() if k != "ok"}
  30. async def _call(params: dict[str, Any]) -> dict[str, Any]:
  31. return await asyncio.to_thread(_ask_gateway, params)
  32. @router.get("/api/messaging/relay")
  33. async def get_relay_links():
  34. """Accounts linked to this instance per shared-bot platform, and each bot's DM link."""
  35. return await _call({"action": "status"})
  36. @router.post("/api/messaging/relay/{platform}/link")
  37. async def request_relay_link(platform: str):
  38. """A one-time ``/link <code>`` for the account that sends it to the shared bot."""
  39. return await _call({"action": "request", "platform": platform})
  40. @router.get("/api/messaging/relay/link/{code}")
  41. async def get_relay_link_state(code: str):
  42. return await _call({"action": "state", "code": code})
  43. @router.delete("/api/messaging/relay/{platform}/accounts/{platform_user_id}")
  44. async def unlink_relay_account(platform: str, platform_user_id: str):
  45. return await _call({"action": "unlink", "platform": platform, "platform_user_id": platform_user_id})