app.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import atexit
  2. import os
  3. import signal
  4. import sys
  5. import threading
  6. from datetime import datetime, timedelta, timezone
  7. from apscheduler.schedulers.background import BackgroundScheduler
  8. from dotenv import load_dotenv
  9. from flask import Flask, request, session
  10. from flask_apscheduler import APScheduler
  11. from flask_babel import Babel
  12. from flask_socketio import SocketIO
  13. from loguru import logger
  14. from config import Config
  15. from database.database import migrate_database
  16. from routes import register_routes
  17. from routes.auth_routes import csrf
  18. from routes.stats_routes import realtime_data_thread
  19. from services.auth.auth_service import AuthConfig
  20. from services.notifications.notifications import (
  21. set_socketio_instance,
  22. start_notification_monitor,
  23. stop_notification_monitor,
  24. )
  25. from services.scheduler.scheduler_tasks import register_scheduler_tasks
  26. from utils.filters import register_filters
  27. log_level = os.getenv("APP_LOG_LEVEL", "DEBUG" if Config.DEBUG else "INFO")
  28. logger.add(
  29. Config.APP_LOG,
  30. rotation="100 MB",
  31. colorize=True,
  32. retention="31 days",
  33. level=log_level,
  34. )
  35. logger.add(sys.stderr, level=log_level, colorize=True)
  36. # Import Telegram integration (optional)
  37. try:
  38. from services.notifications.telegram_integration import (
  39. cleanup_telegram,
  40. initialize_telegram_service,
  41. )
  42. TELEGRAM_AVAILABLE = True
  43. except Exception:
  44. TELEGRAM_AVAILABLE = False
  45. initialize_telegram_service = None
  46. cleanup_telegram = None
  47. # Load environment variables
  48. load_dotenv()
  49. # Global shutdown event
  50. shutdown_event = threading.Event()
  51. def create_app():
  52. # Run database migration at startup
  53. logger.info("Running database migrations with Alembic...")
  54. try:
  55. migrate_database()
  56. logger.info("✓ Database migrations completed successfully")
  57. except Exception as e:
  58. logger.error(f"Database migration failed: {e}")
  59. logger.error(
  60. "Please check your database configuration and run: python manage_db.py init"
  61. )
  62. # Continue anyway - the app might still work with existing schema
  63. # Migrate legacy BLACKLIST_DOMAINS from .env into DB (non-interactive)
  64. try:
  65. from manage_db import migrate_env_blacklist
  66. logger.info("Checking for legacy BLACKLIST_DOMAINS to migrate into DB...")
  67. migrate_env_blacklist(auto_confirm=True)
  68. except Exception as e:
  69. logger.error(f"Error migrating BLACKLIST_DOMAINS into DB: {e}")
  70. app = Flask(__name__, static_folder="./static")
  71. app.config.from_object(Config())
  72. # Configure session for remember me functionality
  73. app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(
  74. days=AuthConfig.REMEMBER_ME_DAYS
  75. )
  76. app.config["SESSION_COOKIE_HTTPONLY"] = AuthConfig.SESSION_COOKIE_HTTPONLY
  77. app.config["SESSION_COOKIE_SECURE"] = AuthConfig.SESSION_COOKIE_SECURE
  78. app.config["SESSION_COOKIE_SAMESITE"] = AuthConfig.SESSION_COOKIE_SAMESITE
  79. # Initialize CSRF protection (shared instance with routes)
  80. csrf.init_app(app)
  81. # Initialize Flask-Babel for i18n
  82. def get_locale():
  83. # 1. Check session
  84. lang = session.get("lang")
  85. if lang and lang in Config.BABEL_SUPPORTED_LOCALES:
  86. logger.debug(f"get_locale: using session lang={lang}")
  87. return lang
  88. # 2. Check cookie
  89. lang = request.cookies.get("lang")
  90. if lang and lang in Config.BABEL_SUPPORTED_LOCALES:
  91. logger.debug(f"get_locale: using cookie lang={lang}")
  92. return lang
  93. # 3. Check Accept-Language header
  94. best_match = request.accept_languages.best_match(
  95. Config.BABEL_SUPPORTED_LOCALES, default=Config.BABEL_DEFAULT_LOCALE
  96. )
  97. logger.debug(
  98. f"get_locale: using Accept-Language best_match={best_match} "
  99. f"(Accept-Language={request.headers.get('Accept-Language')})"
  100. )
  101. return best_match
  102. Babel(app, locale_selector=get_locale)
  103. # Make get_locale available in templates
  104. app.jinja_env.globals["get_locale"] = get_locale
  105. app.jinja_env.globals["LANGUAGES"] = Config.LANGUAGES
  106. # Initialize extensions
  107. # Pass explicit timezone to avoid tzlocal.get_localzone() failures in containers
  108. scheduler = APScheduler(scheduler=BackgroundScheduler(timezone=timezone.utc))
  109. scheduler.init_app(app)
  110. scheduler.start()
  111. # Register custom filters
  112. register_filters(app)
  113. # Register the date format filter for notifications
  114. @app.template_filter("datetime_format")
  115. def datetime_format(value, format="%d/%m/%Y %H:%M"):
  116. """Filtro para formatear fechas en las plantillas"""
  117. if isinstance(value, str):
  118. try:
  119. # Handle ISO format
  120. if "T" in value:
  121. value = datetime.fromisoformat(value.replace("Z", "+00:00"))
  122. else:
  123. # Try other common formats
  124. for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]:
  125. try:
  126. value = datetime.strptime(value, fmt)
  127. break
  128. except ValueError:
  129. continue
  130. else:
  131. return value # Could not parse, returning original
  132. except Exception:
  133. return value
  134. if isinstance(value, datetime):
  135. return value.strftime(format)
  136. return value
  137. # Register all route blueprints
  138. register_routes(app)
  139. # Configure response headers
  140. @app.after_request
  141. def set_response_headers(response):
  142. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  143. response.headers["Pragma"] = "no-cache"
  144. response.headers["Expires"] = "0"
  145. return response
  146. return app, scheduler
  147. def setup_scheduler_tasks(scheduler):
  148. # Register all scheduler tasks from services.scheduler.scheduler_tasks and plugins.
  149. register_scheduler_tasks(scheduler)
  150. def shutdown_app(scheduler, socketio, app=None):
  151. if shutdown_event.is_set():
  152. return
  153. logger.info("\n🛑 Shutting down SquidStats...")
  154. # Set shutdown event to stop all threads
  155. shutdown_event.set()
  156. # Stop notification monitor
  157. logger.info("Stopping notification monitor...")
  158. stop_notification_monitor()
  159. # Cleanup Telegram service
  160. if TELEGRAM_AVAILABLE and cleanup_telegram:
  161. logger.info("Cleaning up Telegram service...")
  162. try:
  163. cleanup_telegram()
  164. except Exception as e:
  165. logger.error(f"Error cleaning up Telegram: {e}")
  166. # Stop scheduler
  167. logger.info("Stopping scheduler...")
  168. try:
  169. if scheduler and scheduler.running:
  170. scheduler.shutdown(wait=False)
  171. except Exception as e:
  172. logger.error(f"Error stopping scheduler: {e}")
  173. # SocketIO shutdown is handled by process exit. Avoid calling socketio.stop() here.
  174. logger.info("Stopping SocketIO (handled by process exit)...")
  175. logger.info("✅ Shutdown complete")
  176. def main():
  177. # Create Flask app and scheduler
  178. app, scheduler = create_app()
  179. # Setup scheduler tasks
  180. setup_scheduler_tasks(scheduler)
  181. # Initialize SocketIO
  182. socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
  183. # Set up Socket.IO in the notifications module
  184. set_socketio_instance(socketio)
  185. # Initialize Telegram service if available
  186. if TELEGRAM_AVAILABLE and initialize_telegram_service:
  187. logger.info("Initializing Telegram service...")
  188. try:
  189. initialize_telegram_service()
  190. except Exception as e:
  191. logger.error(f"Failed to initialize Telegram: {e}")
  192. # Start the notification monitor
  193. start_notification_monitor()
  194. # Start real-time data collection thread
  195. socketio.start_background_task(realtime_data_thread, socketio, shutdown_event)
  196. # Register signal handlers for graceful shutdown
  197. def signal_handler(signum, frame):
  198. logger.info(f"\n⚠️ Received signal {signum}")
  199. shutdown_event.set()
  200. sys.exit(0)
  201. signal.signal(signal.SIGINT, signal_handler) # Ctrl+C
  202. signal.signal(signal.SIGTERM, signal_handler) # kill command
  203. # Register cleanup on exit
  204. atexit.register(lambda: shutdown_app(scheduler, socketio, app))
  205. # Run the application
  206. debug_mode = Config.DEBUG
  207. logger.info(
  208. f"Starting SquidStats application in {'debug' if debug_mode else 'production'} mode"
  209. )
  210. # Read host/port from environment variables if they exist (compatible with FLASK_HOST/PORT)
  211. host = Config.LISTEN_HOST
  212. port = Config.LISTEN_PORT
  213. try:
  214. socketio.run(
  215. app, debug=debug_mode, host=host, port=port, allow_unsafe_werkzeug=True
  216. )
  217. except KeyboardInterrupt:
  218. logger.info("\n⚠️ Keyboard interrupt received")
  219. shutdown_app(scheduler, socketio, app)
  220. except Exception as e:
  221. logger.error(f"Application error: {e}")
  222. shutdown_app(scheduler, socketio, app)
  223. raise
  224. if __name__ == "__main__":
  225. main()