setup_files.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. """``/setup-files`` in-chat OAuth setup flow for native attachment delivery.
  2. Extracted from ``adapter.py``: ``GoogleChatAdapter._handle_setup_files_command``
  3. delegates here. Logs under the adapter's pinned logger name.
  4. """
  5. from __future__ import annotations
  6. import asyncio
  7. import contextlib
  8. import io
  9. import logging
  10. from typing import Any, Callable, Dict, Optional
  11. from agent.i18n import t
  12. logger = logging.getLogger("gateway.platforms.google_chat")
  13. # Reply copy lives in the catalog under platform.google_chat.setup_files.* and is resolved
  14. # through ``t()`` at reply time (never at import) so the active language applies.
  15. _K = "platform.google_chat.setup_files."
  16. _EXITED = object() # _run_helper marker: helper called sys.exit but the step tolerates it
  17. async def _run_captured(fn: Callable[..., Any], *args: Any) -> str:
  18. """Run ``fn`` in a thread with stdout captured (the oauth helpers print their output)."""
  19. buf = io.StringIO()
  20. with contextlib.redirect_stdout(buf):
  21. await asyncio.to_thread(fn, *args)
  22. return buf.getvalue()
  23. async def handle_setup_files_command(
  24. adapter: Any, chat_id: str, thread_id: Optional[str], raw_text: str,
  25. sender_email: Optional[str] = None) -> bool:
  26. """Run the in-chat OAuth setup flow. Returns True when the message was consumed.
  27. ``sender_email`` is the per-user OAuth key; ``None`` falls back to the legacy
  28. single-user token slot so pre-multi-user installs keep working.
  29. Subcommands: ``/setup-files`` (status), ``start`` (OAuth URL), ``revoke``,
  30. ``<CODE_OR_URL>`` (exchange). Requires client_secret.json on the host.
  31. """
  32. from . import oauth as oauth_helper
  33. # Same normalization as the token-path sanitizer so cache lookups stay consistent.
  34. sender_key = sender_email.strip().lower() if sender_email else None
  35. parts = raw_text.split(maxsplit=1)
  36. arg = parts[1].strip() if len(parts) > 1 else ""
  37. async def _reply(text: str) -> None:
  38. body: dict[str, Any] = {"text": text}
  39. if thread_id:
  40. body["thread"] = {"name": thread_id}
  41. try:
  42. await adapter._create_message(chat_id, body)
  43. except Exception:
  44. logger.debug("[GoogleChat] /setup-files reply send failed", exc_info=True)
  45. async def _run_helper(step: str, exit_key: Optional[str], fn: Callable[..., Any], *args: Any):
  46. """Captured helper output; ``None`` after replying on failure. ``exit_key``
  47. is the catalog key of the reply on ``SystemExit`` (the helpers' failure signal);
  48. ``None`` tolerates the exit and returns ``_EXITED``."""
  49. try:
  50. return await _run_captured(fn, *args)
  51. except SystemExit:
  52. if exit_key is None:
  53. return _EXITED
  54. await _reply(t(exit_key))
  55. except Exception as exc:
  56. logger.warning("[GoogleChat] /setup-files %s failed: %s", step, exc)
  57. await _reply(t(_K + ("revoke_error" if step == "revoke" else "helper_error"), error=str(exc)))
  58. return None
  59. def _set_user_creds(creds: Any, api: Any) -> None:
  60. """Set (or evict, with ``None``) only the sender's slot: Bob revoking must not
  61. break Alice's per-user token nor the shared legacy fallback."""
  62. if not sender_key:
  63. adapter._user_credentials, adapter._user_chat_api = creds, api
  64. elif creds is None:
  65. adapter._user_creds_by_email.pop(sender_key, None)
  66. adapter._user_chat_api_by_email.pop(sender_key, None)
  67. else:
  68. adapter._user_creds_by_email[sender_key] = creds
  69. adapter._user_chat_api_by_email[sender_key] = api
  70. if not arg:
  71. client_secret_present = oauth_helper._client_secret_path().exists()
  72. token_path = oauth_helper._token_path(sender_key)
  73. creds = oauth_helper.load_user_credentials(sender_key) if token_path.exists() else None
  74. if creds is not None:
  75. who = sender_key or t(_K + "who_shared")
  76. await _reply(t(_K + "active", who=who, token_path=str(token_path)))
  77. elif not client_secret_present:
  78. await _reply(t(_K + "not_configured"))
  79. else:
  80. await _reply(t(_K + "not_authorized_yet"))
  81. return True
  82. if arg == "start":
  83. if not oauth_helper._client_secret_path().exists():
  84. await _reply(t(_K + "no_client_credentials"))
  85. return True
  86. output = await _run_helper("start", _K + "start_failed", oauth_helper.get_auth_url, sender_key)
  87. if output is not None:
  88. await _reply(t(_K + "start_instructions", auth_url=output.strip().splitlines()[-1]))
  89. return True
  90. if arg == "revoke":
  91. output = await _run_helper("revoke", None, oauth_helper.revoke, sender_key)
  92. if output is None:
  93. return True
  94. output = t(_K + "revoke_completed") if output is _EXITED else (output.strip() or t(_K + "revoked"))
  95. _set_user_creds(None, None)
  96. await _reply(t(_K + "done_output", output=output))
  97. return True
  98. # Anything else is the auth code or the pasted failed-redirect URL.
  99. output = await _run_helper("exchange", _K + "exchange_failed", oauth_helper.exchange_auth_code, arg, sender_key)
  100. if output is None:
  101. return True
  102. # Re-load credentials so the next file send uses them without a gateway restart.
  103. try:
  104. new_creds = await asyncio.to_thread(oauth_helper.load_user_credentials, sender_key)
  105. if new_creds is not None:
  106. new_api = await asyncio.to_thread(lambda: oauth_helper.build_user_chat_service(new_creds))
  107. _set_user_creds(new_creds, new_api)
  108. await _reply(t(_K + "authorized"))
  109. return True
  110. except Exception as exc:
  111. logger.warning("[GoogleChat] post-exchange creds load failed: %s", exc)
  112. await _reply(t(_K + "exchanged_not_loaded", token_path=str(oauth_helper._token_path(sender_key)),
  113. output=output.strip()))
  114. return True