feat(release): v6.0.0 - Major C2 platform evolution
- Calendar Profile Scheduler: pianificazione temporizzata con switch automatico e rollback del profilo a fine evento - Tactical APRS Map: tracciamento stazioni in mobilità, filtro dei nodi di flotta e garbage collection dopo 2h - Dynamic Timeframe Analytics: filtri temporali 12H, 24H, 48H, 7D sui grafici Chart.js con etichette intelligenti - Time Machine & Visual Diff: storico backup configurazioni .ini con visualizzatore differenze semantico - Header UX Refactor: riorganizzazione a tre righe compatte con integrazione badge operatori online in tempo reale - Complete i18n: allineamento del dizionario bilingue (IT/EN) su tutta la piattaforma
This commit is contained in:
+260
-25
@@ -9,7 +9,8 @@ function updateClock() {
|
||||
}
|
||||
|
||||
// --- VARIABILI GLOBALI E UI VIEW ---
|
||||
let clients = [];
|
||||
let clients = [];
|
||||
let activeLoggedUsers = [];
|
||||
let me = { logged_in: false, user: '', role: '', allowed_nodes: '' };
|
||||
let isAuthenticated = false;
|
||||
let usersCache = {};
|
||||
@@ -24,6 +25,7 @@ let searchQuery = '';
|
||||
let viewMode = localStorage.getItem('fleetViewMode') || 'grid';
|
||||
let fleetMap = null;
|
||||
let mapMarkers = {};
|
||||
let aprsMarkers = {};
|
||||
|
||||
let currentFocusedNode = null;
|
||||
let currentMmdvmConfig = "";
|
||||
@@ -125,7 +127,8 @@ function openNodeFocus(clientId) {
|
||||
}
|
||||
|
||||
refreshStates();
|
||||
refreshLogs();
|
||||
refreshLogs();
|
||||
setTimeout(loadNodeAnalytics, 300);
|
||||
}
|
||||
|
||||
function closeNodeFocus() {
|
||||
@@ -148,6 +151,7 @@ window.addEventListener('DOMContentLoaded', () => {
|
||||
checkServerUpdate();
|
||||
setInterval(checkServerUpdate, 3600000);
|
||||
refreshAprs();
|
||||
setInterval(cleanupAprsMarkers, 60000);
|
||||
});
|
||||
|
||||
// --- FUNZIONI FILTRO E LAYOUT ---
|
||||
@@ -208,6 +212,16 @@ function applyFilters() {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function showActiveUsers() {
|
||||
if (!activeLoggedUsers || activeLoggedUsers.length === 0) {
|
||||
customAlert("[ USERS ]", "Nessun operatore attualmente loggato.");
|
||||
return;
|
||||
}
|
||||
const html = activeLoggedUsers.map(u => `<div style="padding: 5px; border-bottom: 1px dashed var(--border-light); color: var(--success); font-family: 'JetBrains Mono'; font-size: 0.9rem;">🟢 ${esc(u.toUpperCase())}</div>`).join('');
|
||||
customAlert("[ SYS_OPS_ONLINE ]", html);
|
||||
}
|
||||
|
||||
function fmtAge(sec) {
|
||||
sec = Math.max(0, Math.round(sec));
|
||||
if (sec < 60) return sec + 's';
|
||||
@@ -533,29 +547,25 @@ async function initUI() {
|
||||
const hasAllNodes = allowedList.includes('all');
|
||||
const canOverride = hasAllNodes;
|
||||
|
||||
let actionBtns = '';
|
||||
if (role === 'admin') {
|
||||
actionBtns += `<button id="server-update-btn" onclick="confirmServerUpdate()" class="auth-btn" style="border-color:var(--danger); color:var(--danger) !important; display:none;" title="Aggiornamento Server Disponibile">[ UPD_SERVER ]</button>`;
|
||||
actionBtns += `<button onclick="sendGlobalUpdate()" class="auth-btn" style="color:var(--accent);" data-i18n-title="ttReqCfg" title="${t('ttReqCfg')}">[ ${t('btnReqCfg')} ]</button>`;
|
||||
// 1. Nella barra principale in alto teniamo SOLO [ SYS_ADM ], UTENTE e CONTROLLI SESSIONE
|
||||
let topBarAdminBtn = '';
|
||||
if (role === 'admin' || role === 'node_admin') {
|
||||
topBarAdminBtn = `<button onclick="openAdmin()" class="auth-btn" style="color:var(--primary);" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">[ ${t('btnAdmin')} ]</button>`;
|
||||
}
|
||||
if (canOverride) {
|
||||
actionBtns += `<button onclick="triggerGlobalEmergency()" class="auth-btn" style="color:var(--danger);" data-i18n-title="ttGlobal" title="${t('ttGlobal')}">[ ${t('btnGlobal')} ]</button>`;
|
||||
}
|
||||
if (role === 'admin') {
|
||||
actionBtns += `<button onclick="openAdmin()" class="auth-btn" style="color:var(--primary);" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">[ ${t('btnAdmin')} ]</button>`;
|
||||
}
|
||||
|
||||
authContainer.innerHTML = `${actionBtns}
|
||||
<span style="font-weight:300; font-size:0.85rem; margin: 0 10px; font-family:'JetBrains Mono', monospace; color:var(--primary);">USR: ${esc(String(me.user).toUpperCase())}</span>
|
||||
<button onclick="changeMyPassword()" class="auth-btn" data-i18n-title="ttPass" title="${t('ttPass')}">[ ${t('btnPass')} ]</button>
|
||||
<button onclick="logout()" class="auth-btn" data-i18n-title="ttLogout" title="${t('ttLogout')}">[ ${t('btnLogout')} ]</button>`;
|
||||
|
||||
authContainer.innerHTML = `<div style="display:flex; align-items:center; gap:8px; justify-content:flex-end; flex-wrap:nowrap; width:100%;">
|
||||
${topBarAdminBtn}
|
||||
<span style="font-weight:400; font-size:0.75rem; margin: 0 4px; font-family:'JetBrains Mono', monospace; color:var(--primary); white-space:nowrap; letter-spacing: 1px;">USR: ${esc(String(me.user).toUpperCase())}</span>
|
||||
<button onclick="changeMyPassword()" class="auth-btn" data-i18n-title="ttPass" title="${t('ttPass')}" style="padding:4px 10px; font-size:0.75rem;">[ ${t('btnPass')} ]</button>
|
||||
<button onclick="logout()" class="auth-btn" data-i18n-title="ttLogout" title="${t('ttLogout')}" style="padding:4px 10px; font-size:0.75rem;">[ ${t('btnLogout')} ]</button>
|
||||
</div>`;
|
||||
} else {
|
||||
authContainer.innerHTML = `<button onclick="openLoginModal()" class="auth-btn" style="color:var(--success);">[ AUTH ]</button>`;
|
||||
}
|
||||
|
||||
grid.innerHTML = clients.map(c => {
|
||||
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
|
||||
let showReboot = (role === 'admin' && canControl);
|
||||
let showReboot = (role === 'admin' || role === 'node_admin') && canControl;
|
||||
|
||||
return `
|
||||
<div class="card" id="card-${c.id}" data-status="offline" data-gateways="" data-loc="" data-has-warn="false">
|
||||
@@ -619,6 +629,7 @@ async function initUI() {
|
||||
<button class="btn-cmd" style="border-color: var(--primary); color: var(--primary) !important;" title="Versioni Software" onclick="openVersionsModal('${c.id}')">INFO</button>
|
||||
<button id="btn-svc-${c.id}" class="btn-cmd" style="border-color: var(--text-main);" title="${t('ttSvc')}" onclick="openServicesModal('${c.id}')">${t('btnSvc')}</button>
|
||||
<button class="btn-cmd" style="border-color: var(--accent); color: var(--accent) !important;" title="${t('ttFile')}" onclick="openConfigsModal('${c.id}')">${t('btnFile')}</button>
|
||||
<button class="btn-cmd" style="border-color: var(--success); color: var(--success) !important;" title="${t('liveTerminal')}" onclick="openLogModal('${c.id}')">LOG</button>
|
||||
<button class="btn-cmd" style="border-color: var(--danger); color: var(--danger) !important;" title="${t('ttHat')}" onclick="confirmHatReset('${c.id}')">${t('btnHat')}</button>
|
||||
<button class="btn-cmd" style="border-color: var(--danger); color: var(--danger) !important;" title="${t('ttBoot')}" onclick="confirmReboot('${c.id}')">${t('btnBoot')}</button>
|
||||
<button id="btn-ota-${c.id}" class="btn-cmd" style="border-color: var(--primary); color: var(--primary) !important;" title="Update OTA" onclick="confirmUpdateAgent('${c.id}')">OTA</button>
|
||||
@@ -742,6 +753,13 @@ function initOrUpdateMap() {
|
||||
fleetMap.fitBounds(bounds, { padding: [40, 40] });
|
||||
fleetMap._hasFitted = true;
|
||||
}
|
||||
|
||||
// Assicurati che i marker APRS siano renderizzati
|
||||
for (const [src, data] of Object.entries(aprsMarkers)) {
|
||||
if (!fleetMap.hasLayer(data.marker)) {
|
||||
data.marker.addTo(fleetMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshStates() {
|
||||
@@ -749,6 +767,18 @@ async function refreshStates() {
|
||||
const res = await fetch('/api/states'); const data = await res.json();
|
||||
latestStatesData = data;
|
||||
globalVersionsData = data.versions || {};
|
||||
if (data.web_users !== undefined) {
|
||||
const uEl = document.getElementById('active-users-count');
|
||||
if (uEl) uEl.innerText = data.web_users;
|
||||
const uBadge = document.getElementById('users-badge');
|
||||
if (uBadge) {
|
||||
uBadge.style.cursor = 'pointer';
|
||||
uBadge.onclick = showActiveUsers;
|
||||
}
|
||||
}
|
||||
if (data.logged_users !== undefined) {
|
||||
activeLoggedUsers = data.logged_users;
|
||||
}
|
||||
|
||||
clients.forEach(c => {
|
||||
try {
|
||||
@@ -766,7 +796,7 @@ async function refreshStates() {
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
|
||||
let showReboot = (role === 'admin' && canControl);
|
||||
let showReboot = (role === 'admin' || role === 'node_admin') && canControl;
|
||||
|
||||
let isTx = false;
|
||||
let activeModeColor = "var(--primary)";
|
||||
@@ -1205,6 +1235,7 @@ async function refreshStates() {
|
||||
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--primary); color: var(--primary) !important;" onclick="openVersionsModal('${c.id}')">[ INFO ]</button>`;
|
||||
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--text-main);" onclick="openServicesModal('${c.id}')">[ SVC ]</button>`;
|
||||
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--accent); color: var(--accent) !important;" onclick="openConfigsModal('${c.id}')">[ CFG ]</button>`;
|
||||
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--success); color: var(--success) !important;" onclick="openLogModal('${c.id}')">[ LOG ]</button>`;
|
||||
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--danger); color: var(--danger) !important;" onclick="confirmHatReset('${c.id}')">[ HAT ]</button>`;
|
||||
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--danger); color: var(--danger) !important;" onclick="confirmReboot('${c.id}')">[ RBT ]</button>`;
|
||||
let otaColor = (healthObj && healthObj.agent_update_available) ? 'var(--danger)' : 'var(--primary)';
|
||||
@@ -1242,11 +1273,98 @@ async function refreshAprs() {
|
||||
let html = "";
|
||||
logs.forEach(msg => {
|
||||
html += formatAprsRow(msg);
|
||||
plotAprsOnMap(msg); // Popola mappa all'avvio
|
||||
});
|
||||
tbody.innerHTML = html;
|
||||
} catch (e) { console.error(e); }
|
||||
}
|
||||
|
||||
|
||||
function parseAprsPosition(payload) {
|
||||
// Cerca pattern standard APRS (es. 4603.25N/01315.60E)
|
||||
const posRegex = /([0-9]{2})([0-9]{2}\.[0-9]{1,2})([NS])(.)([0-1][0-9]{2})([0-9]{2}\.[0-9]{1,2})([EOW])/i;
|
||||
const match = payload.match(posRegex);
|
||||
if (match) {
|
||||
let latDeg = parseInt(match[1], 10);
|
||||
let latMin = parseFloat(match[2]);
|
||||
let lat = latDeg + (latMin / 60.0);
|
||||
if (match[3].toUpperCase() === 'S') lat = -lat;
|
||||
|
||||
let lonDeg = parseInt(match[5], 10);
|
||||
let lonMin = parseFloat(match[6]);
|
||||
let lon = lonDeg + (lonMin / 60.0);
|
||||
if (match[7].toUpperCase() === 'W' || match[7].toUpperCase() === 'O') lon = -lon;
|
||||
|
||||
return { lat, lon };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function plotAprsOnMap(msg) {
|
||||
const pos = parseAprsPosition(msg.payload);
|
||||
if (!pos) return;
|
||||
|
||||
const source = msg.source;
|
||||
const sourceBase = source.split('-')[0].toLowerCase();
|
||||
|
||||
// Escludiamo dalla mappa i pacchetti provenienti dai nodi della flotta
|
||||
let isFleetNode = false;
|
||||
for (let i = 0; i < clients.length; i++) {
|
||||
let cid = clients[i].id.toLowerCase();
|
||||
let cname = (clients[i].name || "").split('-')[0].toLowerCase();
|
||||
let ccall = "";
|
||||
if (latestStatesData && latestStatesData.general && latestStatesData.general[cid]) {
|
||||
ccall = (latestStatesData.general[cid].callsign || "").split('-')[0].toLowerCase();
|
||||
}
|
||||
if (sourceBase === cid || sourceBase === cname || (ccall && sourceBase === ccall)) {
|
||||
isFleetNode = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isFleetNode) return;
|
||||
|
||||
if (aprsMarkers[source] && fleetMap) {
|
||||
fleetMap.removeLayer(aprsMarkers[source].marker);
|
||||
}
|
||||
|
||||
const customIcon = L.divIcon({
|
||||
className: 'custom-div-icon',
|
||||
html: `<div style="width: 14px; height: 14px; background-color: #f97316; border-radius: 50%; border: 2px solid #04102e; box-shadow: 0 0 10px rgba(249, 115, 22, 0.8);"></div>`,
|
||||
iconSize: [14, 14],
|
||||
iconAnchor: [7, 7]
|
||||
});
|
||||
|
||||
const popupContent = `
|
||||
<div style="font-family: 'JetBrains Mono', monospace; min-width: 150px;">
|
||||
<div style="font-weight: bold; color: #f97316; margin-bottom: 5px;">${esc(source)} <span style="font-size:0.7rem; color:var(--text-muted);">(APRS)</span></div>
|
||||
<div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 5px;">${esc(msg.time)} via ${esc(msg.path.split(',')[0])}</div>
|
||||
<div style="font-size: 0.75rem; color: var(--text-main); word-wrap: break-word; margin-bottom: 8px;">${esc(msg.payload)}</div>
|
||||
<a href="https://aprs.fi/info/a/${encodeURIComponent(source)}" target="_blank" class="btn-cmd" style="padding: 2px 6px; font-size: 0.7rem; width: 100%; border-color: #f97316; color: #f97316 !important; text-align: center; text-decoration: none; display: block; box-sizing: border-box;">[ APRS.FI ]</a>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const marker = L.marker([pos.lat, pos.lon], { icon: customIcon }).bindPopup(popupContent);
|
||||
|
||||
aprsMarkers[source] = {
|
||||
marker: marker,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
if (fleetMap) {
|
||||
marker.addTo(fleetMap);
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupAprsMarkers() {
|
||||
const now = Date.now();
|
||||
for (const [src, data] of Object.entries(aprsMarkers)) {
|
||||
if (now - data.timestamp > 7200000) { // 2 ore
|
||||
if (fleetMap) fleetMap.removeLayer(data.marker);
|
||||
delete aprsMarkers[src];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatAprsRow(msg) {
|
||||
const time = msg.time || new Date().toLocaleTimeString('it-IT', { hour12: false });
|
||||
const srcHtml = `<a href="https://aprs.fi/info/a/${encodeURIComponent(msg.source)}" target="_blank" style="color: var(--success); text-decoration: none;">${esc(msg.source)}</a>`;
|
||||
@@ -1269,6 +1387,7 @@ function addLiveAprs(msg) {
|
||||
if (tbody.children.length > 100) {
|
||||
tbody.removeChild(tbody.lastChild);
|
||||
}
|
||||
plotAprsOnMap(msg);
|
||||
}
|
||||
|
||||
async function refreshLogs() {
|
||||
@@ -1410,10 +1529,126 @@ const refreshStatesSoon = debounce(refreshStates, 300);
|
||||
const refreshLogsSoon = debounce(() => { refreshLogs(); refreshStats(); }, 500);
|
||||
|
||||
if (typeof io !== 'undefined') {
|
||||
const socket = io();
|
||||
socket.on('mqtt_status', function(data) { const badge = document.getElementById('mqtt-badge'); if (badge) { if (data.connected) { badge.innerText = "MQTT: OK"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: ERR"; badge.className = "mqtt-badge mqtt-offline"; } } });
|
||||
socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); });
|
||||
socket.on('dati_aggiornati', refreshStatesSoon);
|
||||
socket.on('log_aggiornato', refreshLogsSoon);
|
||||
socket.on('aprs_msg', function(data) { addLiveAprs(data); });
|
||||
window.socket = io();
|
||||
window.socket.on('mqtt_status', function(data) { const badge = document.getElementById('mqtt-badge'); if (badge) { if (data.connected) { badge.innerText = "MQTT: OK"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: ERR"; badge.className = "mqtt-badge mqtt-offline"; } } });
|
||||
window.socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); });
|
||||
window.socket.on('dati_aggiornati', refreshStatesSoon);
|
||||
window.socket.on('log_aggiornato', refreshLogsSoon);
|
||||
window.socket.on('aprs_msg', function(data) { addLiveAprs(data); });
|
||||
window.socket.on('web_users_count', function(data) {
|
||||
const el = document.getElementById('active-users-count');
|
||||
if (el && data && data.count !== undefined) {
|
||||
el.innerText = data.count;
|
||||
}
|
||||
if (data && data.users) {
|
||||
activeLoggedUsers = data.users;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
// --- LOGICA ANALYTICS E CHART.JS ---
|
||||
let hwChart = null;
|
||||
let rfChart = null;
|
||||
let currentAnalyticsHours = 24;
|
||||
|
||||
Chart.defaults.color = 'rgba(255, 255, 255, 0.6)';
|
||||
Chart.defaults.font.family = "'JetBrains Mono', monospace";
|
||||
|
||||
function setAnalyticsTimeframe(hours) {
|
||||
currentAnalyticsHours = hours;
|
||||
|
||||
// Update active class on pills
|
||||
[12, 24, 48, 168].forEach(h => {
|
||||
const btn = document.getElementById('btn-ana-' + h);
|
||||
if (btn) {
|
||||
if (h === hours) btn.classList.add('active');
|
||||
else btn.classList.remove('active');
|
||||
}
|
||||
});
|
||||
|
||||
// Update label text
|
||||
const labelEl = document.getElementById('analytics-time-label');
|
||||
if (labelEl) {
|
||||
labelEl.innerText = hours === 168 ? '7D' : hours + 'H';
|
||||
}
|
||||
|
||||
// Reload data
|
||||
loadNodeAnalytics();
|
||||
}
|
||||
|
||||
async function loadNodeAnalytics() {
|
||||
if (!currentFocusedNode) return;
|
||||
try {
|
||||
const res = await fetch(`/api/analytics/${currentFocusedNode}?hours=${currentAnalyticsHours}`);
|
||||
const data = await res.json();
|
||||
|
||||
if (!data.success) return;
|
||||
|
||||
// Dati Telemetria (Ore o Giorni/Ore)
|
||||
const formatLabel = (dTime) => {
|
||||
if (currentAnalyticsHours > 48) {
|
||||
const parts = dTime.split(' ');
|
||||
const dateParts = parts[0].split('-'); // YYYY-MM-DD
|
||||
return `${dateParts[2]}/${dateParts[1]} ${parts[1].substring(0, 5)}`;
|
||||
}
|
||||
return dTime.split(' ')[1].substring(0, 5);
|
||||
};
|
||||
const hwLabels = data.telemetry.map(d => formatLabel(d.time));
|
||||
const tempD = data.telemetry.map(d => d.temp);
|
||||
const cpuD = data.telemetry.map(d => d.cpu);
|
||||
|
||||
if (hwChart) hwChart.destroy();
|
||||
const ctxHw = document.getElementById('chart-hw').getContext('2d');
|
||||
hwChart = new Chart(ctxHw, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: hwLabels,
|
||||
datasets: [
|
||||
{ label: t('chartTemp'), data: tempD, borderColor: '#ef4444', backgroundColor: 'rgba(239,68,68,0.1)', fill: true, tension: 0.3, yAxisID: 'y' },
|
||||
{ label: t('chartCpu'), data: cpuD, borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,0.1)', fill: true, tension: 0.3, yAxisID: 'y1' }
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: { legend: { display: true, position: 'top' } },
|
||||
scales: {
|
||||
x: { grid: { color: 'rgba(255,255,255,0.05)' } },
|
||||
y: { type: 'linear', display: true, position: 'left', grid: { color: 'rgba(255,255,255,0.05)' }, min: 20 },
|
||||
y1: { type: 'linear', display: true, position: 'right', grid: { drawOnChartArea: false }, min: 0, max: 100 }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Dati RF
|
||||
const rfLabels = data.rf.map(d => formatLabel(d.time));
|
||||
const countD = data.rf.map(d => d.count);
|
||||
const berD = data.rf.map(d => d.ber);
|
||||
|
||||
if (rfChart) rfChart.destroy();
|
||||
const ctxRf = document.getElementById('chart-rf').getContext('2d');
|
||||
rfChart = new Chart(ctxRf, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: rfLabels,
|
||||
datasets: [
|
||||
{ label: t('chartTransits'), data: countD, backgroundColor: '#10b981', yAxisID: 'y' },
|
||||
{ label: t('chartBer'), data: berD, type: 'line', borderColor: '#f59e0b', backgroundColor: 'transparent', tension: 0.3, yAxisID: 'y1' }
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: { legend: { display: true, position: 'top' } },
|
||||
scales: {
|
||||
x: { grid: { color: 'rgba(255,255,255,0.05)' } },
|
||||
y: { type: 'linear', display: true, position: 'left', grid: { color: 'rgba(255,255,255,0.05)' }, min: 0 },
|
||||
y1: { type: 'linear', display: true, position: 'right', grid: { drawOnChartArea: false }, min: 0 }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
} catch (e) { console.error("Error loading analytics:", e); }
|
||||
}
|
||||
|
||||
+590
-16
@@ -2,6 +2,17 @@
|
||||
const i18n = {
|
||||
en: {
|
||||
lblLogLimit: "Rows:",
|
||||
btnSched: "SCHED", ttSchedule: "Calendar Profile Scheduler", schedTitle: "CALENDAR PROFILE SCHEDULER",
|
||||
schedNew: "NEW SCHEDULED EVENT", lblSchedTitle: "Event Name:", lblSchedNodes: "Target Nodes:",
|
||||
lblSchedTargetProf: "Target Profile:", lblSchedRestoreProf: "Restore Profile:",
|
||||
lblSchedStart: "Start Date/Time:", lblSchedEnd: "End Date/Time:", btnAddSched: "CREATE SCHEDULE",
|
||||
thSchedTitle: "Title", thSchedNodes: "Nodes", thSchedProf: "Profile", thSchedStart: "Start",
|
||||
thSchedEnd: "End", thSchedStatus: "Status", thSchedActs: "Actions",
|
||||
statusScheduled: "SCHEDULED", statusActive: "ACTIVE", statusCompleted: "COMPLETED", statusCancelled: "CANCELLED", statusExpired: "EXPIRED",
|
||||
confCancelSched: "Cancel this scheduled event?", msgSchedCreated: "SCHEDULE CREATED", msgSchedCancelled: "SCHEDULE CANCELLED",
|
||||
errSchedDates: "End date must be after start date!", errMissingSchedData: "Please fill all required fields!",
|
||||
optAllNodes: "ALL NODES (FLEET)", optNone: "NONE (Leave current)",
|
||||
|
||||
lastTransits: "Lastheard", loginTitle: "SYSTEM_LOGIN",
|
||||
thTime: "Time", thRep: "Repeater", thMode: "Mode", thCall: "Callsign", thDur: "Duration",
|
||||
thUser: "User", thRole: "Role", thNodes: "Nodes", thActs: "Actions",
|
||||
@@ -44,6 +55,17 @@ const i18n = {
|
||||
},
|
||||
it: {
|
||||
lblLogLimit: "Righe:",
|
||||
btnSched: "SCHED", ttSchedule: "Pianificazione Calendario Profili", schedTitle: "CALENDARIO PIANIFICAZIONE PROFILI",
|
||||
schedNew: "NUOVO EVENTO PROGRAMMATO", lblSchedTitle: "Nome Evento:", lblSchedNodes: "Nodi Coinvolti:",
|
||||
lblSchedTargetProf: "Profilo Attivazione:", lblSchedRestoreProf: "Profilo Ripristino:",
|
||||
lblSchedStart: "Data/Ora Inizio:", lblSchedEnd: "Data/Ora Fine:", btnAddSched: "CREA PIANIFICAZIONE",
|
||||
thSchedTitle: "Titolo", thSchedNodes: "Nodi", thSchedProf: "Profilo", thSchedStart: "Inizio",
|
||||
thSchedEnd: "Fine", thSchedStatus: "Stato", thSchedActs: "Azioni",
|
||||
statusScheduled: "PROGRAMMATO", statusActive: "ATTIVO", statusCompleted: "COMPLETATO", statusCancelled: "ANNULLATO", statusExpired: "SCADUTO",
|
||||
confCancelSched: "Annullare questo evento programmato?", msgSchedCreated: "PIANIFICAZIONE CREATA", msgSchedCancelled: "PIANIFICAZIONE ANNULLATA",
|
||||
errSchedDates: "La data di fine deve essere successiva a quella di inizio!", errMissingSchedData: "Compilare tutti i campi obbligatori!",
|
||||
optAllNodes: "TUTTI I NODI (FLOTTA)", optNone: "NESSUNO (Mantieni attivo)",
|
||||
|
||||
lastTransits: "Ultimi ascolti", loginTitle: "ACCESSO SISTEMA",
|
||||
thTime: "Ora", thRep: "Ripetitore", thMode: "Modo", thCall: "Nominativo", thDur: "Durata",
|
||||
thUser: "Utente", thRole: "Ruolo", thNodes: "Nodi", thActs: "Azioni",
|
||||
@@ -82,7 +104,9 @@ const i18n = {
|
||||
lblSysUptime: "Tempo di attività sistema", lblSwVersions: "Versioni Software", lblOtaUpdate: "Aggiornamento OTA", waitConfig: "IN ATTESA DELLA CONFIGURAZIONE...",
|
||||
noDaemonData: "NESSUN DATO DAL DEMONE. RETENTATIVO...", cfgEmpty: "[!] MEMORIA CFG VUOTA", netError: "ERRORE DI RETE", noModesFound: "NESSUN MODO TROVATO NELLA CONFIGURAZIONE",
|
||||
accessDenied: "[ ACCESSO NEGATO ]", savingRestart: "⏳ SALVATAGGIO & RIAVVIO IN CORSO...", stateUpdated: "✅ STATO AGGIORNATO CON SUCCESSO!",
|
||||
phSearch: "CERCA ID/CALL...", btnGrid: "[ GRIGLIA ]", btnList: "[ LISTA ]"
|
||||
phSearch: "CERCA ID/CALL...", btnGrid: "[ GRIGLIA ]", btnList: "[ LISTA ]",
|
||||
liveLogTitle: "[ LIVE_LOG: ", filterAll: "TUTTI I DEMONI", btnScrollOn: "SCROLL: ON", btnScrollOff: "SCROLL: OFF", btnClear: "PULISCI",
|
||||
logConnWait: "Connessione in corso... In attesa dei log per ", logNoData: "Nessun log recente in memoria per ", logApplyFilter: "Applicazione filtro...", btnDownloadZip: "[ SCARICA_TUTTI_CFG_ZIP ]", lblHistory: "STORICO:", optCurrentUnsaved: "Attuale (Non salvata)", btnPreviewDiff: "[ ANTEPRIMA_DIFF ]", btnCancelDiff: "ANNULLA", titleAuditLogs: "[ LOG_SICUREZZA_AUDIT ]", btnRefresh: "AGGIORNA", btnRefreshBracket: "[ AGGIORNA ]", waitLoading: "In attesa di caricamento...", titleAnalytics: "[ ANALITICHE_NODO ]", msgNoAudit: "Nessun log di sicurezza presente.", msgNoModifications: "[ NESSUNA MODIFICA RILEVATA RISPETTO ALLA CONFIGURAZIONE ATTIVA ]", warnUnverifiedDiff: "Non hai verificato il Diff visivo. Sicuro di voler sovrascrivere?", chartTemp: "Temp °C", chartCpu: "CPU %", chartTransits: "Transiti", chartBer: "BER Medio %"
|
||||
}
|
||||
};
|
||||
|
||||
@@ -177,7 +201,44 @@ async function executeUpdateRequest() {
|
||||
}
|
||||
|
||||
// --- MODALE ADMIN & UTENTI ---
|
||||
async function openAdmin() { document.getElementById('admin-modal').style.display = 'flex'; loadUsers(); loadSettings(); cancelEdit(); }
|
||||
async function openAdmin() {
|
||||
document.getElementById('admin-modal').style.display = 'flex';
|
||||
|
||||
// Inietto i bottoni operativi dentro l'header del pannello admin
|
||||
let adminBtnsHtml = '';
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
const hasAllNodes = allowedList.includes('all');
|
||||
const canOverride = hasAllNodes;
|
||||
|
||||
if (role === 'admin') {
|
||||
adminBtnsHtml += `<button id="server-update-btn-modal" onclick="confirmServerUpdate(); closeAdmin();" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; display:none; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ UPD_SERVER ]</button>`;
|
||||
adminBtnsHtml += `<button onclick="sendGlobalUpdate(); closeAdmin();" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ REQ_CFG ]</button>`;
|
||||
}
|
||||
if (role === 'admin' || role === 'node_admin') {
|
||||
adminBtnsHtml += `<button onclick="openScheduleModal(); closeAdmin();" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ SCHED ]</button>`;
|
||||
}
|
||||
if (canOverride) {
|
||||
adminBtnsHtml += `<button onclick="triggerGlobalEmergency(); closeAdmin();" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ GBL_OVR ]</button>`;
|
||||
}
|
||||
|
||||
const adminActionDiv = document.getElementById('admin-action-btns');
|
||||
if (adminActionDiv) {
|
||||
adminActionDiv.innerHTML = adminBtnsHtml;
|
||||
// Se siamo admin eseguiamo anche un check per l'update del server per mostrare/nascondere il tasto
|
||||
if (role === 'admin' && typeof GLOBAL_SERVER_UPDATE_AVAILABLE !== 'undefined' && GLOBAL_SERVER_UPDATE_AVAILABLE) {
|
||||
const upBtn = document.getElementById('server-update-btn-modal');
|
||||
if(upBtn) upBtn.style.display = 'inline-block';
|
||||
}
|
||||
}
|
||||
|
||||
if (me.role === 'admin') {
|
||||
loadUsers();
|
||||
loadSettings();
|
||||
cancelEdit();
|
||||
}
|
||||
loadAuditLogs();
|
||||
}
|
||||
function closeAdmin() { document.getElementById('admin-modal').style.display = 'none'; cancelEdit(); }
|
||||
|
||||
async function loadUsers() {
|
||||
@@ -354,16 +415,29 @@ function controlService(clientId, service, action) {
|
||||
});
|
||||
}
|
||||
|
||||
// --- MODALE EDITOR INI ---
|
||||
let currentEditClient = ""; let currentEditService = "";
|
||||
// --- MODALE EDITOR INI E BACKUP HISTORY ---
|
||||
let currentEditClient = ""; let currentEditService = ""; let currentOriginalConfig = ""; let isDiffMode = false;
|
||||
let historyConfigs = {}; // Cache per i backup
|
||||
|
||||
async function openEditorModal(clientId, service) {
|
||||
currentEditClient = clientId; currentEditService = service; document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`;
|
||||
document.getElementById('config-textarea').value = "AWAITING_STREAM..."; document.getElementById('editor-status').innerText = ""; document.getElementById('editor-modal').style.display = 'flex';
|
||||
currentEditClient = clientId; currentEditService = service; isDiffMode = false;
|
||||
document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`;
|
||||
document.getElementById('config-textarea').value = "AWAITING_STREAM...";
|
||||
document.getElementById('config-textarea').style.display = 'block';
|
||||
document.getElementById('diff-view').style.display = 'none';
|
||||
document.getElementById('btn-cancel-diff').style.display = 'none';
|
||||
document.getElementById('editor-status').innerText = "";
|
||||
document.getElementById('editor-modal').style.display = 'flex';
|
||||
document.getElementById('config-history-select').innerHTML = `<option value="">${t('optCurrentUnsaved')}</option>`;
|
||||
historyConfigs = {};
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/config_file/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`);
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
document.getElementById('config-textarea').value = data.data.raw_text || "EMPTY";
|
||||
currentOriginalConfig = data.data.raw_text || "";
|
||||
document.getElementById('config-textarea').value = currentOriginalConfig;
|
||||
fetchConfigHistory(clientId, service);
|
||||
} else {
|
||||
document.getElementById('config-textarea').value = "ERR:\n" + data.error;
|
||||
}
|
||||
@@ -371,18 +445,118 @@ async function openEditorModal(clientId, service) {
|
||||
document.getElementById('config-textarea').value = "NET_ERR";
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchConfigHistory(clientId, service) {
|
||||
try {
|
||||
const res = await fetch(`/api/config_backups/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`);
|
||||
const data = await res.json();
|
||||
if (data.success && data.backups.length > 0) {
|
||||
const select = document.getElementById('config-history-select');
|
||||
data.backups.forEach(b => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = b.id;
|
||||
opt.text = `${b.timestamp} (${b.username})`;
|
||||
select.appendChild(opt);
|
||||
});
|
||||
}
|
||||
} catch(e) { console.error("History fetch error:", e); }
|
||||
}
|
||||
|
||||
async function loadHistoryConfig() {
|
||||
const val = document.getElementById('config-history-select').value;
|
||||
if (!val) {
|
||||
// Ripristina testualmente la versione corrente se scelgono "Attuale"
|
||||
document.getElementById('config-textarea').value = currentOriginalConfig;
|
||||
return;
|
||||
}
|
||||
|
||||
if (historyConfigs[val]) {
|
||||
document.getElementById('config-textarea').value = historyConfigs[val];
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/config_backups/${val}`);
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
historyConfigs[val] = data.text;
|
||||
document.getElementById('config-textarea').value = data.text;
|
||||
}
|
||||
} catch (e) { console.error(e); }
|
||||
}
|
||||
|
||||
function previewConfigDiff() {
|
||||
const newText = document.getElementById('config-textarea').value;
|
||||
const diffView = document.getElementById('diff-view');
|
||||
const textarea = document.getElementById('config-textarea');
|
||||
|
||||
if (isDiffMode) {
|
||||
// Torna all'editor
|
||||
textarea.style.display = 'block';
|
||||
diffView.style.display = 'none';
|
||||
document.getElementById('btn-cancel-diff').style.display = 'none';
|
||||
isDiffMode = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Calcola il diff visivo
|
||||
const dmp = new diff_match_patch();
|
||||
const diffs = dmp.diff_main(currentOriginalConfig, newText);
|
||||
dmp.diff_cleanupSemantic(diffs);
|
||||
|
||||
let html = "";
|
||||
diffs.forEach(part => {
|
||||
const type = part[0]; // -1 rimossa, 1 aggiunta, 0 uguale
|
||||
const text = esc(part[1]);
|
||||
if (type === 1) html += `<span style="background-color: rgba(46, 204, 113, 0.2); color: #2ecc71;">${text}</span>`;
|
||||
else if (type === -1) html += `<span style="background-color: rgba(231, 76, 60, 0.2); color: #e74c3c; text-decoration: line-through;">${text}</span>`;
|
||||
else html += `<span style="color: var(--text-muted); opacity: 0.8;">${text}</span>`;
|
||||
});
|
||||
|
||||
if (diffs.length === 1 && diffs[0][0] === 0) {
|
||||
html = `<span style="color: var(--success); font-weight: bold;">${t('msgNoModifications')}</span>\n\n` + html;
|
||||
}
|
||||
|
||||
diffView.innerHTML = html;
|
||||
textarea.style.display = 'none';
|
||||
diffView.style.display = 'block';
|
||||
document.getElementById('btn-cancel-diff').style.display = 'block';
|
||||
isDiffMode = true;
|
||||
}
|
||||
|
||||
function cancelDiff() {
|
||||
document.getElementById('config-textarea').style.display = 'block';
|
||||
document.getElementById('diff-view').style.display = 'none';
|
||||
document.getElementById('btn-cancel-diff').style.display = 'none';
|
||||
isDiffMode = false;
|
||||
}
|
||||
|
||||
function closeEditorModal() { document.getElementById('editor-modal').style.display = 'none'; }
|
||||
|
||||
function saveConfig() {
|
||||
const textValue = document.getElementById('config-textarea').value; const statusSpan = document.getElementById('editor-status');
|
||||
customConfirm(t('titleSave'), `${t('confOvr')}<b>${currentEditClient.toUpperCase()}</b>?`, "var(--danger)", async () => {
|
||||
statusSpan.innerText = "WRITING..."; statusSpan.style.color = "var(--success)";
|
||||
try {
|
||||
const res = await fetch('/api/config_file', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: currentEditClient, service: currentEditService, config_data: { "raw_text": textValue } }) });
|
||||
const data = await res.json();
|
||||
if (data.success) { customAlert(t('titleSuccess'), "FILE_WRITTEN"); closeEditorModal(); } else { customAlert(t('titleError'), "ERR: " + esc(data.error), true); statusSpan.innerText = "ERR"; }
|
||||
} catch(e) { customAlert(t('titleError'), t('msgNetErr'), true); statusSpan.innerText = "NET_ERR"; }
|
||||
});
|
||||
const textValue = document.getElementById('config-textarea').value;
|
||||
const statusSpan = document.getElementById('editor-status');
|
||||
|
||||
if (!isDiffMode && textValue !== currentOriginalConfig) {
|
||||
customConfirm(t('titleSave'), t('warnUnverifiedDiff'), "var(--accent)", () => executeSave(textValue, statusSpan));
|
||||
} else {
|
||||
customConfirm(t('titleSave'), `${t('confOvr')}<b>${currentEditClient.toUpperCase()}</b>?`, "var(--danger)", () => executeSave(textValue, statusSpan));
|
||||
}
|
||||
}
|
||||
|
||||
async function executeSave(textValue, statusSpan) {
|
||||
statusSpan.innerText = "WRITING..."; statusSpan.style.color = "var(--success)";
|
||||
try {
|
||||
const res = await fetch('/api/config_file', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: currentEditClient, service: currentEditService, config_data: { "raw_text": textValue } }) });
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
customAlert(t('titleSuccess'), "FILE_WRITTEN");
|
||||
currentOriginalConfig = textValue; // Aggiorna l'originale corrente
|
||||
closeEditorModal();
|
||||
} else {
|
||||
customAlert(t('titleError'), "ERR: " + esc(data.error), true); statusSpan.innerText = "ERR";
|
||||
}
|
||||
} catch(e) { customAlert(t('titleError'), t('msgNetErr'), true); statusSpan.innerText = "NET_ERR"; }
|
||||
}
|
||||
|
||||
// --- MODALE VERSIONI SOFTWARE ---
|
||||
@@ -393,3 +567,403 @@ function openVersionsModal(clientId) {
|
||||
document.getElementById('versions-modal').style.display = 'flex';
|
||||
}
|
||||
function closeVersionsModal() { document.getElementById('versions-modal').style.display = 'none'; }
|
||||
|
||||
|
||||
// -------------------- LIVE LOG MODAL --------------------
|
||||
let currentLogClientId = null;
|
||||
|
||||
function openLogModal(clientId) {
|
||||
currentLogClientId = clientId.toLowerCase();
|
||||
document.getElementById('log-modal-title').innerText = clientId.toUpperCase();
|
||||
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logConnWait')} ${clientId.toUpperCase()}...</span>\n`;
|
||||
document.getElementById('log-modal').style.display = 'flex';
|
||||
document.getElementById('log-service-filter').value = 'ALL';
|
||||
|
||||
// 1. Fetch initial logs
|
||||
fetch(`/api/logs/${clientId}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.success && data.logs.length > 0) {
|
||||
document.getElementById('log-console').innerHTML = '';
|
||||
data.logs.forEach(log => appendLog(log));
|
||||
} else {
|
||||
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logNoData')} ${clientId.toUpperCase()}.</span>\n`;
|
||||
}
|
||||
})
|
||||
.catch(err => console.error("Errore fetch logs:", err));
|
||||
|
||||
// 2. Subscribe WebSocket
|
||||
window.socket.on('live_log_' + currentLogClientId, function(logEntry) {
|
||||
appendLog(logEntry);
|
||||
});
|
||||
}
|
||||
|
||||
function closeLogModal() {
|
||||
document.getElementById('log-modal').style.display = 'none';
|
||||
if (currentLogClientId) {
|
||||
window.socket.off('live_log_' + currentLogClientId);
|
||||
}
|
||||
currentLogClientId = null;
|
||||
}
|
||||
|
||||
let autoScroll = true;
|
||||
|
||||
function toggleAutoScroll() {
|
||||
autoScroll = !autoScroll;
|
||||
const btn = document.getElementById('btn-autoscroll');
|
||||
if (autoScroll) {
|
||||
btn.innerText = t('btnScrollOn') || 'SCROLL: ON';
|
||||
btn.style.borderColor = 'var(--accent)';
|
||||
btn.style.setProperty('color', 'var(--accent)', 'important');
|
||||
scrollToBottom();
|
||||
} else {
|
||||
btn.innerText = t('btnScrollOff') || 'SCROLL: OFF';
|
||||
btn.style.borderColor = 'var(--text-muted)';
|
||||
btn.style.setProperty('color', 'var(--text-muted)', 'important');
|
||||
}
|
||||
}
|
||||
|
||||
function clearLogs() {
|
||||
document.getElementById('log-console').innerHTML = '';
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
const box = document.getElementById('log-console');
|
||||
box.scrollTop = box.scrollHeight;
|
||||
}
|
||||
|
||||
function appendLog(log) {
|
||||
const filter = document.getElementById('log-service-filter').value.toLowerCase();
|
||||
const logSvc = log.service.toLowerCase();
|
||||
if (filter !== 'all' && !logSvc.includes(filter)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const box = document.getElementById('log-console');
|
||||
|
||||
let color = '#c9d1d9';
|
||||
let prefix = log.service.toLowerCase();
|
||||
|
||||
if (prefix.includes('mmdvm')) color = '#58a6ff';
|
||||
else if (prefix.includes('dmr')) color = '#3fb950';
|
||||
else if (prefix.includes('ysf')) color = '#8b5cf6'; // Violetto per YSF
|
||||
else if (prefix.includes('dstar') || prefix.includes('d-star')) color = '#f97316'; // Arancio per D-Star
|
||||
else if (prefix.includes('nxdn')) color = '#10b981'; // Verde NXDN
|
||||
else if (prefix.includes('p25')) color = '#ffcc00'; // Giallo P25
|
||||
|
||||
const span = document.createElement('div');
|
||||
span.style.marginBottom = '2px';
|
||||
|
||||
const timeSpan = `<span style="color: #8b949e;">[${log.time}]</span>`;
|
||||
const svcSpan = `<span style="color: ${color}; font-weight: bold;">[${log.service}]</span>`;
|
||||
|
||||
span.innerHTML = `${timeSpan} ${svcSpan} ${escapeHtml(log.text)}`;
|
||||
|
||||
// Remove default "Connessione in corso..." if present
|
||||
if (box.innerHTML.includes(t('logConnWait'))) {
|
||||
box.innerHTML = '';
|
||||
}
|
||||
|
||||
box.appendChild(span);
|
||||
|
||||
// Keep max 1000 lines in DOM to prevent lag
|
||||
if (box.childElementCount > 1000) {
|
||||
box.removeChild(box.firstChild);
|
||||
}
|
||||
|
||||
if (autoScroll) scrollToBottom();
|
||||
}
|
||||
|
||||
function escapeHtml(unsafe) {
|
||||
return unsafe
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function renderLogs() {
|
||||
// When filter changes, we just clear and wait for new logs, or we could refetch.
|
||||
// For simplicity, we clear the console and fetch again from server.
|
||||
if (currentLogClientId) {
|
||||
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logApplyFilter')}</span>\n`;
|
||||
fetch(`/api/logs/${currentLogClientId}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
document.getElementById('log-console').innerHTML = '';
|
||||
if (data.success) {
|
||||
data.logs.forEach(log => appendLog(log));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// --- SECURITY AUDIT LOGS ---
|
||||
async function loadAuditLogs() {
|
||||
try {
|
||||
const res = await fetch('/api/audit_logs');
|
||||
const data = await res.json();
|
||||
const container = document.getElementById('audit-logs-container');
|
||||
if (data.success && data.logs) {
|
||||
if (data.logs.length === 0) {
|
||||
container.innerHTML = `<span style="color: var(--text-muted);">${t('msgNoAudit')}</span>`;
|
||||
return;
|
||||
}
|
||||
let html = '';
|
||||
data.logs.forEach(log => {
|
||||
html += `<div style="border-bottom: 1px dashed var(--border-light); padding: 4px 0; display: flex; gap: 15px;">
|
||||
<span style="color: var(--text-muted); flex: 0 0 140px;">[${log.time}]</span>
|
||||
<span style="color: var(--primary); flex: 0 0 100px;">${esc(log.user.toUpperCase())}</span>
|
||||
<span style="color: var(--success); flex: 0 0 80px;">${esc(log.node.toUpperCase())}</span>
|
||||
<span style="color: var(--text-main); flex: 1;">${esc(log.cmd)}</span>
|
||||
</div>`;
|
||||
});
|
||||
container.innerHTML = html;
|
||||
}
|
||||
} catch(e) { console.error("Error loading audit logs:", e); }
|
||||
}
|
||||
|
||||
|
||||
// --- MODALE CALENDARIO SCHEDULAZIONE PROFILI ---
|
||||
async function openScheduleModal() {
|
||||
document.getElementById('schedule-modal').style.display = 'flex';
|
||||
populateScheduleNodeOptions();
|
||||
loadSchedules();
|
||||
|
||||
// Inizializza le date con orari coerenti (Inizio: adesso + 5 min, Fine: adesso + 2 ore)
|
||||
const now = new Date();
|
||||
const in5m = new Date(now.getTime() + 5 * 60000);
|
||||
const in2h = new Date(now.getTime() + 125 * 60000);
|
||||
|
||||
const toLocalISO = (d) => {
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
};
|
||||
|
||||
document.getElementById('sched-start').value = toLocalISO(in5m);
|
||||
document.getElementById('sched-end').value = toLocalISO(in2h);
|
||||
}
|
||||
|
||||
function closeScheduleModal() {
|
||||
document.getElementById('schedule-modal').style.display = 'none';
|
||||
}
|
||||
|
||||
function updateScheduleProfileOptions() {
|
||||
const selNodes = document.getElementById('sched-nodes-select');
|
||||
const selTarget = document.getElementById('sched-target-prof');
|
||||
const selRestore = document.getElementById('sched-restore-prof');
|
||||
if (!selNodes || !selTarget || !selRestore) return;
|
||||
|
||||
// Proviamo a estrarre i nomi dei profili dal primo nodo selezionato
|
||||
const selectedCid = selNodes.value;
|
||||
let profiles = { "A": "Profilo A", "B": "Profilo B" }; // Default
|
||||
|
||||
if (selectedCid !== 'all' && globalHealthData[selectedCid] && globalHealthData[selectedCid].profiles) {
|
||||
profiles = globalHealthData[selectedCid].profiles;
|
||||
} else {
|
||||
// Se è 'all', cerchiamo il primo nodo disponibile che abbia i profili valorizzati
|
||||
for (let cid in globalHealthData) {
|
||||
if (globalHealthData[cid] && globalHealthData[cid].profiles && Object.keys(globalHealthData[cid].profiles).length > 0) {
|
||||
profiles = globalHealthData[cid].profiles;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Aggiorniamo le select
|
||||
let htmlTarget = "";
|
||||
let htmlRestore = "";
|
||||
|
||||
for (const [pKey, pLabel] of Object.entries(profiles)) {
|
||||
htmlTarget += `<option value="${pKey}">${pKey} (${esc(pLabel)})</option>`;
|
||||
htmlRestore += `<option value="${pKey}">${pKey} (${esc(pLabel)})</option>`;
|
||||
}
|
||||
htmlRestore += `<option value="NONE" data-i18n="optNone">NONE (Leave active)</option>`;
|
||||
|
||||
// Salviamo i valori attuali se possibile per non resettarli
|
||||
const currTarget = selTarget.value;
|
||||
const currRestore = selRestore.value;
|
||||
|
||||
selTarget.innerHTML = htmlTarget;
|
||||
selRestore.innerHTML = htmlRestore;
|
||||
|
||||
if(currTarget && [...selTarget.options].some(o => o.value === currTarget)) selTarget.value = currTarget;
|
||||
if(currRestore && [...selRestore.options].some(o => o.value === currRestore)) selRestore.value = currRestore;
|
||||
|
||||
// Riapplichiamo le traduzioni per l'opzione NONE se in italiano
|
||||
if (currentLang === 'it') {
|
||||
const noneOpt = selRestore.querySelector('option[value="NONE"]');
|
||||
if(noneOpt) noneOpt.innerText = "NESSUNO (Mantieni attivo)";
|
||||
}
|
||||
}
|
||||
|
||||
function populateScheduleNodeOptions() {
|
||||
const sel = document.getElementById('sched-nodes-select');
|
||||
if (!sel) return;
|
||||
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
const hasAll = allowedList.includes('all');
|
||||
|
||||
let html = '';
|
||||
if (hasAll || role === 'admin') {
|
||||
html += `<option value="all">${t('optAllNodes')}</option>`;
|
||||
}
|
||||
|
||||
clients.forEach(c => {
|
||||
if (hasAll || allowedList.includes(c.id.toLowerCase())) {
|
||||
html += `<option value="${c.id}">${esc(c.name)} (${c.id.toUpperCase()})</option>`;
|
||||
}
|
||||
});
|
||||
|
||||
sel.innerHTML = html;
|
||||
sel.addEventListener('change', updateScheduleProfileOptions);
|
||||
updateScheduleProfileOptions();
|
||||
}
|
||||
|
||||
async function loadSchedules() {
|
||||
const tbody = document.getElementById('schedules-table-body');
|
||||
if (!tbody) return;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/schedules');
|
||||
const data = await res.json();
|
||||
|
||||
if (!data.success || !data.schedules || data.schedules.length === 0) {
|
||||
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:15px;">NO_SCHEDULES_FOUND</td></tr>`;
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = data.schedules.map(s => {
|
||||
let statusColor = "var(--text-muted)";
|
||||
let statusClass = "";
|
||||
let statusText = s.status;
|
||||
|
||||
if (s.status === 'SCHEDULED') {
|
||||
statusColor = "#f59e0b";
|
||||
statusText = t('statusScheduled');
|
||||
} else if (s.status === 'ACTIVE') {
|
||||
statusColor = "var(--success)";
|
||||
statusClass = "blink";
|
||||
statusText = t('statusActive');
|
||||
} else if (s.status === 'COMPLETED') {
|
||||
statusColor = "var(--text-muted)";
|
||||
statusText = t('statusCompleted');
|
||||
} else if (s.status === 'CANCELLED') {
|
||||
statusColor = "var(--danger)";
|
||||
statusText = t('statusCancelled');
|
||||
} else if (s.status === 'EXPIRED') {
|
||||
statusColor = "var(--text-muted)";
|
||||
statusText = t('statusExpired');
|
||||
}
|
||||
|
||||
const isFinished = ['COMPLETED', 'CANCELLED', 'EXPIRED'].includes(s.status);
|
||||
|
||||
|
||||
// Tentativo di dedurre il profilo di partenza dal primo nodo o dai nodi target
|
||||
let startProf = "?";
|
||||
let cids = s.target_nodes.toLowerCase() === 'all' ? Object.keys(globalHealthData) : s.target_nodes.toLowerCase().split(',');
|
||||
for (let i = 0; i < cids.length; i++) {
|
||||
let cid = cids[i].trim();
|
||||
let card = document.getElementById(`card-${cid}`);
|
||||
if (card && card.dataset.lastMode) {
|
||||
startProf = card.dataset.lastMode;
|
||||
// Se leggiamo DMR o D-STAR non è un nome di profilo. Dobbiamo guardare se nel telemetry c'è una hint
|
||||
let tel = latestStatesData && latestStatesData.telemetry && latestStatesData.telemetry[cid] ? latestStatesData.telemetry[cid] : {};
|
||||
if(tel.alt && tel.alt.includes('SCHED:')) {
|
||||
startProf = tel.alt.split(':')[1].trim();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (startProf === "?" || startProf.length > 5) startProf = "CURR"; // Current
|
||||
|
||||
let profDisplay = `<span style="color:var(--text-muted);">${esc(startProf)}</span> ➔ <b style="color:var(--accent);">${esc(s.target_profile)}</b>`;
|
||||
if (s.restore_profile !== 'NONE') {
|
||||
profDisplay += ` ➔ <span style="color:var(--success);">${esc(s.restore_profile)}</span>`;
|
||||
}
|
||||
|
||||
return `<tr>
|
||||
<td style="font-weight:bold; color:var(--text-main);">${esc(s.title)}</td>
|
||||
<td><span style="color:var(--primary); font-family:'JetBrains Mono',monospace;">${esc(s.target_nodes.toUpperCase())}</span></td>
|
||||
<td style="font-family:'JetBrains Mono',monospace;">${profDisplay}</td>
|
||||
<td style="font-size:0.8rem; color:var(--text-muted);">${esc(s.start_time.substring(5, 16))}</td>
|
||||
<td style="font-size:0.8rem; color:var(--text-muted);">${esc(s.end_time.substring(5, 16))}</td>
|
||||
<td><span class="${statusClass}" style="color:${statusColor}; font-weight:bold; font-size:0.8rem;">[ ${statusText} ]</span></td>
|
||||
<td style="text-align:right;">
|
||||
${!isFinished ? `<button onclick="cancelSchedule(${s.id})" class="btn-cmd" style="border-color:var(--danger); color:var(--danger)!important; padding:4px 8px; font-size:0.75rem; width:auto; flex:none;">DEL</button>` : '—'}
|
||||
</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
|
||||
} catch(e) {
|
||||
console.error("Error loading schedules:", e);
|
||||
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; color:var(--danger); padding:15px;">NET_ERR</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function submitSchedule() {
|
||||
const title = document.getElementById('sched-title').value.trim();
|
||||
const targetNodes = document.getElementById('sched-nodes-select').value;
|
||||
const targetProf = document.getElementById('sched-target-prof').value.trim().toUpperCase();
|
||||
const restoreProf = document.getElementById('sched-restore-prof').value.trim().toUpperCase();
|
||||
const startTime = document.getElementById('sched-start').value;
|
||||
const endTime = document.getElementById('sched-end').value;
|
||||
|
||||
if (!title || !targetNodes || !targetProf || !startTime || !endTime) {
|
||||
return customAlert(t('titleError'), t('errMissingSchedData'), true);
|
||||
}
|
||||
|
||||
if (startTime >= endTime) {
|
||||
return customAlert(t('titleError'), t('errSchedDates'), true);
|
||||
}
|
||||
|
||||
const payload = {
|
||||
title: title,
|
||||
target_nodes: targetNodes,
|
||||
target_profile: targetProf,
|
||||
restore_profile: restoreProf,
|
||||
start_time: startTime,
|
||||
end_time: endTime
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (data.success) {
|
||||
customAlert(t('titleSuccess'), t('msgSchedCreated'));
|
||||
document.getElementById('sched-title').value = '';
|
||||
loadSchedules();
|
||||
} else {
|
||||
customAlert(t('titleError'), esc(data.error), true);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error(e);
|
||||
customAlert(t('titleError'), t('msgNetErr'), true);
|
||||
}
|
||||
}
|
||||
|
||||
function cancelSchedule(sid) {
|
||||
customConfirm(t('titleAction'), t('confCancelSched'), "var(--danger)", async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/schedules/${sid}`, { method: 'DELETE' });
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
customAlert(t('titleSuccess'), t('msgSchedCancelled'));
|
||||
loadSchedules();
|
||||
} else {
|
||||
customAlert(t('titleError'), esc(data.error), true);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error(e);
|
||||
customAlert(t('titleError'), t('msgNetErr'), true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user