app.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import atexit
  2. import os
  3. import signal
  4. import sys
  5. import threading
  6. from datetime import datetime, timedelta, timezone
  7. from pathlib import Path
  8. from apscheduler.schedulers.background import BackgroundScheduler
  9. from dotenv import load_dotenv
  10. from flask import Flask, request, session
  11. from flask_apscheduler import APScheduler
  12. from flask_babel import Babel
  13. from flask_socketio import SocketIO
  14. from loguru import logger
  15. from config import Config
  16. from database.database import migrate_database
  17. from routes import register_routes
  18. from routes.auth_routes import csrf
  19. from routes.stats_routes import realtime_data_thread
  20. from services.auth.auth_service import AuthConfig
  21. from services.notifications.notifications import (
  22. set_socketio_instance,
  23. start_notification_monitor,
  24. stop_notification_monitor,
  25. )
  26. from services.notifications.telegram_integration import (
  27. cleanup_telegram,
  28. initialize_telegram_service,
  29. )
  30. from services.scheduler.scheduler_tasks import register_scheduler_tasks
  31. from utils.filters import register_filters
  32. log_level = os.getenv("APP_LOG_LEVEL", "DEBUG" if Config.DEBUG else "INFO")
  33. # Remove the default loguru stderr handler before adding custom ones,
  34. # otherwise every message is printed twice (default + explicit add).
  35. logger.remove()
  36. logger.add(
  37. Config.APP_LOG,
  38. rotation="100 MB",
  39. colorize=True,
  40. retention="31 days",
  41. level=log_level,
  42. )
  43. logger.add(sys.stderr, level=log_level, colorize=True)
  44. TELEGRAM_AVAILABLE = True
  45. # Load environment variables
  46. load_dotenv()
  47. # Global shutdown event
  48. shutdown_event = threading.Event()
  49. def create_app():
  50. # Ensure quota is disabled by default on first run (flag file must exist to disable).
  51. _quota_disabled_flag = Path(__file__).resolve().parent / "quota_disabled"
  52. if not _quota_disabled_flag.exists():
  53. try:
  54. _quota_disabled_flag.write_text("disabled\n", encoding="utf-8")
  55. logger.info(
  56. "Quota system disabled by default (created quota_disabled flag)"
  57. )
  58. except OSError as e:
  59. logger.warning("Could not create quota_disabled flag: %s", e)
  60. # Run database migration at startup
  61. logger.info("Running database migrations with Alembic...")
  62. try:
  63. migrate_database()
  64. logger.info("✓ Database migrations completed successfully")
  65. except Exception as e:
  66. logger.error(f"Database migration failed: {e}")
  67. logger.error(
  68. "Please check your database configuration and run: python manage_db.py init"
  69. )
  70. # Continue anyway - the app might still work with existing schema
  71. # Migrate legacy BLACKLIST_DOMAINS and Squid env vars from .env into DB (non-interactive)
  72. try:
  73. from manage_db import migrate_env_blacklist, migrate_env_squid_config
  74. logger.info("Checking for legacy BLACKLIST_DOMAINS to migrate into DB...")
  75. migrate_env_blacklist(auto_confirm=True)
  76. logger.info("Checking for legacy Squid env vars to migrate into DB...")
  77. migrate_env_squid_config(auto_confirm=True)
  78. except Exception as e:
  79. logger.error(f"Error migrating legacy environment configuration into DB: {e}")
  80. # Compile Babel translations from sources/ at startup
  81. try:
  82. from tools.build_messages import compile_po, merge_sources, write_messages_po
  83. _translations_dir = Path(__file__).resolve().parent / "translations"
  84. for _lang_dir in _translations_dir.iterdir():
  85. if not _lang_dir.is_dir():
  86. continue
  87. _sources_dir = _lang_dir / "sources"
  88. _output_path = _lang_dir / "LC_MESSAGES" / "messages.po"
  89. if _sources_dir.exists():
  90. logger.info(f"Building translations for lang: {_lang_dir.name}")
  91. _entries = merge_sources(_sources_dir)
  92. if _entries:
  93. write_messages_po(_output_path, _entries, _lang_dir.name)
  94. compile_po(_translations_dir)
  95. logger.info("✓ Babel translations compiled successfully")
  96. except Exception as e:
  97. logger.warning(f"Could not compile translations at startup: {e}")
  98. app = Flask(__name__, static_folder="./static")
  99. app.config.from_object(Config())
  100. # Configure session for remember me functionality
  101. app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(
  102. days=AuthConfig.REMEMBER_ME_DAYS
  103. )
  104. app.config["SESSION_COOKIE_HTTPONLY"] = AuthConfig.SESSION_COOKIE_HTTPONLY
  105. app.config["SESSION_COOKIE_SECURE"] = AuthConfig.SESSION_COOKIE_SECURE
  106. app.config["SESSION_COOKIE_SAMESITE"] = AuthConfig.SESSION_COOKIE_SAMESITE
  107. # Initialize CSRF protection (shared instance with routes)
  108. csrf.init_app(app)
  109. # Initialize Flask-Babel for i18n
  110. def get_locale():
  111. # 1. Check session
  112. lang = session.get("lang")
  113. if lang and lang in Config.BABEL_SUPPORTED_LOCALES:
  114. logger.debug(f"get_locale: using session lang={lang}")
  115. return lang
  116. # 2. Check cookie
  117. lang = request.cookies.get("lang")
  118. if lang and lang in Config.BABEL_SUPPORTED_LOCALES:
  119. logger.debug(f"get_locale: using cookie lang={lang}")
  120. return lang
  121. # 3. Check Accept-Language header
  122. best_match = request.accept_languages.best_match(
  123. Config.BABEL_SUPPORTED_LOCALES, default=Config.BABEL_DEFAULT_LOCALE
  124. )
  125. logger.debug(
  126. f"get_locale: using Accept-Language best_match={best_match} "
  127. f"(Accept-Language={request.headers.get('Accept-Language')})"
  128. )
  129. return best_match
  130. Babel(app, locale_selector=get_locale)
  131. # Make get_locale available in templates
  132. app.jinja_env.globals["get_locale"] = get_locale
  133. app.jinja_env.globals["LANGUAGES"] = Config.LANGUAGES
  134. # Initialize extensions
  135. # Pass explicit timezone to avoid tzlocal.get_localzone() failures in containers
  136. scheduler = APScheduler(scheduler=BackgroundScheduler(timezone=timezone.utc))
  137. scheduler.init_app(app)
  138. # Register custom filters
  139. register_filters(app)
  140. # Register the date format filter for notifications
  141. @app.template_filter("datetime_format")
  142. def datetime_format(value, format="%d/%m/%Y %H:%M"):
  143. """Filtro para formatear fechas en las plantillas"""
  144. if isinstance(value, str):
  145. try:
  146. # Handle ISO format
  147. if "T" in value:
  148. value = datetime.fromisoformat(value.replace("Z", "+00:00"))
  149. else:
  150. # Try other common formats
  151. for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]:
  152. try:
  153. value = datetime.strptime(value, fmt)
  154. break
  155. except ValueError:
  156. continue
  157. else:
  158. return value # Could not parse, returning original
  159. except Exception:
  160. return value
  161. if isinstance(value, datetime):
  162. return value.strftime(format)
  163. return value
  164. # Register all route blueprints
  165. register_routes(app)
  166. # Configure response headers
  167. @app.after_request
  168. def set_response_headers(response):
  169. if request.path.startswith("/static/") and response.status_code == 200:
  170. # Static filenames are not content-hashed, so they must remain revalidatable.
  171. response.headers["Cache-Control"] = "public, max-age=3600, must-revalidate"
  172. else:
  173. # Revalidate dynamic/private data without disabling the browser's bfcache.
  174. response.headers["Cache-Control"] = "private, no-cache"
  175. response.headers["X-Content-Type-Options"] = "nosniff"
  176. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  177. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  178. response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
  179. response.headers["Permissions-Policy"] = (
  180. "camera=(), microphone=(), geolocation=()"
  181. )
  182. if request.is_secure:
  183. response.headers["Strict-Transport-Security"] = (
  184. "max-age=31536000; includeSubDomains"
  185. )
  186. return response
  187. return app, scheduler
  188. def setup_scheduler_tasks(scheduler):
  189. # Register all scheduler tasks from services.scheduler.scheduler_tasks and plugins.
  190. register_scheduler_tasks(scheduler)
  191. def shutdown_app(scheduler, socketio, app=None):
  192. if shutdown_event.is_set():
  193. return
  194. logger.info("\n🛑 Shutting down SquidStats...")
  195. # Set shutdown event to stop all threads
  196. shutdown_event.set()
  197. # Stop notification monitor
  198. logger.info("Stopping notification monitor...")
  199. stop_notification_monitor()
  200. # Cleanup Telegram service
  201. if TELEGRAM_AVAILABLE and cleanup_telegram:
  202. logger.info("Cleaning up Telegram service...")
  203. try:
  204. cleanup_telegram()
  205. except Exception as e:
  206. logger.error(f"Error cleaning up Telegram: {e}")
  207. # Stop scheduler
  208. logger.info("Stopping scheduler...")
  209. try:
  210. if scheduler and scheduler.running:
  211. scheduler.shutdown(wait=False)
  212. except Exception as e:
  213. logger.error(f"Error stopping scheduler: {e}")
  214. logger.info("✅ Shutdown complete")
  215. def main():
  216. # Create Flask app and scheduler
  217. app, scheduler = create_app()
  218. # Setup scheduler tasks
  219. setup_scheduler_tasks(scheduler)
  220. # Start the scheduler after registering jobs
  221. scheduler.start()
  222. # Initialize SocketIO
  223. socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
  224. # Set up Socket.IO in the notifications module
  225. set_socketio_instance(socketio)
  226. # Initialize Telegram service if available
  227. if TELEGRAM_AVAILABLE and initialize_telegram_service:
  228. logger.info("Initializing Telegram service...")
  229. try:
  230. initialize_telegram_service()
  231. except Exception as e:
  232. logger.error(f"Failed to initialize Telegram: {e}")
  233. # Start the notification monitor
  234. start_notification_monitor()
  235. # Start real-time data collection thread
  236. socketio.start_background_task(realtime_data_thread, socketio, shutdown_event)
  237. # Register signal handlers for graceful shutdown
  238. def signal_handler(signum, frame):
  239. logger.info(f"\n⚠️ Received signal {signum}")
  240. shutdown_event.set()
  241. sys.exit(0)
  242. signal.signal(signal.SIGINT, signal_handler) # Ctrl+C
  243. signal.signal(signal.SIGTERM, signal_handler) # kill command
  244. # Register cleanup on exit
  245. atexit.register(lambda: shutdown_app(scheduler, socketio, app))
  246. # Run the application
  247. debug_mode = Config.DEBUG
  248. logger.info(
  249. f"Starting SquidStats application in {'debug' if debug_mode else 'production'} mode"
  250. )
  251. # Read host/port from environment variables if they exist (compatible with FLASK_HOST/PORT)
  252. host = Config.LISTEN_HOST
  253. port = Config.LISTEN_PORT
  254. try:
  255. socketio.run(
  256. app,
  257. debug=debug_mode,
  258. host=host,
  259. port=port,
  260. allow_unsafe_werkzeug=True,
  261. )
  262. except KeyboardInterrupt:
  263. logger.info("\n⚠️ Keyboard interrupt received")
  264. shutdown_app(scheduler, socketio, app)
  265. except Exception as e:
  266. logger.error(f"Application error: {e}")
  267. shutdown_app(scheduler, socketio, app)
  268. raise
  269. if __name__ == "__main__":
  270. main()