// --- SISTEMA TRADUZIONI (i18n) & HELPERS --- const i18n = { en: { lblLogLimit: "Rows:", lastTransits: "Lastheard", loginTitle: "SYSTEM_LOGIN", thTime: "Time", thRep: "Repeater", thMode: "Mode", thCall: "Callsign", thDur: "Duration", thUser: "User", thRole: "Role", thNodes: "Nodes", thActs: "Actions", btnReqCfg: "REQ_CFG", btnGlobal: "GBL_OVR", btnAdmin: "SYS_ADM", btnPass: "CHG_PWD", btnLogout: "LOGOUT", btnSvc: "SVC", btnFile: "CFG", btnBoot: "REBOOT", btnAdd: "ADD", waitNet: "> Waiting network...", waitData: "Waiting for node data...", forceUpdate: "FORCE_UPD", adminTitle: "SYS_ADMIN", adminDBSync: "DB_SYNC_CFG", adminTime: "Daily Update Time:", adminSave: "SAVE_CFG", roleOp: "Operator", modSvcTitle: "DAEMONS:", modFileTitle: "CFG_FILES", modEditTitle: "EDIT:", warnEdit: "[WARN] DIRECT EDIT ACTIVE", btnEdit: "EDIT", btnStart: "START", btnRestart: "RST", btnStop: "STOP", btnSave: "WRITE_FILE", btnHat: "RST_HAT", confHat: "PHYSICAL RESET MMDVM ON: ", confOp: "Confirm operation on ", confTgOn: "ENABLE Telegram notifications for ", confTgOff: "MUTE Telegram notifications for ", confOvr: "Are you sure you want to overwrite file on ", warnDaemon: "[WARN] DAEMON OFFLINE", promptOvr: "GLOBAL OVERRIDE", promptOvrConfirm: "Confirm sending to ENTIRE network?", modUpdateTitle: "GBL_UPDATE", confUpdate: "Do you want to request updated data and configuration files from all nodes in the fleet?", alertUpdateOk: "ACK", btnConfReset: "CONFIRM", btnCancel: "ABORT", promptPass: "NEW PWD:", titleError: "ERR", titleSuccess: "OK", titleAction: "CONFIRM", titleDelete: "DEL_USR", titleSave: "SAVE", titleGlobal: "GBL_OVR", btnYes: "EXECUTE", msgDelUser: "DELETE USER?", msgPassOk: "PWD_UPDATED", msgPassErr: "PWD_ERR", msgLoginFail: "AUTH_FAIL", msgConfigSaved: "CFG_SAVED", msgConfigErr: "CFG_ERR", msgNetErr: "NET_ERR", msgOvrSel: "SELECT_PROF:", msgOvrOk: "CMD_BROADCASTED", msgMissUser: "MISSING_USR", msgMissPass: "MISSING_PWD", btnSvcKo: "DAEMON_ERR", phNewPass: "NEW_PWD (EMPTY=KEEP)", phPass: "PWD", titleSwitch: "SW_PROF", confSwitch: "SWITCH TO ", titleBoot: "SYS_REBOOT", confBoot: "REBOOT NODE ", ttReqCfg: "REQ_DATA", ttGlobal: "GBL_OVR", ttAdmin: "ADMIN", ttPass: "CHG_PWD", ttLogout: "LOGOUT", ttProfA: "PROF_A", ttProfB: "PROF_B", ttTgOn: "TG_ON", ttTgOff: "TG_OFF", ttSvc: "DAEMONS", ttFile: "FILES", ttHat: "RST_HAT", ttBoot: "REBOOT", ttSwitchTo: "SW_TO: ", ttSvcStart: "START", ttSvcRestart: "RST", ttSvcEdit: "EDIT", ttSvcStop: "STOP", ttLang: "LANG", statTopTG: "TOP_TG", statTopCall: "TOP_CALL", statLoading: "LOADING...", statAvgDur: "AVG_DUR", statTodayTx: "TX_TODAY", statNoData: "NO_DATA", statTitle: "DAILY_STATS", statAllNodes: "ALL_NODES", modVersions: "SW_VERSIONS", filtAll: "ALL_NODES", filtOnline: "ONLINE", filtOffline: "OFFLINE", filtAlerts: "ALERTS" }, it: { lblLogLimit: "Righe:", lastTransits: "Ultimi ascolti", loginTitle: "SYSTEM_LOGIN", thTime: "Ora", thRep: "Ripetitore", thMode: "Modo", thCall: "Nominativo", thDur: "Durata", thUser: "Utente", thRole: "Ruolo", thNodes: "Nodi", thActs: "Azioni", btnReqCfg: "REQ_CFG", btnGlobal: "GBL_OVR", btnAdmin: "SYS_ADM", btnPass: "CHG_PWD", btnLogout: "LOGOUT", btnSvc: "SVC", btnFile: "CFG", btnBoot: "REBOOT", btnAdd: "ADD", waitNet: "> Attesa rete...", waitData: "In attesa dei dati dal nodo...", forceUpdate: "FORCE_UPD", adminTitle: "SYS_ADMIN", adminDBSync: "DB_SYNC_CFG", adminTime: "Orario Aggiornamento:", adminSave: "SAVE_CFG", roleOp: "Operatore", modSvcTitle: "DAEMONS:", modFileTitle: "CFG_FILES", modEditTitle: "EDIT:", warnEdit: "[WARN] DIRECT EDIT ACTIVE", btnEdit: "EDIT", btnStart: "START", btnRestart: "RST", btnStop: "STOP", btnSave: "WRITE_FILE", btnHat: "RST_HAT", confHat: "PHYSICAL RESET MMDVM ON: ", confOp: "Confermi l'operazione su ", confTgOn: "Vuoi ATTIVARE le notifiche Telegram per il nodo ", confTgOff: "Vuoi SILENZIARE le notifiche Telegram per il nodo ", confOvr: "Sei sicuro di voler sovrascrivere il file su ", warnDaemon: "[WARN] DAEMON OFFLINE", promptOvr: "GBL_OVR", promptOvrConfirm: "Confermi l'invio a TUTTA la rete?", modUpdateTitle: "GBL_UPDATE", confUpdate: "Vuoi richiedere i dati e i file di configurazione aggiornati a tutti i nodi della flotta?", alertUpdateOk: "ACK", btnConfReset: "CONFIRM", btnCancel: "ABORT", promptPass: "NEW PWD:", titleError: "ERR", titleSuccess: "OK", titleAction: "CONFIRM", titleDelete: "DEL_USR", titleSave: "SAVE", titleGlobal: "GBL_OVR", btnYes: "EXECUTE", msgDelUser: "DELETE USER?", msgPassOk: "PWD_UPDATED", msgPassErr: "PWD_ERR", msgLoginFail: "AUTH_FAIL", msgConfigSaved: "CFG_SAVED", msgConfigErr: "CFG_ERR", msgNetErr: "NET_ERR", msgOvrSel: "SELECT_PROF:", msgOvrOk: "CMD_BROADCASTED", msgMissUser: "MISSING_USR", msgMissPass: "MISSING_PWD", btnSvcKo: "DAEMON_ERR", phNewPass: "NEW_PWD (EMPTY=KEEP)", phPass: "PWD", titleSwitch: "SW_PROF", confSwitch: "SWITCH TO ", titleBoot: "SYS_REBOOT", confBoot: "REBOOT NODE ", ttReqCfg: "REQ_DATA", ttGlobal: "GBL_OVR", ttAdmin: "ADMIN", ttPass: "CHG_PWD", ttLogout: "LOGOUT", ttProfA: "Passa al Profilo A", ttProfB: "Passa al Profilo B", ttTgOn: "Abilita notifiche Telegram", ttTgOff: "Disabilita notifiche Telegram", ttSvc: "Gestisci demoni di sistema", ttFile: "Modifica file .ini da remoto", ttHat: "Reset fisico scheda modem", ttBoot: "Riavvia sistema operativo", ttSwitchTo: "SW_TO: ", ttSvcStart: "START", ttSvcRestart: "RST", ttSvcEdit: "EDIT", ttSvcStop: "STOP", ttLang: "LANG", statTopTG: "TOP_TG", statTopCall: "TOP_CALL", statLoading: "LOADING...", statAvgDur: "AVG_DUR", statTodayTx: "TX_TODAY", statNoData: "NO_DATA", statTitle: "DAILY_STATS", statAllNodes: "ALL_NODES", modVersions: "SW_VERSIONS", filtAll: "ALL_NODES", filtOnline: "ONLINE", filtOffline: "OFFLINE", filtAlerts: "ALERTS" } }; let currentLang = localStorage.getItem('lang') || 'en'; function t(key) { return i18n[currentLang][key] || key; } function toggleLang() { currentLang = currentLang === 'it' ? 'en' : 'it'; localStorage.setItem('lang', currentLang); location.reload(); } function applyTranslations() { const langBtn = document.getElementById('lang-btn'); if (langBtn) langBtn.innerText = currentLang === 'it' ? "ENG" : "ITA"; document.querySelectorAll('[data-i18n]').forEach(el => { const key = el.getAttribute('data-i18n'); if (i18n[currentLang][key]) el.innerHTML = i18n[currentLang][key]; }); document.querySelectorAll('[data-i18n-title]').forEach(el => { const key = el.getAttribute('data-i18n-title'); if (i18n[currentLang][key]) el.title = i18n[currentLang][key]; }); const newPassInput = document.getElementById('new-pass'); if (newPassInput && editingUserId) newPassInput.placeholder = t('phNewPass'); else if (newPassInput) newPassInput.placeholder = t('phPass'); } function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } function q(s) { return esc(JSON.stringify(String(s ?? ''))); } // --- DIALOGHI ALERT & CONFIRM --- function customAlert(title, desc, isError = false) { const color = isError ? 'var(--danger)' : 'var(--success)'; document.getElementById('alert-title').innerHTML = '> ' + title; document.getElementById('alert-title').style.color = color; document.getElementById('alert-box').style.borderTopColor = color; document.getElementById('alert-desc').innerHTML = desc; document.getElementById('alert-modal').style.display = 'flex'; } function customConfirm(title, desc, color, callback) { document.getElementById('confirm-title').innerHTML = '> ' + title; document.getElementById('confirm-title').style.color = color; document.getElementById('confirm-box').style.borderTopColor = color; document.getElementById('confirm-desc').innerHTML = desc; document.getElementById('confirm-yes-btn').style.borderColor = color; document.getElementById('confirm-yes-btn').style.color = color; document.getElementById('confirm-yes-btn').innerText = t('btnYes'); document.getElementById('confirm-cancel-btn').innerText = t('btnCancel'); confirmActionCallback = callback; document.getElementById('confirm-modal').style.display = 'flex'; } function executeConfirmAction() { document.getElementById('confirm-modal').style.display = 'none'; if (confirmActionCallback) { confirmActionCallback(); confirmActionCallback = null; } } // --- MODALE LOGIN --- function openLoginModal() { document.getElementById('login-modal').style.display = 'flex'; setTimeout(() => document.getElementById('modal-username').focus(), 100); } function closeLoginModal() { document.getElementById('login-modal').style.display = 'none'; document.getElementById('modal-username').value = ''; document.getElementById('modal-password').value = ''; } function handleLoginEnter(e) { if (e.key === 'Enter') performLogin(); } // --- MODALE RESET HAT --- function confirmHatReset(id) { currentResetHatId = id; document.getElementById('reset-hat-desc').innerText = `${t('confHat')}${id.toUpperCase()}?`; document.getElementById('reset-hat-modal').style.display = 'flex'; } function closeHatResetModal() { document.getElementById('reset-hat-modal').style.display = 'none'; currentResetHatId = null; } async function executeHatReset() { if (!currentResetHatId) return; const clientId = currentResetHatId; closeHatResetModal(); try { const res = await fetch('/api/command', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: clientId, type: 'RESET_HAT' }) }); const data = await res.json(); if(!data.success) { customAlert(t('titleError'), esc(data.error), true); } refreshStates(); } catch (e) { console.error(e); } } // --- MODALE GLOBAL UPDATE --- function sendGlobalUpdate() { document.getElementById('update-modal').style.display = 'flex'; } function closeUpdateModal() { document.getElementById('update-modal').style.display = 'none'; } async function executeUpdateRequest() { closeUpdateModal(); try { await fetch('/api/update_nodes', { method: 'POST' }); customAlert(t('titleSuccess'), t('alertUpdateOk')); } catch (e) { console.error(e); } } // --- MODALE ADMIN & UTENTI --- async function openAdmin() { document.getElementById('admin-modal').style.display = 'flex'; loadUsers(); loadSettings(); cancelEdit(); } function closeAdmin() { document.getElementById('admin-modal').style.display = 'none'; cancelEdit(); } async function loadUsers() { const res = await fetch('/api/users'); if (!res.ok) return; const users = await res.json(); usersCache = {}; users.forEach(u => { usersCache[u.id] = u; }); document.getElementById('users-table-body').innerHTML = users.map(u => `
NO_PROFS_FOUND
`; } container.innerHTML = html; document.getElementById('override-desc').innerText = t('msgOvrSel'); document.getElementById('override-modal').style.display = 'flex'; } function sendGlobalAction(action) { document.getElementById('override-modal').style.display = 'none'; customConfirm(t('titleGlobal'), t('promptOvrConfirm'), "var(--danger)", async () => { try { const res = await fetch('/api/global_command', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({type: action}) }); const d = await res.json(); if(d.success) customAlert(t('titleSuccess'), t('msgOvrOk')); else customAlert(t('titleError'), esc(d.error), true); refreshStates(); } catch(e) { console.error(e); } }); } // --- CAMBIO PASSWORD --- function changeMyPassword() { document.getElementById('new-password-input').value = ''; document.getElementById('password-modal').style.display = 'flex'; setTimeout(() => document.getElementById('new-password-input').focus(), 100); } function closePasswordModal() { document.getElementById('password-modal').style.display = 'none'; } async function executePasswordChange() { const p = document.getElementById('new-password-input').value; if (!p) return; closePasswordModal(); try { const res = await fetch('/api/change_password', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username: me.user, new_password: p}) }); if ((await res.json()).success) { customAlert(t('titleSuccess'), t('msgPassOk')); setTimeout(() => logout(), 1500); } else { customAlert(t('titleError'), t('msgPassErr'), true); } } catch(e) { console.error(e); } } // --- MODALE FILE CONFIGURAZIONE --- function fileLabel(stem, names) { const key = String(stem).toLowerCase(); const full = (names || []).find(n => String(n).replace(/\.[^.]*$/, '').toLowerCase() === key); if (full) { const m = String(full).match(/^(.*?)(\.[^.]*)?$/); return String(m[1]).toUpperCase() + (m[2] || ''); } return String(stem).toUpperCase() + '.INI'; } function openConfigsModal(clientId) { const data = globalHealthData[clientId.toLowerCase()]; const listDiv = document.getElementById('configs-list'); let listaFile = data ? (data.config_files || data.files || []) : []; const fileNames = (data && data.file_names) || []; if (listaFile.length === 0) { listDiv.innerHTML = `${t('waitData')}
`; } else { listDiv.innerHTML = listaFile.map(f => `NO_DATA
"; return; } let html = ""; for (const [name, status] of Object.entries(data.processes)) { const isOnline = status.toLowerCase() === 'online'; const statusColor = isOnline ? 'var(--success)' : 'var(--danger)'; html += `NO_DATA. RESTART SVCS TO PUSH LOGS.
"; } else { let html = ""; for (const [software, version] of Object.entries(versions)) { html += `