import atexit import os import signal import sys import threading from datetime import datetime, timedelta, timezone from pathlib import Path from apscheduler.schedulers.background import BackgroundScheduler from dotenv import load_dotenv from flask import Flask, request, session from flask_apscheduler import APScheduler from flask_babel import Babel from flask_socketio import SocketIO from loguru import logger from config import Config from database.database import migrate_database from routes import register_routes from routes.auth_routes import csrf from routes.stats_routes import realtime_data_thread from services.auth.auth_service import AuthConfig from services.notifications.notifications import ( set_socketio_instance, start_notification_monitor, stop_notification_monitor, ) from services.notifications.telegram_integration import ( cleanup_telegram, initialize_telegram_service, ) from services.scheduler.scheduler_tasks import register_scheduler_tasks from utils.filters import register_filters log_level = os.getenv("APP_LOG_LEVEL", "DEBUG" if Config.DEBUG else "INFO") # Remove the default loguru stderr handler before adding custom ones, # otherwise every message is printed twice (default + explicit add). logger.remove() logger.add( Config.APP_LOG, rotation="100 MB", colorize=True, retention="31 days", level=log_level, ) logger.add(sys.stderr, level=log_level, colorize=True) TELEGRAM_AVAILABLE = True # Load environment variables load_dotenv() # Global shutdown event shutdown_event = threading.Event() def create_app(): # Ensure quota is disabled by default on first run (flag file must exist to disable). _quota_disabled_flag = Path(__file__).resolve().parent / "quota_disabled" if not _quota_disabled_flag.exists(): try: _quota_disabled_flag.write_text("disabled\n", encoding="utf-8") logger.info( "Quota system disabled by default (created quota_disabled flag)" ) except OSError as e: logger.warning("Could not create quota_disabled flag: %s", e) # Run database migration at startup logger.info("Running database migrations with Alembic...") try: migrate_database() logger.info("✓ Database migrations completed successfully") except Exception as e: logger.error(f"Database migration failed: {e}") logger.error( "Please check your database configuration and run: python manage_db.py init" ) # Continue anyway - the app might still work with existing schema # Migrate legacy BLACKLIST_DOMAINS from .env into DB (non-interactive) try: from manage_db import migrate_env_blacklist logger.info("Checking for legacy BLACKLIST_DOMAINS to migrate into DB...") migrate_env_blacklist(auto_confirm=True) except Exception as e: logger.error(f"Error migrating BLACKLIST_DOMAINS into DB: {e}") # Compile Babel translations from sources/ at startup try: from tools.build_messages import compile_po, merge_sources, write_messages_po _translations_dir = Path(__file__).resolve().parent / "translations" for _lang_dir in _translations_dir.iterdir(): if not _lang_dir.is_dir(): continue _sources_dir = _lang_dir / "sources" _output_path = _lang_dir / "LC_MESSAGES" / "messages.po" if _sources_dir.exists(): logger.info(f"Building translations for lang: {_lang_dir.name}") _entries = merge_sources(_sources_dir) if _entries: write_messages_po(_output_path, _entries, _lang_dir.name) compile_po(_translations_dir) logger.info("✓ Babel translations compiled successfully") except Exception as e: logger.warning(f"Could not compile translations at startup: {e}") app = Flask(__name__, static_folder="./static") app.config.from_object(Config()) # Configure session for remember me functionality app.config["PERMANENT_SESSION_LIFETIME"] = timedelta( days=AuthConfig.REMEMBER_ME_DAYS ) app.config["SESSION_COOKIE_HTTPONLY"] = AuthConfig.SESSION_COOKIE_HTTPONLY app.config["SESSION_COOKIE_SECURE"] = AuthConfig.SESSION_COOKIE_SECURE app.config["SESSION_COOKIE_SAMESITE"] = AuthConfig.SESSION_COOKIE_SAMESITE # Initialize CSRF protection (shared instance with routes) csrf.init_app(app) # Initialize Flask-Babel for i18n def get_locale(): # 1. Check session lang = session.get("lang") if lang and lang in Config.BABEL_SUPPORTED_LOCALES: logger.debug(f"get_locale: using session lang={lang}") return lang # 2. Check cookie lang = request.cookies.get("lang") if lang and lang in Config.BABEL_SUPPORTED_LOCALES: logger.debug(f"get_locale: using cookie lang={lang}") return lang # 3. Check Accept-Language header best_match = request.accept_languages.best_match( Config.BABEL_SUPPORTED_LOCALES, default=Config.BABEL_DEFAULT_LOCALE ) logger.debug( f"get_locale: using Accept-Language best_match={best_match} " f"(Accept-Language={request.headers.get('Accept-Language')})" ) return best_match Babel(app, locale_selector=get_locale) # Make get_locale available in templates app.jinja_env.globals["get_locale"] = get_locale app.jinja_env.globals["LANGUAGES"] = Config.LANGUAGES # Initialize extensions # Pass explicit timezone to avoid tzlocal.get_localzone() failures in containers scheduler = APScheduler(scheduler=BackgroundScheduler(timezone=timezone.utc)) scheduler.init_app(app) # Register custom filters register_filters(app) # Register the date format filter for notifications @app.template_filter("datetime_format") def datetime_format(value, format="%d/%m/%Y %H:%M"): """Filtro para formatear fechas en las plantillas""" if isinstance(value, str): try: # Handle ISO format if "T" in value: value = datetime.fromisoformat(value.replace("Z", "+00:00")) else: # Try other common formats for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]: try: value = datetime.strptime(value, fmt) break except ValueError: continue else: return value # Could not parse, returning original except Exception: return value if isinstance(value, datetime): return value.strftime(format) return value # Register all route blueprints register_routes(app) # Configure response headers @app.after_request def set_response_headers(response): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Pragma"] = "no-cache" response.headers["Expires"] = "0" return response return app, scheduler def setup_scheduler_tasks(scheduler): # Register all scheduler tasks from services.scheduler.scheduler_tasks and plugins. register_scheduler_tasks(scheduler) def shutdown_app(scheduler, socketio, app=None): if shutdown_event.is_set(): return logger.info("\n🛑 Shutting down SquidStats...") # Set shutdown event to stop all threads shutdown_event.set() # Stop notification monitor logger.info("Stopping notification monitor...") stop_notification_monitor() # Cleanup Telegram service if TELEGRAM_AVAILABLE and cleanup_telegram: logger.info("Cleaning up Telegram service...") try: cleanup_telegram() except Exception as e: logger.error(f"Error cleaning up Telegram: {e}") # Stop scheduler logger.info("Stopping scheduler...") try: if scheduler and scheduler.running: scheduler.shutdown(wait=False) except Exception as e: logger.error(f"Error stopping scheduler: {e}") logger.info("✅ Shutdown complete") def main(): # Create Flask app and scheduler app, scheduler = create_app() # Setup scheduler tasks setup_scheduler_tasks(scheduler) # Start the scheduler after registering jobs scheduler.start() # Initialize SocketIO socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading") # Set up Socket.IO in the notifications module set_socketio_instance(socketio) # Initialize Telegram service if available if TELEGRAM_AVAILABLE and initialize_telegram_service: logger.info("Initializing Telegram service...") try: initialize_telegram_service() except Exception as e: logger.error(f"Failed to initialize Telegram: {e}") # Start the notification monitor start_notification_monitor() # Start real-time data collection thread socketio.start_background_task(realtime_data_thread, socketio, shutdown_event) # Register signal handlers for graceful shutdown def signal_handler(signum, frame): logger.info(f"\n⚠️ Received signal {signum}") shutdown_event.set() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Ctrl+C signal.signal(signal.SIGTERM, signal_handler) # kill command # Register cleanup on exit atexit.register(lambda: shutdown_app(scheduler, socketio, app)) # Run the application debug_mode = Config.DEBUG logger.info( f"Starting SquidStats application in {'debug' if debug_mode else 'production'} mode" ) # Read host/port from environment variables if they exist (compatible with FLASK_HOST/PORT) host = Config.LISTEN_HOST port = Config.LISTEN_PORT try: socketio.run( app, debug=debug_mode, host=host, port=port, allow_unsafe_werkzeug=True, ) except KeyboardInterrupt: logger.info("\n⚠️ Keyboard interrupt received") shutdown_app(scheduler, socketio, app) except Exception as e: logger.error(f"Application error: {e}") shutdown_app(scheduler, socketio, app) raise if __name__ == "__main__": main()