Files
fleet-control-server/templates/index.html
T
iv3jdv e1b344f509 feat: rilascio versione 4.0 - Advanced Filtering, List View e Gateway States
- UI: Aggiunta barra sticky nella vista NODES con ricerca testuale real-time (ID, Callsign, Locazione).
- UI: Aggiunti filtri rapidi per stato (Online/Offline) e per protocollo (DMR, YSF, D-STAR, NXDN).
- UI: Implementato toggle Grid/List view per ottimizzare la lettura di flotte con molti nodi.
- Core: Nuovo sistema di tracciamento real-time degli stati dei Gateway tramite MQTT (linking, unlinked, failed).
- Core: Lettura avanzata della configurazione DMRGateway per il rilevamento dinamico dei Multi-Network (fino a 5 reti DMR contemporanee).
- UI: Introdotti badge visivi dinamici per i Gateway con colorazione basata sullo stato di connessione ai Reflector/TG.
2026-10-24 15:42:49 +02:00

1474 lines
117 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" href="data:,">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fleet Control Console</title>
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#0d1117">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="apple-touch-icon" href="/icon-512.png">
<meta name="apple-mobile-web-app-title" content="Fleet C2">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
<style>
/* --- TEMA MODERNO (Soft UI / Tailwind inspired) --- */
:root {
--primary: #3b82f6; --success: #10b981; --danger: #ef4444; --accent: #8b5cf6;
--bg-gradient: #0f172a;
--card-bg: #1e293b;
--border-color: rgba(255, 255, 255, 0.1);
--text-main: #f8fafc;
--text-muted: #94a3b8;
--topbar-bg: #1e293b;
}
* { box-sizing: border-box; }
body { font-family: 'Inter', sans-serif; background: var(--bg-gradient); margin: 0; padding: 0; color: var(--text-main); min-height: 100vh; }
#top-bar-container { position: sticky; top: 0; z-index: 100; padding: 15px 20px; display: flex; justify-content: center; background: rgba(15, 23, 42, 0.85); backdrop-filter: blur(10px); margin-bottom: 30px; }
#top-bar { background: var(--topbar-bg); padding: 12px 30px; display: flex; justify-content: space-between; align-items: center; border-radius: 12px; border: 1px solid var(--border-color); width: 100%; max-width: 1400px; box-shadow: 0 4px 15px rgba(0,0,0,0.3); }
.title-brand { font-size: 1.2rem; font-weight: 800; letter-spacing: 2px; color: var(--text-main); font-family: 'JetBrains Mono', monospace; }
.nav-tabs { display: flex; gap: 15px; margin-left: 30px; flex: 1; }
.nav-tab { background: transparent; border: none; color: var(--text-muted); font-size: 0.95rem; font-weight: 800; cursor: pointer; padding: 8px 16px; border-radius: 8px; transition: all 0.2s ease; font-family: 'Inter', sans-serif; letter-spacing: 1px; }
.nav-tab:hover { color: var(--text-main); background: rgba(255,255,255,0.05); }
.nav-tab.active { color: var(--primary); background: rgba(59, 130, 246, 0.1); }
.theme-switch { background: transparent; border: 1px solid var(--border-color); color: var(--text-muted); padding: 6px 14px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem; font-family: 'Inter', sans-serif; transition: all 0.2s; }
.theme-switch:hover { color: var(--text-main); border-color: var(--text-main); }
/* FILTRI E CONTROLLI VIEW (Versione 4.0) */
.filter-bar { background: var(--topbar-bg); border-radius: 12px; border: 1px solid var(--border-color); padding: 10px 20px; display: flex; gap: 15px; flex-wrap: wrap; align-items: center; justify-content: space-between; box-shadow: 0 4px 12px rgba(0,0,0,0.2); margin-bottom: 20px; }
.filter-pill { background: transparent; border: 1px solid var(--border-color); color: var(--text-muted); padding: 6px 14px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; cursor: pointer; transition: all 0.2s ease; }
.filter-pill:hover { background: rgba(255,255,255,0.05); color: var(--text-main); }
.filter-pill.active { background: rgba(59, 130, 246, 0.15); color: var(--primary); border-color: var(--primary); }
/* GRIGLIA E LISTA (Versione 4.0) */
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 20px; max-width: 1400px; margin: 0 auto; padding: 0 20px; }
.list-view { display: flex; flex-direction: column; gap: 10px; max-width: 1400px; margin: 0 auto; padding: 0 20px; }
.list-view .card { flex-direction: row; flex-wrap: wrap; align-items: center; justify-content: space-between; padding: 15px; gap: 15px; }
.list-view .card-header { border-bottom: none; padding-bottom: 0; margin-bottom: 0; flex: 1 1 200px; }
.list-view .health-bar { display: flex; flex-wrap: nowrap; margin-bottom: 0; flex: 1 1 auto; justify-content: center; }
.list-view .freq-bar { margin-bottom: 0; padding: 5px 10px; flex: 1 1 auto; }
.list-view .ts-container { flex-direction: row; margin-bottom: 0; flex: 1 1 250px; }
.list-view .terminal-log { display: none; }
.list-view .node-meta { margin-bottom: 0; text-align: left; }
.list-view .admin-dropdown { width: auto; flex: 0 0 auto; }
.card { background: var(--card-bg) !important; border-radius: 12px; padding: 20px; border: 1px solid var(--border-color); border-top: 3px solid var(--border-color) !important; display: flex; flex-direction: column; box-shadow: 0 4px 12px rgba(0,0,0,0.2) !important; filter: none !important; opacity: 1 !important; transition: all 0.3s ease; }
.card-header { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-start; gap: 10px; margin-bottom: 15px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; }
.client-name { font-size: 1.2rem; font-weight: 800; white-space: normal; word-break: break-word; flex: 1 1 100px; line-height: 1.2; padding-top: 2px; }
.header-badges { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; justify-content: flex-end; flex: 1 1 auto; }
.badge-id { font-size: 0.75rem; font-family: 'JetBrains Mono', monospace; background: rgba(0,0,0,0.3); padding: 4px 8px; border-radius: 6px; border: 1px solid var(--border-color); color: var(--text-muted); }
.health-bar { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.75rem; font-weight: 600; background: rgba(0,0,0,0.2); padding: 10px; border-radius: 8px; margin-bottom: 15px; border: 1px solid var(--border-color); font-family: 'JetBrains Mono', monospace; text-align: center; }
.health-bar > span { background: rgba(255,255,255,0.03); padding: 6px; border-radius: 6px; }
.freq-bar { display: flex; justify-content: space-around; font-size: 0.8rem; font-weight: 800; background: rgba(0,0,0,0.2); padding: 8px 10px; border-radius: 8px; margin-bottom: 10px; border: 1px dashed var(--border-color); font-family: 'JetBrains Mono', monospace; }
.freq-tx { color: #f87171; } .freq-rx { color: #4ade80; }
.seen-bar { display: flex; flex-wrap: wrap; justify-content: center; gap: 4px 14px; font-size: 0.7rem; font-family: 'JetBrains Mono', monospace; color: var(--text-muted); margin: -6px 0 12px 0; }
.seen-item b { font-weight: 700; }
.seen-item.ok b { color: var(--success); }
.seen-item.warn, .seen-item.warn b { color: #f59e0b; font-weight: 700; }
.node-meta { font-size: 0.75rem; color: #8b949e; text-align: center; margin-bottom: 10px; line-height: 1.4; }
.node-meta-item { display: block; }
.type-badge { font-size: 0.65rem; padding: 4px 8px; border-radius: 6px; font-weight: 700; text-transform: uppercase; display: inline-block; margin-left: 0; vertical-align: middle; }
.type-repeater { background: rgba(59, 130, 246, 0.15); color: var(--primary); border: 1px solid var(--primary); }
.type-hotspot { background: rgba(139, 92, 246, 0.15); color: var(--accent); border: 1px solid var(--accent); }
.status-display { text-align: center; font-family: 'Inter', sans-serif; font-size: 0.9rem; font-weight: 700; padding: 8px; border-radius: 6px; background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); margin-bottom: 10px; color: var(--text-muted); }
.card.online .status-display { color: var(--success); border-color: rgba(16, 185, 129, 0.4); background: rgba(16, 185, 129, 0.1); }
.status-offline { color: var(--danger) !important; border-color: rgba(239, 68, 68, 0.4) !important; }
/* GATEWAY BAR (Versione 4.0) */
.gateway-bar { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 15px; justify-content: center; }
.ts-container { display: flex; flex-direction: column; gap: 6px; margin-bottom: 15px; }
.dmr-info { font-size: 0.85rem; font-weight: 600; font-family: 'JetBrains Mono', monospace; padding: 8px 12px; border-radius: 6px; background: rgba(0,0,0,0.2) !important; border: 1px solid var(--border-color); border-left: 4px solid var(--border-color) !important; color: var(--text-muted) !important; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: all 0.3s; }
.terminal-log { background: #010409; color: var(--text-muted); font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; border-radius: 6px; padding: 10px; max-height: 90px; overflow-y: auto; border: 1px solid var(--border-color); line-height: 1.4; margin-bottom: 15px; box-shadow: inset 0 2px 5px rgba(0,0,0,0.5); scrollbar-width: thin; scrollbar-color: var(--border-color) transparent; }
.actions { display: none; gap: 8px; flex-wrap: wrap; margin-top: auto; }
.btn-cmd { flex: 1; padding: 8px 10px; border: 1px solid transparent; background: rgba(255,255,255,0.05) !important; border-radius: 6px; font-weight: 600; font-size: 0.75rem; cursor: pointer; color: var(--text-main) !important; font-family: 'Inter', sans-serif; transition: all 0.2s ease; display: flex; align-items: center; justify-content: center; gap: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.2) !important; }
.btn-cmd:hover { filter: brightness(1.2); }
details.admin-dropdown summary { list-style: none; display: flex; justify-content: center; align-items: center; }
details.admin-dropdown summary::-webkit-details-marker { display: none; }
.mqtt-badge { padding: 4px 10px; border-radius: 6px; font-size: 0.75rem; font-weight: 800; font-family: 'JetBrains Mono', monospace; transition: all 0.3s ease; border: 1px solid var(--border-color); display: flex; align-items: center; justify-content: center; height: 30px;}
.mqtt-online { background: rgba(16, 185, 129, 0.1); color: var(--success); border-color: var(--success); }
.mqtt-offline { background: rgba(239, 68, 68, 0.1); color: var(--danger); border-color: var(--danger); animation: danger-glow 2s infinite; }
.table-container { background: var(--card-bg); border-radius: 12px; border: 1px solid var(--border-color); overflow-x: auto; overflow-y: auto; max-height: 500px; margin: 0 20px 40px 20px; -webkit-overflow-scrolling: touch; box-shadow: 0 4px 12px rgba(0,0,0,0.2); }
thead th { position: sticky; top: 0; z-index: 10; background: #0f172a; border-bottom: 2px solid var(--primary); }
table { width: 100%; min-width: 100%; border-collapse: collapse; text-align: left; font-size: 0.85rem; font-family: 'Inter', sans-serif; white-space: nowrap; }
th, td { padding: 12px 16px; border-bottom: 1px solid var(--border-color); line-height: 1.6; vertical-align: middle; }
th { background-color: rgba(255, 255, 255, 0.02); font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; font-size: 0.75rem; color: var(--text-muted); }
tbody tr:nth-child(even) { background-color: rgba(255, 255, 255, 0.015); }
@keyframes soft-glow { 0% { box-shadow: 0 0 5px var(--pulse-color, var(--primary)); border-color: var(--border-color); } 50% { box-shadow: 0 0 15px var(--pulse-color, var(--primary)); border-color: var(--pulse-color, var(--primary)); } 100% { box-shadow: 0 0 5px var(--pulse-color, var(--primary)); border-color: var(--border-color); } }
.tx-active-unified { animation: soft-glow 2s infinite !important; color: var(--text-main) !important; background: rgba(0,0,0,0.3) !important; border-left: 4px solid var(--pulse-color, var(--primary)) !important; }
@keyframes danger-glow { 0% { box-shadow: 0 0 5px var(--danger); border-color: var(--border-color); } 50% { box-shadow: 0 0 15px var(--danger); border-color: var(--danger); } 100% { box-shadow: 0 0 5px var(--danger); border-color: var(--border-color); } }
.blink { animation: danger-glow 1.5s infinite; color: var(--danger) !important; border: 1px solid var(--danger) !important; }
.modal-overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(15, 23, 42, 0.9); z-index:1000; align-items:center; justify-content:center; backdrop-filter: blur(5px); }
.modal-top { z-index: 5000 !important; }
.modal-content { background:var(--card-bg); border:1px solid var(--border-color); padding:25px; border-radius:12px; max-height: 90vh; overflow-y: auto; box-shadow: 0 10px 40px rgba(0,0,0,0.5); }
.auth-btn { background: rgba(255,255,255,0.05); color: var(--text-main); border: 1px solid var(--border-color); padding: 6px 12px; border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.8rem; font-family: 'Inter', sans-serif; transition: all 0.2s; }
.auth-btn:hover { border-color: var(--text-main); background: rgba(255,255,255,0.1); }
input, select { background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); color: var(--text-main); padding: 8px 12px; border-radius: 6px; font-family: 'Inter', sans-serif; outline: none; }
input:focus, select:focus { border-color: var(--primary); }
input:disabled { opacity: 0.5; cursor: not-allowed; }
option { background: var(--card-bg); color: var(--text-main); }
.mini-card { background: var(--card-bg); border-radius: 10px; border: 1px solid var(--border-color); padding: 15px 10px; display: flex; flex-direction: column; align-items: center; justify-content: space-between; text-align: center; transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease; cursor: pointer; box-shadow: 0 4px 6px rgba(0,0,0,0.1); height: 105px; width: 160px; overflow: hidden; }
.mini-card:hover { transform: translateY(-4px); box-shadow: 0 8px 15px rgba(0,0,0,0.3); }
.mini-card-content { width: 100%; overflow: hidden; }
.mini-card-name { font-weight: 800; font-size: 0.95rem; width: 100%; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mini-card-status { font-size: 0.65rem; font-weight: 800; padding: 4px 6px; border-radius: 6px; width: 100%; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
@media (max-width: 768px) {
#top-bar-container { top: 0; padding: 10px; margin-bottom: 15px; }
#top-bar { flex-direction: column; padding: 15px; gap: 12px; border-radius: 12px; }
.title-brand { font-size: 1.1rem; text-align: center; width: 100%; }
#top-bar > div { width: 100%; flex-wrap: wrap; justify-content: center; gap: 8px !important; }
#auth-container { width: 100%; justify-content: center; flex-wrap: wrap; padding-top: 12px; border-top: 1px solid var(--border-color); }
#auth-container > span { width: 100%; text-align: center; margin-bottom: 8px; font-family: 'Inter', sans-serif; }
.auth-btn, .theme-switch { flex: 1 1 auto; text-align: center; }
.nav-tabs { position: fixed; bottom: 0; left: 0; width: 100%; background: var(--topbar-bg); border-top: 1px solid var(--border-color); margin: 0; padding: 10px 0; justify-content: space-around; z-index: 1000; flex-direction: row; gap: 0; padding-bottom: env(safe-area-inset-bottom, 10px); box-shadow: 0 -4px 15px rgba(0,0,0,0.3); }
.nav-tab { font-size: 1rem; padding: 12px; flex: 1; text-align: center; border-radius: 0; }
body { padding-bottom: 70px; }
.filter-bar { flex-direction: column; }
.list-view .card { flex-direction: column; align-items: stretch; }
}
</style>
</head>
<body>
<div id="top-bar-container">
<div id="top-bar">
<div class="title-brand">FLEET CONTROL CONSOLE</div>
<div class="nav-tabs">
<button class="nav-tab active" onclick="switchView('home')" id="tab-home">HOME</button>
<button class="nav-tab" onclick="switchView('nodes')" id="tab-nodes">NODES</button>
</div>
<div style="display: flex; align-items: center; gap: 12px;">
<span id="mqtt-badge" class="mqtt-badge mqtt-offline">MQTT: CHECKING...</span>
<button class="theme-switch" id="lang-btn" onclick="toggleLang()" data-i18n-title="ttLang">🇮🇹 ITA</button>
<button class="theme-switch" id="push-btn" onclick="subscribeToPush()">🔔 PUSH</button>
<div id="auth-container" style="display:flex; align-items:center; gap:8px;"></div>
</div>
</div>
</div>
<div id="view-nodes" style="display: none;">
<!-- Barra Filtri Versione 4.0 -->
<div style="max-width: 1400px; margin: 0 auto; padding: 0 20px;">
<div class="filter-bar">
<div style="display: flex; gap: 8px; flex-wrap: wrap;" id="node-filters">
<button class="filter-pill active" onclick="setFilter('all')" data-i18n="filtAll">All Nodes</button>
<button class="filter-pill" onclick="setFilter('online')" data-i18n="filtOnline">Online</button>
<button class="filter-pill" onclick="setFilter('offline')" data-i18n="filtOffline">Offline</button>
<div style="width: 1px; background: var(--border-color); margin: 0 5px;"></div>
<button class="filter-pill" onclick="setFilter('dmr')" style="color: #3b82f6; border-color: rgba(59,130,246,0.3);">DMR</button>
<button class="filter-pill" onclick="setFilter('ysf')" style="color: #8b5cf6; border-color: rgba(139,92,246,0.3);">YSF</button>
<button class="filter-pill" onclick="setFilter('d-star')" style="color: #06b6d4; border-color: rgba(6,182,212,0.3);">D-STAR</button>
<button class="filter-pill" onclick="setFilter('nxdn')" style="color: #10b981; border-color: rgba(16,185,129,0.3);">NXDN</button>
</div>
<div style="display: flex; gap: 10px; align-items: center; width: auto; flex-grow: 1; justify-content: flex-end;">
<input type="text" id="node-search" placeholder="Search ID / Callsign..." onkeyup="applyFilters()" style="padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); background: rgba(0,0,0,0.2); color: white; flex-grow: 1; max-width: 200px;">
<button id="view-toggle-btn" class="btn-cmd" style="background: rgba(255,255,255,0.1); padding: 8px 12px; flex: 0 0 auto; width: auto;" onclick="toggleViewMode()" title="Toggle Grid/List View">🔲 GRID</button>
</div>
</div>
</div>
<div class="grid" id="client-grid"></div>
</div>
<div id="view-home">
<div style="max-width: 1400px; margin: 0 auto 20px auto; padding: 0 20px;">
<h3 style="margin: 0 0 15px 0; font-weight: 800; display: flex; align-items: center; gap: 10px; color: var(--text-main);">
<span style="font-size: 1.2rem;">🟢</span> <span>FLEET STATUS</span>
</h3>
<div id="home-mini-nodes" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 15px;"></div>
</div>
<div style="max-width: 1400px; margin: 0 auto 30px auto;">
<div style="padding: 0 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 15px;">
<h3 style="margin: 0; font-weight: 800; display: flex; align-items: center; gap: 10px; color: var(--text-main);">
<span style="font-size: 1.5rem;">📡</span> <span data-i18n="lastTransits">Lastheard</span>
</h3>
<select id="stat-node-filter" onchange="refreshStats(); refreshLogs();" style="font-weight: bold; cursor: pointer;">
<option value="all">🌐 ALL NODES</option>
</select>
</div>
<div class="table-container" style="margin-bottom: 0;">
<table>
<thead>
<tr>
<th data-i18n="thTime">Time</th>
<th data-i18n="thRep">Repeater</th>
<th data-i18n="thMode">Mode</th>
<th style="text-align: center;">YSF Mode</th>
<th style="text-align: center;">Source</th>
<th style="text-align: center;">REF / SLOT</th>
<th data-i18n="thCall">Callsign</th>
<th>Target / TG</th>
<th data-i18n="thDur">Duration</th>
<th>BER</th>
<th>RSSI</th>
</tr>
</thead>
<tbody id="log-body"></tbody>
</table>
</div>
</div>
<div style="max-width: 1400px; margin: 0 auto 30px auto; padding: 0 20px;">
<h3 style="margin: 0 0 15px 0; font-weight: 800; display: flex; align-items: center; gap: 10px; color: var(--text-main);">
<span style="font-size: 1.5rem;">📊</span> <span data-i18n="statTitle">DAILY STATISTICS</span>
</h3>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
<div class="card" style="padding: 15px; border-top-color: var(--accent) !important;">
<h4 style="margin: 0 0 10px 0; color: var(--accent);" data-i18n="statTopTG">🎯 TOP TALKGROUPS</h4>
<div id="stat-tgs" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading">Loading...</div>
</div>
<div class="card" style="padding: 15px; border-top-color: var(--success) !important;">
<h4 style="margin: 0 0 10px 0; color: var(--success);" data-i18n="statTopCall">🗣️ TOP CALLSIGNS</h4>
<div id="stat-calls" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading">Loading...</div>
</div>
<div class="card" style="padding: 15px; border-top-color: var(--primary) !important; display: flex; justify-content: space-around; align-items: center; text-align: center; flex-direction: row;">
<div>
<div style="font-size: 1.8rem; font-weight: 800; color: var(--text-main); font-family: 'JetBrains Mono', monospace;"><span id="stat-avg">--</span>s</div>
<div style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: bold;" data-i18n="statAvgDur">⏱️ AVERAGE DURATION</div>
</div>
<div style="width: 1px; height: 50px; background: var(--border-color);"></div>
<div>
<div style="font-size: 1.8rem; font-weight: 800; color: var(--text-main); font-family: 'JetBrains Mono', monospace;"><span id="stat-today">--</span></div>
<div style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: bold;" data-i18n="statTodayTx">📡 TRANSITS TODAY</div>
</div>
</div>
</div>
</div>
</div>
<footer>
<div style="text-align: center; padding: 25px; color: var(--text-muted); font-size: 0.85rem; font-weight: 600; display: flex; justify-content: center; align-items: center; gap: 15px; flex-wrap: wrap;">
<span>&copy; 2026 <strong>IV3JDV @ ARIFVG</strong></span>
<span style="opacity: 0.5;">|</span>
<a href="https://git.arifvg.it/iv3jdv/fleet-control-server" target="_blank" style="color: inherit; text-decoration: none; display: flex; align-items: center; gap: 6px; transition: color 0.2s;">
<span>Gitea Home</span>
</a>
<span style="opacity: 0.5;">|</span>
<span style="font-family: 'JetBrains Mono', monospace; color: var(--accent);">Rev: {{ git_commit }}</span>
<span style="opacity: 0.5;">|</span>
<span id="last-update">Sync: --:--</span>
</div>
</footer>
<div id="login-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:400px;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border-color); padding-bottom:15px; margin-bottom:20px;">
<h2 style="margin:0; color:var(--primary);" data-i18n="loginTitle">🔒 System Login</h2>
<button onclick="closeLoginModal()" style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:var(--danger);">✖</button>
</div>
<div style="display:flex; flex-direction:column; gap:15px;">
<input type="text" id="modal-username" placeholder="Username" style="width:100%; padding:12px; font-size:1rem;" onkeypress="handleLoginEnter(event)">
<input type="password" id="modal-password" placeholder="Password" style="width:100%; padding:12px; font-size:1rem;" onkeypress="handleLoginEnter(event)">
<button onclick="performLogin()" class="btn-cmd" style="background:var(--success); width:100%; padding:12px; margin-top:10px; font-size:1rem;">LOGIN</button>
</div>
</div>
</div>
<div id="admin-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:900px;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border-color); padding-bottom:15px; margin-bottom:20px;">
<h2 style="margin:0;" data-i18n="adminTitle">🛠️ User & System Management</h2>
<button onclick="closeAdmin()" style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:var(--danger);">✖</button>
</div>
<div style="display:flex; flex-wrap:wrap; gap:10px; margin-bottom:20px; background:rgba(0,0,0,0.2); padding:15px; border-radius:16px; align-items:center;">
<input type="text" id="new-user" placeholder="Username" style="flex:1; min-width:120px;">
<input type="password" id="new-pass" placeholder="Password" style="flex:1; min-width:120px;">
<select id="new-role" style="flex:0.5; min-width:100px;">
<option value="operator" data-i18n="roleOp">Operator</option>
<option value="admin">Admin</option>
</select>
<input type="text" id="new-nodes" placeholder="Nodes (eg: ir3uic,ir3q)" style="flex:2; min-width:150px;">
<button id="btn-user-submit" onclick="submitUser()" class="btn-cmd" style="background:var(--success); flex:0.5;" data-i18n="btnAdd">+ ADD</button>
<button id="btn-user-cancel" onclick="cancelEdit()" class="btn-cmd" style="background:var(--text-muted); flex:0.2; display:none;">✖</button>
</div>
<div style="margin-bottom:20px; background:rgba(59, 130, 246, 0.05); padding:20px; border-radius:16px; border: 1px solid var(--primary);">
<h4 style="margin:0 0 15px 0; color:var(--primary);" data-i18n="adminDBSync">⚙️ Database Sync Configuration</h4>
<div style="display:grid; grid-template-columns: 1fr 1fr; gap:15px; margin-bottom:15px;">
<div><label style="font-size:0.8rem; font-weight:bold; display:block; margin-bottom:5px;">URL DB DMR (.dat):</label><input type="text" id="url-dmr-input" style="width:100%;"></div>
<div><label style="font-size:0.8rem; font-weight:bold; display:block; margin-bottom:5px;">URL DB NXDN (.csv):</label><input type="text" id="url-nxdn-input" style="width:100%;"></div>
</div>
<div style="display:flex; justify-content:space-between; align-items:center; border-top:1px solid var(--border-color); padding-top:15px;">
<div style="display:flex; align-items:center; gap:10px;"><label style="font-size:0.8rem; font-weight:bold;" data-i18n="adminTime">Daily Update Time:</label><input type="time" id="update-time-input"></div>
<button onclick="saveSettings()" class="btn-cmd" style="background:var(--accent); max-width: 250px;" data-i18n="adminSave">SAVE CONFIGURATION</button>
</div>
</div>
<div style="overflow-x:auto;">
<table style="width:100%; border-collapse:collapse; text-align:left;">
<thead><tr><th>ID</th><th data-i18n="thUser">User</th><th data-i18n="thRole">Role</th><th data-i18n="thNodes">Nodes</th><th style="text-align:center;" data-i18n="thActs">Actions</th></tr></thead>
<tbody id="users-table-body"></tbody>
</table>
</div>
</div>
</div>
<div id="services-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:550px;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border-color); padding-bottom:15px; margin-bottom:15px;">
<h2 style="margin:0; color:var(--accent);"><span data-i18n="modSvcTitle">⚙️ System Daemons:</span> <span id="svc-modal-title" style="color:var(--text-main);"></span></h2>
<button onclick="closeServicesModal()" style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:var(--danger);">✖</button>
</div>
<div id="services-list" style="max-height: 400px; overflow-y: auto; padding-right:10px;"></div>
</div>
</div>
<div id="configs-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:500px;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border-color); padding-bottom:15px; margin-bottom:15px;">
<h2 style="margin:0; color:#8e44ad;" data-i18n="modFileTitle">📂 Configuration Files</h2>
<button onclick="closeConfigsModal()" style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:var(--danger);">✖</button>
</div>
<div id="configs-list" style="display:flex; flex-direction:column; gap:10px;"></div>
</div>
</div>
<div id="editor-modal" class="modal-overlay">
<div class="modal-content" style="width:95%; max-width:900px; border: 1px solid var(--accent);">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
<h3 style="margin:0; color:var(--accent);"><span data-i18n="modEditTitle">📝 INI File Editor:</span> <span id="editor-title" style="color:var(--text-main);"></span></h3>
<button onclick="closeEditorModal()" style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:var(--danger);">✖</button>
</div>
<div style="background:rgba(239, 68, 68, 0.1); border-left:4px solid var(--danger); padding:10px; margin-bottom:15px; font-size:0.85rem; font-weight:bold; border-radius: 8px;" data-i18n="warnEdit">
⚠️ WARNING: This editor directly manipulates remote node parameters.
</div>
<textarea id="config-textarea" spellcheck="false" style="width:100%; height:55vh; background:#0f172a; color:#10b981; font-family:'JetBrains Mono', monospace; font-size:0.95rem; padding:15px; border-radius:12px; border:1px solid #334155; resize:none; box-sizing:border-box; outline:none;"></textarea>
<div style="display:flex; justify-content:space-between; margin-top:20px; align-items:center;">
<span id="editor-status" style="font-size:0.9rem; font-weight:bold;"></span>
<button onclick="saveConfig()" class="btn-cmd" style="background:var(--danger); max-width: 250px;" data-i18n="btnSave">💾 SAVE & SEND</button>
</div>
</div>
</div>
<div id="alert-modal" class="modal-overlay modal-top">
<div class="modal-content" style="width:90%; max-width:400px; text-align:center; border: 2px solid var(--primary);" id="alert-box">
<h2 style="margin-top:0;" id="alert-title">ℹ️ INFO</h2>
<p style="margin-bottom:25px; color:var(--text-main); font-weight: 600;" id="alert-desc">Message</p>
<button onclick="document.getElementById('alert-modal').style.display='none'" class="btn-cmd" style="background:var(--primary); padding:12px; width:100%;">OK</button>
</div>
</div>
<div id="confirm-modal" class="modal-overlay modal-top">
<div class="modal-content" style="width:90%; max-width:400px; text-align:center; border: 2px solid var(--danger);" id="confirm-box">
<h2 style="margin-top:0;" id="confirm-title">⚠️ WARNING</h2>
<p style="margin-bottom:25px; color:var(--text-main); font-weight: 600;" id="confirm-desc">Are you sure?</p>
<div style="display:flex; flex-direction:column; gap:15px;">
<button id="confirm-yes-btn" onclick="executeConfirmAction()" class="btn-cmd" style="background:var(--danger); padding:15px; font-size:1.1rem; font-weight:800;">YES, PROCEED</button>
<button id="confirm-cancel-btn" onclick="document.getElementById('confirm-modal').style.display='none'" class="btn-cmd" style="background:var(--text-muted); padding:12px; margin-top:10px;">CANCEL</button>
</div>
</div>
</div>
<div id="password-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:400px; text-align:center; border: 1px solid var(--accent);">
<h2 style="margin-top:0; color:var(--accent);">🔑 <span data-i18n="btnPass">PASSWORD CHANGE</span></h2>
<p style="margin-bottom:20px; color:var(--text-main); font-weight: 600;" data-i18n="promptPass">Enter the new password:</p>
<input type="password" id="new-password-input" style="width:100%; padding:12px; font-size:1rem; margin-bottom:20px; text-align:center;" placeholder="***">
<div style="display:flex; flex-direction:column; gap:10px;">
<button onclick="executePasswordChange()" class="btn-cmd" style="background:var(--success); padding:15px; font-size:1.1rem; font-weight:800;" data-i18n="titleSave">💾 SAVE</button>
<button onclick="closePasswordModal()" class="btn-cmd" style="background:var(--text-muted); padding:12px;" data-i18n="btnCancel">CANCEL</button>
</div>
</div>
</div>
<div id="override-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:400px; text-align:center;">
<h2 style="margin-top:0; color:var(--danger);">🚨 <span data-i18n="titleGlobal">GLOBAL OVERRIDE</span> 🚨</h2>
<p style="margin-bottom:25px; color:var(--text-muted); font-weight: 600;" id="override-desc">Select the profile to send to the ENTIRE network:</p>
<div id="global-btn-container" style="display:flex; flex-direction:column; gap:15px; margin-bottom: 15px;"></div>
<button onclick="document.getElementById('override-modal').style.display='none'" class="btn-cmd" style="background:var(--text-muted); padding:12px; width:100%;" data-i18n="btnCancel">CANCEL</button>
</div>
</div>
<div id="reset-hat-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:400px; text-align:center; border: 1px solid var(--danger);">
<h2 style="margin-top:0; color:var(--danger);">🔌 <span data-i18n="btnHat">RESET HAT</span> 🔌</h2>
<p style="margin-bottom:25px; color:var(--text-main); font-weight: 600;" id="reset-hat-desc">Do you want to send a PHYSICAL RESET to the radio board?</p>
<div style="display:flex; flex-direction:column; gap:15px;">
<button onclick="executeHatReset()" class="btn-cmd blink" style="background:var(--danger); padding:15px; font-size:1.1rem; font-weight:800;" data-i18n="btnConfReset">⚠️ CONFIRM RESET</button>
<button onclick="closeHatResetModal()" class="btn-cmd" style="background:var(--text-muted); padding:12px; margin-top:10px;" data-i18n="btnCancel">CANCEL</button>
</div>
</div>
</div>
<div id="update-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:400px; text-align:center; border: 1px solid var(--accent);">
<h2 style="margin-top:0; color:var(--accent);">🔄 <span data-i18n="modUpdateTitle">GLOBAL UPDATE</span> 🔄</h2>
<p style="margin-bottom:25px; color:var(--text-main); font-weight: 600;" data-i18n="confUpdate">Do you want to request updated data from all nodes in the fleet?</p>
<div style="display:flex; flex-direction:column; gap:15px;">
<button onclick="executeUpdateRequest()" class="btn-cmd" style="background:var(--accent); padding:15px; font-size:1.1rem; font-weight:800;" data-i18n="btnReqCfg">🔄 REQ CONFIG</button>
<button onclick="closeUpdateModal()" class="btn-cmd" style="background:var(--text-muted); padding:12px; margin-top:10px;" data-i18n="btnCancel">CANCEL</button>
</div>
</div>
</div>
<div id="versions-modal" class="modal-overlay">
<div class="modal-content" style="width:90%; max-width:450px;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border-color); padding-bottom:15px; margin-bottom:15px;">
<h2 style="margin:0; color:var(--primary);">ℹ️ <span data-i18n="modVersions">Software & Firmware</span></h2>
<button onclick="closeVersionsModal()" style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:var(--danger);">✖</button>
</div>
<div id="versions-list" style="background: #010409; padding: 15px; border-radius: 8px; border: 1px solid var(--border-color); font-family: 'JetBrains Mono', monospace; font-size: 0.85rem; line-height: 1.8; color: var(--text-main);">
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.min.js"></script>
<script>
// --- 1. TRANSLATION SYSTEM (i18n) ---
const i18n = {
en: {
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 CONFIG", btnGlobal: "🚨 GLOBAL OVERRIDE", btnAdmin: "🛠️ ADMIN", btnPass: "🔑 PASS", btnLogout: "LOGOUT",
btnSvc: "⚙️ SVC", btnFile: "📂 FILE", btnBoot: "🔄 BOOT", btnAdd: "+ ADD",
waitNet: "> Waiting network...", waitData: "Waiting for node data...", forceUpdate: "🔄 FORCE UPDATE",
adminTitle: "🛠️ User & System Management", adminDBSync: "⚙️ Database Sync Config", adminTime: "Daily Update Time:", adminSave: "SAVE CONFIG", roleOp: "Operator",
modSvcTitle: "⚙️ System Daemons:", modFileTitle: "📂 Config Files", modEditTitle: "📝 INI Editor:",
warnEdit: "⚠️ WARNING: This editor directly manipulates remote node parameters.",
btnEdit: "📝 EDIT", btnStart: "▶ START", btnRestart: "🔄 RESTART", btnStop: "🛑 STOP", btnSave: "💾 SAVE & SEND",
btnHat: "🔌 RESET HAT", confHat: "Are you sure you want to physically reset the MMDVM board on node ",
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: "⚠️ SVC KO - CHECK DAEMONS ⚠️",
promptOvr: "GLOBAL OVERRIDE", promptOvrConfirm: "Confirm sending to ENTIRE network?",
modUpdateTitle: "🔄 GLOBAL UPDATE", confUpdate: "Do you want to request updated data and configuration files from all nodes in the fleet?", alertUpdateOk: "Request sent successfully!",
btnConfReset: "⚠️ CONFIRM RESET", btnCancel: "CANCEL", promptPass: "Enter the new password:",
titleError: "❌ ERROR", titleSuccess: "✅ SUCCESS", titleAction: "⚙️ CONFIRM ACTION", titleDelete: "🗑️ DELETE USER", titleSave: "💾 SAVE", titleGlobal: "🚨 GLOBAL OVERRIDE",
btnYes: "YES, PROCEED", msgDelUser: "Confirm user deletion?", msgPassOk: "Password updated successfully!", msgPassErr: "Failed to update password.", msgLoginFail: "Login Failed",
msgConfigSaved: "Configuration saved!", msgConfigErr: "Error saving configuration", msgNetErr: "Network Error", msgOvrSel: "Select the profile to send to the ENTIRE network:",
msgOvrOk: "Command successfully sent to the network!", msgMissUser: "Missing Username", msgMissPass: "Password required for new user", btnSvcKo: "⚠️ DAEMON KO",
phNewPass: "New pass (empty to keep)", phPass: "Password",
titleSwitch: "SWITCH PROFILE", confSwitch: "Are you sure you want to switch to", titleBoot: "SYSTEM REBOOT", confBoot: "Are you sure you want to REBOOT node ",
ttReqCfg: "Request immediate data update", ttGlobal: "Force profile switch on network", ttAdmin: "User and system management", ttPass: "Change your password", ttLogout: "Log out",
ttProfA: "Switch to Profile A", ttProfB: "Switch to Profile B", ttTgOn: "Enable Telegram notifications", ttTgOff: "Disable Telegram notifications", ttSvc: "Manage system daemons", ttFile: "Edit .ini configuration files", ttHat: "Send physical reset to modem", ttBoot: "Reboot node operating system",
ttSwitchTo: "Switch to profile: ", ttSvcStart: "Start service", ttSvcRestart: "Restart service", ttSvcEdit: "Edit configuration", ttSvcStop: "Stop service", ttLang: "Change language",
statTopTG: "🎯 TOP TALKGROUPS", statTopCall: "🗣️ TOP CALLSIGNS", statLoading: "Loading...", statAvgDur: "⏱️ AVERAGE DURATION", statTodayTx: "📡 TRANSITS TODAY", statNoData: "No data",
statTitle: "DAILY STATISTICS", statAllNodes: "ALL NODES", modVersions: "Software & Firmware",
filtAll: "All Nodes", filtOnline: "Online", filtOffline: "Offline"
},
it: {
lastTransits: "Ultimi ascolti", loginTitle: "🔒 Login di Sistema",
thTime: "Ora", thRep: "Ripetitore", thMode: "Modo", thCall: "Nominativo", thDur: "Durata",
thUser: "Utente", thRole: "Ruolo", thNodes: "Nodi", thActs: "Azioni",
btnReqCfg: "🔄 RICHIEDI CONFIG", btnGlobal: "🚨 OVERRIDE GLOBALE", btnAdmin: "🛠️ ADMIN", btnPass: "🔑 PASS", btnLogout: "LOGOUT",
btnSvc: "⚙️ SVC", btnFile: "📂 FILE", btnBoot: "🔄 BOOT", btnAdd: "+ AGGIUNGI",
waitNet: "> Attesa rete...", waitData: "In attesa dei dati dal nodo...", forceUpdate: "🔄 FORZA AGGIORNAMENTO",
adminTitle: "🛠️ Gestione Utenti e Sistema", adminDBSync: "⚙️ Sincronizzazione Database", adminTime: "Orario Aggiornamento:", adminSave: "SALVA CONFIG", roleOp: "Operatore",
modSvcTitle: "⚙️ Demoni Sistema:", modFileTitle: "📂 File di Configurazione", modEditTitle: "📝 Editor INI:",
warnEdit: "⚠️ ATTENZIONE: Questo editor manipola direttamente i parametri del nodo remoto.",
btnEdit: "📝 MODIFICA", btnStart: "▶ START", btnRestart: "🔄 RESTART", btnStop: "🛑 STOP", btnSave: "💾 SALVA ED INVIA",
btnHat: "🔌 RESET HAT", confHat: "Sei sicuro di voler resettare fisicamente la scheda MMDVM sul nodo ",
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: "⚠️ SVC KO - CONTROLLA DEMONI ⚠️",
promptOvr: "OVERRIDE GLOBALE", promptOvrConfirm: "Confermi l'invio a TUTTA la rete?",
modUpdateTitle: "🔄 AGGIORNAMENTO GLOBALE", confUpdate: "Vuoi richiedere i dati e i file di configurazione aggiornati a tutti i nodi della flotta?", alertUpdateOk: "Richiesta inviata con successo!",
btnConfReset: "⚠️ CONFERMA RESET", btnCancel: "ANNULLA", promptPass: "Inserisci la nuova password:",
titleError: "❌ ERRORE", titleSuccess: "✅ OK", titleAction: "⚙️ CONFERMA AZIONE", titleDelete: "🗑️ ELIMINA UTENTE", titleSave: "💾 SALVATAGGIO", titleGlobal: "🚨 OVERRIDE GLOBALE",
btnYes: "SI, PROCEDI", msgDelUser: "Confermi l'eliminazione dell'utente?", msgPassOk: "Password aggiornata con successo!", msgPassErr: "Errore durante l'aggiornamento della password.", msgLoginFail: "Login Fallito",
msgConfigSaved: "Configurazione salvata!", msgConfigErr: "Errore durante il salvataggio", msgNetErr: "Errore di rete", msgOvrSel: "Seleziona il profilo da inviare a TUTTA la rete:",
msgOvrOk: "Comando inviato con successo a tutta la rete!", msgMissUser: "Username mancante", msgMissPass: "Password obbligatoria per il nuovo utente", btnSvcKo: "⚠️ DEMONE KO",
phNewPass: "Nuova pass (vuota per non cambiare)", phPass: "Password",
titleSwitch: "CAMBIO PROFILO", confSwitch: "Sei sicuro di voler passare al", titleBoot: "RIAVVIO SISTEMA", confBoot: "Sei sicuro di voler RIAVVIARE il nodo ",
ttReqCfg: "Richiedi aggiornamento dati", ttGlobal: "Forza cambio profilo globale", ttAdmin: "Gestione utenti e sistema", ttPass: "Cambia la tua password", ttLogout: "Disconnetti",
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: "Passa al profilo: ", ttSvcStart: "Avvia servizio", ttSvcRestart: "Riavvia servizio", ttSvcEdit: "Modifica configurazione", ttSvcStop: "Ferma servizio", ttLang: "Cambia lingua",
statTopTG: "🎯 TOP TALKGROUPS", statTopCall: "🗣️ TOP CALLSIGNS", statLoading: "Caricamento...", statAvgDur: "⏱️ DURATA MEDIA", statTodayTx: "📡 TRANSITI OGGI", statNoData: "Nessun dato",
statTitle: "STATISTICHE GIORNALIERE", statAllNodes: "TUTTA LA RETE", modVersions: "Software & Firmware",
filtAll: "Tutti i nodi", filtOnline: "Attivi", filtOffline: "Offline"
}
};
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() {
document.getElementById('lang-btn').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 => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
function q(s) { return esc(JSON.stringify(String(s ?? ''))); }
const HANG_TIME_MS = 180000;
// --- VARIABILI GLOBALI E UI VIEW ---
let clients = []; let me = { logged_in: false, user: '', role: '', allowed_nodes: '' };
let isAuthenticated = false; let usersCache = {}; let globalHealthData = {}; let globalVersionsData = {};
let editingUserId = null; let currentResetHatId = null; let confirmActionCallback = null;
let currentFilter = 'all'; let searchQuery = ''; let viewMode = localStorage.getItem('fleetViewMode') || 'grid';
function switchView(viewName) {
document.getElementById('view-home').style.display = 'none';
document.getElementById('view-nodes').style.display = 'none';
document.getElementById('tab-home').classList.remove('active');
document.getElementById('tab-nodes').classList.remove('active');
document.getElementById(`view-${viewName}`).style.display = 'block';
document.getElementById(`tab-${viewName}`).classList.add('active');
localStorage.setItem('fleetDefaultView', viewName);
if (viewName === 'nodes') { applyViewMode(); }
}
window.addEventListener('DOMContentLoaded', () => {
const savedView = localStorage.getItem('fleetDefaultView') || 'home';
switchView(savedView);
});
// --- FUNZIONI FILTRO E LAYOUT VERSIONE 4.0 ---
function setFilter(filter) {
currentFilter = filter;
document.querySelectorAll('.filter-pill').forEach(btn => {
if (btn.getAttribute('onclick') === `setFilter('${filter}')`) btn.classList.add('active');
else btn.classList.remove('active');
});
applyFilters();
}
function toggleViewMode() {
viewMode = viewMode === 'grid' ? 'list' : 'grid';
localStorage.setItem('fleetViewMode', viewMode);
applyViewMode();
}
function applyViewMode() {
const gridDiv = document.getElementById('client-grid');
const btnToggle = document.getElementById('view-toggle-btn');
if (viewMode === 'list') {
gridDiv.className = 'list-view';
btnToggle.innerText = '📄 LIST';
} else {
gridDiv.className = 'grid';
btnToggle.innerText = '🔲 GRID';
}
}
function applyFilters() {
searchQuery = document.getElementById('node-search').value.toLowerCase();
clients.forEach(c => {
const card = document.getElementById(`card-${c.id}`);
if (!card) return;
let show = true;
let status = card.dataset.status || 'offline';
let gatewaysStr = card.dataset.gateways || '';
if (currentFilter === 'online' && status !== 'online') show = false;
if (currentFilter === 'offline' && status === 'online') show = false;
if (['dmr', 'ysf', 'd-star', 'nxdn'].includes(currentFilter)) {
if (!gatewaysStr.includes(currentFilter)) show = false;
}
if (searchQuery !== '') {
const searchStr = `${c.id.toLowerCase()} ${c.name.toLowerCase()} ${(card.dataset.loc || '').toLowerCase()}`;
if (!searchStr.includes(searchQuery)) show = false;
}
card.style.display = show ? 'flex' : 'none';
});
}
function fmtAge(sec) {
sec = Math.max(0, Math.round(sec));
if (sec < 60) return sec + 's';
if (sec < 3600) return Math.floor(sec / 60) + 'm';
if (sec < 86400) return Math.floor(sec / 3600) + 'h';
return Math.floor(sec / 86400) + 'd';
}
function seenItem(label, age, tip, warn) {
const cls = warn ? 'warn' : (age !== undefined && age < 300 ? 'ok' : 'idle');
const txt = age === undefined ? '—' : fmtAge(age);
return `<span class="seen-item ${cls}" title="${esc(tip)}">${warn ? '⚠ ' : ''}${label} <b>${txt}</b></span>`;
}
function renderSeen(c, data, isOnline) {
const div = document.getElementById(`seen-${c.id}`);
if (!div) return;
const it = currentLang === 'it';
const ages = (data.last_seen && data.last_seen[c.id.toLowerCase()]) || {};
const upSec = data.uptime || 0;
let html = '';
const warnM = ages.mmdvm === undefined && isOnline && upSec > 600;
const tipM = it ? `Ultimo evento dal topic mmdvm/${c.id}/json (TX, cambio modo...). Su un nodo tranquillo può passare molto tempo.`
: `Last event from topic mmdvm/${c.id}/json (TX, mode change...). It can be a long time on a quiet node.`;
const tipMW = it ? `Nessun evento MMDVM ricevuto da quando il server è attivo (${fmtAge(upSec)}): controlla che MMDVMHost sia connesso al broker.`
: `No MMDVM event received since the server started (${fmtAge(upSec)}): check that MMDVMHost is connected to the broker.`;
html += seenItem('MMDVM', ages.mmdvm, warnM ? tipMW : tipM, warnM);
if (ages.gateway !== undefined) {
html += seenItem('GW', ages.gateway, it ? 'Ultimo evento dai gateway (DMR/NXDN/YSF/P25/D-Star)' : 'Last event from the gateways (DMR/NXDN/YSF/P25/D-Star)', false);
}
const hObj = (data.health && data.health[c.id.toLowerCase()]) || {};
const iv = Number(hObj.interval) > 0 ? Number(hObj.interval) : 60;
const warnA = isOnline && (ages.health === undefined ? upSec > Math.max(300, iv * 5) : ages.health > Math.max(180, iv * 3));
const tipA = warnA
? (it ? 'L\'agent del nodo non invia più lo stato (devices/<id>/services): connessione bloccata?' : 'The node agent stopped sending its status (devices/<id>/services): stuck connection?')
: (it ? 'Ultimo stato ricevuto dall\'agent del nodo (devices/<id>/services)' : 'Last status received from the node agent (devices/<id>/services)');
html += seenItem('AGENT', ages.health, tipA, warnA);
div.innerHTML = html;
div.style.display = 'flex';
}
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.borderColor = 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.borderColor = color;
document.getElementById('confirm-desc').innerHTML = desc;
document.getElementById('confirm-yes-btn').style.background = 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; }
}
function sendCommand(clientId, type, customTitle, customMsg, customColor) {
const title = customTitle || t('titleAction');
const msg = customMsg || `${t('confOp')}<b>${clientId.toUpperCase()}</b>?`;
const color = customColor || "var(--primary)";
customConfirm(title, msg, color, async () => {
try {
const res = await fetch('/api/command', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId, type }) });
const data = await res.json();
if(!data.success) { customAlert(t('titleError'), esc(data.error), true); }
refreshStates();
} catch (e) { console.error(e); }
});
}
function confirmSwitch(id, mode) {
const data = globalHealthData[id.toLowerCase()];
let profileName = mode === 'A' ? "PROFILE A" : "PROFILE B";
if (data && data.profiles && data.profiles[mode]) profileName = data.profiles[mode];
const title = `🔄 ${t('titleSwitch')}`;
const msg = `${t('confSwitch')} <b>${esc(profileName)}</b> -> <b>${id.toUpperCase()}</b>?`;
const color = mode === 'A' ? "var(--accent)" : "#eab308";
sendCommand(id, mode, title, msg, color);
}
function confirmReboot(id) { sendCommand(id, 'REBOOT', `🔄 ${t('titleBoot')}`, `${t('confBoot')}<b>${id.toUpperCase()}</b>?`, "var(--danger)"); }
function confirmUpdateAgent(id) { sendCommand(id, 'UPDATE_AGENT', `⬇️ UPDATE OTA`, `Confermi l'aggiornamento dello script tramite git pull sul nodo <b>${id.toUpperCase()}</b>?`, "#2563eb"); }
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); }
}
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); }
}
function sendTgCommand(clientId, comando) {
const msg = (comando === 'TG:ON') ? t('confTgOn') : t('confTgOff');
customConfirm("💬 TELEGRAM", `${msg}<b>${clientId.toUpperCase()}</b>?`, "var(--primary)", async () => {
try {
const res = await fetch('/api/command', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: clientId, type: comando }) });
const data = await res.json();
if(!data.success) { customAlert(t('titleError'), esc(data.error), true); }
refreshStates();
} catch (e) { console.error(e); }
});
}
async function initUI() {
applyTranslations();
try {
try { const meRes = await fetch('/api/me'); if (meRes.ok) me = await meRes.json(); } catch (e) { console.error(e); }
isAuthenticated = !!me.logged_in;
const response = await fetch('/api/clients');
clients = await response.json();
clients = clients.filter(c => /^[A-Za-z0-9_\-]+$/.test(String(c.id)));
const statSelect = document.getElementById('stat-node-filter');
if (statSelect) {
let opts = `<option value="all">🌐 ${t('statAllNodes')}</option>`;
clients.forEach(c => { opts += `<option value="${c.id}">${esc(c.name)} (${c.id.toUpperCase()})</option>`; });
statSelect.innerHTML = opts;
}
const grid = document.getElementById('client-grid');
const authContainer = document.getElementById('auth-container');
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
if (isAuthenticated) {
let adminBtn = role === 'admin' ? `
<button id="server-update-btn" onclick="confirmServerUpdate()" class="auth-btn" style="background:var(--danger); color:white !important; display:none; border: 2px solid white; animation: pulse-red 1.5s infinite;" title="Aggiornamento Server Disponibile">🔄 UPDATE SERVER</button>
<button onclick="sendGlobalUpdate()" class="auth-btn" style="background:#f59e0b; color:white;" data-i18n-title="ttReqCfg" title="${t('ttReqCfg')}">${t('btnReqCfg')}</button>
<button onclick="triggerGlobalEmergency()" class="auth-btn" style="background:#ef4444; color:white;" data-i18n-title="ttGlobal" title="${t('ttGlobal')}">${t('btnGlobal')}</button>
<button onclick="openAdmin()" class="auth-btn" style="background:var(--accent); color:white;" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">${t('btnAdmin')}</button>` : '';
authContainer.innerHTML = `${adminBtn}
<span style="font-weight:800; font-size:0.9rem; margin: 0 10px;">👤 ${esc(String(me.user).toUpperCase())}</span>
<button onclick="changeMyPassword()" class="auth-btn" style="background:#64748b; color:white;" data-i18n-title="ttPass" title="${t('ttPass')}">${t('btnPass')}</button>
<button onclick="logout()" class="auth-btn" style="background:var(--text-main); color:var(--card-bg);" data-i18n-title="ttLogout" title="${t('ttLogout')}">${t('btnLogout')}</button>`;
} else {
authContainer.innerHTML = `<button onclick="openLoginModal()" class="auth-btn" style="background:var(--primary); color:white; padding: 8px 25px;">LOGIN</button>`;
}
grid.innerHTML = clients.map(c => {
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
let showReboot = (role === 'admin');
return `
<div class="card" id="card-${c.id}" data-status="offline" data-gateways="" data-loc="">
<div class="card-header">
<span class="client-name" title="${esc(c.name)}">${esc(c.name)}</span>
<div class="header-badges">
<span class="badge-id">ID: ${c.id.toUpperCase()}</span>
<span class="badge-id" id="agent-badge-${c.id}" style="display: none; color: #38bdf8; background: rgba(56, 189, 248, 0.1);"></span>
<div id="type-badge-${c.id}" class="type-badge" style="display: none;"></div>
</div>
</div>
<!-- Barra dei Gateway (Versione 4.0) -->
<div class="gateway-bar" id="gw-bar-${c.id}"></div>
<div class="freq-bar" id="freq-container-${c.id}" style="display: none;">
<span><span class="freq-tx">TX:</span> <span id="freq-tx-${c.id}">...</span></span>
<span><span class="freq-rx">RX:</span> <span id="freq-rx-${c.id}">...</span></span>
</div>
<div class="node-meta" id="meta-container-${c.id}" style="display: none;">
<span class="node-meta-item">📍 <strong id="loc-${c.id}">...</strong></span>
<span class="node-meta-item" style="margin-top: 4px; color: var(--text-muted);">Lat: <span id="lat-${c.id}">...</span> | Lon: <span id="lon-${c.id}">...</span></span>
</div>
<div class="health-bar" id="health-${c.id}" style="display: none;">
<span>⚡ <span id="cpu-${c.id}">--</span>%</span>
<span>🌡️ <span id="temp-${c.id}">--</span>°C</span>
<span>🧠 <span id="ram-${c.id}">--</span>%</span>
<span>💾 <span id="disk-${c.id}">--</span>%</span>
<span style="grid-column: span 2;" title="System Uptime">⏱️ <span id="up-${c.id}">--</span></span>
</div>
<div class="seen-bar" id="seen-${c.id}" style="display: none;"></div>
<div class="status-display" id="status-${c.id}">Offline</div>
<div id="ts-container-${c.id}" class="ts-container">
<div class="dmr-info" id="dmr-ts1-${c.id}">TS1: ...</div>
<div class="dmr-info" id="dmr-ts2-${c.id}">TS2: ...</div>
</div>
<div class="dmr-info" id="dmr-alt-${c.id}" style="display: none; text-align: center; font-weight: 800;"></div>
<div class="terminal-log" id="sys-log-${c.id}">${t('waitNet')}</div>
<div id="svc-warn-${c.id}" class="blink" style="display: none; text-align: center; margin-bottom: 15px; border-radius: 8px; padding: 10px;">
<span style="font-size: 0.85rem;" data-i18n="warnDaemon">${t('warnDaemon')}</span>
</div>
${canControl ? `
<div id="prof-btns-${c.id}" style="width: 100%; gap: 10px; display: none; margin-bottom: 8px;"></div>
<div style="width: 100%; display: flex; gap: 10px; margin-bottom: 8px;">
<button class="btn-cmd" style="background: rgba(255, 255, 255, 0.05); color: var(--text-main) !important;" title="${t('ttTgOn')}" onclick="sendTgCommand('${c.id}', 'TG:ON')">🔔 TG ON</button>
<button class="btn-cmd" style="background: rgba(255, 255, 255, 0.05); color: var(--text-main) !important;" title="${t('ttTgOff')}" onclick="sendTgCommand('${c.id}', 'TG:OFF')">🔇 TG OFF</button>
</div>
` : ''}
${showReboot ? `
<details class="admin-dropdown" style="width: 100%;">
<summary id="admin-summary-${c.id}" class="btn-cmd" style="background: rgba(255,255,255,0.05); border: 1px solid var(--border-color); color: var(--text-muted) !important;">⚙️ Admin Tools</summary>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding-top: 10px;">
<button class="btn-cmd" style="background: var(--primary); border: none; color: white !important;" title="Versioni Software" onclick="openVersionsModal('${c.id}')">ℹ️ INFO</button>
<button id="btn-svc-${c.id}" class="btn-cmd" style="background: #334155; border: none; color: white !important;" title="${t('ttSvc')}" onclick="openServicesModal('${c.id}')">${t('btnSvc')}</button>
<button class="btn-cmd" style="background: var(--accent); border: none; color: white !important;" title="${t('ttFile')}" onclick="openConfigsModal('${c.id}')">${t('btnFile')}</button>
<button class="btn-cmd" style="background: #ea580c; border: none; color: white !important;" title="${t('ttHat')}" onclick="confirmHatReset('${c.id}')">${t('btnHat')}</button>
<button class="btn-cmd" style="background: var(--danger); border: none; color: white !important;" title="${t('ttBoot')}" onclick="confirmReboot('${c.id}')">${t('btnBoot')}</button>
<button id="btn-ota-${c.id}" class="btn-cmd" style="background: #2563eb; border: none; color: white !important;" title="Update OTA" onclick="confirmUpdateAgent('${c.id}')">⬇️ OTA</button>
</div>
</details>
` : ''}
</div>`;
}).join('');
const miniGrid = document.getElementById('home-mini-nodes');
if (miniGrid) {
miniGrid.innerHTML = clients.map(c => `
<div id="mini-card-${c.id}" class="mini-card" onclick="switchView('nodes'); setTimeout(()=>document.getElementById('card-${c.id}').scrollIntoView({behavior:'smooth', block: 'center'}), 200);">
<div class="mini-card-content">
<div id="mini-name-${c.id}" class="mini-card-name" title="${esc(c.name)}">${esc(c.name)}</div>
<div id="mini-id-${c.id}" style="font-family: 'JetBrains Mono', monospace; font-size: 0.65rem; color: var(--text-muted); margin-top: 2px;">ID: ${c.id.toUpperCase()}</div>
</div>
<div id="mini-status-${c.id}" class="mini-card-status" style="color: var(--danger); background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.2);" title="OFFLINE">OFFLINE</div>
</div>
`).join('');
}
refreshStates(); refreshLogs(); refreshStats();
} catch (e) { console.error(e); }
}
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(); }
async function performLogin() {
const user = document.getElementById('modal-username').value; const pass = document.getElementById('modal-password').value;
if (!user || !pass) return;
const res = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user, pass }) });
const data = await res.json();
if (res.ok) { location.reload(); }
else if (res.status === 429) { customAlert(t('titleError'), esc(data.error || t('msgLoginFail')), true); }
else { customAlert(t('titleError'), t('msgLoginFail'), true); }
}
async function logout() { try { await fetch('/api/logout', { method: 'POST' }); } catch (e) { console.error(e); } sessionStorage.clear(); location.reload(); }
async function refreshStates() {
try {
const res = await fetch('/api/states'); const data = await res.json();
globalVersionsData = data.versions || {};
clients.forEach(c => {
const statusDiv = document.getElementById(`status-${c.id}`); const cardDiv = document.getElementById(`card-${c.id}`);
if (!statusDiv || !cardDiv) return;
let stateValue = data.states[c.id.toLowerCase()] || data.states[c.id] || "OFFLINE";
stateValue = String(stateValue).trim().toUpperCase(); statusDiv.innerText = stateValue;
const isOnline = !stateValue.includes("OFF") && stateValue !== "";
cardDiv.dataset.status = isOnline ? 'online' : 'offline';
renderSeen(c, data, isOnline);
let genObj = data.general && data.general[c.id.toLowerCase()];
const nameSpan = cardDiv.querySelector('.client-name');
const idBadge = cardDiv.querySelector('.badge-id');
const typeBadge = document.getElementById(`type-badge-${c.id}`);
if (genObj && isOnline) {
nameSpan.innerText = genObj.callsign;
idBadge.innerText = `ID: ${genObj.radio_id}`;
idBadge.style.background = "var(--primary)"; idBadge.style.color = "#ffffff"; idBadge.style.borderColor = "var(--primary)";
if (typeBadge && genObj.duplex !== undefined) {
typeBadge.style.display = 'inline-block';
if (genObj.duplex === "1") { typeBadge.innerText = "REPEATER"; typeBadge.className = "type-badge type-repeater"; }
else { typeBadge.innerText = "HOTSPOT"; typeBadge.className = "type-badge type-hotspot"; }
}
} else {
nameSpan.innerText = c.name;
idBadge.innerText = `ID: ${c.id.toUpperCase()}`;
idBadge.style.background = "rgba(255,255,255,0.1)"; idBadge.style.color = "var(--text-muted)"; idBadge.style.borderColor = "var(--border-color)";
if (typeBadge) typeBadge.style.display = 'none';
}
let telemetryObj = data.telemetry[c.id.toLowerCase()] || data.telemetry[c.id] || { ts1: "...", ts2: "...", alt: "", idle: true };
if (typeof telemetryObj === 'string') telemetryObj = { ts1: telemetryObj, ts2: "...", alt: "", idle: true };
const tsContainer = document.getElementById(`ts-container-${c.id}`); const ts1Div = document.getElementById(`dmr-ts1-${c.id}`); const ts2Div = document.getElementById(`dmr-ts2-${c.id}`); const altDiv = document.getElementById(`dmr-alt-${c.id}`);
let isTx = false; let activeModeColor = "var(--success)"; let isIdle = telemetryObj.idle === true;
if (telemetryObj.alt && telemetryObj.alt !== "") {
if (tsContainer) tsContainer.style.display = "none";
if (altDiv) {
altDiv.style.display = "block"; altDiv.innerText = telemetryObj.alt; let altText = telemetryObj.alt.toUpperCase();
if (altText.includes("NXDN")) activeModeColor = "#10b981"; else if (altText.includes("YSF")) activeModeColor = "#8b5cf6"; else if (altText.includes("D-STAR")) activeModeColor = "#06b6d4"; else if (altText.includes("P25")) activeModeColor = "#f59e0b";
isTx = altText.includes("🟢") || altText.includes("🟣") || altText.includes("🔵") || altText.includes("🟠");
altDiv.style.setProperty('--pulse-color', activeModeColor);
if (isTx) { altDiv.classList.add('tx-active-unified'); } else { altDiv.classList.remove('tx-active-unified'); altDiv.style.setProperty('color', 'var(--text-muted)', 'important'); altDiv.style.setProperty('border-left', `4px solid var(--border-color)`, 'important'); }
}
} else {
if (altDiv) altDiv.style.display = "none";
if (tsContainer) tsContainer.style.display = "flex";
activeModeColor = "var(--primary)";
if (ts1Div && ts2Div) {
let isSimplex = (genObj && genObj.duplex === "0");
ts1Div.style.display = isSimplex ? 'none' : 'block';
[ts1Div, ts2Div].forEach((div, idx) => {
if (isSimplex && idx === 0) return;
const val = String((idx === 0 ? telemetryObj.ts1 : telemetryObj.ts2) ?? '');
const fullLabel = `TS${idx + 1}`;
div.innerText = `${fullLabel}: ${val}`;
div.style.setProperty('--pulse-color', activeModeColor);
if (val.includes("🎙️")) { isTx = true; div.classList.add('tx-active-unified'); }
else { div.classList.remove('tx-active-unified'); div.style.setProperty('color', 'var(--text-muted)', 'important'); div.style.setProperty('border-left', '4px solid var(--border-color)', 'important'); }
});
}
}
let healthObj = data.health && data.health[c.id.toLowerCase()];
let infoObj = data.info && data.info[c.id.toLowerCase()];
const freqContainer = document.getElementById(`freq-container-${c.id}`); const freqTx = document.getElementById(`freq-tx-${c.id}`); const freqRx = document.getElementById(`freq-rx-${c.id}`);
const metaContainer = document.getElementById(`meta-container-${c.id}`);
const locSpan = document.getElementById(`loc-${c.id}`);
const latSpan = document.getElementById(`lat-${c.id}`);
const lonSpan = document.getElementById(`lon-${c.id}`);
if (infoObj && isOnline) {
if (freqContainer) { freqContainer.style.display = 'flex'; freqTx.innerText = infoObj.tx; freqRx.innerText = infoObj.rx; }
if (metaContainer) {
metaContainer.style.display = 'block';
locSpan.innerText = infoObj.loc;
cardDiv.dataset.loc = infoObj.loc;
if(latSpan) latSpan.innerText = infoObj.lat;
if(lonSpan) lonSpan.innerText = infoObj.lon;
}
} else {
if (freqContainer) freqContainer.style.display = 'none';
if (metaContainer) metaContainer.style.display = 'none';
}
const healthContainer = document.getElementById(`health-${c.id}`); const cpuSpan = document.getElementById(`cpu-${c.id}`); const tempSpan = document.getElementById(`temp-${c.id}`); const ramSpan = document.getElementById(`ram-${c.id}`); const diskSpan = document.getElementById(`disk-${c.id}`);
// --- RENDERING GATEWAY BAR (Versione 4.0 - Gestione Stati Action) ---
const gwBar = document.getElementById(`gw-bar-${c.id}`);
if (gwBar && healthObj) {
let gwHtml = "";
let gwData = data.gateway_states && data.gateway_states[c.id.toLowerCase()] ? data.gateway_states[c.id.toLowerCase()] : {};
let processes = healthObj.processes || {};
let activeGatewaysStr = "";
const gwMap = [
{ id: 'dmrgateway', label: 'DMR', color: '#3b82f6', tint: 'rgba(59, 130, 246, 0.15)', proto: 'DMR' },
{ id: 'ysfgateway', label: 'YSF', color: '#8b5cf6', tint: 'rgba(139, 92, 246, 0.15)', proto: 'YSF' },
{ id: 'dstargateway', label: 'D-STAR', color: '#06b6d4', tint: 'rgba(6, 182, 212, 0.15)', proto: 'D-STAR' },
{ id: 'nxdngateway', label: 'NXDN', color: '#10b981', tint: 'rgba(16, 185, 129, 0.15)', proto: 'NXDN' },
{ id: 'p25gateway', label: 'P25', color: '#f59e0b', tint: 'rgba(245, 158, 11, 0.15)', proto: 'P25' }
];
if (isOnline) {
gwMap.forEach(gw => {
let isActiveProc = processes[gw.id] && processes[gw.id].toLowerCase() === 'online';
if (isActiveProc) {
activeGatewaysStr += gw.proto.toLowerCase() + ",";
let stateInfo = gwData[gw.proto] || { action: 'IDLE', dest: '---' };
let action = (stateInfo.action || 'IDLE').toLowerCase();
let dest = stateInfo.dest && stateInfo.dest !== '---' ? stateInfo.dest : '';
let badgeBg, badgeColor, badgeBorder, suffix = '', extraClass = '';
// Gestione degli stati: linking/linked, unlinked, failed
if (action === 'linking' || action === 'linked' || (dest !== '' && action !== 'unlinked' && action !== 'failed')) {
badgeBg = gw.color;
badgeColor = 'white';
badgeBorder = gw.color;
if (dest) suffix = `: ${dest}`;
else suffix = ` [LINKING]`;
} else if (action === 'failed') {
badgeBg = 'var(--danger)';
badgeColor = 'white';
badgeBorder = 'var(--danger)';
suffix = ' [FAILED]';
extraClass = 'blink';
} else if (action === 'unlinked') {
badgeBg = 'transparent';
badgeColor = 'var(--text-muted)';
badgeBorder = 'var(--border-color)';
suffix = ' [UNLINKED]';
} else {
// Default/IDLE (Nessuna azione esplicita ricevuta di recente)
badgeBg = gw.tint;
badgeColor = gw.color;
badgeBorder = gw.color;
}
if (gw.proto === 'DMR' && gwData['DMR_NETS'] && gwData['DMR_NETS'].length > 0) {
gwData['DMR_NETS'].forEach(netName => {
let netText = `DMR: ${esc(netName)}${esc(suffix)}`;
gwHtml += `<span class="${extraClass}" style="font-size: 0.65rem; font-family: 'JetBrains Mono', monospace; font-weight: 800; padding: 3px 6px; border-radius: 4px; border: 1px solid ${badgeBorder}; background: ${badgeBg}; color: ${badgeColor}; transition: all 0.3s ease;" title="Stato: ${action.toUpperCase()}">${netText}</span>`;
});
} else {
let text = `${gw.label}${esc(suffix)}`;
gwHtml += `<span class="${extraClass}" style="font-size: 0.65rem; font-family: 'JetBrains Mono', monospace; font-weight: 800; padding: 3px 6px; border-radius: 4px; border: 1px solid ${badgeBorder}; background: ${badgeBg}; color: ${badgeColor}; transition: all 0.3s ease;" title="Stato: ${action.toUpperCase()}">${text}</span>`;
}
}
});
}
cardDiv.dataset.gateways = activeGatewaysStr;
gwBar.innerHTML = gwHtml;
} else if (gwBar) {
gwBar.innerHTML = "";
cardDiv.dataset.gateways = "";
}
// -------------------------------------------------------------------------
if (healthObj && isOnline) {
healthContainer.style.display = 'flex';
let cpu = healthObj.cpu; cpuSpan.innerText = cpu; cpuSpan.style.color = cpu < 50 ? 'var(--success)' : (cpu < 80 ? '#f59e0b' : 'var(--danger)');
let tempVal = healthObj.temp; tempSpan.innerText = tempVal; tempSpan.style.color = tempVal < 55 ? 'var(--success)' : (tempVal < 70 ? '#f59e0b' : 'var(--danger)');
ramSpan.innerText = healthObj.ram; let d = healthObj.disk; diskSpan.innerText = d; diskSpan.style.color = d < 85 ? 'inherit' : (d < 95 ? '#f59e0b' : 'var(--danger)');
let upSpan = document.getElementById(`up-${c.id}`);
if (upSpan && healthObj.uptime) { upSpan.innerText = fmtAge(healthObj.uptime); }
let agentBadge = document.getElementById(`agent-badge-${c.id}`);
if (agentBadge && healthObj.agent_version) { agentBadge.innerText = `Agent v${healthObj.agent_version}`; agentBadge.style.display = 'inline-block'; }
const profBtnsDiv = document.getElementById(`prof-btns-${c.id}`);
const profKeys = JSON.stringify(healthObj.profiles || {});
if (profBtnsDiv && profBtnsDiv.dataset.keys !== profKeys) {
profBtnsDiv.dataset.keys = profKeys;
if (healthObj.profiles && Object.keys(healthObj.profiles).length > 0) {
profBtnsDiv.style.display = 'flex';
let html = ''; const colors = ["var(--accent)", "#eab308", "var(--success)", "var(--primary)"]; let idx = 0;
for (const [pKey, pLabel] of Object.entries(healthObj.profiles)) {
let col = colors[idx % colors.length];
html += `<button class="btn-cmd" style="background: ${col}; flex: 1; border: none; color: white !important;" title="${esc(t('ttSwitchTo') + pLabel)}" onclick="confirmSwitch('${c.id}', ${q(pKey)})">${esc(pLabel)}</button>`;
idx++;
}
profBtnsDiv.innerHTML = html;
} else { profBtnsDiv.style.display = 'none'; profBtnsDiv.innerHTML = ''; }
}
} else {
if (healthContainer) healthContainer.style.display = 'none';
let agentBadge = document.getElementById(`agent-badge-${c.id}`);
if (agentBadge) agentBadge.style.display = 'none';
}
globalHealthData[c.id.toLowerCase()] = healthObj;
let hasOfflineService = false;
if (healthObj && healthObj.processes) {
for (const [svcName, svcStatus] of Object.entries(healthObj.processes)) { if (svcStatus.toLowerCase() !== 'online') { hasOfflineService = true; break; } }
}
const warnBadge = document.getElementById(`svc-warn-${c.id}`); const btnSvc = document.getElementById(`btn-svc-${c.id}`);
if (warnBadge) warnBadge.style.display = hasOfflineService ? 'block' : 'none';
if (btnSvc) {
if (hasOfflineService) { btnSvc.style.background = 'var(--danger)'; btnSvc.classList.add('blink'); btnSvc.innerHTML = t('btnSvcKo'); }
else { btnSvc.style.background = '#334155'; btnSvc.classList.remove('blink'); btnSvc.innerHTML = t('btnSvc'); }
}
let btnOta = document.getElementById(`btn-ota-${c.id}`);
let adminSummary = document.getElementById(`admin-summary-${c.id}`);
if (btnOta) {
if (healthObj && healthObj.agent_update_available) {
btnOta.style.setProperty('background', 'var(--danger)', 'important');
btnOta.style.setProperty('color', 'white', 'important');
btnOta.style.setProperty('border', '1px solid var(--danger)', 'important');
btnOta.style.animation = 'danger-glow 1.5s infinite';
if (adminSummary) {
adminSummary.innerHTML = "⚠️ ADMIN (UPDATE OTA!)";
adminSummary.style.setProperty('color', 'var(--danger)', 'important');
adminSummary.style.setProperty('border-color', 'var(--danger)', 'important');
adminSummary.style.animation = 'danger-glow 1.5s infinite';
}
} else {
btnOta.style.setProperty('background', '#2563eb', 'important');
btnOta.style.setProperty('color', 'white', 'important');
btnOta.style.setProperty('border', '1px solid transparent', 'important');
btnOta.style.animation = 'none';
if (adminSummary) {
adminSummary.innerHTML = "⚙️ Admin Tools";
adminSummary.style.setProperty('color', 'var(--text-muted)', 'important');
adminSummary.style.setProperty('border-color', 'var(--border-color)', 'important');
adminSummary.style.animation = 'none';
}
}
}
if (isOnline) {
cardDiv.classList.add('online'); statusDiv.classList.remove('status-offline'); cardDiv.style.opacity = "1"; cardDiv.style.filter = "none";
if (isTx) cardDiv.dataset.lastTx = Date.now();
let timeSinceTx = Date.now() - (parseInt(cardDiv.dataset.lastTx) || 0);
let showActiveColor = isTx || (!isIdle && timeSinceTx < HANG_TIME_MS);
cardDiv.style.setProperty('border-top-color', showActiveColor ? activeModeColor : "var(--border-color)", 'important');
if(isTx) {
let shadowRGB = '59, 130, 246';
if (activeModeColor === '#10b981') shadowRGB = '16, 185, 129'; else if (activeModeColor === '#8b5cf6') shadowRGB = '139, 92, 246'; else if (activeModeColor === '#06b6d4') shadowRGB = '6, 182, 212'; else if (activeModeColor === '#f59e0b') shadowRGB = '245, 158, 11';
cardDiv.style.boxShadow = `0 0 20px rgba(${shadowRGB}, 0.5) !important`;
} else { cardDiv.style.boxShadow = '0 4px 12px rgba(0,0,0,0.2) !important'; }
} else {
cardDiv.classList.remove('online'); statusDiv.classList.add('status-offline'); cardDiv.style.opacity = "0.7"; cardDiv.style.filter = "grayscale(80%)";
cardDiv.style.setProperty('border-top-color', '#64748b', 'important'); cardDiv.style.boxShadow = 'none !important';
}
const miniCard = document.getElementById(`mini-card-${c.id}`);
const miniStatus = document.getElementById(`mini-status-${c.id}`);
const miniName = document.getElementById(`mini-name-${c.id}`);
const miniId = document.getElementById(`mini-id-${c.id}`);
if (miniCard && miniStatus) {
if (genObj && isOnline) {
if (miniName) miniName.innerText = genObj.callsign;
if (miniId) miniId.innerText = `ID: ${genObj.radio_id}`;
}
else {
if (miniName) miniName.innerText = c.name;
if (miniId) miniId.innerText = `ID: ${c.id.toUpperCase()}`;
}
if (isOnline) {
miniCard.style.borderColor = "var(--success)";
miniCard.style.opacity = "1";
miniCard.style.filter = "none";
miniStatus.innerText = stateValue;
miniStatus.title = stateValue;
miniStatus.style.color = "var(--success)";
miniStatus.style.background = "rgba(16, 185, 129, 0.1)";
miniStatus.style.borderColor = "rgba(16, 185, 129, 0.2)";
} else {
miniCard.style.borderColor = "var(--border-color)";
miniCard.style.opacity = "0.6";
miniCard.style.filter = "grayscale(80%)";
miniStatus.innerText = "OFFLINE";
miniStatus.title = "OFFLINE";
miniStatus.style.color = "var(--danger)";
miniStatus.style.background = "rgba(239, 68, 68, 0.1)";
miniStatus.style.borderColor = "rgba(239, 68, 68, 0.2)";
}
}
});
applyFilters();
document.getElementById('last-update').innerText = "Sync: " + new Date().toLocaleTimeString();
} catch (e) { console.error(e); }
}
async function refreshLogs() {
try {
const res = await fetch('/api/logs'); const logs = await res.json();
const tbody = document.getElementById('log-body'); let tableHTML = ""; let networkLogs = {};
logs.forEach(row => {
const time = row[0] ? row[0].split(' ')[1] : "--:--";
const clientId = row[1]; const protocol = row[2] || "DMR"; let source = row[3] || "---"; const target = row[4] || "---";
const rawSlot = row[5]; const source_ext = row[8]; const rawRssi = row[9]; const sourceConn = row[10]; const ysfMode = row[11];
let sourceHtml = esc(source);
if (source_ext && source_ext.trim() !== "") { sourceHtml += ` <span style="font-size:0.8em; color:var(--text-muted); font-family:'JetBrains Mono', monospace;">/${esc(source_ext)}</span>`; }
let slotDisplay = rawSlot && String(rawSlot).trim() !== "" && rawSlot !== "undefined" ? (protocol === "DMR" && !String(rawSlot).toUpperCase().startsWith("TS") ? `TS${rawSlot}` : rawSlot) : "---";
let protoColor = "#3b82f6"; if (protocol === "NXDN") protoColor = "#10b981"; else if (protocol === "YSF") protoColor = "#8b5cf6"; else if (protocol === "D-STAR") protoColor = "#06b6d4"; else if (protocol === "P25") protoColor = "#f59e0b";
let sourceBadge = sourceConn ? (sourceConn.toLowerCase() === 'rf' ? '<span style="color:#f87171; font-weight:800;">RF</span>' : (sourceConn.toLowerCase() === 'network' ? '<span style="color:#38bdf8; font-weight:800;">NET</span>' : `<span style="font-weight:800; color:var(--text-muted);">${esc(sourceConn).toUpperCase()}</span>`)) : "---";
let modeDisplay = ysfMode && ysfMode.trim() !== "" ? `<span style="font-size:0.7rem; color:var(--accent); border: 1px solid var(--accent); padding: 2px 4px; border-radius: 4px;">${esc(ysfMode).toUpperCase()}</span>` : "---";
let rssiDisplay = '---';
if (rawRssi && rawRssi !== 0) {
let sLabel = "S0";
if (rawRssi >= -93) {
let over = Math.round((rawRssi + 93) / 10) * 10;
sLabel = over > 0 ? `S9<sup style="color: var(--danger); font-weight: 800;">+${over}</sup>` : "S9";
} else {
let sUnits = Math.floor((rawRssi + 141) / 6) + 1;
sLabel = `S${Math.max(1, Math.min(9, sUnits))}`;
}
let activeSegs = 1;
if (rawRssi >= -53) activeSegs = 9; else if (rawRssi >= -63) activeSegs = 8; else if (rawRssi >= -73) activeSegs = 7; else if (rawRssi >= -83) activeSegs = 6; else if (rawRssi >= -93) activeSegs = 5; else if (rawRssi >= -105) activeSegs = 4; else if (rawRssi >= -117) activeSegs = 3; else if (rawRssi >= -129) activeSegs = 2;
let barsHtml = ''; const heights = [4, 5, 6, 7, 8, 10, 12, 14, 14];
for (let i = 0; i < 9; i++) {
let color = "rgba(255,255,255,0.1)";
if (i < activeSegs) { if (i < 5) color = "var(--success)"; else if (i < 7) color = "#f59e0b"; else color = "var(--danger)"; }
barsHtml += `<div style="width: 4px; height: ${heights[i]}px; background: ${color}; border-radius: 1px;"></div>`;
}
rssiDisplay = `<div style="display: flex; align-items: center; gap: 10px;" title="${esc(rawRssi)} dBm"><div style="min-width: 40px; text-align: right; font-weight: bold; font-family: 'Inter', sans-serif;">${sLabel}</div><div style="display: flex; align-items: flex-end; gap: 2px; height: 14px;">${barsHtml}</div><span style="font-size: 0.85em; color: var(--text-muted); min-width: 7ch; text-align: right;">${esc(rawRssi)} dBm</span></div>`;
}
if (source.includes("🌐")) {
if (!networkLogs[clientId]) networkLogs[clientId] = "";
networkLogs[clientId] += `<div style="border-bottom:1px solid rgba(255,255,255,0.05); padding:4px 0;"><span style="color:var(--text-muted);">[${esc(time)}]</span> <span style="color:${protoColor}; font-weight:bold;">[${esc(protocol)}]</span> <span style="color:var(--text-main);">${esc(source.replace("🌐", "").trim())}</span></div>`;
} else {
const selectedFilter = document.getElementById('stat-node-filter').value;
if (selectedFilter === 'all' || String(clientId).toLowerCase() === selectedFilter) {
tableHTML += `<tr>
<td data-label="${t('thTime')}">${esc(time)}</td>
<td data-label="${t('thRep')}"><b style="color:var(--text-main);">${esc(String(clientId).toUpperCase())}</b></td>
<td data-label="${t('thMode')}"><span style="background:${protoColor}; color:white; padding:4px 8px; border-radius:6px; font-size:0.7rem; font-weight:800;">${esc(protocol)}</span></td>
<td data-label="YSF Mode" style="text-align:center;">${modeDisplay}</td>
<td data-label="Source" style="text-align:center; font-family:'JetBrains Mono', monospace;">${sourceBadge}</td>
<td data-label="REF/SLOT" style="font-family:'JetBrains Mono', monospace; font-weight:bold; text-align:center;">${esc(slotDisplay)}</td>
<td data-label="${t('thCall')}" style="color:var(--accent); font-weight:800;">${sourceHtml}</td>
<td data-label="Target / TG" style="font-family:'JetBrains Mono', monospace;">${esc(target.trim())}</td>
<td data-label="${t('thDur')}">${esc(row[6])}s</td>
<td data-label="BER">${esc(row[7])}%</td>
<td data-label="RSSI" style="font-family:'JetBrains Mono', monospace;">${rssiDisplay}</td>
</tr>`;
}
}
});
tbody.innerHTML = tableHTML;
clients.forEach(c => { const localDiv = document.getElementById(`sys-log-${c.id}`); if (localDiv && networkLogs[c.id]) { localDiv.innerHTML = networkLogs[c.id]; } });
} catch (e) { console.error(e); }
}
async function refreshStats() {
try {
const node = document.getElementById('stat-node-filter').value || 'all';
const res = await fetch(`/api/stats?node=${node}`); const data = await res.json();
document.getElementById('stat-tgs').innerHTML = data.top_tgs.map((t, i) => `<div><b style="color:var(--text-main);">${i+1}. ${esc(t.target)}</b> <span style="float:right; background:rgba(255,255,255,0.05); padding:2px 6px; border-radius:4px;">${t.count} tx</span></div>`).join('') || t('statNoData');
document.getElementById('stat-calls').innerHTML = data.top_calls.map((c, i) => `<div><b style="color:var(--text-main);">${i+1}. ${esc(c.call)}</b> <span style="float:right; background:rgba(255,255,255,0.05); padding:2px 6px; border-radius:4px;">${c.count} tx</span></div>`).join('') || t('statNoData');
document.getElementById('stat-avg').innerText = data.avg_duration; document.getElementById('stat-today').innerText = data.today_tx;
} catch (e) { console.error("Errore statistiche:", e); }
}
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 => `
<tr>
<td>${u.id}</td><td style="font-weight:bold;">${esc(u.username)}</td><td><span style="background:rgba(255,255,255,0.1); padding:2px 8px; border-radius:6px; font-size:0.8rem;">${esc(String(u.role).toUpperCase())}</span></td><td>${esc(u.allowed_nodes)}</td>
<td style="text-align:center;">
<button onclick="startEditUser(${Number(u.id)})" class="btn-cmd" style="background:var(--accent); padding:6px; width:auto; display:inline-block; margin-right:5px; border:none; color:white !important;">✏️</button>
<button onclick="deleteUser(${u.id})" class="btn-cmd" style="background:var(--danger); padding:6px; width:auto; display:inline-block; border:none; color:white !important;">🗑️</button>
</td>
</tr>`).join('');
}
function startEditUser(id) {
const u = usersCache[id]; if (!u) return;
editingUserId = id; document.getElementById('new-user').value = u.username; document.getElementById('new-user').disabled = true; document.getElementById('new-pass').value = ""; document.getElementById('new-pass').placeholder = t('phNewPass'); document.getElementById('new-role').value = u.role; document.getElementById('new-nodes').value = u.allowed_nodes;
const btnSubmit = document.getElementById('btn-user-submit'); btnSubmit.innerHTML = t('titleSave'); btnSubmit.style.background = "var(--accent)"; document.getElementById('btn-user-cancel').style.display = "block";
}
function cancelEdit() {
editingUserId = null; document.getElementById('new-user').value = ""; document.getElementById('new-user').disabled = false; document.getElementById('new-pass').value = ""; document.getElementById('new-pass').placeholder = t('phPass'); document.getElementById('new-role').value = "operator"; document.getElementById('new-nodes').value = "";
const btnSubmit = document.getElementById('btn-user-submit'); btnSubmit.innerHTML = t('btnAdd'); btnSubmit.style.background = "var(--success)"; document.getElementById('btn-user-cancel').style.display = "none";
}
async function submitUser() {
const username = document.getElementById('new-user').value; const password = document.getElementById('new-pass').value; const role = document.getElementById('new-role').value; let allowed = document.getElementById('new-nodes').value;
if (!username) return customAlert(t('titleError'), t('msgMissUser'), true);
const payload = { username, role, allowed_nodes: allowed || 'all' }; if (password) payload.password = password;
if (editingUserId) {
const res = await fetch(`/api/users/${editingUserId}`, { method: 'PUT', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) }); const data = await res.json();
if (data.success) { cancelEdit(); loadUsers(); } else customAlert(t('titleError'), esc(data.error), true);
} else {
if (!password) return customAlert(t('titleError'), t('msgMissPass'), true);
const res = await fetch('/api/users', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) }); const data = await res.json();
if (data.success) { cancelEdit(); loadUsers(); } else customAlert(t('titleError'), esc(data.error), true);
}
}
function deleteUser(id) { customConfirm(t('titleDelete'), t('msgDelUser'), "var(--danger)", async () => { const r = await fetch(`/api/users/${id}`, {method: 'DELETE'}); const dd = await r.json().catch(() => ({})); if (!dd.success) customAlert(t('titleError'), esc(dd.error || 'Error'), true); loadUsers(); cancelEdit(); }); }
function triggerGlobalEmergency() {
let uniqueProfiles = {};
for (const id in globalHealthData) {
if (globalHealthData[id] && globalHealthData[id].profiles) {
for (const [k, v] of Object.entries(globalHealthData[id].profiles)) { uniqueProfiles[k] = v; }
}
}
const container = document.getElementById('global-btn-container'); let html = ''; const colors = ["var(--accent)", "#eab308", "var(--success)", "var(--primary)"]; let idx = 0;
for (const [k, v] of Object.entries(uniqueProfiles)) {
let col = colors[idx % colors.length];
html += `<button onclick="sendGlobalAction(${q(k)})" class="btn-cmd" style="background:${col}; padding:15px; font-size:1.1rem; font-weight:bold; border:none; color:white !important;">${esc(v)}</button>`;
idx++;
}
if (Object.keys(uniqueProfiles).length === 0) { html = `<p style="color:var(--danger); font-weight:bold;">No profiles configured on the network.</p>`; }
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); }
});
}
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); }
}
async function loadSettings() { try { const res = await fetch('/api/config'); if (!res.ok) return; const data = await res.json(); document.getElementById('update-time-input').value = data.update_schedule; document.getElementById('url-dmr-input').value = data.url_dmr; document.getElementById('url-nxdn-input').value = data.url_nxdn; } catch (e) { console.error(e); } }
async function saveSettings() {
const payload = { update_schedule: document.getElementById('update-time-input').value, url_dmr: document.getElementById('url-dmr-input').value, url_nxdn: document.getElementById('url-nxdn-input').value };
try { const res = await fetch('/api/config', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) }); const data = await res.json();
if (data.success) customAlert(t('titleSuccess'), t('msgConfigSaved')); else customAlert(t('titleError'), esc(data.error || t('msgConfigErr')), true);
} catch (e) { console.error(e); }
}
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 = `<div style="text-align:center; padding:20px;"><p style="color:var(--text-muted); margin-bottom:15px;">${t('waitData')}</p><button onclick="sendGlobalUpdate(); closeConfigsModal();" class="btn-cmd" style="background:var(--accent);">${t('forceUpdate')}</button></div>`;
else listDiv.innerHTML = listaFile.map(f => `<div style="display:flex; justify-content:space-between; align-items:center; padding:12px; background:rgba(255,255,255,0.05); border-radius:12px; border:1px solid var(--border-color); margin-bottom:8px;"><span style="font-family:'JetBrains Mono',monospace; font-weight:bold;">${esc(fileLabel(f, fileNames))}</span><button onclick="closeConfigsModal(); openEditorModal(${q(clientId)}, ${q(f)})" class="btn-cmd" style="background:#8e44ad; max-width:120px; border:none; color:white !important;">${t('btnEdit')}</button></div>`).join('');
document.getElementById('configs-modal').style.display = 'flex';
}
function closeConfigsModal() { document.getElementById('configs-modal').style.display = 'none'; }
function openServicesModal(clientId) { document.getElementById('svc-modal-title').innerText = clientId.toUpperCase(); document.getElementById('services-modal').style.display = 'flex'; renderServicesList(clientId); }
function closeServicesModal() { document.getElementById('services-modal').style.display = 'none'; }
function renderServicesList(clientId) {
const data = globalHealthData[clientId.toLowerCase()]; const listDiv = document.getElementById('services-list');
if (!data || !data.processes || Object.keys(data.processes).length === 0) { listDiv.innerHTML = "<p style='text-align:center; color:var(--text-muted);'>No service data available.</p>"; 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 += `<div style="display:flex; justify-content:space-between; align-items:center; padding:15px; border-bottom:1px solid var(--border-color); background:rgba(255,255,255,0.02); border-radius:12px; margin-bottom:8px; border-left: 5px solid ${statusColor};">
<div><strong style="font-size:1.1rem; display:block; font-family:'JetBrains Mono',monospace;">${esc(name)}</strong><span class="${isOnline?'':'blink'}" style="color:${statusColor}; font-size:0.8rem; font-weight:800;">${esc(String(status).toUpperCase())}</span></div>
<div style="display:flex; gap:8px;">
${!isOnline ? `<button onclick="controlService(${q(clientId)},${q(name)}, 'start')" class="btn-cmd" style="background:var(--success); border:none; color:white !important;">▶</button>` : ''}
<button onclick="controlService(${q(clientId)}, ${q(name)}, 'restart')" class="btn-cmd" style="background:#f59e0b; border:none; color:white !important;">🔄</button>
<button onclick="openEditorModal(${q(clientId)}, ${q(name)})" class="btn-cmd" style="background:#8e44ad; border:none; color:white !important;">📝</button>
${isOnline ? `<button onclick="controlService(${q(clientId)},${q(name)}, 'stop')" class="btn-cmd" style="background:var(--danger); border:none; color:white !important;">🛑</button>` : ''}
</div>
</div>`;
}
listDiv.innerHTML = html;
}
function controlService(clientId, service, action) {
customConfirm(t('titleAction'), `${t('confOp')}<b>${esc(service)}</b>?`, "var(--accent)", async () => {
try { const res = await fetch('/api/service_control', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId, service, action }) }); const data = await res.json();
if(!data.success) customAlert(t('titleError'), "Error: " + esc(data.error), true);
} catch(e) { console.error(e); }
});
}
let currentEditClient = ""; let currentEditService = "";
async function openEditorModal(clientId, service) {
currentEditClient = clientId; currentEditService = service; document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`;
document.getElementById('config-textarea').value = "Connecting to server..."; document.getElementById('editor-status').innerText = ""; document.getElementById('editor-modal').style.display = 'flex';
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 file"; else document.getElementById('config-textarea').value = "ERROR:\n" + data.error; } catch(e) { document.getElementById('config-textarea').value = "Connection error."; }
}
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 = "Sending..."; 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 updated!"); closeEditorModal(); } else { customAlert(t('titleError'), "Server error: " + esc(data.error), true); statusSpan.innerText = "❌ Error"; }
} catch(e) { customAlert(t('titleError'), t('msgNetErr'), true); statusSpan.innerText = "❌ Network Error"; }
});
}
function openVersionsModal(clientId) {
const versions = globalVersionsData[clientId.toLowerCase()]; const listDiv = document.getElementById('versions-list');
if (!versions || Object.keys(versions).length === 0) { listDiv.innerHTML = "<span style='color: var(--text-muted);'>Nessun dato ancora ricevuto. Usa il tasto 🔄 RESTART sui servizi del nodo per forzare l'invio del log di avvio.</span>"; }
else { let html = ""; for (const [software, version] of Object.entries(versions)) { html += `<div><strong style="color: var(--primary); display: inline-block; width: 140px;">${esc(software)}:</strong> <span style="color: var(--success); font-weight: bold;">${esc(version)}</span></div>`; } listDiv.innerHTML = html; }
document.getElementById('versions-modal').style.display = 'flex';
}
function closeVersionsModal() { document.getElementById('versions-modal').style.display = 'none'; }
async function subscribeToPush() {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) { customAlert("Error", "Push notifications are not supported by this browser.", true); return; }
if (!me.logged_in) { openLoginModal(); return; }
const permission = await Notification.requestPermission();
if (permission !== 'granted') { customAlert("Error", "Push notifications permission denied.", true); return; }
try {
const reg = await navigator.serviceWorker.ready; const res = await fetch('/api/vapid_public_key'); const { public_key } = await res.json();
const subscription = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlB64ToUint8Array(public_key) });
const subRes = await fetch('/api/subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(subscription) });
if (!subRes.ok) throw new Error('subscribe failed: HTTP ' + subRes.status);
customAlert("Success", "Push notifications enabled successfully!"); document.getElementById('push-btn').style.color = 'var(--success)';
} catch (e) { console.error(e); customAlert("Error", "Failed to enable notifications.", true); }
}
async function checkPushStatus() {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) return;
try { const reg = await navigator.serviceWorker.ready; const subscription = await reg.pushManager.getSubscription(); const btn = document.getElementById('push-btn'); if (subscription && btn) { btn.style.color = 'var(--success)'; } } catch(e) { console.error(e); }
}
function urlB64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i); return outputArray; }
async function checkServerUpdate() {
if (!isAuthenticated || me.role !== 'admin') return;
try { const res = await fetch('/api/server_update/check'); const data = await res.json(); const btn = document.getElementById('server-update-btn'); if (btn) { btn.style.display = data.update_available ? 'inline-block' : 'none'; } } catch (e) { console.error(e); }
}
function confirmServerUpdate() {
customConfirm("🔄 UPDATE SERVER", "Vuoi scaricare l'ultima versione del server da Gitea/GitHub e riavviare il servizio backend?", "var(--danger)", async () => {
try { const res = await fetch('/api/server_update/apply', { method: 'POST' }); const data = await res.json(); if (data.success) { customAlert("✅ SUCCESS", "Aggiornamento in corso. La pagina si ricaricherà a breve."); setTimeout(() => location.reload(), 5000); } else { customAlert("❌ ERRORE", esc(data.error), true); } } catch (e) { console.error(e); customAlert("❌ ERRORE", "Errore di rete.", true); }
});
}
setInterval(checkServerUpdate, 3600000); setTimeout(checkServerUpdate, 5000);
initUI(); checkPushStatus();
setInterval(refreshStates, 15000); setInterval(() => { refreshLogs(); refreshStats(); }, 60000);
function debounce(fn, ms) { let tm = null; return () => { clearTimeout(tm); tm = setTimeout(fn, ms); }; }
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: ONLINE"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: OFFLINE"; badge.className = "mqtt-badge mqtt-offline"; } } });
socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); });
socket.on('dati_aggiornati', refreshStatesSoon); socket.on('log_aggiornato', refreshLogsSoon);
}
</script>
<script>
if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/sw.js').catch(err => { console.log('ServiceWorker fallita: ', err); }); }); }
</script>
</body>
</html>