telegram_integration.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. """
  2. Telegram Integration Wrapper
  3. Integrates Telegram notifications with the existing notification system.
  4. All configuration is loaded from the database via telegram_config_service.
  5. """
  6. import asyncio
  7. import threading
  8. import time
  9. from collections.abc import Callable
  10. from functools import wraps
  11. from typing import Any
  12. from loguru import logger
  13. from config import Config
  14. from services.notifications.telegram_config_service import (
  15. load_config as load_telegram_config,
  16. )
  17. from services.notifications.telegram_service import (
  18. NotificationPriority,
  19. TelegramService,
  20. parse_http_proxy_url,
  21. )
  22. # ---------------------------------------------------------------------------
  23. # Single persistent background event loop
  24. # ---------------------------------------------------------------------------
  25. # All Telegram async operations run on this one loop, which lives in its own
  26. # daemon thread for the entire lifetime of the process. Using a dedicated
  27. # loop eliminates the "event loop must not change after connection" error that
  28. # Telethon raises when callers create a fresh loop per request, and it
  29. # guarantees the Telethon SQLiteSession is only ever touched from one thread,
  30. # preventing "database is locked" conflicts.
  31. # ---------------------------------------------------------------------------
  32. _bg_loop: asyncio.AbstractEventLoop | None = None
  33. _bg_thread: threading.Thread | None = None
  34. _bg_lock = threading.Lock()
  35. _telegram_service: TelegramService | None = None
  36. def _start_background_loop(loop: asyncio.AbstractEventLoop) -> None:
  37. asyncio.set_event_loop(loop)
  38. loop.run_forever()
  39. def _get_background_loop() -> asyncio.AbstractEventLoop:
  40. """Return the shared background event loop, starting it on first call."""
  41. global _bg_loop, _bg_thread
  42. if _bg_loop is not None and _bg_loop.is_running():
  43. return _bg_loop
  44. with _bg_lock:
  45. # Double-check after acquiring the lock.
  46. if _bg_loop is not None and _bg_loop.is_running():
  47. return _bg_loop
  48. _bg_loop = asyncio.new_event_loop()
  49. _bg_thread = threading.Thread(
  50. target=_start_background_loop,
  51. args=(_bg_loop,),
  52. daemon=True,
  53. name="telegram-event-loop",
  54. )
  55. _bg_thread.start()
  56. # Wait until the loop is actually running.
  57. deadline = time.monotonic() + 5.0
  58. while not _bg_loop.is_running():
  59. if time.monotonic() > deadline:
  60. raise RuntimeError(
  61. "Telegram background event loop did not start in time"
  62. )
  63. time.sleep(0.01)
  64. logger.debug(
  65. "Telegram background event loop started (thread: telegram-event-loop)"
  66. )
  67. return _bg_loop
  68. def run_async(coro, timeout: float = 60) -> Any:
  69. """
  70. Submit *coro* to the shared Telegram background event loop and block the
  71. calling thread until the result is available (or *timeout* seconds elapse).
  72. Using the same loop for every call ensures Telethon never sees its
  73. internal asyncio state created on a different loop.
  74. """
  75. loop = _get_background_loop()
  76. future = asyncio.run_coroutine_threadsafe(coro, loop)
  77. return future.result(timeout=timeout)
  78. def async_to_sync(async_func: Callable) -> Callable:
  79. """Decorator that runs an async function on the shared Telegram loop."""
  80. @wraps(async_func)
  81. def wrapper(*args, **kwargs):
  82. return run_async(async_func(*args, **kwargs))
  83. return wrapper
  84. def initialize_telegram_service() -> bool:
  85. """
  86. Initialize or reinitialize the Telegram service from DB configuration.
  87. Returns:
  88. True if the service was initialized successfully.
  89. """
  90. global _telegram_service
  91. cfg = load_telegram_config()
  92. if not cfg.get("enabled"):
  93. logger.info("Telegram notifications disabled in configuration")
  94. return False
  95. api_id_raw = cfg.get("api_id", "")
  96. api_hash = cfg.get("api_hash", "")
  97. if not api_id_raw or not api_hash:
  98. logger.warning(
  99. "Telegram API credentials not configured. "
  100. "Set them via the admin panel → Telegram Configuration."
  101. )
  102. return False
  103. try:
  104. api_id = int(api_id_raw)
  105. except (ValueError, TypeError):
  106. logger.error(f"Invalid Telegram API ID (not an integer): {api_id_raw!r}")
  107. return False
  108. try:
  109. proxy_config = None
  110. if Config.HTTP_PROXY:
  111. proxy_config = parse_http_proxy_url(Config.HTTP_PROXY)
  112. if proxy_config:
  113. logger.info(f"Using HTTP proxy for Telegram: {Config.HTTP_PROXY}")
  114. else:
  115. logger.warning(f"Invalid proxy URL for Telegram: {Config.HTTP_PROXY}")
  116. # Reset the singleton so a fresh instance picks up new credentials.
  117. TelegramService._instance = None
  118. _telegram_service = TelegramService(
  119. api_id=api_id,
  120. api_hash=api_hash,
  121. bot_token=cfg.get("bot_token") or None,
  122. session_name=cfg.get("session_name") or "squidstats_bot",
  123. phone=cfg.get("phone") or None,
  124. enabled=True,
  125. proxy=proxy_config,
  126. )
  127. logger.info("Telegram service initialized successfully from DB configuration")
  128. return True
  129. except Exception as e:
  130. logger.error(f"Failed to initialize Telegram service: {e}")
  131. return False
  132. def cleanup_telegram() -> None:
  133. """Cleanup Telegram service on application shutdown."""
  134. global _telegram_service
  135. if _telegram_service:
  136. try:
  137. run_async(_telegram_service.disconnect())
  138. except Exception as e:
  139. logger.debug("Error disconnecting Telegram service: %s", e)
  140. _telegram_service = None
  141. logger.info("Telegram service cleaned up")
  142. def map_notification_type_to_priority(notification_type: str) -> NotificationPriority:
  143. """Map internal notification type to Telegram message priority."""
  144. mapping = {
  145. "error": NotificationPriority.CRITICAL,
  146. "warning": NotificationPriority.HIGH,
  147. "success": NotificationPriority.NORMAL,
  148. "info": NotificationPriority.LOW,
  149. }
  150. return mapping.get(notification_type.lower(), NotificationPriority.NORMAL)
  151. def map_source_to_emoji(source: str) -> str:
  152. """Map notification source to a representative emoji."""
  153. mapping = {
  154. "security": "🔒",
  155. "system": "💻",
  156. "squid": "🦑",
  157. "users": "👥",
  158. "git": "📦",
  159. "database": "🗄️",
  160. "network": "🌐",
  161. }
  162. return mapping.get(source.lower(), "📢")
  163. def _get_recipients() -> list[str]:
  164. """Load recipients list from DB configuration."""
  165. cfg = load_telegram_config()
  166. return [r.strip() for r in cfg.get("recipients", []) if r.strip()]
  167. @async_to_sync
  168. async def send_telegram_notification(
  169. notification_type: str,
  170. message: str,
  171. source: str = "system",
  172. extra_data: dict[str, Any] | None = None,
  173. ) -> bool:
  174. """
  175. Send a notification to all configured Telegram recipients.
  176. Args:
  177. notification_type: One of 'info', 'warning', 'error', 'success'.
  178. message: Notification body.
  179. source: Origin label shown in the message header.
  180. extra_data: Optional key/value dict appended to the message.
  181. Returns:
  182. True if the message was delivered to at least one recipient.
  183. """
  184. if _telegram_service is None:
  185. return False
  186. cfg = load_telegram_config()
  187. if not cfg.get("enabled"):
  188. return False
  189. recipients = [r.strip() for r in cfg.get("recipients", []) if r.strip()]
  190. if not recipients:
  191. logger.debug("No Telegram recipients configured")
  192. return False
  193. priority = map_notification_type_to_priority(notification_type)
  194. emoji = map_source_to_emoji(source)
  195. source_display = f"{emoji} {source.title()}"
  196. try:
  197. results = await _telegram_service.send_bulk_notifications(
  198. recipients=recipients,
  199. message=message,
  200. priority=priority,
  201. source=source_display,
  202. extra_data=extra_data,
  203. )
  204. success_count = sum(1 for ok in results.values() if ok)
  205. if success_count > 0:
  206. logger.info(
  207. f"Telegram notification sent to {success_count}/{len(recipients)} recipients"
  208. )
  209. return True
  210. logger.warning("Failed to send Telegram notification to any recipient")
  211. return False
  212. except Exception as e:
  213. logger.error(f"Error sending Telegram notification: {e}")
  214. return False
  215. @async_to_sync
  216. async def send_security_alert_telegram(
  217. alert_type: str, details: dict[str, Any]
  218. ) -> bool:
  219. """Send a security alert to all configured Telegram recipients."""
  220. if _telegram_service is None:
  221. return False
  222. recipients = _get_recipients()
  223. success_count = 0
  224. for recipient in recipients:
  225. try:
  226. if await _telegram_service.send_security_alert(
  227. recipient, alert_type, details
  228. ):
  229. success_count += 1
  230. except Exception as e:
  231. logger.error(f"Failed to send security alert to {recipient}: {e}")
  232. return success_count > 0
  233. @async_to_sync
  234. async def send_system_alert_telegram(
  235. alert_message: str, metrics: dict[str, Any] | None = None
  236. ) -> bool:
  237. """Send a system alert to all configured Telegram recipients."""
  238. if _telegram_service is None:
  239. return False
  240. recipients = _get_recipients()
  241. success_count = 0
  242. for recipient in recipients:
  243. try:
  244. if await _telegram_service.send_system_alert(
  245. recipient, alert_message, metrics
  246. ):
  247. success_count += 1
  248. except Exception as e:
  249. logger.error(f"Failed to send system alert to {recipient}: {e}")
  250. return success_count > 0
  251. @async_to_sync
  252. async def send_user_activity_alert_telegram(
  253. username: str, activity_data: dict[str, Any]
  254. ) -> bool:
  255. """Send a user activity alert to all configured Telegram recipients."""
  256. if _telegram_service is None:
  257. return False
  258. recipients = _get_recipients()
  259. success_count = 0
  260. for recipient in recipients:
  261. try:
  262. if await _telegram_service.send_user_activity_alert(
  263. recipient, username, activity_data
  264. ):
  265. success_count += 1
  266. except Exception as e:
  267. logger.error(f"Failed to send user activity alert to {recipient}: {e}")
  268. return success_count > 0
  269. def telegram_health_check() -> dict:
  270. """Return a health-check dict for the running Telegram service."""
  271. if _telegram_service is None:
  272. cfg = load_telegram_config()
  273. return {
  274. "enabled": cfg.get("enabled", False),
  275. "connected": False,
  276. "bot_mode": False,
  277. "session": cfg.get("session_name", ""),
  278. }
  279. return run_async(_telegram_service.health_check())