telegram_config.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. """Admin Telegram configuration routes."""
  2. from flask import jsonify, render_template, request
  3. from flask_babel import gettext as _
  4. from loguru import logger
  5. from routes.auth_routes import csrf
  6. from services.auth.auth_service import admin_required, api_auth_required
  7. from services.notifications.telegram_config_service import load_config, save_config
  8. def register_routes(bp):
  9. # ------------------------------------------------------------------ #
  10. # View #
  11. # ------------------------------------------------------------------ #
  12. @bp.route("/telegram-config", endpoint="telegram_config")
  13. @admin_required
  14. def telegram_config_view():
  15. cfg = load_config()
  16. # Keep secrets out of the rendered HTML; use flags to indicate existing values.
  17. cfg["has_api_hash"] = bool(cfg.get("api_hash"))
  18. cfg["has_bot_token"] = bool(cfg.get("bot_token"))
  19. cfg["api_hash"] = ""
  20. cfg["bot_token"] = ""
  21. return render_template("admin/telegram_config_page.html", cfg=cfg)
  22. # ------------------------------------------------------------------ #
  23. # Load config (API) #
  24. # ------------------------------------------------------------------ #
  25. @bp.route("/api/telegram/config", methods=["GET"])
  26. @api_auth_required
  27. def telegram_get_config():
  28. cfg = load_config()
  29. cfg["has_api_hash"] = bool(cfg.get("api_hash"))
  30. cfg["has_bot_token"] = bool(cfg.get("bot_token"))
  31. cfg["api_hash"] = ""
  32. cfg["bot_token"] = ""
  33. return jsonify({"status": "success", "config": cfg})
  34. # ------------------------------------------------------------------ #
  35. # Save config #
  36. # ------------------------------------------------------------------ #
  37. @bp.route("/api/telegram/save-config", methods=["POST"])
  38. @csrf.exempt
  39. @api_auth_required
  40. def telegram_save_config():
  41. data = request.get_json(silent=True) or {}
  42. try:
  43. save_config(data)
  44. # Reinitialize the running service so the new credentials take effect
  45. # immediately without restarting the application.
  46. try:
  47. from services.notifications.telegram_integration import (
  48. initialize_telegram_service,
  49. )
  50. initialize_telegram_service()
  51. except Exception as reinit_err:
  52. logger.warning(f"Could not reinitialize Telegram service: {reinit_err}")
  53. return jsonify(
  54. {"status": "success", "message": _("Configuración Telegram guardada.")}
  55. )
  56. except Exception as exc:
  57. logger.error(f"Error al guardar configuración Telegram: {exc}")
  58. return jsonify(
  59. {"status": "error", "message": _("Error al guardar la configuración.")}
  60. ), 500
  61. # ------------------------------------------------------------------ #
  62. # Test connection #
  63. # ------------------------------------------------------------------ #
  64. @bp.route("/api/telegram/test", methods=["POST"])
  65. @csrf.exempt
  66. @api_auth_required
  67. def telegram_test():
  68. try:
  69. from services.notifications.telegram_integration import (
  70. _telegram_service,
  71. initialize_telegram_service,
  72. run_async,
  73. )
  74. # Ensure service is running with the latest config.
  75. if _telegram_service is None:
  76. if not initialize_telegram_service():
  77. cfg = load_config()
  78. if not cfg.get("enabled"):
  79. return jsonify(
  80. {
  81. "status": "error",
  82. "message": _(
  83. "Telegram está deshabilitado en la configuración."
  84. ),
  85. }
  86. ), 400
  87. return jsonify(
  88. {
  89. "status": "error",
  90. "message": _(
  91. "No se pudo inicializar el servicio Telegram. "
  92. "Verifique las credenciales API."
  93. ),
  94. }
  95. ), 400
  96. # Re-import after possible reinitialize
  97. from services.notifications.telegram_integration import (
  98. _telegram_service as svc,
  99. )
  100. health = run_async(svc.health_check())
  101. if health.get("connected"):
  102. return jsonify(
  103. {
  104. "status": "success",
  105. "message": _(
  106. "Conexión con Telegram establecida correctamente."
  107. ),
  108. "details": health,
  109. }
  110. )
  111. else:
  112. return jsonify(
  113. {
  114. "status": "error",
  115. "message": _(
  116. "No se pudo conectar a Telegram. Verifique las credenciales."
  117. ),
  118. "details": health,
  119. }
  120. ), 400
  121. except Exception as exc:
  122. logger.exception(f"Error during Telegram connection test: {exc}")
  123. return jsonify(
  124. {
  125. "status": "error",
  126. "message": _("Error interno al probar la conexión Telegram."),
  127. }
  128. ), 500
  129. # ------------------------------------------------------------------ #
  130. # Status #
  131. # ------------------------------------------------------------------ #
  132. @bp.route("/api/telegram/status", methods=["GET"])
  133. @api_auth_required
  134. def telegram_status():
  135. try:
  136. from services.notifications.telegram_integration import (
  137. _telegram_service,
  138. run_async,
  139. )
  140. if _telegram_service is None:
  141. cfg = load_config()
  142. return jsonify(
  143. {
  144. "status": "ok",
  145. "enabled": cfg.get("enabled", False),
  146. "connected": False,
  147. }
  148. )
  149. health = run_async(_telegram_service.health_check())
  150. return jsonify({"status": "ok", **health})
  151. except Exception as exc:
  152. logger.error(f"Error getting Telegram status: {exc}")
  153. return jsonify(
  154. {"status": "error", "message": _("No se pudo obtener el estado.")}
  155. ), 500
  156. # ------------------------------------------------------------------ #
  157. # Send test message #
  158. # ------------------------------------------------------------------ #
  159. @bp.route("/api/telegram/send-test", methods=["POST"])
  160. @csrf.exempt
  161. @api_auth_required
  162. def telegram_send_test():
  163. try:
  164. from services.notifications.telegram_integration import (
  165. _telegram_service,
  166. initialize_telegram_service,
  167. send_telegram_notification,
  168. )
  169. if _telegram_service is None:
  170. if not initialize_telegram_service():
  171. cfg = load_config()
  172. if not cfg.get("enabled"):
  173. return jsonify(
  174. {
  175. "status": "error",
  176. "message": _(
  177. "Telegram está deshabilitado en la configuración."
  178. ),
  179. }
  180. ), 400
  181. if not cfg.get("recipients"):
  182. return jsonify(
  183. {
  184. "status": "error",
  185. "message": _(
  186. "No hay destinatarios configurados para Telegram."
  187. ),
  188. }
  189. ), 400
  190. return jsonify(
  191. {
  192. "status": "error",
  193. "message": _(
  194. "No se pudo inicializar el servicio Telegram. Verifique las credenciales y la configuración."
  195. ),
  196. }
  197. ), 400
  198. success = send_telegram_notification(
  199. notification_type="info",
  200. message=_("Este es un mensaje de prueba enviado desde SquidStats."),
  201. source="admin",
  202. )
  203. if success:
  204. return jsonify(
  205. {"status": "success", "message": _("Mensaje de prueba enviado.")}
  206. )
  207. cfg = load_config()
  208. if not cfg.get("enabled"):
  209. message = _("Telegram está deshabilitado en la configuración.")
  210. elif not cfg.get("recipients"):
  211. message = _("No hay destinatarios configurados para Telegram.")
  212. else:
  213. message = _(
  214. "No se pudo enviar el mensaje. Verifique la configuración y los destinatarios."
  215. )
  216. return jsonify({"status": "error", "message": message}), 400
  217. except Exception as exc:
  218. logger.error(f"Error sending Telegram test message: {exc}")
  219. return jsonify(
  220. {"status": "error", "message": _("Error al enviar mensaje de prueba.")}
  221. ), 500