navbar.html 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. <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 }">
  2. <!-- UNIFIED CONTAINER WITH THE REST -->
  3. <div class="w-full px-4 sm:px-6 lg:px-8">
  4. <div class="max-w-7xl mx-auto flex items-center justify-between py-4 h-[64px]">
  5. <!-- Brand/Logo Section -->
  6. <div class="flex items-center gap-3 font-bold text-xl text-white no-underline">
  7. <img src="{{ url_for('static', filename='squidstats-64.webp') }}" alt="" width="32" height="32" class="h-8 w-8 object-contain rounded-md" />
  8. <span class="font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-white to-blue-300">{{ _("SquidStats") }}</span>
  9. </div>
  10. <!-- Container for mobile icons (notifications + hamburger) -->
  11. <div class="lg:hidden flex items-center gap-3">
  12. <!-- Mobile Notifications Button -->
  13. <div class="relative" x-data="{ open: false }">
  14. <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") }}">
  15. <i class="fas fa-bell"></i>
  16. <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>
  17. </button>
  18. <!-- Mobile notifications dropdown -->
  19. <div x-show="open"
  20. @click.away="open = false"
  21. @keydown.escape.window="open = false"
  22. x-transition:enter="transition ease-out duration-200"
  23. x-transition:enter-start="opacity-0 scale-95"
  24. x-transition:enter-end="opacity-100 scale-100"
  25. x-transition:leave="transition ease-in duration-150"
  26. x-transition:leave-start="opacity-100 scale-100"
  27. x-transition:leave-end="opacity-0 scale-95"
  28. 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"
  29. style="display: none">
  30. <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
  31. <span class="font-semibold text-gray-800">{{ _("Notificaciones") }}</span>
  32. <button type="button" aria-label="{{ _('Cerrar notificaciones') }}" @click="open = false" class="text-gray-500 hover:text-gray-700 focus:outline-none">
  33. <i class="fas fa-times"></i>
  34. </button>
  35. </div>
  36. <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications-mobile">
  37. <li class="px-4 py-3 text-gray-500 text-center">
  38. {{ _("Cargando notificaciones...") }}
  39. </li>
  40. </ul>
  41. <div class="py-2 px-4 text-center border-t border-gray-200">
  42. <a href="/all-notifications" class="text-sm text-blue-600 hover:underline">{{ _("Ver todas las notificaciones") }}</a>
  43. </div>
  44. </div>
  45. </div>
  46. <!-- Hamburger Button for Mobile -->
  47. <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") }}">
  48. <span class="w-6 h-0.5 bg-white transition-all" :class="{'rotate-45 translate-y-2': mobileMenuOpen}"></span>
  49. <span class="w-6 h-0.5 bg-white transition-all" :class="{'opacity-0': mobileMenuOpen}"></span>
  50. <span class="w-6 h-0.5 bg-white transition-all" :class="{'-rotate-45 -translate-y-2': mobileMenuOpen}"></span>
  51. </button>
  52. </div>
  53. <!-- Navigation Links - Desktop -->
  54. <div class="hidden lg:flex items-center gap-2 lg:ml-10">
  55. <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") }}">
  56. <i class="fas fa-home text-base"></i>
  57. <span class="font-medium">{{ _("Inicio") }}</span>
  58. </a>
  59. <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") }}">
  60. <i class="fas fa-chart-bar text-base"></i>
  61. <span class="font-medium">{{ _("Estadísticas") }}</span>
  62. </a>
  63. <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") }}">
  64. <i class="fas fa-user-friends text-base"></i>
  65. <span class="font-medium">{{ _("Usuarios") }}</span>
  66. </a>
  67. <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") }}">
  68. <i class="fas fa-chart-simple text-base"></i>
  69. <span class="font-medium">{{ _("Reportes") }}</span>
  70. </a>
  71. <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") }}">
  72. <i class="fas fa-ban text-base"></i>
  73. <span class="font-medium">{{ _("Blacklist") }}</span>
  74. </a>
  75. <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") }}">
  76. <i class="fas fa-magnifying-glass text-base"></i>
  77. <span class="font-medium">{{ _("Auditoría") }}</span>
  78. </a>
  79. </div>
  80. <!-- Desktop Notifications -->
  81. <div class="hidden lg:flex items-center gap-3">
  82. <div class="relative" x-data="{ open: false }">
  83. <!-- Desktop Notifications Button -->
  84. <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") }}">
  85. <i class="fas fa-bell"></i>
  86. <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>
  87. </button>
  88. <!-- Desktop notifications dropdown -->
  89. <div x-show="open"
  90. @click.away="open = false"
  91. @keydown.escape.window="open = false"
  92. x-transition:enter="transition ease-out duration-200"
  93. x-transition:enter-start="opacity-0 scale-95"
  94. x-transition:enter-end="opacity-100 scale-100"
  95. x-transition:leave="transition ease-in duration-150"
  96. x-transition:leave-start="opacity-100 scale-100"
  97. x-transition:leave-end="opacity-0 scale-95"
  98. 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"
  99. style="display: none">
  100. <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
  101. <span class="font-semibold text-gray-800">{{ _("Notificaciones") }}</span>
  102. <button type="button" aria-label="{{ _('Cerrar notificaciones') }}" @click="open = false" class="text-gray-500 hover:text-gray-700 focus:outline-none">
  103. <i class="fas fa-times"></i>
  104. </button>
  105. </div>
  106. <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications">
  107. <li class="px-4 py-3 text-gray-500 text-center">
  108. {{ _("Cargando notificaciones...") }}
  109. </li>
  110. </ul>
  111. <div class="py-2 px-4 text-center border-t border-gray-200">
  112. <a href="/all-notifications" class="text-sm text-blue-600 hover:underline">{{ _("Ver todas las notificaciones") }}</a>
  113. </div>
  114. </div>
  115. </div>
  116. <!-- Action Buttons - Desktop -->
  117. <div class="flex items-center gap-3">
  118. <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") }}">
  119. <i class="fas fa-cog"></i>
  120. <span>{{ _("Admin") }}</span>
  121. </a>
  122. <div class="update-btn-wrapper relative inline-block group">
  123. <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") }}">
  124. <span id="squid-update-badge" class="update-badge update-badge--squid hidden">1</span>
  125. <i id="squid-update-icon" class="fas fa-sync-alt"></i>
  126. <span>{{ _("Squid") }}</span>
  127. </button>
  128. <div id="squid-update-tooltip" class="update-tooltip"></div>
  129. </div>
  130. <div class="update-btn-wrapper relative inline-block group">
  131. <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") }}">
  132. <span id="web-update-badge" class="update-badge update-badge--web hidden">1</span>
  133. <i id="web-update-icon" class="fas fa-cloud-download-alt"></i>
  134. <span>{{ _("Web") }}</span>
  135. </button>
  136. <div id="web-update-tooltip" class="update-tooltip"></div>
  137. </div>
  138. <!-- Language Switcher -->
  139. <div class="relative" x-data="{ langOpen: false }">
  140. <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') }}">
  141. <i class="fas fa-globe"></i>
  142. <span class="uppercase">{{ get_locale() }}</span>
  143. </button>
  144. <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;">
  145. {% for code, name in LANGUAGES.items() %}
  146. <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 %}">
  147. {{ name }}
  148. {% if get_locale() == code %}<i class="fas fa-check ml-auto text-blue-500"></i>{% endif %}
  149. </a>
  150. {% endfor %}
  151. </div>
  152. </div>
  153. </div>
  154. </div>
  155. </div>
  156. </div>
  157. <!-- Mobile Menu Overlay -->
  158. <div x-show="mobileMenuOpen" @click="mobileMenuOpen = false" class="fixed inset-0 bg-black bg-opacity-50 z-[999] lg:hidden" style="display: none;">
  159. </div>
  160. <!-- Mobile Menu Content -->
  161. <div x-show="mobileMenuOpen"
  162. x-transition:enter="transition ease-out duration-300"
  163. x-transition:enter-start="opacity-0 transform -translate-y-4"
  164. x-transition:enter-end="opacity-100 transform translate-y-0"
  165. x-transition:leave="transition ease-in duration-200"
  166. x-transition:leave-start="opacity-100 transform translate-y-0"
  167. x-transition:leave-end="opacity-0 transform -translate-y-4"
  168. 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"
  169. style="display: none;">
  170. <div class="p-6">
  171. <!-- Mobile Navigation Links -->
  172. <div class="flex flex-col gap-2 mb-8">
  173. <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">
  174. <i class="fas fa-home text-lg"></i>
  175. <span>{{ _("Inicio") }}</span>
  176. </a>
  177. <a
  178. href="/stats" @click="mobileMenuOpen = false"
  179. 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">
  180. <i class="fas fa-chart-bar text-lg"></i>
  181. <span>{{ _("Estadísticas") }}</span>
  182. </a>
  183. <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">
  184. <i class="fas fa-user-friends text-lg"></i>
  185. <span>{{ _("Usuarios") }}</span>
  186. </a>
  187. <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">
  188. <i class="fas fa-chart-simple text-lg"></i>
  189. <span>{{ _("Reportes") }}</span>
  190. </a>
  191. <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">
  192. <i class="fas fa-ban text-lg"></i>
  193. <span>{{ _("Blacklist") }}</span>
  194. </a>
  195. <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">
  196. <i class="fas fa-magnifying-glass text-lg"></i>
  197. <span>{{ _("Auditoría") }}</span>
  198. </a>
  199. </div>
  200. <!-- Squid and Web buttons in a row -->
  201. <div class="flex flex-row gap-3 mb-8">
  202. <div class="flex flex-1 gap-2">
  203. <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">
  204. <i class="fas fa-cog"></i>
  205. <span>{{ _("Admin") }}</span>
  206. </a>
  207. <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">
  208. <i id="squid-update-icon-mobile" class="fas fa-sync-alt"></i>
  209. <span class="flex items-center gap-2">{{ _("Squid") }} <span id="squid-update-chip-mobile" class="update-chip update-chip--squid hidden">NEW</span></span>
  210. </button>
  211. <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">
  212. <i id="web-update-icon-mobile" class="fas fa-cloud-download-alt"></i>
  213. <span class="flex items-center gap-2">{{ _("Web") }} <span id="web-update-chip-mobile" class="update-chip update-chip--web hidden">NEW</span></span>
  214. </button>
  215. </div>
  216. </div>
  217. <!-- Language Switcher - Mobile -->
  218. <div class="flex gap-2 mb-4">
  219. {% for code, name in LANGUAGES.items() %}
  220. <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 %}">
  221. <i class="fas fa-globe"></i>
  222. <span>{{ name }}</span>
  223. {% if get_locale() == code %}<i class="fas fa-check text-xs"></i>{% endif %}
  224. </a>
  225. {% endfor %}
  226. </div>
  227. </div>
  228. </div>
  229. </div>
  230. </nav>
  231. <!-- Custom Confirm Modal -->
  232. {% include 'components/confirm_modal.html' %}
  233. <!-- Update indicators CSS -->
  234. <link rel="stylesheet" href="{{ url_for('static', filename='css/update-indicators.css') }}" />
  235. <!-- Scripts -->
  236. <script src="{{ url_for('static', filename='src/tailwind.min.js') }}"></script>
  237. <script defer src="{{ url_for('static', filename='src/alpine.min.js') }}"></script>
  238. <script src="{{ url_for('static', filename='js/confirm_modal.js') }}"></script>
  239. <script>
  240. const IS_DEB_INSTALL = {{ is_deb_install | tojson }};
  241. // Enhanced Navbar Functionality with Real-time Notifications
  242. document.addEventListener("DOMContentLoaded", function () {
  243. // Tooltip functionality
  244. function initTooltips() {
  245. const elements = document.querySelectorAll('[data-tooltip]');
  246. elements.forEach(element => {
  247. const tooltipText = element.getAttribute('data-tooltip');
  248. const tooltip = document.createElement('div');
  249. 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';
  250. tooltip.textContent = tooltipText;
  251. element.appendChild(tooltip);
  252. element.addEventListener('mouseenter', function() {
  253. tooltip.classList.remove('invisible', 'opacity-0');
  254. tooltip.classList.add('visible', 'opacity-100');
  255. });
  256. element.addEventListener('mouseleave', function() {
  257. tooltip.classList.remove('visible', 'opacity-100');
  258. tooltip.classList.add('invisible', 'opacity-0');
  259. });
  260. });
  261. }
  262. // Navbar scroll effect
  263. function initNavbarScroll() {
  264. const navbar = document.querySelector('nav');
  265. let lastScrollY = window.scrollY;
  266. window.addEventListener('scroll', () => {
  267. if (window.scrollY > lastScrollY && window.scrollY > 100) {
  268. navbar.style.transform = 'translateY(-100%)';
  269. } else {
  270. navbar.style.transform = 'translateY(0)';
  271. }
  272. lastScrollY = window.scrollY;
  273. });
  274. }
  275. // Active link highlighting
  276. function setActiveLink() {
  277. const currentPath = window.location.pathname;
  278. const links = document.querySelectorAll('nav a[href]');
  279. links.forEach(link => {
  280. if (link.getAttribute('href') === currentPath) {
  281. link.classList.add('text-white', 'bg-white/20');
  282. link.classList.remove('text-gray-200', 'hover:bg-white/10');
  283. }
  284. });
  285. }
  286. // Función para obtener el token CSRF de forma segura
  287. function getCSRFToken() {
  288. const metaTag = document.querySelector('meta[name="csrf-token"]');
  289. if (metaTag) {
  290. return metaTag.getAttribute('content');
  291. }
  292. console.warn('CSRF token meta tag no encontrado');
  293. return '';
  294. }
  295. // Enhanced Notifications System with WebSocket
  296. function initNotifications() {
  297. let notificationSocket = null;
  298. let notificationsData = {
  299. unread_count: 0,
  300. notifications: []
  301. };
  302. // Conectar WebSocket
  303. function connectWebSocket() {
  304. // Flask-SocketIO se conecta automáticamente al host actual
  305. notificationSocket = io();
  306. notificationSocket.on('connect', function() {
  307. console.log('Conectado al servidor de notificaciones Squid');
  308. });
  309. notificationSocket.on('new_notification', function(data) {
  310. addNewNotification(data.notification);
  311. updateNotificationBadges(data.unread_count);
  312. showNotificationToast(data.notification);
  313. });
  314. notificationSocket.on('notification_updated', function(data) {
  315. console.log('Notificación actualizada recibida:', data);
  316. updateExistingNotification(data.notification);
  317. updateNotificationBadges(data.unread_count);
  318. showNotificationToast(data.notification);
  319. });
  320. notificationSocket.on('disconnect', function() {
  321. // Reconectar después de 5 segundos
  322. setTimeout(connectWebSocket, 5000);
  323. });
  324. }
  325. function addNewNotification(notification) {
  326. // Evitar duplicados por ID
  327. const existingIndex = notificationsData.notifications.findIndex(n => n.id === notification.id);
  328. if (existingIndex === -1) {
  329. notificationsData.notifications.unshift(notification);
  330. if (!notification.read) {
  331. notificationsData.unread_count++;
  332. }
  333. // Actualizar ambas listas (desktop y móvil)
  334. updateNotificationLists();
  335. updateNotificationBadges(notificationsData.unread_count);
  336. }
  337. }
  338. function updateExistingNotification(notification) {
  339. // Buscar y actualizar la notificación existente
  340. const existingIndex = notificationsData.notifications.findIndex(n => n.id === notification.id);
  341. if (existingIndex !== -1) {
  342. // Actualizar la notificación existente
  343. notificationsData.notifications[existingIndex] = notification;
  344. // Moverla al principio de la lista
  345. const updated = notificationsData.notifications.splice(existingIndex, 1)[0];
  346. notificationsData.notifications.unshift(updated);
  347. } else {
  348. // Si no existe, agregarla como nueva
  349. notificationsData.notifications.unshift(notification);
  350. }
  351. // Actualizar ambas listas (desktop y móvil)
  352. updateNotificationLists();
  353. }
  354. function showNotificationToast(notification) {
  355. if (!window.toastr) return;
  356. // Construir el título con la fuente
  357. const source = notification.source === 'squid' ? 'Squid' :
  358. notification.source === 'git' ? 'Git' : 'Sistema';
  359. const title = notification.count && notification.count > 1 ?
  360. `${source} (×${notification.count})` : source;
  361. // Mostrar notificación según el tipo
  362. if (notification.type === 'error') {
  363. toastr.error(notification.message, title);
  364. } else if (notification.type === 'warning') {
  365. toastr.warning(notification.message, title);
  366. } else if (notification.type === 'success') {
  367. toastr.success(notification.message, title);
  368. } else {
  369. toastr.info(notification.message, title);
  370. }
  371. }
  372. function updateNotificationLists() {
  373. const desktopUl = document.querySelector(".notifications");
  374. const mobileUl = document.querySelector(".notifications-mobile");
  375. const renderNotificationList = (ul, notifications) => {
  376. if (!ul) return;
  377. ul.innerHTML = "";
  378. // Usar el estado local actual - SOLO notificaciones no leídas
  379. const unreadNotifications = notificationsData.notifications.filter(n => !n.read);
  380. const notificationsToShow = unreadNotifications.slice(0, 10);
  381. if (notificationsToShow.length > 0) {
  382. notificationsToShow.forEach((notification) => {
  383. let bgColor, textColor;
  384. switch(notification.type) {
  385. case 'success':
  386. bgColor = 'bg-green-100';
  387. textColor = 'text-green-600';
  388. break;
  389. case 'warning':
  390. bgColor = 'bg-yellow-100';
  391. textColor = 'text-yellow-600';
  392. break;
  393. case 'error':
  394. bgColor = 'bg-red-100';
  395. textColor = 'text-red-600';
  396. break;
  397. case 'info':
  398. default:
  399. bgColor = 'bg-blue-100';
  400. textColor = 'text-blue-600';
  401. }
  402. // Create list item safely
  403. const li = document.createElement('li');
  404. li.className = `px-4 py-3 flex items-start hover:bg-gray-50 cursor-pointer notification-item ${
  405. notification.read ? 'opacity-60' : ''
  406. }`;
  407. li.dataset.id = notification.id;
  408. const iconSpan = document.createElement('span');
  409. iconSpan.className = `inline-flex items-center justify-center h-8 w-8 rounded-full ${bgColor} ${textColor} mr-3`;
  410. const icon = document.createElement('i');
  411. icon.className = `fas ${notification.icon}`;
  412. iconSpan.appendChild(icon);
  413. const contentDiv = document.createElement('div');
  414. contentDiv.className = 'flex-1';
  415. const sourceP = document.createElement('p');
  416. sourceP.className = 'text-sm font-medium text-gray-900';
  417. sourceP.textContent = notification.source === 'squid' ? 'Squid' :
  418. notification.source === 'git' ? 'Git' : 'Sistema';
  419. const messageP = document.createElement('p');
  420. messageP.className = 'text-sm text-gray-700 mt-1';
  421. messageP.textContent = notification.message;
  422. const timeSpan = document.createElement('span');
  423. timeSpan.className = 'text-xs text-gray-400 mt-1';
  424. timeSpan.textContent = notification.time;
  425. contentDiv.appendChild(sourceP);
  426. contentDiv.appendChild(messageP);
  427. contentDiv.appendChild(timeSpan);
  428. li.appendChild(iconSpan);
  429. li.appendChild(contentDiv);
  430. if (!notification.read) {
  431. const badge = document.createElement('span');
  432. badge.className = 'w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0';
  433. li.appendChild(badge);
  434. }
  435. ul.appendChild(li);
  436. });
  437. } else {
  438. ul.innerHTML = `
  439. <li class='px-4 py-3 text-gray-500 text-center'>
  440. No hay notificaciones nuevas
  441. </li>
  442. `;
  443. }
  444. };
  445. renderNotificationList(desktopUl, notificationsData.notifications);
  446. renderNotificationList(mobileUl, notificationsData.notifications);
  447. }
  448. function updateNotificationBadges(count) {
  449. const badges = document.querySelectorAll('.notification-badge');
  450. badges.forEach(badge => {
  451. if (count > 0) {
  452. badge.textContent = count > 99 ? '99+' : count.toString();
  453. badge.classList.remove('hidden');
  454. } else {
  455. badge.classList.add('hidden');
  456. }
  457. });
  458. }
  459. function markAsRead(notificationIds) {
  460. const csrfToken = getCSRFToken();
  461. fetch('/api/notifications/mark-read', {
  462. method: 'POST',
  463. headers: {
  464. 'Content-Type': 'application/json',
  465. 'X-CSRF-Token': csrfToken,
  466. },
  467. body: JSON.stringify({
  468. ids: notificationIds
  469. })
  470. })
  471. .then(response => {
  472. if (!response.ok) {
  473. throw new Error(`Error HTTP: ${response.status}`);
  474. }
  475. return response.json();
  476. })
  477. .then(data => {
  478. if (data.success) {
  479. // CORRECCIÓN: Filtrar notificaciones marcadas del estado local
  480. notificationsData.notifications = notificationsData.notifications.filter(
  481. notification => !notificationIds.includes(notification.id)
  482. );
  483. notificationsData.unread_count = data.unread_count;
  484. updateNotificationBadges(data.unread_count);
  485. updateNotificationLists();
  486. } else {
  487. console.error('Error del servidor al marcar como leída:', data.error);
  488. showNotificationToast({
  489. type: 'error',
  490. message: 'Error al marcar notificación como leída: ' + (data.error || 'Error desconocido')
  491. });
  492. }
  493. })
  494. .catch(error => {
  495. showNotificationToast({
  496. type: 'error',
  497. message: 'Error al marcar notificación como leída: ' + error.message
  498. });
  499. });
  500. }
  501. function fetchInitialNotifications() {
  502. fetch("/api/notifications")
  503. .then((res) => {
  504. if (!res.ok) {
  505. throw new Error(`Error HTTP: ${res.status}`);
  506. }
  507. return res.json();
  508. })
  509. .then((data) => {
  510. // REEMPLAZAR completamente el estado local
  511. notificationsData.notifications = data.notifications || [];
  512. notificationsData.unread_count = data.unread_count || 0;
  513. updateNotificationLists();
  514. updateNotificationBadges(data.unread_count);
  515. })
  516. .catch((error) => {
  517. console.error('Error fetching notifications:', error);
  518. notificationsData.notifications = [];
  519. notificationsData.unread_count = 0;
  520. updateNotificationLists();
  521. updateNotificationBadges(0);
  522. });
  523. }
  524. // Event listeners para marcar como leído
  525. document.addEventListener('click', function(e) {
  526. const notificationItem = e.target.closest('.notification-item');
  527. if (notificationItem) {
  528. const notificationId = parseInt(notificationItem.dataset.id);
  529. markAsRead([notificationId]);
  530. }
  531. });
  532. // Inicializar
  533. fetchInitialNotifications();
  534. connectWebSocket();
  535. }
  536. // Update indicators: animated badges/glows when Squid or Web updates are available
  537. function initUpdateIndicators() {
  538. const UI = {
  539. squid: {
  540. btn: document.getElementById('squid-update-btn'),
  541. badge: document.getElementById('squid-update-badge'),
  542. icon: document.getElementById('squid-update-icon'),
  543. tooltip: document.getElementById('squid-update-tooltip'),
  544. mobileBtn: document.getElementById('squid-update-btn-mobile'),
  545. mobileIcon: document.getElementById('squid-update-icon-mobile'),
  546. mobileChip: document.getElementById('squid-update-chip-mobile'),
  547. },
  548. web: {
  549. btn: document.getElementById('web-update-btn'),
  550. badge: document.getElementById('web-update-badge'),
  551. icon: document.getElementById('web-update-icon'),
  552. tooltip: document.getElementById('web-update-tooltip'),
  553. mobileBtn: document.getElementById('web-update-btn-mobile'),
  554. mobileIcon: document.getElementById('web-update-icon-mobile'),
  555. mobileChip: document.getElementById('web-update-chip-mobile'),
  556. }
  557. };
  558. function updateUi(type, status) {
  559. const el = UI[type];
  560. if (!el || !el.btn) return;
  561. const baseTooltip = el.btn.getAttribute('data-base-tooltip') || '';
  562. const hasUpdate = status && status.available && status.latest;
  563. // Desktop badge
  564. if (el.badge) {
  565. if (hasUpdate) {
  566. el.badge.classList.remove('hidden');
  567. requestAnimationFrame(() => el.badge.classList.add('is-visible'));
  568. } else {
  569. el.badge.classList.remove('is-visible');
  570. setTimeout(() => el.badge.classList.add('hidden'), 350);
  571. }
  572. }
  573. // Desktop glow/ripple
  574. if (el.btn) {
  575. const glowClass = type === 'squid' ? 'update-available--squid' : 'update-available--web';
  576. if (hasUpdate) {
  577. el.btn.classList.add('update-available', glowClass);
  578. } else {
  579. el.btn.classList.remove('update-available', 'update-available--squid', 'update-available--web');
  580. }
  581. }
  582. // Desktop icon attention
  583. if (el.icon) {
  584. if (hasUpdate) {
  585. el.icon.classList.add('update-icon-attention');
  586. } else {
  587. el.icon.classList.remove('update-icon-attention');
  588. }
  589. }
  590. // Desktop tooltip
  591. if (el.tooltip) {
  592. if (hasUpdate) {
  593. const msg = type === 'squid'
  594. ? {{ _('Nueva versión de Squid disponible:')|tojson }} + ' ' + status.latest
  595. : {{ _('Nueva versión de SquidStats disponible:')|tojson }} + ' ' + status.latest;
  596. el.tooltip.textContent = msg;
  597. } else {
  598. el.tooltip.textContent = baseTooltip;
  599. }
  600. }
  601. // Mobile chip
  602. if (el.mobileChip) {
  603. if (hasUpdate) {
  604. el.mobileChip.classList.remove('hidden');
  605. requestAnimationFrame(() => el.mobileChip.classList.add('is-visible'));
  606. } else {
  607. el.mobileChip.classList.remove('is-visible');
  608. setTimeout(() => el.mobileChip.classList.add('hidden'), 350);
  609. }
  610. }
  611. // Mobile icon attention
  612. if (el.mobileIcon) {
  613. if (hasUpdate) {
  614. el.mobileIcon.classList.add('update-icon-attention');
  615. } else {
  616. el.mobileIcon.classList.remove('update-icon-attention');
  617. }
  618. }
  619. }
  620. function fetchUpdateStatus() {
  621. const cached = sessionStorage.getItem('squidstats_update_status');
  622. const cachedAt = sessionStorage.getItem('squidstats_update_status_at');
  623. const ttl = 5 * 60 * 1000; // 5 minutos
  624. if (cached && cachedAt && (Date.now() - parseInt(cachedAt, 10)) < ttl) {
  625. try {
  626. const data = JSON.parse(cached);
  627. updateUi('squid', data.squid);
  628. updateUi('web', data.web);
  629. return;
  630. } catch (e) {
  631. // continuar a fetch fresco
  632. }
  633. }
  634. fetch('/api/update-status')
  635. .then(res => {
  636. if (!res.ok) throw new Error('HTTP ' + res.status);
  637. return res.json();
  638. })
  639. .then(data => {
  640. sessionStorage.setItem('squidstats_update_status', JSON.stringify(data));
  641. sessionStorage.setItem('squidstats_update_status_at', Date.now().toString());
  642. updateUi('squid', data.squid);
  643. updateUi('web', data.web);
  644. })
  645. .catch(err => {
  646. console.warn('No se pudo obtener el estado de actualizaciones:', err);
  647. // En caso de error, ocultar indicadores para no mostrar información stale
  648. updateUi('squid', { available: false });
  649. updateUi('web', { available: false });
  650. });
  651. }
  652. fetchUpdateStatus();
  653. }
  654. // Initialize all functionality
  655. initTooltips();
  656. initNavbarScroll();
  657. setActiveLink();
  658. initNotifications();
  659. initUpdateIndicators();
  660. });
  661. // Close modals when clicking outside
  662. document.addEventListener("click", function (e) {
  663. if (e.target.classList.contains("modal-overlay")) {
  664. const modals = document.querySelectorAll("[x-show]");
  665. modals.forEach((modal) => {
  666. const alpineData = Alpine.$data(modal);
  667. if (alpineData) {
  668. alpineData.showSquidModal = false;
  669. alpineData.showWebModal = false;
  670. }
  671. });
  672. }
  673. });
  674. // Add escape key handling for modals
  675. document.addEventListener("keydown", function (e) {
  676. if (e.key === "Escape") {
  677. const modals = document.querySelectorAll("[x-show]");
  678. modals.forEach((modal) => {
  679. const alpineData = Alpine.$data(modal);
  680. if (alpineData) {
  681. alpineData.showSquidModal = false;
  682. alpineData.showWebModal = false;
  683. }
  684. });
  685. }
  686. });
  687. // Mobile menu close on outside click
  688. document.addEventListener('click', function(event) {
  689. const mobileMenu = document.querySelector('[x-data]');
  690. const hamburger = document.querySelector('.lg\\:hidden');
  691. const mobileMenuContent = document.querySelector('.absolute.top-full');
  692. if (mobileMenuContent && mobileMenuContent.style.display !== 'none') {
  693. const isClickInside = hamburger.contains(event.target) || mobileMenuContent.contains(event.target);
  694. if (!isClickInside) {
  695. const alpineData = Alpine.$data(mobileMenu);
  696. if (alpineData) {
  697. alpineData.mobileMenuOpen = false;
  698. }
  699. }
  700. }
  701. });
  702. // Función para obtener el token CSRF
  703. function getCSRFToken() {
  704. const metaTag = document.querySelector('meta[name="csrf-token"]');
  705. return metaTag ? metaTag.getAttribute('content') : '';
  706. }
  707. // Funciones de confirmación para actualizaciones
  708. function confirmSquidUpdate() {
  709. showCustomConfirm(
  710. {{ _('¿Estás seguro de que deseas actualizar el servicio Squid? Guarda tu configuración antes de continuar, el servicio se reiniciará automáticamente.')|tojson }},
  711. async () => {
  712. try {
  713. const response = await fetch('/install', {
  714. method: 'POST',
  715. headers: {
  716. 'Content-Type': 'application/x-www-form-urlencoded',
  717. 'Accept': 'application/json',
  718. 'X-CSRFToken': getCSRFToken()
  719. },
  720. body: new URLSearchParams({ csrf_token: getCSRFToken() })
  721. });
  722. const data = await response.json().catch(() => ({}));
  723. if (response.ok && data.status === 'success') {
  724. window.location.reload();
  725. } else {
  726. const message = data.message || {{ _('Error al actualizar Squid')|tojson }};
  727. if (window.toastr) {
  728. toastr.error(message, {{ _('Error al actualizar Squid')|tojson }});
  729. } else {
  730. alert(message);
  731. }
  732. }
  733. } catch (error) {
  734. alert({{ _('Error de conexión')|tojson }});
  735. }
  736. }
  737. );
  738. }
  739. function confirmWebUpdate() {
  740. if (IS_DEB_INSTALL) {
  741. showCustomConfirm(
  742. {{ _("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 }},
  743. function() {},
  744. { onlyClose: true }
  745. );
  746. return;
  747. }
  748. showCustomConfirm(
  749. {{ _('¿Estás seguro de que deseas actualizar SquidStats? Se actualizará la interfaz web, funcionalidades y correcciones de seguridad.')|tojson }},
  750. async () => {
  751. try {
  752. const response = await fetch('/update', {
  753. method: 'POST',
  754. headers: {
  755. 'Content-Type': 'application/x-www-form-urlencoded',
  756. 'X-CSRFToken': getCSRFToken()
  757. },
  758. body: new URLSearchParams({ csrf_token: getCSRFToken() })
  759. });
  760. if (response.ok) {
  761. window.location.reload();
  762. } else {
  763. alert({{ _('Error al actualizar la aplicación web')|tojson }});
  764. }
  765. } catch (error) {
  766. alert({{ _('Error de conexión')|tojson }});
  767. }
  768. }
  769. );
  770. }
  771. // Nav loading spinner for slow pages (e.g. /blacklist)
  772. (function () {
  773. function initNavLoadingOverlay() {
  774. var style = document.createElement('style');
  775. 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}';
  776. document.head.appendChild(style);
  777. var overlay = document.createElement('div');
  778. overlay.id = 'nav-loading-overlay';
  779. 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';
  780. overlay.innerHTML = '<div class="nav-spinner"></div>';
  781. document.body.appendChild(overlay);
  782. document.addEventListener('click', function (e) {
  783. var link = e.target.closest('[data-nav-loading]');
  784. if (!link) return;
  785. overlay.style.display = 'flex';
  786. window.addEventListener('pageshow', function () { overlay.style.display = 'none'; }, { once: true });
  787. });
  788. }
  789. if (document.readyState === 'loading') {
  790. document.addEventListener('DOMContentLoaded', initNavLoadingOverlay);
  791. } else {
  792. initNavLoadingOverlay();
  793. }
  794. }());
  795. </script>