| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869 |
- <nav class="top-0 left-0 right-0 z-[1000] fixed w-full bg-gradient-to-br from-blue-800 to-blue-900 shadow-lg border-b border-white/10 backdrop-blur-md transition-transform duration-300" x-data="{ mobileMenuOpen: false }">
- <!-- UNIFIED CONTAINER WITH THE REST -->
- <div class="w-full px-4 sm:px-6 lg:px-8">
- <div class="max-w-7xl mx-auto flex items-center justify-between py-4 h-[64px]">
- <!-- Brand/Logo Section -->
- <div class="flex items-center gap-3 font-bold text-xl text-white no-underline">
- <img src="{{ url_for('static', filename='squidstats-64.webp') }}" alt="" width="32" height="32" class="h-8 w-8 object-contain rounded-md" />
- <span class="font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-white to-blue-300">{{ _("SquidStats") }}</span>
- </div>
- <!-- Container for mobile icons (notifications + hamburger) -->
- <div class="lg:hidden flex items-center gap-3">
- <!-- Mobile Notifications Button -->
- <div class="relative" x-data="{ open: false }">
- <button type="button" aria-label="{{ _('Notificaciones') }}" @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Notificaciones") }}">
- <i class="fas fa-bell"></i>
- <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
- </button>
- <!-- Mobile notifications dropdown -->
- <div x-show="open"
- @click.away="open = false"
- @keydown.escape.window="open = false"
- x-transition:enter="transition ease-out duration-200"
- x-transition:enter-start="opacity-0 scale-95"
- x-transition:enter-end="opacity-100 scale-100"
- x-transition:leave="transition ease-in duration-150"
- x-transition:leave-start="opacity-100 scale-100"
- x-transition:leave-end="opacity-0 scale-95"
- class="origin-top-right absolute right-0 mt-2 w-80 rounded-lg shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
- style="display: none">
- <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
- <span class="font-semibold text-gray-800">{{ _("Notificaciones") }}</span>
- <button type="button" aria-label="{{ _('Cerrar notificaciones') }}" @click="open = false" class="text-gray-500 hover:text-gray-700 focus:outline-none">
- <i class="fas fa-times"></i>
- </button>
- </div>
- <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications-mobile">
- <li class="px-4 py-3 text-gray-500 text-center">
- {{ _("Cargando notificaciones...") }}
- </li>
- </ul>
- <div class="py-2 px-4 text-center border-t border-gray-200">
- <a href="/all-notifications" class="text-sm text-blue-600 hover:underline">{{ _("Ver todas las notificaciones") }}</a>
- </div>
- </div>
- </div>
- <!-- Hamburger Button for Mobile -->
- <button @click="mobileMenuOpen = !mobileMenuOpen" class="flex flex-col w-8 h-8 justify-center items-center gap-1.5 text-white focus:outline-none z-[1001]" aria-label="{{ _("Toggle menu") }}">
- <span class="w-6 h-0.5 bg-white transition-all" :class="{'rotate-45 translate-y-2': mobileMenuOpen}"></span>
- <span class="w-6 h-0.5 bg-white transition-all" :class="{'opacity-0': mobileMenuOpen}"></span>
- <span class="w-6 h-0.5 bg-white transition-all" :class="{'-rotate-45 -translate-y-2': mobileMenuOpen}"></span>
- </button>
- </div>
- <!-- Navigation Links - Desktop -->
- <div class="hidden lg:flex items-center gap-2 lg:ml-10">
- <a href="/" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Panel principal con conexiones activas") }}">
- <i class="fas fa-home text-base"></i>
- <span class="font-medium">{{ _("Inicio") }}</span>
- </a>
- <a href="/stats" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Estadísticas de rendimiento del cache") }}">
- <i class="fas fa-chart-bar text-base"></i>
- <span class="font-medium">{{ _("Estadísticas") }}</span>
- </a>
- <a href="/logs" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Actividad y logs de usuarios y grupos") }}">
- <i class="fas fa-user-friends text-base"></i>
- <span class="font-medium">{{ _("Usuarios") }}</span>
- </a>
- <a href="/reports" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Reportes y gráficas avanzadas") }}">
- <i class="fas fa-chart-simple text-base"></i>
- <span class="font-medium">{{ _("Reportes") }}</span>
- </a>
- <a href="/blacklist" data-nav-loading="true" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Sitios bloqueados y actividad restringida") }}">
- <i class="fas fa-ban text-base"></i>
- <span class="font-medium">{{ _("Blacklist") }}</span>
- </a>
- <a href="/auditoria" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Auditoría de actividad por usuario y fecha") }}">
- <i class="fas fa-magnifying-glass text-base"></i>
- <span class="font-medium">{{ _("Auditoría") }}</span>
- </a>
- </div>
- <!-- Desktop Notifications -->
- <div class="hidden lg:flex items-center gap-3">
- <div class="relative" x-data="{ open: false }">
- <!-- Desktop Notifications Button -->
- <button type="button" aria-label="{{ _('Notificaciones') }}" @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Notificaciones") }}">
- <i class="fas fa-bell"></i>
- <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
- </button>
- <!-- Desktop notifications dropdown -->
- <div x-show="open"
- @click.away="open = false"
- @keydown.escape.window="open = false"
- x-transition:enter="transition ease-out duration-200"
- x-transition:enter-start="opacity-0 scale-95"
- x-transition:enter-end="opacity-100 scale-100"
- x-transition:leave="transition ease-in duration-150"
- x-transition:leave-start="opacity-100 scale-100"
- x-transition:leave-end="opacity-0 scale-95"
- class="origin-top-right absolute right-0 mt-2 w-80 rounded-lg shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
- style="display: none">
- <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
- <span class="font-semibold text-gray-800">{{ _("Notificaciones") }}</span>
- <button type="button" aria-label="{{ _('Cerrar notificaciones') }}" @click="open = false" class="text-gray-500 hover:text-gray-700 focus:outline-none">
- <i class="fas fa-times"></i>
- </button>
- </div>
- <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications">
- <li class="px-4 py-3 text-gray-500 text-center">
- {{ _("Cargando notificaciones...") }}
- </li>
- </ul>
- <div class="py-2 px-4 text-center border-t border-gray-200">
- <a href="/all-notifications" class="text-sm text-blue-600 hover:underline">{{ _("Ver todas las notificaciones") }}</a>
- </div>
- </div>
- </div>
- <!-- Action Buttons - Desktop -->
- <div class="flex items-center gap-3">
- <a href="/admin" class="action-btn flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-blue-600 to-blue-500 text-white shadow hover:from-blue-700 hover:to-blue-600 hover:-translate-y-0.5 transition-all duration-300" data-tooltip="{{ _("Panel de administración del sistema") }}">
- <i class="fas fa-cog"></i>
- <span>{{ _("Admin") }}</span>
- </a>
- <div class="update-btn-wrapper relative inline-block group">
- <button onclick="confirmSquidUpdate()" id="squid-update-btn" class="action-btn update-btn relative flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-emerald-600 to-emerald-400 text-white shadow hover:from-emerald-700 hover:to-emerald-600 hover:-translate-y-0.5 transition-all duration-300" data-base-tooltip="{{ _("Actualizar paquetes y configuración de Squid") }}">
- <span id="squid-update-badge" class="update-badge update-badge--squid hidden">1</span>
- <i id="squid-update-icon" class="fas fa-sync-alt"></i>
- <span>{{ _("Squid") }}</span>
- </button>
- <div id="squid-update-tooltip" class="update-tooltip"></div>
- </div>
- <div class="update-btn-wrapper relative inline-block group">
- <button onclick="confirmWebUpdate()" id="web-update-btn" class="action-btn update-btn relative flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-purple-600 to-purple-400 text-white shadow hover:from-purple-700 hover:to-purple-600 hover:-translate-y-0.5 transition-all duration-300" data-base-tooltip="{{ _("Actualizar aplicación web SquidStats") }}">
- <span id="web-update-badge" class="update-badge update-badge--web hidden">1</span>
- <i id="web-update-icon" class="fas fa-cloud-download-alt"></i>
- <span>{{ _("Web") }}</span>
- </button>
- <div id="web-update-tooltip" class="update-tooltip"></div>
- </div>
- <!-- Language Switcher -->
- <div class="relative" x-data="{ langOpen: false }">
- <button @click="langOpen = !langOpen" @click.outside="langOpen = false" class="flex items-center gap-1 px-3 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 hover:text-white hover:bg-white/10" data-tooltip="{{ _('Idioma') }}">
- <i class="fas fa-globe"></i>
- <span class="uppercase">{{ get_locale() }}</span>
- </button>
- <div x-show="langOpen" x-transition class="absolute right-0 mt-2 w-36 bg-white rounded-lg shadow-xl border border-gray-100 z-50 overflow-hidden" style="display: none;">
- {% for code, name in LANGUAGES.items() %}
- <a href="{{ url_for('i18n.set_language', lang=code) }}" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 hover:text-blue-700 transition-colors {% if get_locale() == code %}bg-blue-50 font-semibold text-blue-700{% endif %}">
- {{ name }}
- {% if get_locale() == code %}<i class="fas fa-check ml-auto text-blue-500"></i>{% endif %}
- </a>
- {% endfor %}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <!-- Mobile Menu Overlay -->
- <div x-show="mobileMenuOpen" @click="mobileMenuOpen = false" class="fixed inset-0 bg-black bg-opacity-50 z-[999] lg:hidden" style="display: none;">
- </div>
- <!-- Mobile Menu Content -->
- <div x-show="mobileMenuOpen"
- x-transition:enter="transition ease-out duration-300"
- x-transition:enter-start="opacity-0 transform -translate-y-4"
- x-transition:enter-end="opacity-100 transform translate-y-0"
- x-transition:leave="transition ease-in duration-200"
- x-transition:leave-start="opacity-100 transform translate-y-0"
- x-transition:leave-end="opacity-0 transform -translate-y-4"
- class="absolute top-full left-0 right-0 bg-gradient-to-b from-blue-800 to-blue-900 shadow-2xl z-[1000] lg:hidden overflow-y-auto border-t border-white/10"
- style="display: none;">
- <div class="p-6">
- <!-- Mobile Navigation Links -->
- <div class="flex flex-col gap-2 mb-8">
- <a href="/" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
- <i class="fas fa-home text-lg"></i>
- <span>{{ _("Inicio") }}</span>
- </a>
- <a
- href="/stats" @click="mobileMenuOpen = false"
- class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
- <i class="fas fa-chart-bar text-lg"></i>
- <span>{{ _("Estadísticas") }}</span>
- </a>
- <a href="/logs" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
- <i class="fas fa-user-friends text-lg"></i>
- <span>{{ _("Usuarios") }}</span>
- </a>
- <a href="/reports" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
- <i class="fas fa-chart-simple text-lg"></i>
- <span>{{ _("Reportes") }}</span>
- </a>
- <a href="/blacklist" data-nav-loading="true" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
- <i class="fas fa-ban text-lg"></i>
- <span>{{ _("Blacklist") }}</span>
- </a>
- <a href="/auditoria" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
- <i class="fas fa-magnifying-glass text-lg"></i>
- <span>{{ _("Auditoría") }}</span>
- </a>
- </div>
- <!-- Squid and Web buttons in a row -->
- <div class="flex flex-row gap-3 mb-8">
- <div class="flex flex-1 gap-2">
- <a href="/admin" @click="mobileMenuOpen = false" class="flex-1 flex items-center justify-center gap-2 px-3 py-3 rounded-lg font-semibold text-sm bg-gradient-to-r from-blue-600 to-blue-500 text-white shadow hover:from-blue-700 hover:to-blue-600 transition-all duration-300">
- <i class="fas fa-cog"></i>
- <span>{{ _("Admin") }}</span>
- </a>
- <button onclick="confirmSquidUpdate(); mobileMenuOpen = false" id="squid-update-btn-mobile" class="flex-1 flex items-center justify-center gap-2 px-3 py-3 rounded-lg font-semibold text-sm bg-gradient-to-r from-emerald-600 to-emerald-400 text-white shadow hover:from-emerald-700 hover:to-emerald-600 transition-all duration-300">
- <i id="squid-update-icon-mobile" class="fas fa-sync-alt"></i>
- <span class="flex items-center gap-2">{{ _("Squid") }} <span id="squid-update-chip-mobile" class="update-chip update-chip--squid hidden">NEW</span></span>
- </button>
- <button onclick="confirmWebUpdate(); mobileMenuOpen = false" id="web-update-btn-mobile" class="flex-1 flex items-center justify-center gap-2 px-3 py-3 rounded-lg font-semibold text-sm bg-gradient-to-r from-purple-600 to-purple-400 text-white shadow hover:from-purple-700 hover:to-purple-600 transition-all duration-300">
- <i id="web-update-icon-mobile" class="fas fa-cloud-download-alt"></i>
- <span class="flex items-center gap-2">{{ _("Web") }} <span id="web-update-chip-mobile" class="update-chip update-chip--web hidden">NEW</span></span>
- </button>
- </div>
- </div>
- <!-- Language Switcher - Mobile -->
- <div class="flex gap-2 mb-4">
- {% for code, name in LANGUAGES.items() %}
- <a href="{{ url_for('i18n.set_language', lang=code) }}" @click="mobileMenuOpen = false" class="flex-1 flex items-center justify-center gap-2 px-3 py-3 rounded-lg font-semibold text-sm transition-all duration-300 {% if get_locale() == code %}bg-white/20 text-white ring-1 ring-white/30{% else %}text-gray-300 hover:text-white hover:bg-white/10{% endif %}">
- <i class="fas fa-globe"></i>
- <span>{{ name }}</span>
- {% if get_locale() == code %}<i class="fas fa-check text-xs"></i>{% endif %}
- </a>
- {% endfor %}
- </div>
- </div>
- </div>
- </div>
- </nav>
- <!-- Custom Confirm Modal -->
- {% include 'components/confirm_modal.html' %}
- <!-- Update indicators CSS -->
- <link rel="stylesheet" href="{{ url_for('static', filename='css/update-indicators.css') }}" />
- <!-- Scripts -->
- <script src="{{ url_for('static', filename='src/tailwind.min.js') }}"></script>
- <script defer src="{{ url_for('static', filename='src/alpine.min.js') }}"></script>
- <script src="{{ url_for('static', filename='js/confirm_modal.js') }}"></script>
- <script>
- const IS_DEB_INSTALL = {{ is_deb_install | tojson }};
- // Enhanced Navbar Functionality with Real-time Notifications
- document.addEventListener("DOMContentLoaded", function () {
- // Tooltip functionality
- function initTooltips() {
- const elements = document.querySelectorAll('[data-tooltip]');
- elements.forEach(element => {
- const tooltipText = element.getAttribute('data-tooltip');
- const tooltip = document.createElement('div');
- tooltip.className = 'absolute invisible bg-gray-900 text-white text-xs rounded py-1 px-2 top-full left-1/2 transform -translate-x-1/2 mt-2 whitespace-nowrap z-50 opacity-0 transition-opacity duration-200';
- tooltip.textContent = tooltipText;
- element.appendChild(tooltip);
-
- element.addEventListener('mouseenter', function() {
- tooltip.classList.remove('invisible', 'opacity-0');
- tooltip.classList.add('visible', 'opacity-100');
- });
-
- element.addEventListener('mouseleave', function() {
- tooltip.classList.remove('visible', 'opacity-100');
- tooltip.classList.add('invisible', 'opacity-0');
- });
- });
- }
- // Navbar scroll effect
- function initNavbarScroll() {
- const navbar = document.querySelector('nav');
- let lastScrollY = window.scrollY;
-
- window.addEventListener('scroll', () => {
- if (window.scrollY > lastScrollY && window.scrollY > 100) {
- navbar.style.transform = 'translateY(-100%)';
- } else {
- navbar.style.transform = 'translateY(0)';
- }
- lastScrollY = window.scrollY;
- });
- }
- // Active link highlighting
- function setActiveLink() {
- const currentPath = window.location.pathname;
- const links = document.querySelectorAll('nav a[href]');
-
- links.forEach(link => {
- if (link.getAttribute('href') === currentPath) {
- link.classList.add('text-white', 'bg-white/20');
- link.classList.remove('text-gray-200', 'hover:bg-white/10');
- }
- });
- }
- // Función para obtener el token CSRF de forma segura
- function getCSRFToken() {
- const metaTag = document.querySelector('meta[name="csrf-token"]');
- if (metaTag) {
- return metaTag.getAttribute('content');
- }
- console.warn('CSRF token meta tag no encontrado');
- return '';
- }
- // Enhanced Notifications System with WebSocket
- function initNotifications() {
- let notificationSocket = null;
- let notificationsData = {
- unread_count: 0,
- notifications: []
- };
- // Conectar WebSocket
- function connectWebSocket() {
- // Flask-SocketIO se conecta automáticamente al host actual
- notificationSocket = io();
-
- notificationSocket.on('connect', function() {
- console.log('Conectado al servidor de notificaciones Squid');
- });
-
- notificationSocket.on('new_notification', function(data) {
- addNewNotification(data.notification);
- updateNotificationBadges(data.unread_count);
- showNotificationToast(data.notification);
- });
-
- notificationSocket.on('notification_updated', function(data) {
- console.log('Notificación actualizada recibida:', data);
- updateExistingNotification(data.notification);
- updateNotificationBadges(data.unread_count);
- showNotificationToast(data.notification);
- });
-
- notificationSocket.on('disconnect', function() {
- // Reconectar después de 5 segundos
- setTimeout(connectWebSocket, 5000);
- });
- }
- function addNewNotification(notification) {
- // Evitar duplicados por ID
- const existingIndex = notificationsData.notifications.findIndex(n => n.id === notification.id);
- if (existingIndex === -1) {
- notificationsData.notifications.unshift(notification);
- if (!notification.read) {
- notificationsData.unread_count++;
- }
-
- // Actualizar ambas listas (desktop y móvil)
- updateNotificationLists();
- updateNotificationBadges(notificationsData.unread_count);
- }
- }
- function updateExistingNotification(notification) {
- // Buscar y actualizar la notificación existente
- const existingIndex = notificationsData.notifications.findIndex(n => n.id === notification.id);
- if (existingIndex !== -1) {
- // Actualizar la notificación existente
- notificationsData.notifications[existingIndex] = notification;
- // Moverla al principio de la lista
- const updated = notificationsData.notifications.splice(existingIndex, 1)[0];
- notificationsData.notifications.unshift(updated);
- } else {
- // Si no existe, agregarla como nueva
- notificationsData.notifications.unshift(notification);
- }
-
- // Actualizar ambas listas (desktop y móvil)
- updateNotificationLists();
- }
- function showNotificationToast(notification) {
- if (!window.toastr) return;
-
- // Construir el título con la fuente
- const source = notification.source === 'squid' ? 'Squid' :
- notification.source === 'git' ? 'Git' : 'Sistema';
- const title = notification.count && notification.count > 1 ?
- `${source} (×${notification.count})` : source;
-
- // Mostrar notificación según el tipo
- if (notification.type === 'error') {
- toastr.error(notification.message, title);
- } else if (notification.type === 'warning') {
- toastr.warning(notification.message, title);
- } else if (notification.type === 'success') {
- toastr.success(notification.message, title);
- } else {
- toastr.info(notification.message, title);
- }
- }
- function updateNotificationLists() {
- const desktopUl = document.querySelector(".notifications");
- const mobileUl = document.querySelector(".notifications-mobile");
-
- const renderNotificationList = (ul, notifications) => {
- if (!ul) return;
-
- ul.innerHTML = "";
-
- // Usar el estado local actual - SOLO notificaciones no leídas
- const unreadNotifications = notificationsData.notifications.filter(n => !n.read);
- const notificationsToShow = unreadNotifications.slice(0, 10);
-
- if (notificationsToShow.length > 0) {
- notificationsToShow.forEach((notification) => {
- let bgColor, textColor;
-
- switch(notification.type) {
- case 'success':
- bgColor = 'bg-green-100';
- textColor = 'text-green-600';
- break;
- case 'warning':
- bgColor = 'bg-yellow-100';
- textColor = 'text-yellow-600';
- break;
- case 'error':
- bgColor = 'bg-red-100';
- textColor = 'text-red-600';
- break;
- case 'info':
- default:
- bgColor = 'bg-blue-100';
- textColor = 'text-blue-600';
- }
-
- // Create list item safely
- const li = document.createElement('li');
- li.className = `px-4 py-3 flex items-start hover:bg-gray-50 cursor-pointer notification-item ${
- notification.read ? 'opacity-60' : ''
- }`;
- li.dataset.id = notification.id;
-
- const iconSpan = document.createElement('span');
- iconSpan.className = `inline-flex items-center justify-center h-8 w-8 rounded-full ${bgColor} ${textColor} mr-3`;
- const icon = document.createElement('i');
- icon.className = `fas ${notification.icon}`;
- iconSpan.appendChild(icon);
-
- const contentDiv = document.createElement('div');
- contentDiv.className = 'flex-1';
-
- const sourceP = document.createElement('p');
- sourceP.className = 'text-sm font-medium text-gray-900';
- sourceP.textContent = notification.source === 'squid' ? 'Squid' :
- notification.source === 'git' ? 'Git' : 'Sistema';
-
- const messageP = document.createElement('p');
- messageP.className = 'text-sm text-gray-700 mt-1';
- messageP.textContent = notification.message;
-
- const timeSpan = document.createElement('span');
- timeSpan.className = 'text-xs text-gray-400 mt-1';
- timeSpan.textContent = notification.time;
-
- contentDiv.appendChild(sourceP);
- contentDiv.appendChild(messageP);
- contentDiv.appendChild(timeSpan);
-
- li.appendChild(iconSpan);
- li.appendChild(contentDiv);
-
- if (!notification.read) {
- const badge = document.createElement('span');
- badge.className = 'w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0';
- li.appendChild(badge);
- }
-
- ul.appendChild(li);
- });
- } else {
- ul.innerHTML = `
- <li class='px-4 py-3 text-gray-500 text-center'>
- No hay notificaciones nuevas
- </li>
- `;
- }
- };
- renderNotificationList(desktopUl, notificationsData.notifications);
- renderNotificationList(mobileUl, notificationsData.notifications);
- }
- function updateNotificationBadges(count) {
- const badges = document.querySelectorAll('.notification-badge');
- badges.forEach(badge => {
- if (count > 0) {
- badge.textContent = count > 99 ? '99+' : count.toString();
- badge.classList.remove('hidden');
- } else {
- badge.classList.add('hidden');
- }
- });
- }
- function markAsRead(notificationIds) {
- const csrfToken = getCSRFToken();
- fetch('/api/notifications/mark-read', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRF-Token': csrfToken,
- },
- body: JSON.stringify({
- ids: notificationIds
- })
- })
- .then(response => {
- if (!response.ok) {
- throw new Error(`Error HTTP: ${response.status}`);
- }
- return response.json();
- })
- .then(data => {
- if (data.success) {
- // CORRECCIÓN: Filtrar notificaciones marcadas del estado local
- notificationsData.notifications = notificationsData.notifications.filter(
- notification => !notificationIds.includes(notification.id)
- );
-
- notificationsData.unread_count = data.unread_count;
- updateNotificationBadges(data.unread_count);
- updateNotificationLists();
- } else {
- console.error('Error del servidor al marcar como leída:', data.error);
- showNotificationToast({
- type: 'error',
- message: 'Error al marcar notificación como leída: ' + (data.error || 'Error desconocido')
- });
- }
- })
- .catch(error => {
- showNotificationToast({
- type: 'error',
- message: 'Error al marcar notificación como leída: ' + error.message
- });
- });
- }
- function fetchInitialNotifications() {
- fetch("/api/notifications")
- .then((res) => {
- if (!res.ok) {
- throw new Error(`Error HTTP: ${res.status}`);
- }
- return res.json();
- })
- .then((data) => {
- // REEMPLAZAR completamente el estado local
- notificationsData.notifications = data.notifications || [];
- notificationsData.unread_count = data.unread_count || 0;
- updateNotificationLists();
- updateNotificationBadges(data.unread_count);
- })
- .catch((error) => {
- console.error('Error fetching notifications:', error);
- notificationsData.notifications = [];
- notificationsData.unread_count = 0;
- updateNotificationLists();
- updateNotificationBadges(0);
- });
- }
- // Event listeners para marcar como leído
- document.addEventListener('click', function(e) {
- const notificationItem = e.target.closest('.notification-item');
- if (notificationItem) {
- const notificationId = parseInt(notificationItem.dataset.id);
- markAsRead([notificationId]);
- }
- });
- // Inicializar
- fetchInitialNotifications();
- connectWebSocket();
- }
- // Update indicators: animated badges/glows when Squid or Web updates are available
- function initUpdateIndicators() {
- const UI = {
- squid: {
- btn: document.getElementById('squid-update-btn'),
- badge: document.getElementById('squid-update-badge'),
- icon: document.getElementById('squid-update-icon'),
- tooltip: document.getElementById('squid-update-tooltip'),
- mobileBtn: document.getElementById('squid-update-btn-mobile'),
- mobileIcon: document.getElementById('squid-update-icon-mobile'),
- mobileChip: document.getElementById('squid-update-chip-mobile'),
- },
- web: {
- btn: document.getElementById('web-update-btn'),
- badge: document.getElementById('web-update-badge'),
- icon: document.getElementById('web-update-icon'),
- tooltip: document.getElementById('web-update-tooltip'),
- mobileBtn: document.getElementById('web-update-btn-mobile'),
- mobileIcon: document.getElementById('web-update-icon-mobile'),
- mobileChip: document.getElementById('web-update-chip-mobile'),
- }
- };
- function updateUi(type, status) {
- const el = UI[type];
- if (!el || !el.btn) return;
- const baseTooltip = el.btn.getAttribute('data-base-tooltip') || '';
- const hasUpdate = status && status.available && status.latest;
- // Desktop badge
- if (el.badge) {
- if (hasUpdate) {
- el.badge.classList.remove('hidden');
- requestAnimationFrame(() => el.badge.classList.add('is-visible'));
- } else {
- el.badge.classList.remove('is-visible');
- setTimeout(() => el.badge.classList.add('hidden'), 350);
- }
- }
- // Desktop glow/ripple
- if (el.btn) {
- const glowClass = type === 'squid' ? 'update-available--squid' : 'update-available--web';
- if (hasUpdate) {
- el.btn.classList.add('update-available', glowClass);
- } else {
- el.btn.classList.remove('update-available', 'update-available--squid', 'update-available--web');
- }
- }
- // Desktop icon attention
- if (el.icon) {
- if (hasUpdate) {
- el.icon.classList.add('update-icon-attention');
- } else {
- el.icon.classList.remove('update-icon-attention');
- }
- }
- // Desktop tooltip
- if (el.tooltip) {
- if (hasUpdate) {
- const msg = type === 'squid'
- ? {{ _('Nueva versión de Squid disponible:')|tojson }} + ' ' + status.latest
- : {{ _('Nueva versión de SquidStats disponible:')|tojson }} + ' ' + status.latest;
- el.tooltip.textContent = msg;
- } else {
- el.tooltip.textContent = baseTooltip;
- }
- }
- // Mobile chip
- if (el.mobileChip) {
- if (hasUpdate) {
- el.mobileChip.classList.remove('hidden');
- requestAnimationFrame(() => el.mobileChip.classList.add('is-visible'));
- } else {
- el.mobileChip.classList.remove('is-visible');
- setTimeout(() => el.mobileChip.classList.add('hidden'), 350);
- }
- }
- // Mobile icon attention
- if (el.mobileIcon) {
- if (hasUpdate) {
- el.mobileIcon.classList.add('update-icon-attention');
- } else {
- el.mobileIcon.classList.remove('update-icon-attention');
- }
- }
- }
- function fetchUpdateStatus() {
- const cached = sessionStorage.getItem('squidstats_update_status');
- const cachedAt = sessionStorage.getItem('squidstats_update_status_at');
- const ttl = 5 * 60 * 1000; // 5 minutos
- if (cached && cachedAt && (Date.now() - parseInt(cachedAt, 10)) < ttl) {
- try {
- const data = JSON.parse(cached);
- updateUi('squid', data.squid);
- updateUi('web', data.web);
- return;
- } catch (e) {
- // continuar a fetch fresco
- }
- }
- fetch('/api/update-status')
- .then(res => {
- if (!res.ok) throw new Error('HTTP ' + res.status);
- return res.json();
- })
- .then(data => {
- sessionStorage.setItem('squidstats_update_status', JSON.stringify(data));
- sessionStorage.setItem('squidstats_update_status_at', Date.now().toString());
- updateUi('squid', data.squid);
- updateUi('web', data.web);
- })
- .catch(err => {
- console.warn('No se pudo obtener el estado de actualizaciones:', err);
- // En caso de error, ocultar indicadores para no mostrar información stale
- updateUi('squid', { available: false });
- updateUi('web', { available: false });
- });
- }
- fetchUpdateStatus();
- }
-
- // Initialize all functionality
- initTooltips();
- initNavbarScroll();
- setActiveLink();
- initNotifications();
- initUpdateIndicators();
- });
- // Close modals when clicking outside
- document.addEventListener("click", function (e) {
- if (e.target.classList.contains("modal-overlay")) {
- const modals = document.querySelectorAll("[x-show]");
- modals.forEach((modal) => {
- const alpineData = Alpine.$data(modal);
- if (alpineData) {
- alpineData.showSquidModal = false;
- alpineData.showWebModal = false;
- }
- });
- }
- });
- // Add escape key handling for modals
- document.addEventListener("keydown", function (e) {
- if (e.key === "Escape") {
- const modals = document.querySelectorAll("[x-show]");
- modals.forEach((modal) => {
- const alpineData = Alpine.$data(modal);
- if (alpineData) {
- alpineData.showSquidModal = false;
- alpineData.showWebModal = false;
- }
- });
- }
- });
- // Mobile menu close on outside click
- document.addEventListener('click', function(event) {
- const mobileMenu = document.querySelector('[x-data]');
- const hamburger = document.querySelector('.lg\\:hidden');
- const mobileMenuContent = document.querySelector('.absolute.top-full');
-
- if (mobileMenuContent && mobileMenuContent.style.display !== 'none') {
- const isClickInside = hamburger.contains(event.target) || mobileMenuContent.contains(event.target);
-
- if (!isClickInside) {
- const alpineData = Alpine.$data(mobileMenu);
- if (alpineData) {
- alpineData.mobileMenuOpen = false;
- }
- }
- }
- });
- // Función para obtener el token CSRF
- function getCSRFToken() {
- const metaTag = document.querySelector('meta[name="csrf-token"]');
- return metaTag ? metaTag.getAttribute('content') : '';
- }
- // Funciones de confirmación para actualizaciones
- function confirmSquidUpdate() {
- showCustomConfirm(
- {{ _('¿Estás seguro de que deseas actualizar el servicio Squid? Guarda tu configuración antes de continuar, el servicio se reiniciará automáticamente.')|tojson }},
- async () => {
- try {
- const response = await fetch('/install', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'Accept': 'application/json',
- 'X-CSRFToken': getCSRFToken()
- },
- body: new URLSearchParams({ csrf_token: getCSRFToken() })
- });
- const data = await response.json().catch(() => ({}));
- if (response.ok && data.status === 'success') {
- window.location.reload();
- } else {
- const message = data.message || {{ _('Error al actualizar Squid')|tojson }};
- if (window.toastr) {
- toastr.error(message, {{ _('Error al actualizar Squid')|tojson }});
- } else {
- alert(message);
- }
- }
- } catch (error) {
- alert({{ _('Error de conexión')|tojson }});
- }
- }
- );
- }
- function confirmWebUpdate() {
- if (IS_DEB_INSTALL) {
- showCustomConfirm(
- {{ _("Esta instalación fue realizada con un paquete .deb y no puede actualizarse desde aquí. Para actualizar, descargue e instale la última versión desde GitHub Releases: https://github.com/kaelthasmanu/SquidStats/releases/latest") | tojson }},
- function() {},
- { onlyClose: true }
- );
- return;
- }
- showCustomConfirm(
- {{ _('¿Estás seguro de que deseas actualizar SquidStats? Se actualizará la interfaz web, funcionalidades y correcciones de seguridad.')|tojson }},
- async () => {
- try {
- const response = await fetch('/update', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'X-CSRFToken': getCSRFToken()
- },
- body: new URLSearchParams({ csrf_token: getCSRFToken() })
- });
- if (response.ok) {
- window.location.reload();
- } else {
- alert({{ _('Error al actualizar la aplicación web')|tojson }});
- }
- } catch (error) {
- alert({{ _('Error de conexión')|tojson }});
- }
- }
- );
- }
- // Nav loading spinner for slow pages (e.g. /blacklist)
- (function () {
- function initNavLoadingOverlay() {
- var style = document.createElement('style');
- style.textContent = '@keyframes nav-spin{to{transform:rotate(360deg)}} #nav-loading-overlay .nav-spinner{width:48px;height:48px;border:4px solid #bfdbfe;border-top-color:#3b82f6;border-radius:50%;animation:nav-spin .8s linear infinite}';
- document.head.appendChild(style);
- var overlay = document.createElement('div');
- overlay.id = 'nav-loading-overlay';
- overlay.style.cssText = 'display:none;position:fixed;inset:0;z-index:9999;background:rgba(239,246,255,.85);backdrop-filter:blur(2px);align-items:center;justify-content:center';
- overlay.innerHTML = '<div class="nav-spinner"></div>';
- document.body.appendChild(overlay);
- document.addEventListener('click', function (e) {
- var link = e.target.closest('[data-nav-loading]');
- if (!link) return;
- overlay.style.display = 'flex';
- window.addEventListener('pageshow', function () { overlay.style.display = 'none'; }, { once: true });
- });
- }
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', initNavLoadingOverlay);
- } else {
- initNavLoadingOverlay();
- }
- }());
- </script>
|