Explorar o código

refactor: clean up code formatting and improve readability across multiple files

Manuel hai 1 ano
pai
achega
3dc85d338c
Modificáronse 5 ficheiros con 321 adicións e 209 borrados
  1. 4 2
      app.py
  2. 10 9
      routes/api_routes.py
  3. 9 10
      routes/main_routes.py
  4. 72 58
      services/auditoria_service.py
  5. 226 130
      services/notifications.py

+ 4 - 2
app.py

@@ -5,10 +5,12 @@ from flask import Flask
 from flask_apscheduler import APScheduler
 from flask_socketio import SocketIO
 from flask_wtf.csrf import CSRFProtect
+
 from config import Config, logger
 from database.database import migrate_database
 from parsers.log import process_logs
 from routes import register_routes
+
 # from routes.main_routes import initialize_proxy_detection
 from routes.stats_routes import realtime_data_thread
 from services.metrics_service import MetricsService
@@ -52,7 +54,7 @@ def create_app():
     register_routes(app)
 
     # Initialize proxy detection
-#    initialize_proxy_detection()
+    #    initialize_proxy_detection()
 
     # Configure response headers
     @app.after_request
@@ -137,4 +139,4 @@ def main():
 
 
 if __name__ == "__main__":
-    main()
+    main()

+ 10 - 9
routes/api_routes.py

@@ -1,5 +1,4 @@
 from flask import Blueprint, current_app, jsonify, request
-from services.notifications import get_all_notifications, mark_notifications_read
 
 from config import logger
 from database.database import get_session
@@ -18,7 +17,10 @@ from services.auditoria_service import (
     get_user_activity_summary,
 )
 from services.metrics_service import MetricsService
-from services.notifications import get_commit_notifications
+from services.notifications import (
+    get_all_notifications,
+    mark_notifications_read,
+)
 
 api_bp = Blueprint("api", __name__)
 
@@ -149,19 +151,18 @@ def api_get_notifications():
         return jsonify(get_all_notifications(limit=10))
     except Exception as e:
         logger.error(f"Error getting notifications: {e}")
-        return jsonify({'unread_count': 0, 'notifications': []})
+        return jsonify({"unread_count": 0, "notifications": []})
 
 
 @api_bp.route("/notifications/mark-read", methods=["POST"])
 def api_mark_notifications_read():
     try:
         data = request.get_json()
-        notification_ids = data.get('ids', [])
+        notification_ids = data.get("ids", [])
         mark_notifications_read(notification_ids)
-        return jsonify({
-            'success': True, 
-            'unread_count': get_all_notifications()['unread_count']
-        })
+        return jsonify(
+            {"success": True, "unread_count": get_all_notifications()["unread_count"]}
+        )
     except Exception as e:
         logger.error(f"Error marking notifications as read: {e}")
-        return jsonify({'success': False}), 500
+        return jsonify({"success": False}), 500

+ 9 - 10
routes/main_routes.py

@@ -1,6 +1,5 @@
 import os
 import time
-from threading import Lock
 from typing import Any
 
 from flask import Blueprint, current_app, redirect, render_template, request
@@ -125,23 +124,23 @@ def _get_dashboard_context() -> tuple[dict[str, Any] | None, tuple[Any, int] | N
 def index():
     """
     Ruta unificada para el dashboard
-    
-    CAMBIO PRINCIPAL: 
+
+    CAMBIO PRINCIPAL:
     - Ahora maneja tanto la carga completa de la página como las actualizaciones parciales
     - Elimina la necesidad de la ruta separada /actualizar-conexiones
-    
+
     Detección de tipo de petición:
     - Petición normal: Devuelve index.html completo
     - Petición parcial (param partial=true): Devuelve solo el contenido de conexiones
     """
-    
+
     # CAMBIO: Detectar si es una petición para contenido parcial
-    is_partial_request = request.args.get('partial') == 'true'
-    
+    is_partial_request = request.args.get("partial") == "true"
+
     context, error_response = _get_dashboard_context()
     if error_response:
         return error_response
-    
+
     # CAMBIO: Si es petición parcial, devolver solo el template de conexiones
     if is_partial_request:
         return render_template(
@@ -153,7 +152,7 @@ def index():
             build_time_ms=context["build_time_ms"],
             connection_count=context["connection_count"],
         )
-    
+
     # Petición normal: devolver la página completa
     return render_template("index.html", **context)
 
@@ -185,4 +184,4 @@ def update_web():
             logger.warning("updateSquidStats() retornó False en /update")
     except Exception:
         logger.exception("Error ejecutando actualización en /update")
-    return redirect(f"/?update_status={'ok' if ok else 'fail'}")
+    return redirect(f"/?update_status={'ok' if ok else 'fail'}")

+ 72 - 58
services/auditoria_service.py

@@ -26,6 +26,7 @@ def _get_tables_in_range(
         current_date += timedelta(days=1)
     return log_tables_in_range
 
+
 def find_by_keyword(
     db: Session, start_str: str, end_str: str, keyword: str, username: str = None
 ) -> dict[str, Any]:
@@ -100,6 +101,7 @@ def find_by_keyword(
 
     return {"results": all_results}
 
+
 def find_social_media_activity(
     db: Session, start_str: str, end_str: str, sites: list[str], username: str = None
 ) -> dict[str, Any]:
@@ -195,6 +197,7 @@ def find_social_media_activity(
 
     return {"results": all_results}
 
+
 def find_by_ip(
     db: Session, start_str: str, end_str: str, ip_address: str
 ) -> dict[str, Any]:
@@ -265,6 +268,7 @@ def find_by_ip(
 
     return {"results": all_results}
 
+
 def find_by_response_code(
     db: Session, start_str: str, end_str: str, code: int, username: str = None
 ) -> dict[str, Any]:
@@ -342,6 +346,7 @@ def find_by_response_code(
 
     return {"results": all_results}
 
+
 def get_daily_activity(db: Session, date_str: str, username: str) -> dict[str, Any]:
     try:
         selected_date = datetime.strptime(date_str, "%Y-%m-%d")
@@ -397,6 +402,7 @@ def get_daily_activity(db: Session, date_str: str, username: str) -> dict[str, A
             "error": "An unexpected error occurred while calculating daily activity."
         }
 
+
 def get_all_usernames(db: Session) -> list[str]:
     engine = db.get_bind()
     inspector = inspect(engine)
@@ -435,6 +441,7 @@ def get_all_usernames(db: Session) -> list[str]:
 
     return sorted(all_usernames)
 
+
 def get_user_activity_summary(
     db: Session, username: str, start_str: str, end_str: str
 ) -> dict[str, Any]:
@@ -514,6 +521,7 @@ def get_user_activity_summary(
         ],
     }
 
+
 def get_top_users_by_data(
     db: Session, start_str: str, end_str: str, limit: int = 10
 ) -> dict[str, Any]:
@@ -560,6 +568,7 @@ def get_top_users_by_data(
 
     return {"top_users": top_users_list}
 
+
 def get_top_users_by_requests(
     db: Session, start_str: str, end_str: str, limit: int = 10
 ) -> dict[str, Any]:
@@ -603,6 +612,7 @@ def get_top_users_by_requests(
         ]
     }
 
+
 def get_top_urls_by_data(
     db: Session, start_str: str, end_str: str, limit: int = 15
 ) -> dict[str, Any]:
@@ -647,6 +657,7 @@ def get_top_urls_by_data(
 
     return {"top_urls": top_urls_list}
 
+
 def get_top_ips_by_data(
     db: Session, start_str: str, end_str: str, limit: int = 10
 ) -> dict[str, Any]:
@@ -692,6 +703,7 @@ def get_top_ips_by_data(
         ]
     }
 
+
 def find_denied_access(
     db: Session, start_str: str, end_str: str, username: str = None
 ) -> dict[str, Any]:
@@ -754,36 +766,36 @@ def find_denied_access(
 
     return {"results": all_results}
 
+
 def find_suspicious_activity(db, threshold=50, hours=1):
     """
     Find IPs with suspicious activity (many requests in short time)
     Returns: list of tuples [(ip, count), ...]
     """
     from datetime import datetime, timedelta
-    
+
     try:
         since_time = datetime.now() - timedelta(hours=hours)
-        
+
         # Get all user tables to check across all dates
         engine = db.get_bind()
         inspector = inspect(engine)
         all_tables = inspector.get_table_names()
         user_tables = [t for t in all_tables if t.startswith("user_") and len(t) == 13]
-        
+
         ip_counts = defaultdict(int)
-        
+
         for table_name in user_tables:
             date_suffix = table_name.split("_")[1]
             try:
                 UserModel, LogModel = get_dynamic_models(date_suffix)
                 if UserModel is None or LogModel is None:
                     continue
-                
+
                 # Use ORM to count requests per IP
                 results = (
                     db.query(
-                        UserModel.ip,
-                        func.count(LogModel.id).label("request_count")
+                        UserModel.ip, func.count(LogModel.id).label("request_count")
                     )
                     .join(LogModel, LogModel.user_id == UserModel.id)
                     .filter(LogModel.created_at >= since_time)
@@ -791,47 +803,48 @@ def find_suspicious_activity(db, threshold=50, hours=1):
                     .having(func.count(LogModel.id) > threshold)
                     .all()
                 )
-                
+
                 for row in results:
                     ip_counts[row[0]] += row.request_count
-                    
+
             except Exception as e:
                 print(f"Error processing table {table_name}: {e}")
                 continue
-        
+
         # Sort by count descending and return top 10
         sorted_ips = sorted(ip_counts.items(), key=lambda x: x[1], reverse=True)[:10]
         return sorted_ips
-        
+
     except Exception as e:
         print(f"Error finding suspicious activity: {e}")
         return []
 
+
 def get_active_users_count(db, hours=1):
     """
     Count unique active users in the last N hours
     Returns: number of unique users
     """
     from datetime import datetime, timedelta
-    
+
     try:
         since_time = datetime.now() - timedelta(hours=hours)
-        
+
         # Get all user tables to check across all dates
         engine = db.get_bind()
         inspector = inspect(engine)
         all_tables = inspector.get_table_names()
         user_tables = [t for t in all_tables if t.startswith("user_") and len(t) == 13]
-        
+
         active_users = set()
-        
+
         for table_name in user_tables:
             date_suffix = table_name.split("_")[1]
             try:
                 UserModel, LogModel = get_dynamic_models(date_suffix)
                 if UserModel is None or LogModel is None:
                     continue
-                
+
                 # Use ORM to get distinct usernames with activity in time range
                 usernames = (
                     db.query(UserModel.username.distinct())
@@ -840,177 +853,178 @@ def get_active_users_count(db, hours=1):
                         LogModel.created_at >= since_time,
                         UserModel.username.isnot(None),
                         UserModel.username != "",
-                        UserModel.username != "-"
+                        UserModel.username != "-",
                     )
                     .all()
                 )
-                
+
                 for username_row in usernames:
                     active_users.add(username_row[0])
-                    
+
             except Exception as e:
                 print(f"Error processing table {table_name}: {e}")
                 continue
-        
+
         return len(active_users)
-        
+
     except Exception as e:
         print(f"Error counting active users: {e}")
         return 0
 
+
 def get_high_usage_users(db, hours=24, limit=5, threshold_mb=500):
     """
     Get users with high data consumption
     Returns: list of tuples [(username, usage_mb), ...]
     """
     from datetime import datetime, timedelta
-    
+
     try:
         since_time = datetime.now() - timedelta(hours=hours)
-        
+
         # Get all user tables to check across all dates
         engine = db.get_bind()
         inspector = inspect(engine)
         all_tables = inspector.get_table_names()
         user_tables = [t for t in all_tables if t.startswith("user_") and len(t) == 13]
-        
+
         user_usage = defaultdict(float)
-        
+
         for table_name in user_tables:
             date_suffix = table_name.split("_")[1]
             try:
                 UserModel, LogModel = get_dynamic_models(date_suffix)
                 if UserModel is None or LogModel is None:
                     continue
-                
+
                 # Use ORM to sum data usage per user
                 results = (
                     db.query(
                         UserModel.username,
-                        func.sum(LogModel.data_transmitted).label("total_bytes")
+                        func.sum(LogModel.data_transmitted).label("total_bytes"),
                     )
                     .join(LogModel, LogModel.user_id == UserModel.id)
                     .filter(
                         LogModel.created_at >= since_time,
                         UserModel.username.isnot(None),
                         UserModel.username != "",
-                        UserModel.username != "-"
+                        UserModel.username != "-",
                     )
                     .group_by(UserModel.username)
                     .all()
                 )
-                
+
                 for row in results:
                     usage_mb = (row.total_bytes or 0) / (1024 * 1024)
                     user_usage[row[0]] += usage_mb
-                    
+
             except Exception as e:
                 print(f"Error processing table {table_name}: {e}")
                 continue
-        
+
         # Filter by threshold and sort
         filtered_users = [
-            (username, usage) for username, usage in user_usage.items() 
+            (username, usage)
+            for username, usage in user_usage.items()
             if usage > threshold_mb
         ]
         sorted_users = sorted(filtered_users, key=lambda x: x[1], reverse=True)[:limit]
-        
+
         return sorted_users
-        
+
     except Exception as e:
         print(f"Error getting high usage users: {e}")
         return []
 
+
 def get_failed_auth_attempts(db, hours=1, threshold=10):
     """
     Get failed authentication attempts
     Returns: number of failed attempts
     """
     from datetime import datetime, timedelta
-    
+
     try:
         since_time = datetime.now() - timedelta(hours=hours)
-        
+
         # Get all user tables to check across all dates
         engine = db.get_bind()
         inspector = inspect(engine)
         all_tables = inspector.get_table_names()
         user_tables = [t for t in all_tables if t.startswith("user_") and len(t) == 13]
-        
+
         total_failed = 0
-        
+
         for table_name in user_tables:
             date_suffix = table_name.split("_")[1]
             try:
                 UserModel, LogModel = get_dynamic_models(date_suffix)
                 if UserModel is None or LogModel is None:
                     continue
-                
+
                 # Use ORM to count failed auth attempts (401, 407, 403 responses)
                 count = (
                     db.query(func.count(LogModel.id))
                     .filter(
                         LogModel.created_at >= since_time,
-                        LogModel.response.in_([401, 407, 403])
+                        LogModel.response.in_([401, 407, 403]),
                     )
                     .scalar()
                 )
-                
+
                 total_failed += count or 0
-                    
+
             except Exception as e:
                 print(f"Error processing table {table_name}: {e}")
                 continue
-        
+
         return total_failed
-        
+
     except Exception as e:
         print(f"Error getting failed auth attempts: {e}")
         return 0
 
+
 def get_denied_requests(db, hours=1, threshold=5):
     """
     Get denied requests
     Returns: number of denied requests
     """
     from datetime import datetime, timedelta
-    
+
     try:
         since_time = datetime.now() - timedelta(hours=hours)
-        
+
         # Get all user tables to check across all dates
         engine = db.get_bind()
         inspector = inspect(engine)
         all_tables = inspector.get_table_names()
         user_tables = [t for t in all_tables if t.startswith("user_") and len(t) == 13]
-        
+
         total_denied = 0
-        
+
         for table_name in user_tables:
             date_suffix = table_name.split("_")[1]
             try:
                 UserModel, LogModel = get_dynamic_models(date_suffix)
                 if UserModel is None or LogModel is None:
                     continue
-                
+
                 # Use ORM to count denied requests (403 responses)
                 count = (
                     db.query(func.count(LogModel.id))
-                    .filter(
-                        LogModel.created_at >= since_time,
-                        LogModel.response == 403
-                    )
+                    .filter(LogModel.created_at >= since_time, LogModel.response == 403)
                     .scalar()
                 )
-                
+
                 total_denied += count or 0
-                    
+
             except Exception as e:
                 print(f"Error processing table {table_name}: {e}")
                 continue
-        
+
         return total_denied
-        
+
     except Exception as e:
         print(f"Error getting denied requests: {e}")
-        return 0
+        return 0

+ 226 - 130
services/notifications.py

@@ -1,169 +1,229 @@
 import os
 import subprocess
-from datetime import datetime
 import threading
 import time
-from typing import List, Dict, Any
+from datetime import datetime
+from typing import Any
 
 # Enhanced notifications storage
-notifications_store = {
-    'notifications': [],
-    'unread_count': 0,
-    'last_check': None
-}
+notifications_store = {"notifications": [], "unread_count": 0, "last_check": None}
 
 # Global variable for Socket.IO
 socketio = None
 
+
 def set_socketio_instance(sio):
     global socketio
     socketio = sio
 
+
 def set_commit_notifications(has_updates, messages):
     """Keep for compatibility"""
     # Convert commits to system notifications
     if has_updates and messages:
         for msg in messages:
-            add_notification('info', f"Commit: {msg}", 'fa-code-branch', 'git')
+            add_notification("info", f"Commit: {msg}", "fa-code-branch", "git")
+
 
 def get_commit_notifications():
     """Keep for compatibility with existing code"""
     return {
-        'has_updates': len([n for n in notifications_store['notifications'] if n.get('source') == 'git']) > 0,
-        'commits': [n['message'].replace('Commit: ', '') for n in notifications_store['notifications'] if n.get('source') == 'git']
+        "has_updates": len(
+            [
+                n
+                for n in notifications_store["notifications"]
+                if n.get("source") == "git"
+            ]
+        )
+        > 0,
+        "commits": [
+            n["message"].replace("Commit: ", "")
+            for n in notifications_store["notifications"]
+            if n.get("source") == "git"
+        ],
     }
 
-def add_notification(notification_type: str, message: str, icon: str = None, source: str = "system"):
+
+def add_notification(
+    notification_type: str, message: str, icon: str = None, source: str = "system"
+):
     """Adds a notification to the system and emits via Socket.IO if configured"""
     notification = {
-        'id': len(notifications_store['notifications']) + 1,
-        'type': notification_type,  # 'info', 'warning', 'error', 'success'
-        'message': message,
-        'icon': icon or get_default_icon(notification_type),
-        'timestamp': datetime.now().isoformat(),
-        'time': 'Hace unos momentos',
-        'read': False,
-        'source': source
+        "id": len(notifications_store["notifications"]) + 1,
+        "type": notification_type,  # 'info', 'warning', 'error', 'success'
+        "message": message,
+        "icon": icon or get_default_icon(notification_type),
+        "timestamp": datetime.now().isoformat(),
+        "time": "Hace unos momentos",
+        "read": False,
+        "source": source,
     }
-    
+
     # Add to the beginning of the list
-    notifications_store['notifications'].insert(0, notification)
-    
+    notifications_store["notifications"].insert(0, notification)
+
     # Increment unread counter
-    if not notification['read']:
-        notifications_store['unread_count'] += 1
-    
+    if not notification["read"]:
+        notifications_store["unread_count"] += 1
+
     # Keep maximum 50 notifications
-    if len(notifications_store['notifications']) > 50:
+    if len(notifications_store["notifications"]) > 50:
         # Remove oldest ones, but keep unread if possible
-        old_notifications = notifications_store['notifications'][50:]
+        old_notifications = notifications_store["notifications"][50:]
         for old_notif in old_notifications:
-            if not old_notif['read']:
-                notifications_store['unread_count'] -= 1
-        notifications_store['notifications'] = notifications_store['notifications'][:50]
-    
+            if not old_notif["read"]:
+                notifications_store["unread_count"] -= 1
+        notifications_store["notifications"] = notifications_store["notifications"][:50]
+
     # Emit via Socket.IO if configured
     if socketio:
-        socketio.emit('new_notification', {
-            'notification': notification,
-            'unread_count': notifications_store['unread_count']
-        })
-    
+        socketio.emit(
+            "new_notification",
+            {
+                "notification": notification,
+                "unread_count": notifications_store["unread_count"],
+            },
+        )
+
     return notification
 
+
 def get_default_icon(notification_type):
     icons = {
-        'info': 'fa-info-circle',
-        'warning': 'fa-exclamation-triangle',
-        'error': 'fa-times-circle',
-        'success': 'fa-check-circle'
+        "info": "fa-info-circle",
+        "warning": "fa-exclamation-triangle",
+        "error": "fa-times-circle",
+        "success": "fa-check-circle",
     }
-    return icons.get(notification_type, 'fa-bell')
+    return icons.get(notification_type, "fa-bell")
+
 
-def get_all_notifications(limit: int = 10) -> Dict[str, Any]:
+def get_all_notifications(limit: int = 10) -> dict[str, Any]:
     """Gets all system notifications"""
     return {
-        'unread_count': notifications_store['unread_count'],
-        'notifications': notifications_store['notifications'][:limit]
+        "unread_count": notifications_store["unread_count"],
+        "notifications": notifications_store["notifications"][:limit],
     }
 
-def mark_notifications_read(notification_ids: List[int]):
+
+def mark_notifications_read(notification_ids: list[int]):
     """Marks notifications as read"""
-    for notification in notifications_store['notifications']:
-        if notification['id'] in notification_ids and not notification['read']:
-            notification['read'] = True
-            notifications_store['unread_count'] -= 1
+    for notification in notifications_store["notifications"]:
+        if notification["id"] in notification_ids and not notification["read"]:
+            notification["read"] = True
+            notifications_store["unread_count"] -= 1
+
 
 def check_squid_service():
     """Checks Squid service status and generates notifications"""
     try:
         # Check if Squid is running
         result = subprocess.run(
-            ['systemctl', 'is-active', 'squid'],
+            ["systemctl", "is-active", "squid"],
             capture_output=True,
             text=True,
-            timeout=10
+            timeout=10,
         )
-        
+
         if result.returncode != 0:
-            add_notification('error', 'Squid service is not running', 'fa-exclamation-triangle', 'squid')
+            add_notification(
+                "error",
+                "Squid service is not running",
+                "fa-exclamation-triangle",
+                "squid",
+            )
         else:
             # Check recent Squid error logs
             log_check = subprocess.run(
-                ['journalctl', '-u', 'squid', '--since', '1 hour ago', '--no-pager'],
+                ["journalctl", "-u", "squid", "--since", "1 hour ago", "--no-pager"],
                 capture_output=True,
                 text=True,
-                timeout=10
+                timeout=10,
             )
-            
-            if 'error' in log_check.stdout.lower() or 'failed' in log_check.stdout.lower():
-                add_notification('warning', 'Errors detected in Squid logs', 'fa-exclamation-triangle', 'squid')
-                
+
+            if (
+                "error" in log_check.stdout.lower()
+                or "failed" in log_check.stdout.lower()
+            ):
+                add_notification(
+                    "warning",
+                    "Errors detected in Squid logs",
+                    "fa-exclamation-triangle",
+                    "squid",
+                )
+
     except subprocess.TimeoutExpired:
-        add_notification('warning', 'Timeout checking Squid status', 'fa-clock', 'squid')
+        add_notification(
+            "warning", "Timeout checking Squid status", "fa-clock", "squid"
+        )
     except Exception as e:
         print(f"Error checking Squid service: {e}")
 
+
 def check_squid_log_health():
     """Checks Squid logs health"""
     try:
         log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
-        
+
         if os.path.exists(log_file):
             # Check if log file is growing
             stat_info = os.stat(log_file)
             file_size_mb = stat_info.st_size / (1024 * 1024)
-            
+
             if file_size_mb > 100:  # More than 100MB
-                add_notification('warning', f'Squid log very large: {file_size_mb:.1f}MB', 'fa-file-alt', 'squid')
-            
+                add_notification(
+                    "warning",
+                    f"Squid log very large: {file_size_mb:.1f}MB",
+                    "fa-file-alt",
+                    "squid",
+                )
+
             # Check last modification (not updated in more than 5 minutes)
             last_modified = datetime.fromtimestamp(stat_info.st_mtime)
             time_diff = datetime.now() - last_modified
             if time_diff.total_seconds() > 300:  # 5 minutes
-                add_notification('warning', 'Squid log not updated for more than 5 minutes', 'fa-clock', 'squid')
-                
+                add_notification(
+                    "warning",
+                    "Squid log not updated for more than 5 minutes",
+                    "fa-clock",
+                    "squid",
+                )
+
         else:
-            add_notification('error', f'Squid log file not found: {log_file}', 'fa-file-exclamation', 'squid')
-            
+            add_notification(
+                "error",
+                f"Squid log file not found: {log_file}",
+                "fa-file-exclamation",
+                "squid",
+            )
+
     except Exception as e:
         print(f"Error checking Squid log health: {e}")
 
+
 def check_system_health():
     """Checks general system health"""
     try:
         # Check disk usage
-        disk_usage = os.statvfs('/')
-        free_disk = (disk_usage.f_bavail * disk_usage.f_frsize) / (1024 ** 3)  # GB free
-        
+        disk_usage = os.statvfs("/")
+        free_disk = (disk_usage.f_bavail * disk_usage.f_frsize) / (1024**3)  # GB free
+
         if free_disk < 1:  # Less than 1GB free
-            add_notification('error', f'Critical disk space: {free_disk:.1f}GB free', 'fa-hdd', 'system')
+            add_notification(
+                "error",
+                f"Critical disk space: {free_disk:.1f}GB free",
+                "fa-hdd",
+                "system",
+            )
         elif free_disk < 5:  # Less than 5GB free
-            add_notification('warning', f'Low disk space: {free_disk:.1f}GB free', 'fa-hdd', 'system')
-            
+            add_notification(
+                "warning", f"Low disk space: {free_disk:.1f}GB free", "fa-hdd", "system"
+            )
+
     except Exception as e:
         print(f"Error checking system health: {e}")
 
+
 # Function for commits
 def has_remote_commits_with_messages(
     repo_path: str, branch: str = "main"
@@ -225,9 +285,11 @@ def has_remote_commits_with_messages(
         print(f"Error al ejecutar comandos git: {e.stderr}")
         return False, []
 
+
 # Thread for periodic checks
 def start_notification_monitor():
     """Inicia el monitor de notificaciones en segundo plano"""
+
     def monitor_loop():
         check_count = 0
         while True:
@@ -237,132 +299,166 @@ def start_notification_monitor():
                     current_file_dir = os.path.dirname(os.path.abspath(__file__))
                     repo_path = os.path.dirname(current_file_dir)  # Go up one level
                     if os.path.exists(repo_path):
-                        has_updates, messages = has_remote_commits_with_messages(repo_path)
+                        has_updates, messages = has_remote_commits_with_messages(
+                            repo_path
+                        )
                         set_commit_notifications(has_updates, messages)
-                
+
                 # CRITICAL checks every 2 minutes (always)
                 check_squid_service()
                 check_squid_log_health()
                 check_system_health()
-                
+
                 # SECURITY checks every 5 minutes (every 2-3 cycles)
                 if check_count % 3 == 0:
                     check_security_events()
-                
+
                 # USER checks every 10 minutes (every 5 cycles)
                 if check_count % 5 == 0:
                     check_user_activity()
-                
+
                 check_count += 1
                 if check_count > 1000:  # Prevent overflow
                     check_count = 0
-                
+
             except Exception as e:
                 print(f"Error in notification monitor: {e}")
-            
+
             time.sleep(120)  # Wait 2 minutes between cycles
-    
+
     thread = threading.Thread(target=monitor_loop, daemon=True)
     thread.start()
 
+
 # Specific functions for Squid that can be called from other parts
 def notify_squid_restart_success():
     """Notify successful Squid restart"""
-    add_notification('success', 'Squid restarted successfully', 'fa-sync-alt', 'squid')
+    add_notification("success", "Squid restarted successfully", "fa-sync-alt", "squid")
+
 
 def notify_squid_restart_failed(error_message: str = ""):
     """Notify failed Squid restart"""
-    message = 'Error restarting Squid'
+    message = "Error restarting Squid"
     if error_message:
-        message += f': {error_message}'
-    add_notification('error', message, 'fa-exclamation-triangle', 'squid')
+        message += f": {error_message}"
+    add_notification("error", message, "fa-exclamation-triangle", "squid")
+
 
 def notify_squid_config_error(error_message: str):
     """Notify Squid configuration error"""
-    add_notification('error', f'Squid configuration error: {error_message}', 'fa-cog', 'squid')
+    add_notification(
+        "error", f"Squid configuration error: {error_message}", "fa-cog", "squid"
+    )
+
 
 def notify_squid_high_usage(warning_message: str):
     """Notify high Squid resource usage"""
-    add_notification('warning', warning_message, 'fa-chart-line', 'squid')
+    add_notification("warning", warning_message, "fa-chart-line", "squid")
+
 
 def check_security_events():
     """Checks security events from the database"""
     try:
         from database.database import get_session
         from services.auditoria_service import (
-            find_suspicious_activity, 
+            find_suspicious_activity,
+            get_denied_requests,
             get_failed_auth_attempts,
-            get_denied_requests
         )
-        
+
         db = get_session()
-        
+
         # 1. Failed authentication attempts
         failed_auth_count = get_failed_auth_attempts(db, hours=1)
         if failed_auth_count > 15:
-            add_notification('warning', 
-                f'{failed_auth_count} failed authentication attempts in the last hour', 
-                'fa-shield-alt', 'security')
-        
+            add_notification(
+                "warning",
+                f"{failed_auth_count} failed authentication attempts in the last hour",
+                "fa-shield-alt",
+                "security",
+            )
+
         # 2. Denied requests
         denied_count = get_denied_requests(db, hours=1)
         if denied_count > 20:
-            add_notification('warning',
-                f'{denied_count} denied requests in the last hour',
-                'fa-ban', 'security')
-        
+            add_notification(
+                "warning",
+                f"{denied_count} denied requests in the last hour",
+                "fa-ban",
+                "security",
+            )
+
         # 3. Suspicious IPs (many requests in short time)
         suspicious_ips = find_suspicious_activity(db, threshold=100, hours=1)
         for ip, count in suspicious_ips:
             if count > 200:  # More than 200 requests in 1 hour
-                add_notification('warning',
-                    f'Suspicious activity from IP {ip}: {count} requests/hour',
-                    'fa-user-secret', 'security')
+                add_notification(
+                    "warning",
+                    f"Suspicious activity from IP {ip}: {count} requests/hour",
+                    "fa-user-secret",
+                    "security",
+                )
             elif count > 500:  # More than 500 requests - critical
-                add_notification('error',
-                    f'Critical activity from IP {ip}: {count} requests/hour',
-                    'fa-exclamation-triangle', 'security')
-        
+                add_notification(
+                    "error",
+                    f"Critical activity from IP {ip}: {count} requests/hour",
+                    "fa-exclamation-triangle",
+                    "security",
+                )
+
         db.close()
-                
+
     except Exception as e:
         print(f"Error checking security events: {e}")
 
+
 def check_user_activity():
     """Checks user activity from the database"""
     try:
         from database.database import get_session
-        from services.auditoria_service import get_active_users_count, get_high_usage_users
-        
+        from services.auditoria_service import (
+            get_active_users_count,
+            get_high_usage_users,
+        )
+
         db = get_session()
-        
+
         # 1. Active users in the last hour
         active_users = get_active_users_count(db, hours=1)
-        
+
         if active_users > 50:
-            add_notification('info',
-                f'High activity: {active_users} users connected in the last hour',
-                'fa-users', 'users')
-        
+            add_notification(
+                "info",
+                f"High activity: {active_users} users connected in the last hour",
+                "fa-users",
+                "users",
+            )
+
         elif active_users == 0:
-            add_notification('warning',
-                'No active users in the last hour',
-                'fa-users', 'users')
-        
+            add_notification(
+                "warning", "No active users in the last hour", "fa-users", "users"
+            )
+
         # 2. Users with high data consumption
         high_usage_users = get_high_usage_users(db, hours=24, threshold_mb=100)
-        
+
         for user, usage_mb in high_usage_users[:3]:  # Top 3
             if usage_mb > 1000:  # More than 1GB
-                add_notification('warning',
-                    f'User {user} consumed {usage_mb:.0f}MB in 24h',
-                    'fa-chart-line', 'users')
+                add_notification(
+                    "warning",
+                    f"User {user} consumed {usage_mb:.0f}MB in 24h",
+                    "fa-chart-line",
+                    "users",
+                )
             elif usage_mb > 500:  # More than 500MB
-                add_notification('info',
-                    f'User {user} consumed {usage_mb:.0f}MB in 24h',
-                    'fa-user', 'users')
-        
+                add_notification(
+                    "info",
+                    f"User {user} consumed {usage_mb:.0f}MB in 24h",
+                    "fa-user",
+                    "users",
+                )
+
         db.close()
-                    
+
     except Exception as e:
-        print(f"Error checking user activity: {e}")
+        print(f"Error checking user activity: {e}")