app.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 from .env into DB (non-interactive)
  72. try:
  73. from manage_db import migrate_env_blacklist
  74. logger.info("Checking for legacy BLACKLIST_DOMAINS to migrate into DB...")
  75. migrate_env_blacklist(auto_confirm=True)
  76. except Exception as e:
  77. logger.error(f"Error migrating BLACKLIST_DOMAINS into DB: {e}")
  78. # Compile Babel translations from sources/ at startup
  79. try:
  80. from tools.build_messages import compile_po, merge_sources, write_messages_po
  81. _translations_dir = Path(__file__).resolve().parent / "translations"
  82. for _lang_dir in _translations_dir.iterdir():
  83. if not _lang_dir.is_dir():
  84. continue
  85. _sources_dir = _lang_dir / "sources"
  86. _output_path = _lang_dir / "LC_MESSAGES" / "messages.po"
  87. if _sources_dir.exists():
  88. logger.info(f"Building translations for lang: {_lang_dir.name}")
  89. _entries = merge_sources(_sources_dir)
  90. if _entries:
  91. write_messages_po(_output_path, _entries, _lang_dir.name)
  92. compile_po(_translations_dir)
  93. logger.info("✓ Babel translations compiled successfully")
  94. except Exception as e:
  95. logger.warning(f"Could not compile translations at startup: {e}")
  96. app = Flask(__name__, static_folder="./static")
  97. app.config.from_object(Config())
  98. # Configure session for remember me functionality
  99. app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(
  100. days=AuthConfig.REMEMBER_ME_DAYS
  101. )
  102. app.config["SESSION_COOKIE_HTTPONLY"] = AuthConfig.SESSION_COOKIE_HTTPONLY
  103. app.config["SESSION_COOKIE_SECURE"] = AuthConfig.SESSION_COOKIE_SECURE
  104. app.config["SESSION_COOKIE_SAMESITE"] = AuthConfig.SESSION_COOKIE_SAMESITE
  105. # Initialize CSRF protection (shared instance with routes)
  106. csrf.init_app(app)
  107. # Initialize Flask-Babel for i18n
  108. def get_locale():
  109. # 1. Check session
  110. lang = session.get("lang")
  111. if lang and lang in Config.BABEL_SUPPORTED_LOCALES:
  112. logger.debug(f"get_locale: using session lang={lang}")
  113. return lang
  114. # 2. Check cookie
  115. lang = request.cookies.get("lang")
  116. if lang and lang in Config.BABEL_SUPPORTED_LOCALES:
  117. logger.debug(f"get_locale: using cookie lang={lang}")
  118. return lang
  119. # 3. Check Accept-Language header
  120. best_match = request.accept_languages.best_match(
  121. Config.BABEL_SUPPORTED_LOCALES, default=Config.BABEL_DEFAULT_LOCALE
  122. )
  123. logger.debug(
  124. f"get_locale: using Accept-Language best_match={best_match} "
  125. f"(Accept-Language={request.headers.get('Accept-Language')})"
  126. )
  127. return best_match
  128. Babel(app, locale_selector=get_locale)
  129. # Make get_locale available in templates
  130. app.jinja_env.globals["get_locale"] = get_locale
  131. app.jinja_env.globals["LANGUAGES"] = Config.LANGUAGES
  132. # Initialize extensions
  133. # Pass explicit timezone to avoid tzlocal.get_localzone() failures in containers
  134. scheduler = APScheduler(scheduler=BackgroundScheduler(timezone=timezone.utc))
  135. scheduler.init_app(app)
  136. # Register custom filters
  137. register_filters(app)
  138. # Register the date format filter for notifications
  139. @app.template_filter("datetime_format")
  140. def datetime_format(value, format="%d/%m/%Y %H:%M"):
  141. """Filtro para formatear fechas en las plantillas"""
  142. if isinstance(value, str):
  143. try:
  144. # Handle ISO format
  145. if "T" in value:
  146. value = datetime.fromisoformat(value.replace("Z", "+00:00"))
  147. else:
  148. # Try other common formats
  149. for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]:
  150. try:
  151. value = datetime.strptime(value, fmt)
  152. break
  153. except ValueError:
  154. continue
  155. else:
  156. return value # Could not parse, returning original
  157. except Exception:
  158. return value
  159. if isinstance(value, datetime):
  160. return value.strftime(format)
  161. return value
  162. # Register all route blueprints
  163. register_routes(app)
  164. # Configure response headers
  165. @app.after_request
  166. def set_response_headers(response):
  167. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  168. response.headers["Pragma"] = "no-cache"
  169. response.headers["Expires"] = "0"
  170. return response
  171. return app, scheduler
  172. def setup_scheduler_tasks(scheduler):
  173. # Register all scheduler tasks from services.scheduler.scheduler_tasks and plugins.
  174. register_scheduler_tasks(scheduler)
  175. def shutdown_app(scheduler, socketio, app=None):
  176. if shutdown_event.is_set():
  177. return
  178. logger.info("\n🛑 Shutting down SquidStats...")
  179. # Set shutdown event to stop all threads
  180. shutdown_event.set()
  181. # Stop notification monitor
  182. logger.info("Stopping notification monitor...")
  183. stop_notification_monitor()
  184. # Cleanup Telegram service
  185. if TELEGRAM_AVAILABLE and cleanup_telegram:
  186. logger.info("Cleaning up Telegram service...")
  187. try:
  188. cleanup_telegram()
  189. except Exception as e:
  190. logger.error(f"Error cleaning up Telegram: {e}")
  191. # Stop scheduler
  192. logger.info("Stopping scheduler...")
  193. try:
  194. if scheduler and scheduler.running:
  195. scheduler.shutdown(wait=False)
  196. except Exception as e:
  197. logger.error(f"Error stopping scheduler: {e}")
  198. logger.info("✅ Shutdown complete")
  199. def main():
  200. # Create Flask app and scheduler
  201. app, scheduler = create_app()
  202. # Setup scheduler tasks
  203. setup_scheduler_tasks(scheduler)
  204. # Start the scheduler after registering jobs
  205. scheduler.start()
  206. # Initialize SocketIO
  207. socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
  208. # Set up Socket.IO in the notifications module
  209. set_socketio_instance(socketio)
  210. # Initialize Telegram service if available
  211. if TELEGRAM_AVAILABLE and initialize_telegram_service:
  212. logger.info("Initializing Telegram service...")
  213. try:
  214. initialize_telegram_service()
  215. except Exception as e:
  216. logger.error(f"Failed to initialize Telegram: {e}")
  217. # Start the notification monitor
  218. start_notification_monitor()
  219. # Start real-time data collection thread
  220. socketio.start_background_task(realtime_data_thread, socketio, shutdown_event)
  221. # Register signal handlers for graceful shutdown
  222. def signal_handler(signum, frame):
  223. logger.info(f"\n⚠️ Received signal {signum}")
  224. shutdown_event.set()
  225. sys.exit(0)
  226. signal.signal(signal.SIGINT, signal_handler) # Ctrl+C
  227. signal.signal(signal.SIGTERM, signal_handler) # kill command
  228. # Register cleanup on exit
  229. atexit.register(lambda: shutdown_app(scheduler, socketio, app))
  230. # Run the application
  231. debug_mode = Config.DEBUG
  232. logger.info(
  233. f"Starting SquidStats application in {'debug' if debug_mode else 'production'} mode"
  234. )
  235. # Read host/port from environment variables if they exist (compatible with FLASK_HOST/PORT)
  236. host = Config.LISTEN_HOST
  237. port = Config.LISTEN_PORT
  238. try:
  239. socketio.run(
  240. app,
  241. debug=debug_mode,
  242. host=host,
  243. port=port,
  244. allow_unsafe_werkzeug=True,
  245. )
  246. except KeyboardInterrupt:
  247. logger.info("\n⚠️ Keyboard interrupt received")
  248. shutdown_app(scheduler, socketio, app)
  249. except Exception as e:
  250. logger.error(f"Application error: {e}")
  251. shutdown_app(scheduler, socketio, app)
  252. raise
  253. if __name__ == "__main__":
  254. main()