// manager_wifi_gate.js (function (window, $) { 'use strict'; const R = window.ITCRemote; if (!R) { console.error('ITCRemote no está definido. Asegúrate de cargar manager_wifi.js antes.'); return; } // --------------------------------------------------------- // ALERTA de la pantalla de conexión // --------------------------------------------------------- function showAlert(text, type = 'warning') { const $alert = $('#gateAlert'); $alert .removeClass() .addClass('alert small mt-3 d-block alert-' + type) .text(text); } function hideAlert() { $('#gateAlert') .removeClass() .addClass('alert small mt-3 d-none') .text(''); } // --------------------------------------------------------- // MANEJO UI CONECTAR // --------------------------------------------------------- const form = document.getElementById('gateForm'); const hashInput = document.getElementById('hashInput'); const btnEnter = document.getElementById('btnEnter'); const deviceImg = document.getElementById('deviceImg'); const recaptchaInput = document.getElementById('recaptcha_token'); const IMG_DEFAULT = '../../img/wf-login-dispositivos.gif'; const IMG_CONNECTING = '../../img/wf-login-dispositivos-conn.gif'; const IMG_CONNECTED = '../../img/wf-login-dispositivos.gif'; if (deviceImg) { deviceImg.src = IMG_DEFAULT; } // Forzar mayúsculas al escribir/pegar if (hashInput) { hashInput.addEventListener('input', () => { const pos = hashInput.selectionStart; hashInput.value = hashInput.value.toUpperCase(); try { hashInput.setSelectionRange(pos, pos); } catch (e) {} }); } function mostrarPantallaApp() { $('#gateSection').addClass('hidden'); $('#appSection').removeClass('hidden'); } // --------------------------------------------------------- // AL CARGAR LA PÁGINA: si ya estaba conectado en esta sesión, // saltamos la pantalla de conexión y vamos directos a la app. // --------------------------------------------------------- $(function () { try { const storedConnected = sessionStorage.getItem('itcConnected') === '1'; const storedHash = sessionStorage.getItem('itcHash') || null; if (storedConnected && storedHash) { console.log('🔁 Sesión previa detectada, saltando pantalla de conexión…'); // Restaurar estado básico de dispositivo R.setCurrentDevice(storedHash, null); // Ocultar gate y mostrar app $('#gateSection').addClass('hidden'); $('#appSection').removeClass('hidden'); // Pedir INFO y rellenar pestaña if (typeof R.requestInfoAndFill === 'function') { R.requestInfoAndFill(6000).catch(err => { console.warn('Error recargando info tras refresh:', err); }); } } } catch (e) { console.warn('No se pudo restaurar sesión previa:', e); } }); // --------------------------------------------------------- // SUBMIT del formulario de conexión // --------------------------------------------------------- if (form) { form.addEventListener('submit', function (ev) { ev.preventDefault(); hideAlert(); const hash = (hashInput.value || '').trim(); if (!hash) { showAlert('Introduce un código válido.', 'danger'); hashInput.focus(); return; } if (typeof grecaptcha === 'undefined' || !RECAPTCHA_SITE_KEY) { showAlert('Error de configuración reCAPTCHA. Inténtalo más tarde.', 'danger'); return; } // 1) Ejecutar reCAPTCHA v3 grecaptcha.ready(function () { grecaptcha.execute(RECAPTCHA_SITE_KEY, { action: 'remote_login' }) .then(function (token) { // Llamar al JSP pasándole el token como parámetro GET const url = '../api/recaptcha-check.jsp?token=' + encodeURIComponent(token); return fetch(url, { method: 'GET' // GET o POST da igual mientras el token vaya en la URL }); }) .then(function (res) { return res.json().then(function (data) { return { ok: res.ok, data: data }; }); }) .then(function (result) { if (!result.ok || !result.data.ok) { console.error('reCAPTCHA inválido:', result.data); showAlert('Error validando reCAPTCHA. Inténtalo de nuevo.', 'danger'); return; } // Si todo OK: doLogin(hash); }) .catch(function (err) { console.error('Error en reCAPTCHA:', err); showAlert('Error validando reCAPTCHA. Inténtalo de nuevo.', 'danger'); }); }); }); } async function doLogin(hash) { btnEnter.disabled = true; btnEnter.innerHTML = ' Conectando...'; if (deviceImg) { deviceImg.src = IMG_CONNECTING; deviceImg.alt = 'Conectando con el dispositivo'; } try { const infoResponse = await R.sendDeviceCommand({ hash: hash, request: 'login', timeoutMs: 10000 // 👆 nada de recaptcha aquí }); R.setCurrentDevice(hash, infoResponse); if (typeof R.fillDeviceInfoUI === 'function') { R.fillDeviceInfoUI(infoResponse, hash); } if (deviceImg) { deviceImg.src = IMG_CONNECTED; deviceImg.alt = 'Dispositivo conectado'; } showAlert('Conectado correctamente.', 'success'); mostrarPantallaApp(); if (typeof R.requestInfoAndFill === 'function') { R.requestInfoAndFill(6000).catch(err => { console.warn('Error recargando info tras connect:', err); }); } } catch (err) { if (deviceImg) { deviceImg.src = IMG_DEFAULT; deviceImg.alt = 'Imagen del dispositivo'; } showAlert('No se ha podido conectar con el dispositivo: ' + err.message, 'danger'); } finally { btnEnter.disabled = false; btnEnter.innerHTML = ' Conectar'; } } })(window, jQuery);