onboard.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """QQBot scan-to-configure (QR code onboard). Mirrors the Feishu pattern: synchronous HTTP + one entry-point
  2. ``qr_register()`` (create task → display QR → poll → decrypt) against ``q.qq.com`` bind-task endpoints."""
  3. from __future__ import annotations
  4. from pm import install_hint
  5. import logging
  6. import time
  7. from enum import IntEnum
  8. from typing import Optional, Tuple
  9. from urllib.parse import quote
  10. from .constants import (
  11. ONBOARD_API_TIMEOUT, ONBOARD_CREATE_PATH, ONBOARD_POLL_INTERVAL, ONBOARD_POLL_PATH, PORTAL_HOST, QR_URL_TEMPLATE)
  12. from .crypto import decrypt_secret, generate_bind_key
  13. from .utils import get_api_headers
  14. logger = logging.getLogger(__name__)
  15. class BindStatus(IntEnum):
  16. """Status codes returned by ``_poll_bind_result``."""
  17. NONE, PENDING, COMPLETED, EXPIRED = 0, 1, 2, 3
  18. try:
  19. import qrcode as _qrcode_mod
  20. except (ImportError, TypeError):
  21. _qrcode_mod = None # type: ignore[assignment]
  22. def _render_qr(url: str) -> bool:
  23. """Try to render a QR code in the terminal. Returns True if successful."""
  24. if _qrcode_mod is None:
  25. return False
  26. try:
  27. qr = _qrcode_mod.QRCode(error_correction=_qrcode_mod.constants.ERROR_CORRECT_M, border=2)
  28. qr.add_data(url)
  29. qr.make(fit=True)
  30. qr.print_ascii(invert=True)
  31. return True
  32. except Exception:
  33. return False
  34. def _portal_post(path: str, payload: dict, timeout: float, fail_msg: str) -> dict:
  35. """Synchronous POST to the portal host; raises RuntimeError on non-zero ``retcode``."""
  36. import httpx
  37. with httpx.Client(timeout=timeout, follow_redirects=True) as client:
  38. resp = client.post(f"https://{PORTAL_HOST}{path}", json=payload, headers=get_api_headers())
  39. resp.raise_for_status()
  40. data = resp.json()
  41. if data.get("retcode") != 0:
  42. raise RuntimeError(data.get("msg", fail_msg))
  43. return data
  44. def _create_bind_task(timeout: float = ONBOARD_API_TIMEOUT) -> tuple[str, str]:
  45. """Create a bind task and return *(task_id, aes_key_base64)*."""
  46. key = generate_bind_key()
  47. data = _portal_post(ONBOARD_CREATE_PATH, {"key": key}, timeout, "create_bind_task failed")
  48. task_id = (data.get("data") or {}).get("task_id")
  49. if not task_id:
  50. raise RuntimeError("create_bind_task: missing task_id in response")
  51. logger.debug("create_bind_task ok: task_id=%s", task_id)
  52. return task_id, key
  53. def _poll_bind_result(task_id: str, timeout: float = ONBOARD_API_TIMEOUT) -> tuple[BindStatus, str, str, str]:
  54. """Poll *task_id*; returns ``(status, bot_appid, bot_encrypt_secret, user_openid)``."""
  55. d = _portal_post(ONBOARD_POLL_PATH, {"task_id": task_id}, timeout, "poll_bind_result failed").get("data", {})
  56. return (BindStatus(d.get("status", 0)), str(d.get("bot_appid", "")), d.get("bot_encrypt_secret", ""),
  57. d.get("user_openid", ""))
  58. def build_connect_url(task_id: str) -> str:
  59. """Build the QR-code target URL for a given *task_id*."""
  60. return QR_URL_TEMPLATE.format(task_id=quote(task_id))
  61. _MAX_REFRESHES = 3
  62. def qr_register(timeout_seconds: int = 600) -> Optional[dict]:
  63. """Run the QR registration flow; returns ``{"app_id", "client_secret", "user_openid"}``
  64. or None on failure / expiry / cancellation. Unexpected errors propagate."""
  65. deadline = time.monotonic() + timeout_seconds
  66. for refresh_count in range(_MAX_REFRESHES + 1):
  67. try:
  68. task_id, aes_key = _create_bind_task()
  69. except Exception as exc:
  70. logger.warning("[QQBot onboard] Failed to create bind task: %s", exc)
  71. return None
  72. url = build_connect_url(task_id)
  73. print()
  74. if _render_qr(url):
  75. print(f" Scan the QR code above, or open this URL directly:\n {url}")
  76. else:
  77. print(f" Open this URL in QQ on your phone:\n {url}")
  78. print(" For a scannable QR code, run: "
  79. f"{install_hint('messaging')}")
  80. print()
  81. while time.monotonic() < deadline:
  82. try:
  83. status, app_id, encrypted_secret, user_openid = _poll_bind_result(task_id)
  84. except Exception:
  85. time.sleep(ONBOARD_POLL_INTERVAL)
  86. continue
  87. if status == BindStatus.COMPLETED:
  88. client_secret = decrypt_secret(encrypted_secret, aes_key)
  89. print()
  90. print(f" QR scan complete! (App ID: {app_id})")
  91. if user_openid:
  92. print(f" Scanner's OpenID: {user_openid}")
  93. return {"app_id": app_id, "client_secret": client_secret, "user_openid": user_openid}
  94. if status == BindStatus.EXPIRED:
  95. if refresh_count >= _MAX_REFRESHES:
  96. logger.warning("[QQBot onboard] QR code expired %d times — giving up", _MAX_REFRESHES)
  97. return None
  98. print(f"\n QR code expired, refreshing... ({refresh_count + 1}/{_MAX_REFRESHES})")
  99. break # next for-loop iteration creates a new task
  100. time.sleep(ONBOARD_POLL_INTERVAL)
  101. else:
  102. logger.warning("[QQBot onboard] Poll timed out after %ds", timeout_seconds)
  103. return None
  104. return None