Parcourir la source

Resolve merge conflicts keeping main version

Manuel il y a 9 mois
Parent
commit
8d10307fad

+ 9 - 3
README.md

@@ -237,7 +237,7 @@ apt install git python3 python3-pip python3-venv libmariadb-dev curl
 1. Get Script With curl o wget:
 
 ```bash
- wget https://github.com/kaelthasmanu/SquidStats/releases/download/1.0/install.sh
+ wget https://github.com/kaelthasmanu/SquidStats/releases/download/2.2/install.sh
 ```
 
 2. Add permission execution:
@@ -585,7 +585,7 @@ Warning: 🚨 The first execution may cause high CPU usage.
 1. Get Script With curl o wget:
 
 ```bash
- wget https://github.com/kaelthasmanu/SquidStats/releases/download/1.0/install.sh
+ wget https://github.com/kaelthasmanu/SquidStats/releases/download/2.2/install.sh
 ```
 
 2. Add permission execution:
@@ -631,7 +631,13 @@ To ensure the application starts automatically when the system boot :
 
 ## Testing Information
 
-This software has been thoroughly tested and is compatible with Squid version 6.12 in Ubuntu 24.04 and Debian12. Please ensure your Squid installation matches this version or newer for optimal performance.
+This software has been thoroughly tested and is compatible with Squid version 6.12 in the following distributions:
+
+- **Ubuntu**: 24.04 LTS
+- **Debian**: 12 and 13
+- **Alpine Linux**: 3.23.3
+
+Please ensure your Squid installation matches this version or newer for optimal performance. For Docker container environments, Alpine Linux 3.23.3 is recommended due to its small size and compatibility.
 
 ## Uninstall SquidStats
 

+ 9 - 3
README_es.md

@@ -237,7 +237,7 @@ apt install git python3 python3-pip python3-venv libmariadb-dev curl
 1. Obtener el Script con curl o wget:
 
 ```bash
- wget https://github.com/kaelthasmanu/SquidStats/releases/download/1.0/install.sh
+ wget https://github.com/kaelthasmanu/SquidStats/releases/download/2.2/install.sh
 ```
 
 2. Agregar permisos de ejecución:
@@ -608,7 +608,7 @@ Advertencia: 🚨 La primera ejecución puede causar alto uso de CPU.
 1. Obtener el Script con curl o wget:
 
 ```bash
- wget https://github.com/kaelthasmanu/SquidStats/releases/download/1.0/install.sh
+ wget https://github.com/kaelthasmanu/SquidStats/releases/download/2.2/install.sh
 ```
 
 2. Agregar permisos de ejecución:
@@ -657,7 +657,13 @@ Para asegurar que la aplicación inicie automáticamente cuando el sistema arran
 
 ## Información de Pruebas
 
-Este software ha sido probado exhaustivamente y es compatible con Squid versión 6.12 en Ubuntu 24.04 y Debian12. Por favor asegúrate de que tu instalación de Squid coincida con esta versión o una más nueva para un rendimiento óptimo.
+Este software ha sido probado exhaustivamente y es compatible con Squid versión 6.12 en las siguientes distribuciones:
+
+- **Ubuntu**: 24.04 LTS
+- **Debian**: 12 y 13
+- **Alpine Linux**: 3.23.3
+
+Por favor asegúrate de que tu instalación de Squid coincida con esta versión o una más nueva para un rendimiento óptimo. Para entornos de contenedores Docker, se recomienda usar Alpine Linux 3.23.3 por su tamaño reducido y compatibilidad.
 
 ## Desinstalar SquidStats
 

+ 5 - 3
app.py

@@ -10,8 +10,9 @@ from dotenv import load_dotenv
 from flask import Flask
 from flask_apscheduler import APScheduler
 from flask_socketio import SocketIO
+from loguru import logger
 
-from config import Config, logger
+from config import Config
 from database.database import migrate_database
 from parsers.log import process_logs
 from routes import register_routes
@@ -26,6 +27,9 @@ from services.notifications import (
     start_notification_monitor,
     stop_notification_monitor,
 )
+from utils.filters import register_filters
+
+logger.add("logs/app.log", rotation="100 MB", retention="31 days", level="INFO")
 
 # Import Telegram integration (optional)
 try:
@@ -40,8 +44,6 @@ except Exception:
     initialize_telegram_service = None
     cleanup_telegram = None
 
-from utils.filters import register_filters
-
 # Load environment variables
 load_dotenv()
 

+ 2 - 8
config.py

@@ -1,14 +1,8 @@
-import logging
 import os
 from typing import Any
 
 from dotenv import load_dotenv
-
-# Configure logging first
-logging.basicConfig(
-    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
-)
-logger = logging.getLogger(__name__)
+from loguru import logger
 
 # Try to load environment variables
 try:
@@ -120,7 +114,7 @@ class Config:
     LOG_FORMAT = safe_get_env("LOG_FORMAT", "DETAILED").upper()
 
     # Application version
-    VERSION = safe_get_env("VERSION", "2.2")
+    VERSION = safe_get_env("VERSION", "2.3")
 
     # Authentication settings
     JWT_SECRET_KEY = SECRET_KEY

+ 3 - 16
database/database.py

@@ -1,4 +1,3 @@
-import logging
 import os
 from datetime import date, datetime
 from typing import Any
@@ -6,6 +5,7 @@ from urllib.parse import urlparse
 
 from alembic.config import Config as AlembicConfig
 from alembic.runtime.migration import MigrationContext
+from loguru import logger
 from sqlalchemy import (
     BigInteger,
     Column,
@@ -24,11 +24,6 @@ from sqlalchemy.orm import declarative_base, sessionmaker
 from alembic import command
 from config import Config
 
-logging.basicConfig(
-    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
-)
-logger = logging.getLogger(__name__)
-
 Base = declarative_base()
 _engine = None
 _Session = None
@@ -319,20 +314,12 @@ def create_dynamic_tables(engine, date_suffix: str = None):
 
     user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
 
-    creation_logger = logging.getLogger(f"CreateTable_{date_suffix or 'today'}")
-    creation_logger.propagate = False  # Evita que el log suba al logger raíz
-    if not creation_logger.handlers:
-        handler = logging.StreamHandler()
-        formatter = logging.Formatter(
-            "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
-        )
-        handler.setFormatter(formatter)
-        creation_logger.addHandler(handler)
+    logger.info(f"CreateTable_{date_suffix or 'today'}")
 
     if not table_exists(engine, user_table_name) or not table_exists(
         engine, log_table_name
     ):
-        creation_logger.info(
+        logger.info(
             f"Creating dynamic tables for date suffix '{date_suffix}': {user_table_name}, {log_table_name}"
         )
         DynamicBase = declarative_base()

+ 1 - 1
example.env

@@ -1,4 +1,4 @@
-VERSION=2.2
+VERSION=2.3
 SECRET_KEY="your-secret-key-here-generate-with-python-secrets"
 SQUID_HOST="127.0.0.1"
 SQUID_PORT=3128

+ 2 - 2
install.sh

@@ -218,7 +218,7 @@ updateOrCloneRepo() {
 
 updateEnvVersion() {
     local install_dir="${1:-/opt/SquidStats}"
-    local CURRENT_VERSION="2.2.1"  # Variable de versión actual del script
+    local CURRENT_VERSION="2.3"  # Variable de versión actual del script
     local env_file="$install_dir/.env"
     
     if [ ! -f "$env_file" ]; then
@@ -260,7 +260,7 @@ createEnvFile() {
     else
         echo "Creando archivo de configuración .env..."
         cat >"$env_file" <<EOF
-VERSION=2.2.1
+VERSION=2.3
 SECRET_KEY="your-secret-key-here-generate-with-python-secrets"
 SQUID_HOST=127.0.0.1
 SQUID_PORT=3128

+ 1 - 7
manage_db.py

@@ -13,12 +13,12 @@ Usage:
     python manage_db.py create     # Create a new migration
 """
 
-import logging
 import sys
 from pathlib import Path
 
 from alembic.config import Config as AlembicConfig
 from dotenv import load_dotenv
+from loguru import logger
 
 from alembic import command
 
@@ -29,12 +29,6 @@ sys.path.insert(0, str(project_root))
 # Load environment variables
 load_dotenv()
 
-# Configure logging
-logging.basicConfig(
-    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
-)
-logger = logging.getLogger(__name__)
-
 
 def get_alembic_config():
     """Get Alembic configuration."""

+ 3 - 10
parsers/log.py

@@ -1,8 +1,8 @@
-import logging
 import os
 import time
 from datetime import datetime
 
+from loguru import logger
 from sqlalchemy.exc import IntegrityError, SQLAlchemyError
 
 from config import Config
@@ -17,13 +17,6 @@ from database.database import (
     table_exists,
 )
 
-logging.basicConfig(
-    level=logging.INFO,
-    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-    handlers=[logging.StreamHandler(), logging.FileHandler("log_processor.log")],
-)
-logger = logging.getLogger(__name__)
-
 
 class DatabaseManager:
     def __init__(self, engine=None, session=None):
@@ -312,7 +305,7 @@ def process_logs(log_file):
                         f"File truncated (size: {file_size} < position: {last_position})"
                     )
                     last_position = 0
-            logger.info(f"Reading from position: {last_position}")
+            # logger.info(f"Reading from position: {last_position}")
             user_cache = {}
             logs_to_insert, new_users_to_insert, denied_to_insert = [], [], []
             processed_lines = inserted_logs = inserted_users = inserted_denied = 0
@@ -454,7 +447,7 @@ def process_logs(log_file):
             metadata.updated_at = datetime.now()
             session.commit()
             elapsed = time.time() - start_time
-            logger.info(f"Processing completed. Lines: {processed_lines}")
+            # logger.info(f"Processing completed. Lines: {processed_lines}")
             logger.info(
                 f"Logs inserted: {inserted_logs}, New users: {inserted_users}, Denied: {inserted_denied}"
             )

+ 2 - 1
requirements.txt

@@ -10,9 +10,10 @@ psutil==7.2.2
 eventlet
 flask_socketio==5.6.0
 pytz
-requests
+requests==2.32.5
 #icapclient3
 uvicorn
 PyJWT==2.11.0
 bcrypt==5.0.0
 telethon>=1.42.0
+loguru==0.7.3

+ 106 - 542
routes/admin_routes.py

@@ -1,3 +1,5 @@
+import os
+
 from flask import (
     Blueprint,
     current_app,
@@ -9,40 +11,30 @@ from flask import (
     url_for,
 )
 from loguru import logger
+from sqlalchemy import MetaData, Table, func, inspect, select, text
 
 from config import Config
+from database.database import get_engine, get_session
 from services.auth_service import AuthService, admin_required, api_auth_required
-from services.config_service import save_config as service_save_config
-from services.db_admin_service import delete_table_data as service_delete_table_data
-from services.db_info_service import get_tables_info as service_get_tables_info
-from services.logs_service import read_logs as service_read_logs
-from services.split_config_service import (
-    get_split_files_info as service_get_split_files_info,
-)
-from services.split_config_service import (
-    get_split_view_data as service_get_split_view_data,
-)
-from services.split_config_service import (
-    split_config as service_split_config,
-)
 from services.squid_config_splitter import SquidConfigSplitter
-from services.system_service import (
-    reload_squid as service_reload_squid,
-)
-from services.system_service import (
-    restart_squid as service_restart_squid,
-)
+from services.db_info_service import get_tables_info as service_get_tables_info
+from services.config_service import save_config as service_save_config
 from services.user_service import (
+    get_all_users as service_get_all_users,
     create_user as service_create_user,
-)
-from services.user_service import (
+    update_user as service_update_user,
     delete_user as service_delete_user,
 )
-from services.user_service import (
-    get_all_users as service_get_all_users,
+from services.logs_service import read_logs as service_read_logs
+from services.system_service import (
+    restart_squid as service_restart_squid,
+    reload_squid as service_reload_squid,
 )
-from services.user_service import (
-    update_user as service_update_user,
+from services.db_admin_service import delete_table_data as service_delete_table_data
+from services.split_config_service import (
+    split_config as service_split_config,
+    get_split_view_data as service_get_split_view_data,
+    get_split_files_info as service_get_split_files_info,
 )
 from utils.admin import SquidConfigManager
 
@@ -50,41 +42,32 @@ admin_bp = Blueprint("admin", __name__)
 
 # Global manager instance
 config_manager = SquidConfigManager()
-from services.acls_service import add_acl as service_add_acl
-from services.acls_service import delete_acl as service_delete_acl
-from services.acls_service import edit_acl as service_edit_acl
 from services.admin_helpers import (
     load_env_vars,
     save_env_vars,
+    get_table_row_count,
+    get_table_size,
 )
+
 from services.blacklist_service import (
+    test_pihole_connection,
     import_domains_from_file,
     import_domains_from_url,
     merge_and_save_blacklist,
     save_custom_list,
-    test_pihole_connection,
-)
-from services.delay_pools_service import (
-    add_delay_pool as service_add_delay_pool,
-)
-from services.delay_pools_service import (
-    delete_delay_pool as service_delete_delay_pool,
-)
-from services.delay_pools_service import (
-    edit_delay_pool as service_edit_delay_pool,
 )
+from services.acls_service import add_acl as service_add_acl, edit_acl as service_edit_acl, delete_acl as service_delete_acl
 from services.http_access_service import (
     add_http_access as service_add_http_access,
-)
-from services.http_access_service import (
-    delete_http_access as service_delete_http_access,
-)
-from services.http_access_service import (
     edit_http_access as service_edit_http_access,
-)
-from services.http_access_service import (
+    delete_http_access as service_delete_http_access,
     move_http_access as service_move_http_access,
 )
+from services.delay_pools_service import (
+    add_delay_pool as service_add_delay_pool,
+    edit_delay_pool as service_edit_delay_pool,
+    delete_delay_pool as service_delete_delay_pool,
+)
 
 
 @admin_bp.route("/")
@@ -118,20 +101,18 @@ def view_config():
 def edit_config():
     if request.method == "POST":
         new_content = request.form["config_content"]
-        try:
-            config_manager.save_config(new_content)
-            flash("Configuration saved successfully", "success")
+        ok, message = service_save_config(new_content, config_manager)
+        if ok:
+            flash(message, "success")
             return redirect(url_for("admin.view_config"))
-        except Exception as e:
-            # Log full exception; avoid showing raw exception text to users
-            logger.exception("Error saving configuration")
+        else:
             try:
                 show_details = bool(current_app.debug)
             except RuntimeError:
                 show_details = False
 
             if show_details:
-                flash(f"Error saving configuration: {str(e)}", "error")
+                flash(f"Error saving configuration: {message}", "error")
             else:
                 flash("Error saving configuration", "error")
     return render_template(
@@ -179,14 +160,10 @@ def add_acl():
     options = request.form.getlist("options[]")
     comment = request.form.get("comment", "").strip()
 
-    success, message = service_add_acl(
-        name, acl_type, values, options, comment, config_manager
-    )
+    success, message = service_add_acl(name, acl_type, values, options, comment, config_manager)
     flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_acls"))
-    success, message = service_add_acl(
-        name, acl_type, values, options, comment, config_manager
-    )
+    success, message = service_add_acl(name, acl_type, values, options, comment, config_manager)
     flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_acls"))
 
@@ -202,72 +179,13 @@ def edit_acl():
     options = request.form.getlist("options[]")
     comment = request.form.get("comment", "").strip()
 
-    if not acl_id or not new_name or not acl_type or not values:
-        flash("Datos incompletos para editar la ACL", "error")
-        return redirect(url_for("admin.manage_acls"))
-
     try:
         acl_index = int(acl_id)
-        acls = config_manager.get_acls()
-
-        if 0 <= acl_index < len(acls):
-            target_acl = acls[acl_index]
-            # line_number from parser is 1-based, convert to 0-based index
-            target_line = target_acl["line_number"] - 1
-
-            # Build new ACL line
-            acl_parts = ["acl", new_name]
-            if options:
-                acl_parts.extend(options)
-            acl_parts.append(acl_type)
-            acl_parts.extend(values)
-            new_acl_line = " ".join(acl_parts)
-
-            # Check if using modular configuration
-            if config_manager.is_modular:
-                acl_content = config_manager.read_modular_config("100_acls.conf")
-                if acl_content is not None:
-                    lines = acl_content.split("\n")
-
-                    # Replace the ACL line (line_number is 1-based, list index is 0-based)
-                    if 0 <= target_line < len(lines):
-                        # Check if there's a comment before this ACL
-                        has_comment = target_line > 0 and lines[
-                            target_line - 1
-                        ].strip().startswith("#")
-
-                        # Replace the ACL line
-                        lines[target_line] = new_acl_line
-
-                        # Handle comment
-                        if has_comment:
-                            if comment:
-                                # Update existing comment
-                                lines[target_line - 1] = f"# {comment}"
-                            else:
-                                # Remove existing comment
-                                lines.pop(target_line - 1)
-                        else:
-                            if comment:
-                                # Insert new comment before the ACL
-                                lines.insert(target_line, f"# {comment}")
-
-                        new_content = "\n".join(lines)
-                        if config_manager.save_modular_config(
-                            "100_acls.conf", new_content
-                        ):
-                            flash(
-                                f"ACL '{new_name}' actualizada exitosamente", "success"
-                            )
-                        else:
-                            flash("Error al guardar la ACL", "error")
-                    else:
-                        flash("Línea de ACL no encontrada", "error")
-                    return redirect(url_for("admin.manage_acls"))
-
-    success, message = service_edit_acl(
-        acl_index, new_name, acl_type, values, options, comment, config_manager
-    )
+    except (ValueError, TypeError):
+        flash("ID de ACL inválido", "error")
+        return redirect(url_for("admin.manage_acls"))
+
+    success, message = service_edit_acl(acl_index, new_name, acl_type, values, options, comment, config_manager)
     flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_acls"))
 
@@ -277,73 +195,14 @@ def edit_acl():
 def delete_acl():
     """Delete an ACL using its ID (index) and line number."""
     acl_id = request.form.get("id")
-
     try:
         acl_index = int(acl_id)
-        acls = config_manager.get_acls()
-
-        if 0 <= acl_index < len(acls):
-            acl_to_delete = acls[acl_index]
-            # line_number from parser is 1-based, convert to 0-based index
-            target_line = acl_to_delete["line_number"] - 1
-
-            # Check if using modular configuration
-            if config_manager.is_modular:
-                acl_content = config_manager.read_modular_config("100_acls.conf")
-                if acl_content is not None:
-                    lines = acl_content.split("\n")
-
-                    # Check if there's a comment before this ACL (line_number is 1-based, we need 0-based)
-                    comment_to_remove = None
-                    if target_line > 0 and lines[target_line - 1].strip().startswith(
-                        "#"
-                    ):
-                        comment_to_remove = target_line - 1
-
-                    # Remove lines (comment + ACL or just ACL)
-                    new_lines = []
-                    for i, line in enumerate(lines):
-                        if i == target_line:
-                            continue  # Skip the ACL line
-                        if comment_to_remove is not None and i == comment_to_remove:
-                            continue  # Skip the comment line
-                        new_lines.append(line)
-
-                    new_content = "\n".join(new_lines)
-                    if config_manager.save_modular_config("100_acls.conf", new_content):
-                        flash(
-                            f"ACL '{acl_to_delete['name']}' eliminada exitosamente",
-                            "success",
-                        )
-                    else:
-                        flash("Error al eliminar la ACL", "error")
-                    return redirect(url_for("admin.manage_acls"))
-
-            # Fallback to main config
-            lines = config_manager.config_content.split("\n")
-
-            # Check if there's a comment before this ACL (convert to 0-based index)
-            comment_to_remove = None
-            if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
-                comment_to_remove = target_line - 1
-
-            # Remove lines (comment + ACL or just ACL)
-            new_lines = []
-            for i, line in enumerate(lines):
-                if i == target_line:
-                    continue  # Skip the ACL line
-                if comment_to_remove is not None and i == comment_to_remove:
-                    continue  # Skip the comment line
-                new_lines.append(line)
-
-            new_content = "\n".join(new_lines)
-            config_manager.save_config(new_content)
-            flash(f"ACL '{acl_to_delete['name']}' eliminada exitosamente", "success")
-        else:
-            flash("ACL no encontrada", "error")
-    except (ValueError, IndexError):
-        flash("Error al eliminar la ACL", "error")
+    except (ValueError, TypeError):
+        flash("ID de ACL inválido", "error")
+        return redirect(url_for("admin.manage_acls"))
 
+    success, message = service_delete_acl(acl_index, config_manager)
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_acls"))
 
 
@@ -361,16 +220,14 @@ def manage_http_access():
     return render_template("admin/http_access.html", rules=rules)
 
 
-@admin_bp.route("/blacklist", methods=["GET"])
+@admin_bp.route("/blacklist", methods=["GET"]) 
 @admin_required
 def manage_blacklist():
     """Render the blacklist management UI."""
     env_vars = load_env_vars()
     # Provide current blacklist domains to the template
     blacklist = env_vars.get("BLACKLIST_DOMAINS", "")
-    return render_template(
-        "admin/blacklist.html", env_vars=env_vars, blacklist=blacklist
-    )
+    return render_template("admin/blacklist.html", env_vars=env_vars, blacklist=blacklist)
 
 
 @admin_bp.route("/blacklist/test-connection", methods=["POST"])
@@ -488,15 +345,11 @@ def edit_http_access():
 
     try:
         rule_index = int(index)
-        acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
-
-        if not acl_string:
-            flash("Debe especificar al menos una ACL", "error")
-            return redirect(url_for("admin.manage_http_access"))
+    except (ValueError, TypeError):
+        flash("Índice de regla inválido", "error")
+        return redirect(url_for("admin.manage_http_access"))
 
-    success, message = service_edit_http_access(
-        rule_index, action, acls, description, config_manager
-    )
+    success, message = service_edit_http_access(rule_index, action, acls, description, config_manager)
     flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_http_access"))
 
@@ -509,9 +362,7 @@ def add_http_access():
     acls = request.form.getlist("acls[]")
     description = request.form.get("description", "").strip()
 
-    success, message = service_add_http_access(
-        action, acls, description, config_manager
-    )
+    success, message = service_add_http_access(action, acls, description, config_manager)
     flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_http_access"))
 
@@ -525,93 +376,12 @@ def move_http_access():
 
     try:
         rule_index = int(index)
+    except (ValueError, TypeError):
+        flash("Índice de regla inválido", "error")
+        return redirect(url_for("admin.manage_http_access"))
 
-        # Check if using modular configuration
-        if config_manager.is_modular:
-            http_content = config_manager.read_modular_config("120_http_access.conf")
-            if http_content is not None:
-                lines = http_content.split("\n")
-                http_lines_indices = []
-
-                # Find all http_access lines
-                for i, line in enumerate(lines):
-                    if line.strip().startswith(
-                        "http_access "
-                    ) and not line.strip().startswith("#"):
-                        http_lines_indices.append(i)
-
-                if rule_index >= len(http_lines_indices):
-                    flash("Índice de regla inválido", "error")
-                    return redirect(url_for("admin.manage_http_access"))
-
-                current_line_index = http_lines_indices[rule_index]
-
-                if direction == "up" and rule_index > 0:
-                    target_line_index = http_lines_indices[rule_index - 1]
-                    # Swap lines
-                    lines[current_line_index], lines[target_line_index] = (
-                        lines[target_line_index],
-                        lines[current_line_index],
-                    )
-                elif direction == "down" and rule_index < len(http_lines_indices) - 1:
-                    target_line_index = http_lines_indices[rule_index + 1]
-                    # Swap lines
-                    lines[current_line_index], lines[target_line_index] = (
-                        lines[target_line_index],
-                        lines[current_line_index],
-                    )
-
-                new_content = "\n".join(lines)
-                if config_manager.save_modular_config(
-                    "120_http_access.conf", new_content
-                ):
-                    flash(
-                        f"Regla movida {direction == 'up' and 'arriba' or 'abajo'} exitosamente",
-                        "success",
-                    )
-                else:
-                    flash("Error al mover la regla", "error")
-                return redirect(url_for("admin.manage_http_access"))
-
-        # Fallback to main config
-        lines = config_manager.config_content.split("\n")
-        http_lines_indices = []
-
-        for i, line in enumerate(lines):
-            if line.strip().startswith("http_access ") and not line.strip().startswith(
-                "#"
-            ):
-                http_lines_indices.append(i)
-
-        if rule_index >= len(http_lines_indices):
-            flash("Índice de regla inválido", "error")
-            return redirect(url_for("admin.manage_http_access"))
-
-        current_line_index = http_lines_indices[rule_index]
-
-        if direction == "up" and rule_index > 0:
-            target_line_index = http_lines_indices[rule_index - 1]
-            lines[current_line_index], lines[target_line_index] = (
-                lines[target_line_index],
-                lines[current_line_index],
-            )
-        elif direction == "down" and rule_index < len(http_lines_indices) - 1:
-            target_line_index = http_lines_indices[rule_index + 1]
-            lines[current_line_index], lines[target_line_index] = (
-                lines[target_line_index],
-                lines[current_line_index],
-            )
-
-        new_content = "\n".join(lines)
-        config_manager.save_config(new_content)
-        flash(
-            f"Regla movida {direction == 'up' and 'arriba' or 'abajo'} exitosamente",
-            "success",
-        )
-
-    except (ValueError, IndexError) as e:
-        flash(f"Error al mover la regla: {str(e)}", "error")
-
+    success, message = service_move_http_access(rule_index, direction, config_manager)
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_http_access"))
 
 
@@ -621,58 +391,8 @@ def delete_delay_pool():
     """Delete all directives related to a specific delay pool"""
     pool_number = request.form.get("pool_number")
 
-    try:
-        # Check if using modular configuration
-        if config_manager.is_modular:
-            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
-            if delay_content is not None:
-                lines = delay_content.split("\n")
-                new_lines = []
-
-                # Remove all lines related to this pool number
-                for line in lines:
-                    stripped = line.strip()
-                    # Skip delay_class, delay_parameters, and delay_access for this pool
-                    if (
-                        stripped.startswith(f"delay_class {pool_number} ")
-                        or stripped.startswith(f"delay_parameters {pool_number} ")
-                        or stripped.startswith(f"delay_access {pool_number} ")
-                    ):
-                        continue
-                    new_lines.append(line)
-
-                new_content = "\n".join(new_lines)
-                if config_manager.save_modular_config(
-                    "110_delay_pools.conf", new_content
-                ):
-                    flash(
-                        f"Delay Pool #{pool_number} eliminado exitosamente", "success"
-                    )
-                else:
-                    flash("Error al eliminar el delay pool", "error")
-                return redirect(url_for("admin.manage_delay_pools"))
-
-        # Fallback to main config
-        lines = config_manager.config_content.split("\n")
-        new_lines = []
-
-        for line in lines:
-            stripped = line.strip()
-            if (
-                stripped.startswith(f"delay_class {pool_number} ")
-                or stripped.startswith(f"delay_parameters {pool_number} ")
-                or stripped.startswith(f"delay_access {pool_number} ")
-            ):
-                continue
-            new_lines.append(line)
-
-        new_content = "\n".join(new_lines)
-        config_manager.save_config(new_content)
-        flash(f"Delay Pool #{pool_number} eliminado exitosamente", "success")
-
-    except Exception as e:
-        flash(f"Error al eliminar el delay pool: {str(e)}", "error")
-
+    success, message = service_delete_delay_pool(pool_number, config_manager)
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_delay_pools"))
 
 
@@ -686,9 +406,7 @@ def edit_delay_pool():
     access_actions = request.form.getlist("access_action[]")
     access_acls = request.form.getlist("access_acl[]")
 
-    success, message = service_edit_delay_pool(
-        pool_number, pool_class, parameters, access_actions, access_acls, config_manager
-    )
+    success, message = service_edit_delay_pool(pool_number, pool_class, parameters, access_actions, access_acls, config_manager)
     flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_delay_pools"))
 
@@ -703,9 +421,7 @@ def add_delay_pool():
     access_actions = request.form.getlist("access_action[]")
     access_acls = request.form.getlist("access_acl[]")
 
-    success, message = service_add_delay_pool(
-        pool_number, pool_class, parameters, access_actions, access_acls, config_manager
-    )
+    success, message = service_add_delay_pool(pool_number, pool_class, parameters, access_actions, access_acls, config_manager)
     flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_delay_pools"))
 
@@ -717,39 +433,15 @@ def view_logs():
     max_lines = request.args.get("lines", 250, type=int)
     max_lines = min(max(max_lines, 10), 1000)  # Between 10 and 1000 lines
 
-    log_files = [
-        Config.SQUID_LOG,
-        Config.SQUID_CACHE_LOG,
-    ]
-    logs = {}
-    for log_file in log_files:
-        try:
-            with open(log_file) as f:
-                # Read the last N lines
-                lines = f.readlines()
-                logs[os.path.basename(log_file)] = lines[-max_lines:]
-        except FileNotFoundError:
-            logs[os.path.basename(log_file)] = ["Log file not found"]
-        except Exception as e:
-            # Log the exception with traceback on the server
-            logger.exception("Error reading log file %s", log_file)
-            try:
-                show_details = bool(current_app.debug)
-            except RuntimeError:
-                show_details = False
-
-            if show_details:
-                logs[os.path.basename(log_file)] = [f"Error reading log: {str(e)}"]
-            else:
-                logs[os.path.basename(log_file)] = ["Error reading log"]
-
+    log_files = [Config.SQUID_LOG, Config.SQUID_CACHE_LOG]
+    logs = service_read_logs(log_files, max_lines, debug=bool(current_app.debug))
     return render_template("admin/logs.html", logs=logs, max_lines=max_lines)
 
 
 @admin_bp.route("/users")
 @admin_required
 def manage_users():
-    users = AuthService.get_all_users()
+    users = service_get_all_users()
     return render_template("admin/users.html", users=users)
 
 
@@ -761,22 +453,10 @@ def create_user():
         password = request.form.get("password")
         role = request.form.get("role", "admin")
 
-        if not username or not password:
-            flash("El nombre de usuario y la contraseña son obligatorios", "error")
-            return redirect(url_for("admin.create_user"))
-
-        if len(password) < 8:
-            flash("La contraseña debe tener al menos 8 caracteres", "error")
-            return redirect(url_for("admin.create_user"))
-
-        if AuthService.create_user(username, password, role):
-            flash("Usuario creado exitosamente", "success")
+        ok, message = service_create_user(username, password, role)
+        flash(message, "success" if ok else "error")
+        if ok:
             return redirect(url_for("admin.manage_users"))
-        else:
-            flash(
-                "Error al crear usuario. El nombre de usuario ya puede existir.",
-                "error",
-            )
 
     return render_template("admin/user_form.html", user=None, action="create")
 
@@ -790,19 +470,10 @@ def edit_user(user_id):
         role = request.form.get("role")
         is_active = 1 if request.form.get("is_active") else 0
 
-        if password and len(password) < 8:
-            flash("La contraseña debe tener al menos 8 caracteres", "error")
-            return redirect(url_for("admin.edit_user", user_id=user_id))
-
-        update_data = {"username": username, "role": role, "is_active": is_active}
-        if password:
-            update_data["password"] = password
-
-        if AuthService.update_user(user_id, **update_data):
-            flash("Usuario actualizado exitosamente", "success")
+        ok, message = service_update_user(user_id, username, password, role, is_active)
+        flash(message, "success" if ok else "error")
+        if ok:
             return redirect(url_for("admin.manage_users"))
-        else:
-            flash("Error al actualizar usuario", "error")
 
     users = AuthService.get_all_users()
     user = next((u for u in users if u["id"] == user_id), None)
@@ -816,105 +487,40 @@ def edit_user(user_id):
 @admin_bp.route("/users/<int:user_id>/delete", methods=["POST"])
 @admin_required
 def delete_user(user_id):
-    if AuthService.delete_user(user_id):
-        flash("Usuario eliminado exitosamente", "success")
-    else:
-        flash(
-            "Error al eliminar usuario. No se puede eliminar el usuario admin.", "error"
-        )
+    ok, message = service_delete_user(user_id)
+    flash(message, "success" if ok else "error")
     return redirect(url_for("admin.manage_users"))
 
 
 @admin_bp.route("/api/restart-squid", methods=["POST"])
 @api_auth_required
 def restart_squid():
-    try:
-        os.system("systemctl restart squid")
-        return jsonify({"status": "success", "message": "Squid restarted successfully"})
-    except Exception as e:
-        logger.exception("Error restarting squid")
-        try:
-            show_details = bool(current_app.debug)
-        except RuntimeError:
-            show_details = False
-
-        resp = {"status": "error", "message": "Internal server error"}
-        if show_details:
-            resp["details"] = str(e)
-        return jsonify(resp), 500
+    success, message, details = service_restart_squid()
+    if success:
+        return jsonify({"status": "success", "message": message})
+    resp = {"status": "error", "message": message}
+    if bool(current_app.debug) and details:
+        resp["details"] = details
+    return jsonify(resp), 500
 
 
 @admin_bp.route("/api/reload-squid", methods=["POST"])
 @api_auth_required
 def reload_squid():
-    try:
-        os.system("systemctl reload squid")
-        return jsonify(
-            {"status": "success", "message": "Configuration reloaded successfully"}
-        )
-    except Exception as e:
-        logger.exception("Error reloading squid configuration")
-        try:
-            show_details = bool(current_app.debug)
-        except RuntimeError:
-            show_details = False
-
-        resp = {"status": "error", "message": "Internal server error"}
-        if show_details:
-            resp["details"] = str(e)
-        return jsonify(resp), 500
+    success, message, details = service_reload_squid()
+    if success:
+        return jsonify({"status": "success", "message": message})
+    resp = {"status": "error", "message": message}
+    if bool(current_app.debug) and details:
+        resp["details"] = details
+    return jsonify(resp), 500
 
 
 @admin_bp.route("/api/get-tables", methods=["GET"])
 @api_auth_required
 def get_tables():
-    session = None
-    try:
-        engine = get_engine()
-        inspector = inspect(engine)
-        session = get_session()
-        db_type = Config.DATABASE_TYPE
-
-        tables = inspector.get_table_names()
-        table_info = []
-
-        for table_name in tables:
-            try:
-                rows = get_table_row_count(session, engine, table_name)
-                size = get_table_size(session, db_type, table_name)
-
-                table_info.append(
-                    {
-                        "name": table_name,
-                        "rows": rows,
-                        "size": size,
-                        "has_data": rows > 0,
-                    }
-                )
-
-            except Exception as e:
-                logger.warning(f"Error processing table {table_name}: {e}")
-                table_info.append(
-                    {
-                        "name": table_name,
-                        "rows": 0,
-                        "size": 0,
-                        "has_data": False,
-                    }
-                )
-
-        return jsonify({"status": "success", "tables": table_info})
-
-    except Exception as e:
-        logger.exception("Error getting database tables")
-        resp = {"status": "error", "message": "Error interno del servidor"}
-        if current_app.debug:
-            resp["details"] = str(e)
-        return jsonify(resp), 500
-
-    finally:
-        if session:
-            session.close()
+    resp, code = service_get_tables_info()
+    return jsonify(resp), code
 
 
 @admin_bp.route("/clean-data")
@@ -954,26 +560,8 @@ def delete_table_data():
                 }
             ), 400
 
-        engine = get_engine()
-        inspector = inspect(engine)
-
-        # Verify table exists
-        if table_name not in inspector.get_table_names():
-            return jsonify({"status": "error", "message": "La tabla no existe"}), 404
-
-        # Delete all data from table
-        metadata = MetaData()
-        table = Table(table_name, metadata, autoload_with=engine)
-        with engine.connect() as conn:
-            conn.execute(table.delete())
-            conn.commit()
-
-        return jsonify(
-            {
-                "status": "success",
-                "message": f"Datos de la tabla '{table_name}' eliminados correctamente",
-            }
-        )
+        resp, code = service_delete_table_data(table_name)
+        return jsonify(resp), code
 
     except Exception as e:
         logger.exception("Error deleting data from table")
@@ -993,18 +581,14 @@ def delete_table_data():
 def split_config_view():
     """Vista para dividir el archivo squid.conf en archivos modulares."""
     try:
-        splitter = SquidConfigSplitter()
-        split_info = splitter.get_split_info()
-        output_exists = splitter.check_output_dir_exists()
-        files_count = splitter.count_files_in_output_dir()
-
+        data = service_get_split_view_data()
         return render_template(
             "admin/split_config.html",
-            split_info=split_info,
-            output_dir=splitter.output_dir,
-            input_file=splitter.input_file,
-            output_exists=output_exists,
-            files_count=files_count,
+            split_info=data["split_info"],
+            output_dir=data["output_dir"],
+            input_file=data["input_file"],
+            output_exists=data["output_exists"],
+            files_count=data["files_count"],
         )
     except Exception as e:
         logger.exception("Error al cargar la vista de división de configuración")
@@ -1020,34 +604,15 @@ def split_config():
         data = request.get_json() or {}
         strict = data.get("strict", False)
 
-        splitter = SquidConfigSplitter(strict=strict)
+        resp, code = service_split_config(strict=strict)
 
-        if not os.path.exists(splitter.input_file):
-            return jsonify(
-                {
-                    "status": "error",
-                    "message": f"Archivo squid.conf no encontrado en: {splitter.input_file}",
-                }
-            ), 404
-
-        results = splitter.split_config()
+        # Reload config_manager to detect modular configuration if successful
+        if code == 200:
+            global config_manager
+            config_manager = SquidConfigManager()
+            logger.info("Config manager reloaded after splitting configuration")
 
-        # Reload config_manager to detect modular configuration
-        global config_manager
-        config_manager = SquidConfigManager()
-        logger.info("Config manager reloaded after splitting configuration")
-
-        return jsonify(
-            {
-                "status": "success",
-                "message": f"Configuración dividida exitosamente en {len(results)} archivos",
-                "data": {
-                    "output_dir": splitter.output_dir,
-                    "files": results,
-                    "total_files": len(results),
-                },
-            }
-        )
+        return jsonify(resp), code
 
     except FileNotFoundError as e:
         logger.error(f"Archivo no encontrado: {e}")
@@ -1097,9 +662,8 @@ def split_config():
 def get_split_files():
     """API endpoint para obtener la lista de archivos generados en squid.d."""
     splitter = SquidConfigSplitter()
-    result = SquidConfigSplitter.get_split_files_info(splitter.output_dir)
+    result = service_get_split_files_info(splitter.output_dir)
 
-    if result["status"] == "success":
+    if result.get("status") == "success":
         return jsonify(result)
-    else:
-        return jsonify(result), result.get("code", 500)
+    return jsonify(result), result.get("code", 500)

+ 1 - 1
routes/api_routes.py

@@ -1,6 +1,6 @@
 from flask import Blueprint, current_app, jsonify, request
+from loguru import logger
 
-from config import logger
 from database.database import get_session
 from services.auditoria_service import (
     find_by_ip,

+ 1 - 1
routes/auth_routes.py

@@ -16,8 +16,8 @@ from flask import (
     url_for,
 )
 from flask_wtf.csrf import CSRFProtect
+from loguru import logger
 
-from config import logger
 from services.auth_service import AuthConfig, AuthService
 
 auth_bp = Blueprint("auth", __name__, url_prefix="/auth")

+ 1 - 1
routes/logs_routes.py

@@ -2,8 +2,8 @@ import os
 from datetime import datetime
 
 from flask import Blueprint, jsonify, render_template, request
+from loguru import logger
 
-from config import logger
 from database.database import get_session
 from services.blacklist_users import find_blacklisted_sites
 from services.fetch_data_logs import get_users_logs

+ 2 - 3
routes/main_routes.py

@@ -3,8 +3,9 @@ import time
 from typing import Any
 
 from flask import Blueprint, redirect, render_template, request
+from loguru import logger
 
-from config import Config, logger
+from config import Config
 from parsers.connections import group_by_user, parse_raw_data
 from parsers.squid_info import fetch_squid_info_stats
 from services.fetch_data import fetch_squid_data
@@ -211,8 +212,6 @@ def all_notifications():
             ),
         )
     except Exception as e:
-        from config import logger
-
         logger.error(f"Error loading notifications page: {e}")
         return render_template(
             "all_notifications.html",

+ 1 - 1
routes/reports_routes.py

@@ -1,8 +1,8 @@
 from datetime import date, datetime
 
 from flask import Blueprint, render_template, request
+from loguru import logger
 
-from config import logger
 from database.database import get_dynamic_models, get_session
 from services.fetch_data_logs import get_metrics_for_date
 from services.get_reports import get_important_metrics

+ 1 - 1
routes/stats_routes.py

@@ -4,9 +4,9 @@ from datetime import datetime
 from threading import Lock
 
 from flask import Blueprint, render_template  # , request, jsonify
+from loguru import logger
 
 # from services.icap_service import scan_file_with_icap
-from config import logger
 from parsers.cache import fetch_squid_cache_stats
 from services.metrics_service import MetricsService
 from services.system_info import (

+ 3 - 15
services/acls_service.py

@@ -1,9 +1,7 @@
 from loguru import logger
 
 
-def add_acl(
-    name: str, acl_type: str, values: list, options: list, comment: str, config_manager
-) -> tuple[bool, str]:
+def add_acl(name: str, acl_type: str, values: list, options: list, comment: str, config_manager) -> tuple[bool, str]:
     if not name or not acl_type or not values:
         return False, "Debe proporcionar nombre, tipo y al menos un valor para la ACL"
 
@@ -54,15 +52,7 @@ def add_acl(
         return False, str(e)
 
 
-def edit_acl(
-    acl_index: int,
-    new_name: str,
-    acl_type: str,
-    values: list,
-    options: list,
-    comment: str,
-    config_manager,
-) -> tuple[bool, str]:
+def edit_acl(acl_index: int, new_name: str, acl_type: str, values: list, options: list, comment: str, config_manager) -> tuple[bool, str]:
     try:
         acls = config_manager.get_acls()
         if not (0 <= acl_index < len(acls)):
@@ -83,9 +73,7 @@ def edit_acl(
             if acl_content is not None:
                 lines = acl_content.split("\n")
                 if 0 <= target_line < len(lines):
-                    has_comment = target_line > 0 and lines[
-                        target_line - 1
-                    ].strip().startswith("#")
+                    has_comment = target_line > 0 and lines[target_line - 1].strip().startswith("#")
                     lines[target_line] = new_acl_line
                     if has_comment:
                         if comment:

+ 0 - 1
services/admin_helpers.py

@@ -1,5 +1,4 @@
 import os
-
 from sqlalchemy import MetaData, Table, func, select, text
 
 

+ 1 - 1
services/auditoria_service.py

@@ -1,8 +1,8 @@
 from collections import defaultdict
 from datetime import datetime, timedelta
 from typing import Any
-from venv import logger
 
+from loguru import logger
 from sqlalchemy import func, inspect, or_, text
 from sqlalchemy.exc import SQLAlchemyError
 from sqlalchemy.orm import Session

+ 2 - 1
services/auth_service.py

@@ -13,8 +13,9 @@ from functools import wraps
 import bcrypt
 import jwt
 from flask import flash, redirect, request, session, url_for
+from loguru import logger
 
-from config import Config, logger
+from config import Config
 from database.database import AdminUser, get_session
 
 

+ 2 - 8
services/blacklist_service.py

@@ -19,9 +19,7 @@ def test_pihole_connection(host: str, token: str | None = None) -> tuple[bool, s
         params["auth"] = token
 
     try:
-        resp = requests.get(
-            f"{url}/admin/api.php", params=params, headers=headers, timeout=6
-        )
+        resp = requests.get(f"{url}/admin/api.php", params=params, headers=headers, timeout=6)
         if resp.status_code == 200:
             return True, "Conexión a Pi-hole exitosa"
         return False, f"Respuesta inesperada de Pi-hole: {resp.status_code}"
@@ -73,11 +71,7 @@ def import_domains_from_url(url: str) -> tuple[bool, set, str]:
 
 
 def merge_and_save_blacklist(existing_env: dict, new_domains: set) -> None:
-    existing = [
-        d.strip()
-        for d in existing_env.get("BLACKLIST_DOMAINS", "").split(",")
-        if d.strip()
-    ]
+    existing = [d.strip() for d in existing_env.get("BLACKLIST_DOMAINS", "").split(",") if d.strip()]
     merged = set(existing)
     merged.update(new_domains)
     existing_env["BLACKLIST_DOMAINS"] = ",".join(sorted(merged))

+ 10 - 0
services/config_service.py

@@ -0,0 +1,10 @@
+from loguru import logger
+
+
+def save_config(new_content: str, config_manager) -> tuple[bool, str]:
+    try:
+        config_manager.save_config(new_content)
+        return True, "Configuration saved successfully"
+    except Exception as e:
+        logger.exception("Error saving configuration")
+        return False, str(e)

+ 2 - 8
services/db_admin_service.py

@@ -1,9 +1,7 @@
 import re
-
-from loguru import logger
 from sqlalchemy import MetaData, Table, inspect
-
 from database.database import get_engine
+from loguru import logger
 
 
 def delete_table_data(table_name: str):
@@ -43,8 +41,4 @@ def delete_table_data(table_name: str):
 
     except Exception as e:
         logger.exception("Error deleting data from table %s", table_name)
-        return {
-            "status": "error",
-            "message": "Error interno del servidor",
-            "details": str(e),
-        }, 500
+        return {"status": "error", "message": "Error interno del servidor", "details": str(e)}, 500

+ 2 - 3
services/db_info_service.py

@@ -1,9 +1,8 @@
 from loguru import logger
 from sqlalchemy import inspect
-
-from config import Config
 from database.database import get_engine, get_session
 from services.admin_helpers import get_table_row_count, get_table_size
+from config import Config
 
 
 def get_tables_info():
@@ -39,7 +38,7 @@ def get_tables_info():
 
         return {"status": "success", "tables": table_info}, 200
 
-    except Exception:
+    except Exception as e:
         logger.exception("Error getting database tables")
         resp = {"status": "error", "message": "Error interno del servidor"}
         return resp, 500

+ 7 - 31
services/delay_pools_service.py

@@ -18,9 +18,7 @@ def delete_delay_pool(pool_number: str, config_manager) -> tuple[bool, str]:
                         continue
                     new_lines.append(line)
                 new_content = "\n".join(new_lines)
-                if config_manager.save_modular_config(
-                    "110_delay_pools.conf", new_content
-                ):
+                if config_manager.save_modular_config("110_delay_pools.conf", new_content):
                     return True, f"Delay Pool #{pool_number} eliminado exitosamente"
                 else:
                     return False, "Error al eliminar delay pool modular"
@@ -45,14 +43,7 @@ def delete_delay_pool(pool_number: str, config_manager) -> tuple[bool, str]:
         return False, str(e)
 
 
-def edit_delay_pool(
-    pool_number: str,
-    pool_class: str,
-    parameters: str,
-    access_actions: list,
-    access_acls: list,
-    config_manager,
-) -> tuple[bool, str]:
+def edit_delay_pool(pool_number: str, pool_class: str, parameters: str, access_actions: list, access_acls: list, config_manager) -> tuple[bool, str]:
     try:
         new_directives = []
         new_directives.append(f"delay_class {pool_number} {pool_class}")
@@ -74,9 +65,7 @@ def edit_delay_pool(
                         insert_index = i
                         # skip existing block (we will rebuild)
                         continue
-                    if pool_found and (
-                        line.strip().startswith("delay_class ") or line.strip() == ""
-                    ):
+                    if pool_found and (line.strip().startswith("delay_class ") or line.strip() == ""):
                         pool_found = False
                     if not pool_found:
                         new_lines.append(line)
@@ -87,9 +76,7 @@ def edit_delay_pool(
                 else:
                     new_lines.extend(new_directives)
                 new_content = "\n".join(new_lines)
-                if config_manager.save_modular_config(
-                    "110_delay_pools.conf", new_content
-                ):
+                if config_manager.save_modular_config("110_delay_pools.conf", new_content):
                     return True, f"Delay Pool #{pool_number} actualizado exitosamente"
                 else:
                     return False, "Error al guardar delay pool modular"
@@ -108,9 +95,7 @@ def edit_delay_pool(
         if insert_index >= 0:
             # remove existing block lines starting at insert_index until next blank or next delay_class
             j = insert_index
-            while j < len(lines) and not (
-                lines[j].strip().startswith("delay_class ") and j != insert_index
-            ):
+            while j < len(lines) and not (lines[j].strip().startswith("delay_class ") and j != insert_index):
                 j += 1
             new_lines = lines[:insert_index] + new_directives + lines[j:]
         else:
@@ -124,14 +109,7 @@ def edit_delay_pool(
         return False, str(e)
 
 
-def add_delay_pool(
-    pool_number: str,
-    pool_class: str,
-    parameters: str,
-    access_actions: list,
-    access_acls: list,
-    config_manager,
-) -> tuple[bool, str]:
+def add_delay_pool(pool_number: str, pool_class: str, parameters: str, access_actions: list, access_acls: list, config_manager) -> tuple[bool, str]:
     try:
         new_directives = []
         new_directives.append(f"delay_class {pool_number} {pool_class}")
@@ -146,9 +124,7 @@ def add_delay_pool(
                 lines = delay_content.split("\n")
                 lines.extend(new_directives)
                 new_content = "\n".join(lines)
-                if config_manager.save_modular_config(
-                    "110_delay_pools.conf", new_content
-                ):
+                if config_manager.save_modular_config("110_delay_pools.conf", new_content):
                     return True, f"Delay Pool #{pool_number} creado exitosamente"
                 else:
                     return False, "Error al crear delay pool modular"

+ 1 - 7
services/fetch_data_logs.py

@@ -1,20 +1,14 @@
-import logging
 import re
 from datetime import date, datetime
 from typing import Any
 
+from loguru import logger
 from sqlalchemy import func, inspect
 from sqlalchemy.ext.automap import automap_base
 from sqlalchemy.orm import Session
 
 from database.database import get_concat_function, get_dynamic_models, get_session
 
-# Configuración básica de logging
-logging.basicConfig(
-    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
-)
-logger = logging.getLogger(__name__)
-
 # Patrones de validación para nombres de tabla y fechas
 TABLE_NAME_PATTERN = re.compile(r"^[a-z_]{3,20}$")
 DATE_SUFFIX_PATTERN = re.compile(r"^\d{8}$")

+ 7 - 23
services/http_access_service.py

@@ -2,11 +2,7 @@ from loguru import logger
 
 
 def _find_http_lines(lines):
-    return [
-        i
-        for i, line in enumerate(lines)
-        if line.strip().startswith("http_access ") and not line.strip().startswith("#")
-    ]
+    return [i for i, line in enumerate(lines) if line.strip().startswith("http_access ") and not line.strip().startswith("#")]
 
 
 def delete_http_access(rule_index: int, config_manager) -> tuple[bool, str]:
@@ -21,9 +17,7 @@ def delete_http_access(rule_index: int, config_manager) -> tuple[bool, str]:
                 # remove the line
                 del lines[http_lines_indices[rule_index]]
                 new_content = "\n".join(lines)
-                if config_manager.save_modular_config(
-                    "120_http_access.conf", new_content
-                ):
+                if config_manager.save_modular_config("120_http_access.conf", new_content):
                     return True, "Regla HTTP Access eliminada exitosamente"
                 else:
                     return False, "Error al eliminar la regla modular"
@@ -42,9 +36,7 @@ def delete_http_access(rule_index: int, config_manager) -> tuple[bool, str]:
         return False, str(e)
 
 
-def edit_http_access(
-    rule_index: int, action: str, acls: list, description: str, config_manager
-) -> tuple[bool, str]:
+def edit_http_access(rule_index: int, action: str, acls: list, description: str, config_manager) -> tuple[bool, str]:
     try:
         acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
         if not acl_string:
@@ -68,9 +60,7 @@ def edit_http_access(
                         i += 1
                 lines[i] = new_rule
                 new_content = "\n".join(lines)
-                if config_manager.save_modular_config(
-                    "120_http_access.conf", new_content
-                ):
+                if config_manager.save_modular_config("120_http_access.conf", new_content):
                     return True, "Regla HTTP Access actualizada exitosamente"
                 else:
                     return False, "Error al guardar regla modular"
@@ -96,9 +86,7 @@ def edit_http_access(
         return False, str(e)
 
 
-def add_http_access(
-    action: str, acls: list, description: str, config_manager
-) -> tuple[bool, str]:
+def add_http_access(action: str, acls: list, description: str, config_manager) -> tuple[bool, str]:
     try:
         acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
         if not acl_string:
@@ -115,9 +103,7 @@ def add_http_access(
                 lines = http_content.split("\n")
                 lines.extend(lines_to_add)
                 new_content = "\n".join(lines)
-                if config_manager.save_modular_config(
-                    "120_http_access.conf", new_content
-                ):
+                if config_manager.save_modular_config("120_http_access.conf", new_content):
                     return True, "Regla HTTP Access agregada exitosamente"
                 else:
                     return False, "Error al guardar regla modular"
@@ -132,9 +118,7 @@ def add_http_access(
         return False, str(e)
 
 
-def move_http_access(
-    rule_index: int, direction: str, config_manager
-) -> tuple[bool, str]:
+def move_http_access(rule_index: int, direction: str, config_manager) -> tuple[bool, str]:
     try:
         if config_manager.is_modular:
             http_content = config_manager.read_modular_config("120_http_access.conf")

+ 0 - 1
services/logs_service.py

@@ -1,5 +1,4 @@
 import os
-
 from loguru import logger
 
 

+ 1 - 3
services/metrics_service.py

@@ -1,13 +1,11 @@
-import logging
 from datetime import datetime, timedelta
 from typing import Any
 
+from loguru import logger
 from sqlalchemy import desc
 
 from database.database import SystemMetrics, get_session
 
-logger = logging.getLogger(__name__)
-
 
 class MetricsService:
     @staticmethod

+ 1 - 4
services/notifications.py

@@ -1,5 +1,4 @@
 import hashlib
-import logging
 import os
 import subprocess
 import threading
@@ -7,14 +6,12 @@ from contextlib import contextmanager
 from datetime import datetime, timedelta
 from typing import Any
 
+from loguru import logger
 from sqlalchemy import and_, desc, func
 from sqlalchemy.orm import Session
 
 from database.database import Notification, get_session
 
-# Logger
-logger = logging.getLogger(__name__)
-
 # Import Telegram integration (optional - fails gracefully if not configured)
 try:
     from services.telegram_integration import send_telegram_notification

+ 5 - 24
services/split_config_service.py

@@ -1,7 +1,5 @@
 import os
-
 from loguru import logger
-
 from services.squid_config_splitter import SquidConfigSplitter
 
 
@@ -20,44 +18,27 @@ def split_config(strict=False):
     splitter = SquidConfigSplitter(strict=strict)
 
     if not os.path.exists(splitter.input_file):
-        return {
-            "status": "error",
-            "message": f"Archivo squid.conf no encontrado en: {splitter.input_file}",
-        }, 404
+        return {"status": "error", "message": f"Archivo squid.conf no encontrado en: {splitter.input_file}"}, 404
 
     try:
         results = splitter.split_config()
         return {
             "status": "success",
             "message": f"Configuración dividida exitosamente en {len(results)} archivos",
-            "data": {
-                "output_dir": splitter.output_dir,
-                "files": results,
-                "total_files": len(results),
-            },
+            "data": {"output_dir": splitter.output_dir, "files": results, "total_files": len(results)},
         }, 200
     except FileNotFoundError as e:
         logger.error("Archivo no encontrado: %s", e)
         return {"status": "error", "message": "Archivo requerido no encontrado."}, 404
     except PermissionError as e:
         logger.error("Error de permisos: %s", e)
-        return {
-            "status": "error",
-            "message": "No se tienen permisos suficientes para crear los archivos",
-        }, 403
+        return {"status": "error", "message": "No se tienen permisos suficientes para crear los archivos"}, 403
     except RuntimeError as e:
         logger.error("Error de validación: %s", e)
-        return {
-            "status": "error",
-            "message": "Error de validación de la configuración",
-        }, 400
+        return {"status": "error", "message": "Error de validación de la configuración"}, 400
     except Exception as e:
         logger.exception("Error al dividir el archivo de configuración")
-        return {
-            "status": "error",
-            "message": "Error interno al dividir la configuración",
-            "details": str(e),
-        }, 500
+        return {"status": "error", "message": "Error interno al dividir la configuración", "details": str(e)}, 500
 
 
 def get_split_files_info(output_dir: str):

+ 2 - 1
services/squid_config_splitter.py

@@ -5,7 +5,7 @@ import subprocess
 from dataclasses import dataclass
 from datetime import datetime
 
-from config import logger
+from loguru import logger
 
 
 @dataclass(frozen=True)
@@ -344,6 +344,7 @@ class SquidConfigSplitter:
             logger.info("Validating Squid configuration with 'squid -k parse'...")
             result = subprocess.run(
                 ["squid", "-k", "parse"],
+                # ["docker", "exec", "squid_proxy", "squid", "-k", "parse"],
                 capture_output=True,
                 text=True,
                 timeout=30,

+ 1 - 2
services/system_service.py

@@ -1,6 +1,5 @@
-import subprocess
-
 from loguru import logger
+import subprocess
 
 
 def restart_squid() -> tuple[bool, str, str]:

+ 2 - 3
services/telegram_integration.py

@@ -4,12 +4,13 @@ Integrates Telegram notifications with the existing notification system
 """
 
 import asyncio
-import logging
 from collections.abc import Callable
 from concurrent.futures import ThreadPoolExecutor
 from functools import wraps
 from typing import Any
 
+from loguru import logger
+
 from config import Config
 from services.telegram_service import (
     NotificationPriority,
@@ -18,8 +19,6 @@ from services.telegram_service import (
     parse_http_proxy_url,
 )
 
-logger = logging.getLogger(__name__)
-
 # Thread pool for async execution
 _executor = ThreadPoolExecutor(max_workers=2)
 _telegram_service: TelegramService | None = None

+ 1 - 3
services/telegram_service.py

@@ -1,5 +1,4 @@
 import asyncio
-import logging
 from contextlib import asynccontextmanager
 from datetime import datetime
 from enum import Enum
@@ -7,11 +6,10 @@ from functools import wraps
 from typing import Any, Optional
 from urllib.parse import urlparse
 
+from loguru import logger
 from telethon import TelegramClient, errors
 from telethon.tl.types import InputPeerUser, User
 
-logger = logging.getLogger(__name__)
-
 
 def parse_http_proxy_url(proxy_url: str) -> dict[str, Any] | None:
     """

+ 3 - 9
services/user_service.py

@@ -1,12 +1,11 @@
 from loguru import logger
-
 from services.auth_service import AuthService
 
 
 def get_all_users():
     try:
         return AuthService.get_all_users()
-    except Exception:
+    except Exception as e:
         logger.exception("Error getting users")
         return []
 
@@ -27,9 +26,7 @@ def create_user(username: str, password: str, role: str = "admin") -> tuple[bool
         return False, str(e)
 
 
-def update_user(
-    user_id: int, username: str, password: str, role: str, is_active: int
-) -> tuple[bool, str]:
+def update_user(user_id: int, username: str, password: str, role: str, is_active: int) -> tuple[bool, str]:
     if password and len(password) < 8:
         return False, "La contraseña debe tener al menos 8 caracteres"
 
@@ -52,10 +49,7 @@ def delete_user(user_id: int) -> tuple[bool, str]:
         ok = AuthService.delete_user(user_id)
         if ok:
             return True, "Usuario eliminado exitosamente"
-        return (
-            False,
-            "Error al eliminar usuario. No se puede eliminar el usuario admin.",
-        )
+        return False, "Error al eliminar usuario. No se puede eliminar el usuario admin."
     except Exception as e:
         logger.exception("Error deleting user")
         return False, str(e)

+ 3 - 0
templates/admin/base.html

@@ -136,6 +136,9 @@
                         </span>
                         <span class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-xs font-semibold px-2.5 py-0.5 rounded-full shadow-sm">RC</span>
                     </a>
+                    <a href="/admin/blacklist" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-ban mr-3"></i>Blacklist
+                    </a>
                     <a href="{{ url_for('admin.view_logs') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
                         <i class="fas fa-file-alt mr-3"></i>Logs
                     </a>

+ 106 - 0
templates/admin/blacklist.html

@@ -0,0 +1,106 @@
+{% extends "admin/base.html" %}
+
+{% block content %}
+<div x-data="{ activeTab: 'pihole' }" class="bg-white rounded-lg shadow-lg p-4 sm:p-6">
+    <h2 class="text-xl sm:text-2xl font-bold text-gray-800 mb-4 sm:mb-6">Blacklist - Gestor de Listas</h2>
+
+    <!-- Tabs -->
+    <div class="flex border-b border-gray-200 flex-wrap">
+        <button @click="activeTab = 'pihole'" :class="activeTab === 'pihole' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500'" class="py-2 px-4 border-b-2 font-medium text-sm whitespace-nowrap">
+            Pi-hole
+        </button>
+        <button @click="activeTab = 'adguard'" :class="activeTab === 'adguard' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500'" class="py-2 px-4 border-b-2 font-medium text-sm whitespace-nowrap">
+            AdGuard
+        </button>
+        <button @click="activeTab = 'dnsmasq'" :class="activeTab === 'dnsmasq' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500'" class="py-2 px-4 border-b-2 font-medium text-sm whitespace-nowrap">
+            DNSmasq
+        </button>
+        <button @click="activeTab = 'custom'" :class="activeTab === 'custom' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500'" class="py-2 px-4 border-b-2 font-medium text-sm whitespace-nowrap">
+            Personalizada
+        </button>
+        <button @click="activeTab = 'import'" :class="activeTab === 'import' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500'" class="py-2 px-4 border-b-2 font-medium text-sm whitespace-nowrap">
+            Importar
+        </button>
+    </div>
+
+    <!-- Pi-hole Tab -->
+    <div x-show="activeTab === 'pihole'" class="mt-6">
+        <h3 class="text-lg font-semibold mb-3">Integración Pi-hole</h3>
+        <p class="text-sm text-gray-600 mb-4">Conecta y sincroniza listas bloqueadas desde un servidor Pi-hole. Aquí puedes configurar conexión y ver el estado.</p>
+
+        <form method="POST" action="/admin/blacklist/test-connection" class="grid grid-cols-1 md:grid-cols-2 gap-4">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
+            <div class="bg-gray-50 p-4 rounded border">
+                <label class="text-sm font-medium text-gray-700">Pi-hole Host</label>
+                <input name="host" type="text" class="w-full mt-2 p-2 border rounded" placeholder="192.168.1.2 or example.com" />
+            </div>
+            <div class="bg-gray-50 p-4 rounded border">
+                <label class="text-sm font-medium text-gray-700">API Token</label>
+                <input name="token" type="password" class="w-full mt-2 p-2 border rounded" placeholder="Token (opcional)" />
+            </div>
+
+            <div class="md:col-span-2 mt-4 flex gap-2">
+                <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">Probar Conexión</button>
+        </form>
+        <form method="POST" action="/admin/blacklist/sync" class="mt-0">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
+            <button type="submit" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded">Sincronizar Listas</button>
+        </form>
+            </div>
+    </div>
+
+    <!-- AdGuard Tab -->
+    <div x-show="activeTab === 'adguard'" class="mt-6">
+        <h3 class="text-lg font-semibold mb-3">Integración AdGuard</h3>
+        <p class="text-sm text-gray-600 mb-4">Soporte para fuentes y listas públicas compatibles con AdGuard.</p>
+        <form method="POST" action="/admin/blacklist/import" class="bg-gray-50 p-4 rounded border">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
+            <label class="text-sm font-medium text-gray-700">URL de la lista</label>
+            <input name="url" type="text" class="w-full mt-2 p-2 border rounded" placeholder="https://example.com/list.txt" />
+            <div class="mt-3">
+                <button type="submit" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded">Agregar Lista</button>
+            </div>
+        </form>
+    </div>
+
+    <!-- DNSmasq Tab -->
+    <div x-show="activeTab === 'dnsmasq'" class="mt-6">
+        <h3 class="text-lg font-semibold mb-3">DNSmasq</h3>
+        <p class="text-sm text-gray-600 mb-4">Exporta o importa reglas en formato compatible con dnsmasq.</p>
+        <div class="bg-gray-50 p-4 rounded border">
+            <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">Exportar archivo hosts</button>
+        </div>
+    </div>
+
+    <!-- Custom Tab -->
+    <div x-show="activeTab === 'custom'" class="mt-6">
+        <h3 class="text-lg font-semibold mb-3">Lista Personalizada</h3>
+        <p class="text-sm text-gray-600 mb-4">Añade dominios manualmente o pega una lista separada por comas/lineas.</p>
+        <form method="POST" action="/admin/blacklist/save-custom" class="grid grid-cols-1 gap-4">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
+            <textarea name="custom_list" rows="6" class="w-full p-3 border rounded" placeholder="example.com
+example.org
+"></textarea>
+            <div class="flex gap-2">
+                <button type="submit" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded">Guardar</button>
+                <button type="button" class="bg-gray-200 hover:bg-gray-300 px-4 py-2 rounded">Cancelar</button>
+            </div>
+        </form>
+    </div>
+
+    <!-- Import Tab -->
+    <div x-show="activeTab === 'import'" class="mt-6">
+        <h3 class="text-lg font-semibold mb-3">Importar listas</h3>
+        <p class="text-sm text-gray-600 mb-4">Importa desde archivos locales o pega URLs de listas públicas.</p>
+
+        <form method="POST" action="/admin/blacklist/import" enctype="multipart/form-data" class="bg-gray-50 p-4 rounded border">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
+            <label class="text-sm font-medium text-gray-700">Subir archivo</label>
+            <input name="file" type="file" class="w-full mt-2" />
+            <div class="mt-3">
+                <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">Importar</button>
+            </div>
+        </form>
+    </div>
+</div>
+{% endblock %}

+ 1 - 1
templates/auth/login.html

@@ -171,7 +171,7 @@
 
     <!-- Version Badge -->
     <div class="fixed bottom-4 right-4 text-white/50 text-xs">
-        SquidStats v2.2
+        SquidStats v{{ config.VERSION }}
     </div>
 
     <script>

+ 1 - 3
utils/admin.py

@@ -1,11 +1,9 @@
-import logging
 import os
 import shutil
 from datetime import datetime
 
 from dotenv import load_dotenv
-
-logger = logging.getLogger(__name__)
+from loguru import logger
 
 load_dotenv()
 

+ 1 - 2
utils/filters.py

@@ -1,7 +1,6 @@
-import logging
 from datetime import datetime
 
-logger = logging.getLogger(__name__)
+from loguru import logger
 
 
 def divide_filter(numerator, denominator, precision=2):