app.py 7.6 KB

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