navbar.html 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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 id="squid-update-label" data-loading-label="{{ _('Actualizando...') }}">{{ _("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 id="web-update-label" data-loading-label="{{ _('Actualizando...') }}">{{ _("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 id="squid-update-label-mobile" data-loading-label="{{ _('Actualizando...') }}">{{ _("Squid") }}</span>
  210. <span id="squid-update-chip-mobile" class="update-chip update-chip--squid hidden">NEW</span>
  211. </button>
  212. <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">
  213. <i id="web-update-icon-mobile" class="fas fa-cloud-download-alt"></i>
  214. <span id="web-update-label-mobile" data-loading-label="{{ _('Actualizando...') }}">{{ _("Web") }}</span>
  215. <span id="web-update-chip-mobile" class="update-chip update-chip--web hidden">NEW</span>
  216. </button>
  217. </div>
  218. </div>
  219. <!-- Language Switcher - Mobile -->
  220. <div class="flex gap-2 mb-4">
  221. {% for code, name in LANGUAGES.items() %}
  222. <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 %}">
  223. <i class="fas fa-globe"></i>
  224. <span>{{ name }}</span>
  225. {% if get_locale() == code %}<i class="fas fa-check text-xs"></i>{% endif %}
  226. </a>
  227. {% endfor %}
  228. </div>
  229. </div>
  230. </div>
  231. </div>
  232. </nav>
  233. <!-- Custom Confirm Modal -->
  234. {% include 'components/confirm_modal.html' %}
  235. <!-- Update indicators CSS -->
  236. <link rel="stylesheet" href="{{ url_for('static', filename='css/update-indicators.css') }}" />
  237. <!-- Scripts -->
  238. <script src="{{ url_for('static', filename='src/tailwind.min.js') }}"></script>
  239. <script defer src="{{ url_for('static', filename='src/alpine.min.js') }}"></script>
  240. <script src="{{ url_for('static', filename='js/confirm_modal.js') }}"></script>
  241. <script>
  242. const IS_DEB_INSTALL = {{ is_deb_install | tojson }};
  243. // Enhanced Navbar Functionality with Real-time Notifications
  244. document.addEventListener("DOMContentLoaded", function () {
  245. // Tooltip functionality
  246. function initTooltips() {
  247. const elements = document.querySelectorAll('[data-tooltip]');
  248. elements.forEach(element => {
  249. const tooltipText = element.getAttribute('data-tooltip');
  250. const tooltip = document.createElement('div');
  251. 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';
  252. tooltip.textContent = tooltipText;
  253. element.appendChild(tooltip);
  254. element.addEventListener('mouseenter', function() {
  255. tooltip.classList.remove('invisible', 'opacity-0');
  256. tooltip.classList.add('visible', 'opacity-100');
  257. });
  258. element.addEventListener('mouseleave', function() {
  259. tooltip.classList.remove('visible', 'opacity-100');
  260. tooltip.classList.add('invisible', 'opacity-0');
  261. });
  262. });
  263. }
  264. // Navbar scroll effect
  265. function initNavbarScroll() {
  266. const navbar = document.querySelector('nav');
  267. let lastScrollY = window.scrollY;
  268. window.addEventListener('scroll', () => {
  269. if (window.scrollY > lastScrollY && window.scrollY > 100) {
  270. navbar.style.transform = 'translateY(-100%)';
  271. } else {
  272. navbar.style.transform = 'translateY(0)';
  273. }
  274. lastScrollY = window.scrollY;
  275. });
  276. }
  277. // Active link highlighting
  278. function setActiveLink() {
  279. const currentPath = window.location.pathname;
  280. const links = document.querySelectorAll('nav a[href]');
  281. links.forEach(link => {
  282. if (link.getAttribute('href') === currentPath) {
  283. link.classList.add('text-white', 'bg-white/20');
  284. link.classList.remove('text-gray-200', 'hover:bg-white/10');
  285. }
  286. });
  287. }
  288. // Función para obtener el token CSRF de forma segura
  289. function getCSRFToken() {
  290. const metaTag = document.querySelector('meta[name="csrf-token"]');
  291. if (metaTag) {
  292. return metaTag.getAttribute('content');
  293. }
  294. console.warn('CSRF token meta tag no encontrado');
  295. return '';
  296. }
  297. // Enhanced Notifications System with WebSocket
  298. function initNotifications() {
  299. let notificationSocket = null;
  300. let notificationsData = {
  301. unread_count: 0,
  302. notifications: []
  303. };
  304. // Conectar WebSocket
  305. function connectWebSocket() {
  306. // Flask-SocketIO se conecta automáticamente al host actual
  307. notificationSocket = io();
  308. notificationSocket.on('connect', function() {
  309. console.log('Conectado al servidor de notificaciones Squid');
  310. });
  311. notificationSocket.on('new_notification', function(data) {
  312. addNewNotification(data.notification);
  313. updateNotificationBadges(data.unread_count);
  314. showNotificationToast(data.notification);
  315. });
  316. notificationSocket.on('notification_updated', function(data) {
  317. console.log('Notificación actualizada recibida:', data);
  318. updateExistingNotification(data.notification);
  319. updateNotificationBadges(data.unread_count);
  320. showNotificationToast(data.notification);
  321. });
  322. notificationSocket.on('disconnect', function() {
  323. // Reconectar después de 5 segundos
  324. setTimeout(connectWebSocket, 5000);
  325. });
  326. }
  327. function addNewNotification(notification) {
  328. // Evitar duplicados por ID
  329. const existingIndex = notificationsData.notifications.findIndex(n => n.id === notification.id);
  330. if (existingIndex === -1) {
  331. notificationsData.notifications.unshift(notification);
  332. if (!notification.read) {
  333. notificationsData.unread_count++;
  334. }
  335. // Actualizar ambas listas (desktop y móvil)
  336. updateNotificationLists();
  337. updateNotificationBadges(notificationsData.unread_count);
  338. }
  339. }
  340. function updateExistingNotification(notification) {
  341. // Buscar y actualizar la notificación existente
  342. const existingIndex = notificationsData.notifications.findIndex(n => n.id === notification.id);
  343. if (existingIndex !== -1) {
  344. // Actualizar la notificación existente
  345. notificationsData.notifications[existingIndex] = notification;
  346. // Moverla al principio de la lista
  347. const updated = notificationsData.notifications.splice(existingIndex, 1)[0];
  348. notificationsData.notifications.unshift(updated);
  349. } else {
  350. // Si no existe, agregarla como nueva
  351. notificationsData.notifications.unshift(notification);
  352. }
  353. // Actualizar ambas listas (desktop y móvil)
  354. updateNotificationLists();
  355. }
  356. function showNotificationToast(notification) {
  357. if (!window.toastr) return;
  358. // Construir el título con la fuente
  359. const source = notification.source === 'squid' ? 'Squid' :
  360. notification.source === 'git' ? 'Git' : 'Sistema';
  361. const title = notification.count && notification.count > 1 ?
  362. `${source} (×${notification.count})` : source;
  363. // Mostrar notificación según el tipo
  364. if (notification.type === 'error') {
  365. toastr.error(notification.message, title);
  366. } else if (notification.type === 'warning') {
  367. toastr.warning(notification.message, title);
  368. } else if (notification.type === 'success') {
  369. toastr.success(notification.message, title);
  370. } else {
  371. toastr.info(notification.message, title);
  372. }
  373. }
  374. function updateNotificationLists() {
  375. const desktopUl = document.querySelector(".notifications");
  376. const mobileUl = document.querySelector(".notifications-mobile");
  377. const renderNotificationList = (ul, notifications) => {
  378. if (!ul) return;
  379. ul.innerHTML = "";
  380. // Usar el estado local actual - SOLO notificaciones no leídas
  381. const unreadNotifications = notificationsData.notifications.filter(n => !n.read);
  382. const notificationsToShow = unreadNotifications.slice(0, 10);
  383. if (notificationsToShow.length > 0) {
  384. notificationsToShow.forEach((notification) => {
  385. let bgColor, textColor;
  386. switch(notification.type) {
  387. case 'success':
  388. bgColor = 'bg-green-100';
  389. textColor = 'text-green-600';
  390. break;
  391. case 'warning':
  392. bgColor = 'bg-yellow-100';
  393. textColor = 'text-yellow-600';
  394. break;
  395. case 'error':
  396. bgColor = 'bg-red-100';
  397. textColor = 'text-red-600';
  398. break;
  399. case 'info':
  400. default:
  401. bgColor = 'bg-blue-100';
  402. textColor = 'text-blue-600';
  403. }
  404. // Create list item safely
  405. const li = document.createElement('li');
  406. li.className = `px-4 py-3 flex items-start hover:bg-gray-50 cursor-pointer notification-item ${
  407. notification.read ? 'opacity-60' : ''
  408. }`;
  409. li.dataset.id = notification.id;
  410. const iconSpan = document.createElement('span');
  411. iconSpan.className = `inline-flex items-center justify-center h-8 w-8 rounded-full ${bgColor} ${textColor} mr-3`;
  412. const icon = document.createElement('i');
  413. icon.className = `fas ${notification.icon}`;
  414. iconSpan.appendChild(icon);
  415. const contentDiv = document.createElement('div');
  416. contentDiv.className = 'flex-1';
  417. const sourceP = document.createElement('p');
  418. sourceP.className = 'text-sm font-medium text-gray-900';
  419. sourceP.textContent = notification.source === 'squid' ? 'Squid' :
  420. notification.source === 'git' ? 'Git' : 'Sistema';
  421. const messageP = document.createElement('p');
  422. messageP.className = 'text-sm text-gray-700 mt-1';
  423. messageP.textContent = notification.message;
  424. const timeSpan = document.createElement('span');
  425. timeSpan.className = 'text-xs text-gray-400 mt-1';
  426. timeSpan.textContent = notification.time;
  427. contentDiv.appendChild(sourceP);
  428. contentDiv.appendChild(messageP);
  429. contentDiv.appendChild(timeSpan);
  430. li.appendChild(iconSpan);
  431. li.appendChild(contentDiv);
  432. if (!notification.read) {
  433. const badge = document.createElement('span');
  434. badge.className = 'w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0';
  435. li.appendChild(badge);
  436. }
  437. ul.appendChild(li);
  438. });
  439. } else {
  440. ul.innerHTML = `
  441. <li class='px-4 py-3 text-gray-500 text-center'>
  442. No hay notificaciones nuevas
  443. </li>
  444. `;
  445. }
  446. };
  447. renderNotificationList(desktopUl, notificationsData.notifications);
  448. renderNotificationList(mobileUl, notificationsData.notifications);
  449. }
  450. function updateNotificationBadges(count) {
  451. const badges = document.querySelectorAll('.notification-badge');
  452. badges.forEach(badge => {
  453. if (count > 0) {
  454. badge.textContent = count > 99 ? '99+' : count.toString();
  455. badge.classList.remove('hidden');
  456. } else {
  457. badge.classList.add('hidden');
  458. }
  459. });
  460. }
  461. function markAsRead(notificationIds) {
  462. const csrfToken = getCSRFToken();
  463. fetch('/api/notifications/mark-read', {
  464. method: 'POST',
  465. headers: {
  466. 'Content-Type': 'application/json',
  467. 'X-CSRF-Token': csrfToken,
  468. },
  469. body: JSON.stringify({
  470. ids: notificationIds
  471. })
  472. })
  473. .then(response => {
  474. if (!response.ok) {
  475. throw new Error(`Error HTTP: ${response.status}`);
  476. }
  477. return response.json();
  478. })
  479. .then(data => {
  480. if (data.success) {
  481. // CORRECCIÓN: Filtrar notificaciones marcadas del estado local
  482. notificationsData.notifications = notificationsData.notifications.filter(
  483. notification => !notificationIds.includes(notification.id)
  484. );
  485. notificationsData.unread_count = data.unread_count;
  486. updateNotificationBadges(data.unread_count);
  487. updateNotificationLists();
  488. } else {
  489. console.error('Error del servidor al marcar como leída:', data.error);
  490. showNotificationToast({
  491. type: 'error',
  492. message: 'Error al marcar notificación como leída: ' + (data.error || 'Error desconocido')
  493. });
  494. }
  495. })
  496. .catch(error => {
  497. showNotificationToast({
  498. type: 'error',
  499. message: 'Error al marcar notificación como leída: ' + error.message
  500. });
  501. });
  502. }
  503. function fetchInitialNotifications() {
  504. fetch("/api/notifications")
  505. .then((res) => {
  506. if (!res.ok) {
  507. throw new Error(`Error HTTP: ${res.status}`);
  508. }
  509. return res.json();
  510. })
  511. .then((data) => {
  512. // REEMPLAZAR completamente el estado local
  513. notificationsData.notifications = data.notifications || [];
  514. notificationsData.unread_count = data.unread_count || 0;
  515. updateNotificationLists();
  516. updateNotificationBadges(data.unread_count);
  517. })
  518. .catch((error) => {
  519. console.error('Error fetching notifications:', error);
  520. notificationsData.notifications = [];
  521. notificationsData.unread_count = 0;
  522. updateNotificationLists();
  523. updateNotificationBadges(0);
  524. });
  525. }
  526. // Event listeners para marcar como leído
  527. document.addEventListener('click', function(e) {
  528. const notificationItem = e.target.closest('.notification-item');
  529. if (notificationItem) {
  530. const notificationId = parseInt(notificationItem.dataset.id);
  531. markAsRead([notificationId]);
  532. }
  533. });
  534. // Inicializar
  535. fetchInitialNotifications();
  536. connectWebSocket();
  537. }
  538. // Update indicators: animated badges/glows when Squid or Web updates are available
  539. function initUpdateIndicators() {
  540. const UI = {
  541. squid: {
  542. btn: document.getElementById('squid-update-btn'),
  543. badge: document.getElementById('squid-update-badge'),
  544. icon: document.getElementById('squid-update-icon'),
  545. tooltip: document.getElementById('squid-update-tooltip'),
  546. mobileBtn: document.getElementById('squid-update-btn-mobile'),
  547. mobileIcon: document.getElementById('squid-update-icon-mobile'),
  548. mobileChip: document.getElementById('squid-update-chip-mobile'),
  549. },
  550. web: {
  551. btn: document.getElementById('web-update-btn'),
  552. badge: document.getElementById('web-update-badge'),
  553. icon: document.getElementById('web-update-icon'),
  554. tooltip: document.getElementById('web-update-tooltip'),
  555. mobileBtn: document.getElementById('web-update-btn-mobile'),
  556. mobileIcon: document.getElementById('web-update-icon-mobile'),
  557. mobileChip: document.getElementById('web-update-chip-mobile'),
  558. }
  559. };
  560. function updateUi(type, status) {
  561. const el = UI[type];
  562. if (!el || !el.btn) return;
  563. const baseTooltip = el.btn.getAttribute('data-base-tooltip') || '';
  564. const hasUpdate = status && status.available && status.latest;
  565. // Desktop badge
  566. if (el.badge) {
  567. if (hasUpdate) {
  568. el.badge.classList.remove('hidden');
  569. requestAnimationFrame(() => el.badge.classList.add('is-visible'));
  570. } else {
  571. el.badge.classList.remove('is-visible');
  572. setTimeout(() => el.badge.classList.add('hidden'), 350);
  573. }
  574. }
  575. // Desktop glow/ripple
  576. if (el.btn) {
  577. const glowClass = type === 'squid' ? 'update-available--squid' : 'update-available--web';
  578. if (hasUpdate) {
  579. el.btn.classList.add('update-available', glowClass);
  580. } else {
  581. el.btn.classList.remove('update-available', 'update-available--squid', 'update-available--web');
  582. }
  583. }
  584. // Desktop icon attention
  585. if (el.icon) {
  586. if (hasUpdate && !el.btn.disabled) {
  587. el.icon.classList.add('update-icon-attention');
  588. } else {
  589. el.icon.classList.remove('update-icon-attention');
  590. }
  591. }
  592. // Desktop tooltip
  593. if (el.tooltip) {
  594. if (hasUpdate) {
  595. const msg = type === 'squid'
  596. ? {{ _('Nueva versión de Squid disponible:')|tojson }} + ' ' + status.latest
  597. : {{ _('Nueva versión de SquidStats disponible:')|tojson }} + ' ' + status.latest;
  598. el.tooltip.textContent = msg;
  599. } else {
  600. el.tooltip.textContent = baseTooltip;
  601. }
  602. }
  603. // Mobile chip
  604. if (el.mobileChip) {
  605. if (hasUpdate) {
  606. el.mobileChip.classList.remove('hidden');
  607. requestAnimationFrame(() => el.mobileChip.classList.add('is-visible'));
  608. } else {
  609. el.mobileChip.classList.remove('is-visible');
  610. setTimeout(() => el.mobileChip.classList.add('hidden'), 350);
  611. }
  612. }
  613. // Mobile icon attention
  614. if (el.mobileIcon) {
  615. if (hasUpdate && !el.mobileBtn.disabled) {
  616. el.mobileIcon.classList.add('update-icon-attention');
  617. } else {
  618. el.mobileIcon.classList.remove('update-icon-attention');
  619. }
  620. }
  621. }
  622. function fetchUpdateStatus() {
  623. const cached = sessionStorage.getItem('squidstats_update_status');
  624. const cachedAt = sessionStorage.getItem('squidstats_update_status_at');
  625. const ttl = 5 * 60 * 1000; // 5 minutos
  626. if (cached && cachedAt && (Date.now() - parseInt(cachedAt, 10)) < ttl) {
  627. try {
  628. const data = JSON.parse(cached);
  629. updateUi('squid', data.squid);
  630. updateUi('web', data.web);
  631. return;
  632. } catch (e) {
  633. // continuar a fetch fresco
  634. }
  635. }
  636. fetch('/api/update-status')
  637. .then(res => {
  638. if (!res.ok) throw new Error('HTTP ' + res.status);
  639. return res.json();
  640. })
  641. .then(data => {
  642. sessionStorage.setItem('squidstats_update_status', JSON.stringify(data));
  643. sessionStorage.setItem('squidstats_update_status_at', Date.now().toString());
  644. updateUi('squid', data.squid);
  645. updateUi('web', data.web);
  646. })
  647. .catch(err => {
  648. console.warn('No se pudo obtener el estado de actualizaciones:', err);
  649. // En caso de error, ocultar indicadores para no mostrar información stale
  650. updateUi('squid', { available: false });
  651. updateUi('web', { available: false });
  652. });
  653. }
  654. fetchUpdateStatus();
  655. }
  656. // Initialize all functionality
  657. initTooltips();
  658. initNavbarScroll();
  659. setActiveLink();
  660. initNotifications();
  661. initUpdateIndicators();
  662. });
  663. // Close modals when clicking outside
  664. document.addEventListener("click", function (e) {
  665. if (e.target.classList.contains("modal-overlay")) {
  666. const modals = document.querySelectorAll("[x-show]");
  667. modals.forEach((modal) => {
  668. const alpineData = Alpine.$data(modal);
  669. if (alpineData) {
  670. alpineData.showSquidModal = false;
  671. alpineData.showWebModal = false;
  672. }
  673. });
  674. }
  675. });
  676. // Add escape key handling for modals
  677. document.addEventListener("keydown", function (e) {
  678. if (e.key === "Escape") {
  679. const modals = document.querySelectorAll("[x-show]");
  680. modals.forEach((modal) => {
  681. const alpineData = Alpine.$data(modal);
  682. if (alpineData) {
  683. alpineData.showSquidModal = false;
  684. alpineData.showWebModal = false;
  685. }
  686. });
  687. }
  688. });
  689. // Mobile menu close on outside click
  690. document.addEventListener('click', function(event) {
  691. const mobileMenu = document.querySelector('[x-data]');
  692. const hamburger = document.querySelector('.lg\\:hidden');
  693. const mobileMenuContent = document.querySelector('.absolute.top-full');
  694. if (mobileMenuContent && mobileMenuContent.style.display !== 'none') {
  695. const isClickInside = hamburger.contains(event.target) || mobileMenuContent.contains(event.target);
  696. if (!isClickInside) {
  697. const alpineData = Alpine.$data(mobileMenu);
  698. if (alpineData) {
  699. alpineData.mobileMenuOpen = false;
  700. }
  701. }
  702. }
  703. });
  704. // Función para obtener el token CSRF
  705. function getCSRFToken() {
  706. const metaTag = document.querySelector('meta[name="csrf-token"]');
  707. return metaTag ? metaTag.getAttribute('content') : '';
  708. }
  709. function fitUpdateLabel(button, label) {
  710. const icon = button.querySelector('i');
  711. if (!icon) return;
  712. const buttonStyle = getComputedStyle(button);
  713. const availableWidth = Math.max(
  714. 0,
  715. button.clientWidth
  716. - parseFloat(buttonStyle.paddingLeft)
  717. - parseFloat(buttonStyle.paddingRight)
  718. - icon.getBoundingClientRect().width
  719. - (parseFloat(buttonStyle.columnGap) || 0)
  720. );
  721. label.style.display = 'inline-block';
  722. label.style.flex = '0 0 auto';
  723. label.style.whiteSpace = 'nowrap';
  724. const textWidth = label.getBoundingClientRect().width;
  725. const scale = textWidth > availableWidth ? availableWidth / textWidth : 1;
  726. label.style.flex = `0 0 ${availableWidth}px`;
  727. label.style.transform = `scaleX(${scale})`;
  728. label.style.transformOrigin = 'left center';
  729. }
  730. function setUpdateButtonLoading(type, isLoading) {
  731. const config = {
  732. squid: {
  733. buttonIds: ['squid-update-btn', 'squid-update-btn-mobile'],
  734. iconIds: ['squid-update-icon', 'squid-update-icon-mobile'],
  735. labelIds: ['squid-update-label', 'squid-update-label-mobile'],
  736. chipIds: ['squid-update-chip-mobile'],
  737. idleIcon: 'fa-sync-alt'
  738. },
  739. web: {
  740. buttonIds: ['web-update-btn', 'web-update-btn-mobile'],
  741. iconIds: ['web-update-icon', 'web-update-icon-mobile'],
  742. labelIds: ['web-update-label', 'web-update-label-mobile'],
  743. chipIds: ['web-update-chip-mobile'],
  744. idleIcon: 'fa-cloud-download-alt'
  745. }
  746. }[type];
  747. config.buttonIds.forEach((id) => {
  748. const button = document.getElementById(id);
  749. if (button) {
  750. if (isLoading) button.style.width = `${button.getBoundingClientRect().width}px`;
  751. else button.style.removeProperty('width');
  752. button.disabled = isLoading;
  753. button.setAttribute('aria-busy', String(isLoading));
  754. }
  755. });
  756. config.chipIds.forEach((id) => {
  757. const chip = document.getElementById(id);
  758. if (!chip) return;
  759. if (isLoading) {
  760. chip.dataset.wasHidden = String(chip.classList.contains('hidden'));
  761. chip.classList.add('hidden');
  762. } else {
  763. chip.classList.toggle('hidden', chip.dataset.wasHidden !== 'false');
  764. delete chip.dataset.wasHidden;
  765. }
  766. });
  767. config.iconIds.forEach((id) => {
  768. const icon = document.getElementById(id);
  769. if (!icon) return;
  770. icon.classList.remove('fa-spin', 'fa-spinner', 'fa-sync-alt', 'fa-cloud-download-alt', 'update-icon-attention');
  771. icon.classList.add(isLoading ? 'fa-spinner' : config.idleIcon);
  772. if (isLoading) icon.classList.add('fa-spin');
  773. else if (icon.closest('button')?.classList.contains('update-available')) icon.classList.add('update-icon-attention');
  774. });
  775. config.labelIds.forEach((id) => {
  776. const label = document.getElementById(id);
  777. if (!label) return;
  778. if (!label.dataset.idleLabel) label.dataset.idleLabel = label.textContent;
  779. if (isLoading) {
  780. label.textContent = label.dataset.loadingLabel;
  781. const button = label.closest('button');
  782. if (button) fitUpdateLabel(button, label);
  783. } else {
  784. label.textContent = label.dataset.idleLabel;
  785. label.removeAttribute('style');
  786. }
  787. });
  788. }
  789. // Funciones de confirmación para actualizaciones
  790. function confirmSquidUpdate() {
  791. showCustomConfirm(
  792. {{ _('¿Estás seguro de que deseas actualizar el servicio Squid? Guarda tu configuración antes de continuar, el servicio se reiniciará automáticamente.')|tojson }},
  793. async () => {
  794. setUpdateButtonLoading('squid', true);
  795. try {
  796. const response = await fetch('/install', {
  797. method: 'POST',
  798. headers: {
  799. 'Content-Type': 'application/x-www-form-urlencoded',
  800. 'Accept': 'application/json',
  801. 'X-CSRFToken': getCSRFToken()
  802. },
  803. body: new URLSearchParams({ csrf_token: getCSRFToken() })
  804. });
  805. const data = await response.json().catch(() => ({}));
  806. if (response.ok && data.status === 'success') {
  807. window.location.reload();
  808. } else {
  809. const message = data.message || {{ _('Error al actualizar Squid')|tojson }};
  810. setUpdateButtonLoading('squid', false);
  811. if (window.toastr) {
  812. toastr.error(message, {{ _('Error al actualizar Squid')|tojson }});
  813. } else {
  814. alert(message);
  815. }
  816. }
  817. } catch (error) {
  818. setUpdateButtonLoading('squid', false);
  819. alert({{ _('Error de conexión')|tojson }});
  820. }
  821. }
  822. );
  823. }
  824. function confirmWebUpdate() {
  825. if (IS_DEB_INSTALL) {
  826. showCustomConfirm(
  827. {{ _("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 }},
  828. function() {},
  829. { onlyClose: true }
  830. );
  831. return;
  832. }
  833. showCustomConfirm(
  834. {{ _('¿Estás seguro de que deseas actualizar SquidStats? Se actualizará la interfaz web, funcionalidades y correcciones de seguridad.')|tojson }},
  835. async () => {
  836. setUpdateButtonLoading('web', true);
  837. try {
  838. const response = await fetch('/update', {
  839. method: 'POST',
  840. headers: {
  841. 'Content-Type': 'application/x-www-form-urlencoded',
  842. 'X-CSRFToken': getCSRFToken()
  843. },
  844. body: new URLSearchParams({ csrf_token: getCSRFToken() })
  845. });
  846. if (response.ok) {
  847. window.location.reload();
  848. } else {
  849. setUpdateButtonLoading('web', false);
  850. alert({{ _('Error al actualizar la aplicación web')|tojson }});
  851. }
  852. } catch (error) {
  853. // The web update restarts the service, which can close this request
  854. // before fetch receives the final response.
  855. const restartMessage = {{ _('La actualización se inició correctamente. La aplicación se está reiniciando.')|tojson }};
  856. if (window.toastr) {
  857. toastr.success(restartMessage);
  858. } else {
  859. alert(restartMessage);
  860. }
  861. setTimeout(() => window.location.reload(), 2500);
  862. }
  863. }
  864. );
  865. }
  866. // Nav loading spinner for slow pages (e.g. /blacklist)
  867. (function () {
  868. function initNavLoadingOverlay() {
  869. var style = document.createElement('style');
  870. 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}';
  871. document.head.appendChild(style);
  872. var overlay = document.createElement('div');
  873. overlay.id = 'nav-loading-overlay';
  874. 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';
  875. overlay.innerHTML = '<div class="nav-spinner"></div>';
  876. document.body.appendChild(overlay);
  877. document.addEventListener('click', function (e) {
  878. var link = e.target.closest('[data-nav-loading]');
  879. if (!link) return;
  880. overlay.style.display = 'flex';
  881. window.addEventListener('pageshow', function () { overlay.style.display = 'none'; }, { once: true });
  882. });
  883. }
  884. if (document.readyState === 'loading') {
  885. document.addEventListener('DOMContentLoaded', initNavLoadingOverlay);
  886. } else {
  887. initNavLoadingOverlay();
  888. }
  889. }());
  890. </script>