diff --git a/README.md b/README.md index f180cdc..e3d8375 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 📡 Fleet Control Console - Server (Central Hub) +# 📡 Fleet Control Console - Server (Central Hub) v6.0.0 🌍 *[Read in English](#english) | 🇮🇹 [Leggi in Italiano](#italiano)* @@ -14,60 +14,49 @@ > ℹ️ **Note:** This is the Central Server repository. To monitor remote repeaters, you must install the [Fleet Control Agent](https://git.arifvg.it/iv3jdv/fleet-node-agent.git) on each node. ### 🏗️ Architecture & Technology Stack -The server acts as the brain of the network, built on a highly scalable foundation (v5.0+): +The server acts as the brain of the network, built on a highly scalable foundation (v6.0.0): * **Modular Backend:** Completely decoupled architecture (`core/`, `services/`, `routes/`) for high maintainability and robust background task handling. * **Core Engine:** Flask (Python) with `gevent` for high-concurrency WebSocket handling. -* **Database:** SQLite (WAL mode) for robust User Management, Audit Logs, and Radio Traffic storage. +* **Database:** SQLite (WAL mode) for robust User Management, Audit Logs, Schedules, and Radio Traffic storage. * **Communication:** MQTT for instant data routing + WebSockets (SocketIO) for zero-latency UI updates. -* **Frontend:** Vanilla JS with a modern *Glassmorphism Borderless Executive* NOC (Network Operations Center) design and fully separated logic (`app.js`, `modals.js`). Full i18n (Internationalization) support. +* **Frontend:** Vanilla JS with a modern *Glassmorphism Borderless Executive* NOC (Network Operations Center) design. Full i18n (Internationalization) support for English and Italian. -### ✨ Ultimate Features +### ✨ Ultimate Features (v6.0.0) -#### 🛡️ Proactive Diagnostics (Watchdog) & Global Alerts -* **Hardware Monitoring:** Continuous analysis of remote CPU temperatures and disk space saturation. Automatically triggers Push Notifications before critical failures occur. -* **RF Anomaly Detection:** Real-time monitoring of local RF BER (Bit Error Rate). Detects hardware RF degradation on local transits and alerts admins instantly. -* **Global Service Alerts (v5.3+):** Daemon crashes (e.g., `SVC KO: MMDVMHOST`) are instantly propagated to the global Dashboard grid and interactive Fleet Map for immediate visibility. +#### 🗓️ Calendar Profile Scheduler [NEW] +* Plan automated profile switches (e.g., Regional Nets, Contests, Civil Defense drills) across multiple nodes. +* Seamless background execution: the system automatically triggers the `Target Profile` at the specified start time and gracefully falls back to the `Restore Profile` once the event ends. -#### ⚡ Zero-Latency Real-Time Dashboard -* **WebSocket Powered:** The dashboard updates instantly upon radio traffic or telemetry changes. No heavy HTTP polling, no page reloads. -* **Live MQTT Status:** A real-time badge continuously monitors the connection to the MQTT broker. -* **PWA Ready:** Install the dashboard as a Progressive Web App on iOS/Android for a native, full-screen mobile experience with offline asset caching. +#### 🗺️ Tactical APRS Map [NEW] +* Real-time GIS map showing both your fixed repeater locations and **roaming APRS stations**. +* Automatically extracts and parses APRS payloads from gateway logs. +* Features a smart Garbage Collector that automatically cleans up roaming pins after 2 hours of inactivity. -#### 🔔 Web Push Notifications -* Get instant, native alerts directly on your desktop or mobile device when: - * A node goes offline or comes back online. - * A critical system daemon crashes (Auto-healing failed). - * The Watchdog detects thermal warnings, disk full alerts, or high RF BER. -* Works securely even when the web app is closed or in the background. +#### 🛠️ Advanced Remote Control & Visual Diff [NEW] +* **Time Machine Config Editor:** Edit daemon configuration files (e.g., MMDVMHost.ini) directly from the web interface, with the ability to rollback to previous historical backups. +* **Semantic Visual Diff:** Compare your local unsaved edits against the running config with a rich Green/Red semantic diff viewer before safely committing changes to the node. +* **OTA Server Updates:** Apply server-side Git updates directly from the admin dashboard without SSH access. +* **Service Management & Hardware:** Start/Stop/Restart remote daemons, trigger physical OS reboots, or hard GPIO resets of the MMDVM HAT. -#### 🛠️ Advanced Remote Control & Maintenance -* **OTA Server Updates:** Apply server-side Git updates with a single click directly from the admin dashboard (Over-The-Air) without SSH access, featuring a synchronous, cache-bypassing update checker. -* **Remote .INI Editor:** Edit daemon configuration files (e.g., MMDVMHost.ini) directly from the web interface. -* **Service Management:** Start, Stop, or Restart remote system daemons. -* **Scoped Global Overrides:** Switch profiles (e.g., Profile A/B) simultaneously on multiple nodes, dynamically scoped to the operator's authorized repeaters. -* **Hardware Interventions:** Trigger a physical OS reboot or a hard GPIO reset of the MMDVM HAT directly from the web panel. +#### 📈 Dynamic Analytics & Monitoring [NEW] +* **Timeframe Analytics:** Interactive historical charts (Chart.js) for CPU/Temp and RF Transits/BER. Zoom dynamically across 12H, 24H, 48H, or 7D timeframes with smart axis labeling. +* **Live WebSocket Console:** Zero-latency terminal streams for node daemons. Real-time active operator tracking (see who is logged in and managing the dashboard). +* **Proactive Diagnostics (Watchdog):** Continuous analysis of remote CPU temperatures, disk space, and RF BER. Triggers automated Web Push Notifications. -#### 📊 Unified Monitoring & Statistics -* **Interactive Fleet Map:** Real-time GIS map showing repeater locations, online/offline status, active TX states (pulsing pins), and active watchdog/service warnings. -* **Live Heard Log:** A centralized view of radio traffic across the entire network, auto-resolving DMR and NXDN IDs into callsigns. -* **Software & Firmware Tracking:** Instantly view MMDVM firmware versions and Pi-Star/Gateway component versions for each node. -* **Daily Analytics:** Automatically tracks Top Talkgroups, Top Callsigns, Average duration, and daily transit counts. - -#### 🔐 Security & Access Control -* **Strict Role-Based Access Control (RBAC):** True Zero-Trust architecture. -* **Granular Permissions:** Node management (reboots, config edits, service controls) is strictly bound to explicitly assigned nodes in `allowed_nodes`, uniformly enforced for both *Operators* and *Admins*. -* **System Administration:** Admins retain exclusive rights to global server settings and user management, separated from node-level control. -* **Audit Trail:** Every critical action is securely logged with username, timestamp, and target node. +#### 🔐 Strict Security & Access Control +* **Role-Based Access Control (RBAC):** True Zero-Trust architecture. Node management is bound to explicitly assigned nodes (`allowed_nodes`) for both *Operators* and *Node Admins*. +* **System Administration:** Admins retain exclusive rights to global server settings, schedules, and user management. +* **Security Audit Trail:** Every critical action (reboots, config edits, schedules) is securely logged with username, timestamp, and target node. ### ⚠️ Security Requirement: HTTPS -Please note that **Web Push Notifications** and the **Service Worker** require a secure connection to function. For security reasons, modern browsers only enable these features over **HTTPS**. If you are accessing the console via HTTP (outside of `localhost`), the "Push" button and notification registration will not work. We recommend using a reverse proxy (like Nginx, Caddy, or Traefik) with an SSL certificate. +**Web Push Notifications** and the **Service Worker** require a secure connection. Modern browsers only enable these features over **HTTPS**. We recommend using a reverse proxy (like Nginx, Caddy, or Apache) with an SSL certificate. ### ⚠️ Reverse Proxy & WebSocket Configuration -If you expose the Fleet Console through a reverse proxy like **Apache** on a public IP (HTTPS), standard HTTP proxying will drop Socket.IO real-time connections. You must enable the WebSocket tunnel in Apache: +If using a reverse proxy like **Apache** on HTTPS, you must enable WebSocket tunneling: ```bash sudo a2enmod proxy_wstunnel rewrite headers ``` -And insert the **Rewrite** rules *before* the `ProxyPass` directives inside your `` block: +Insert the **Rewrite** rules *before* the `ProxyPass` directives in your ``: ```apache RewriteEngine On RewriteCond %{HTTP:Upgrade} =websocket [NC] @@ -82,165 +71,46 @@ ProxyPass / http://127.0.0.1:9000/ ProxyPassReverse / http://127.0.0.1:9000/ ``` -### 🚀 Installation Guide - -#### 0. Root Privileges -All installation steps must be executed as the `root` user. -```bash -apt update -apt install build-essential python3-dev libssl-dev libffi-dev python3-pip python3-venv -``` -#### 1. Clone Repository -Clone the repository into the /opt directory to ensure all systemd paths work correctly: -```bash -git clone https://git.arifvg.it/iv3jdv/fleet-control-server.git /opt/fleet-control-server -cd /opt/fleet-control-server -``` -#### 2. Virtual Environment Setup (Recommended) -To prevent conflicts with OS packages (PEP 668), create an isolated environment: -```bash -cd /opt/fleet-control-server -python3 -m venv venv -source venv/bin/activate -pip install --upgrade pip setuptools wheel -pip install -r requirements.txt -``` - -#### 3. Configuration -1. Copy `config.example.json` to `config.json`. -2. Configure your MQTT broker credentials. -3. Define your repeaters in `clients.json`. -4. Generate VAPID keys at [vapidkeys.com](https://vapidkeys.com/) and add them to `config.json` to enable Web Push notifications. *(Note: Push notifications require HTTPS).* -5. Configure dynamic log rotation sizes (`log_max_mb` and `log_backup_count`) directly in `config.json` to manage disk space. - -#### 4. Running as a Service -To run the server continuously in production using Gunicorn: -```bash -cp fleet-console.service /etc/systemd/system/ -systemctl daemon-reload -systemctl enable fleet-console -systemctl start fleet-console -``` -*(Ensure the `.service` file points to the `gunicorn` executable inside your `venv`)*. - --- ## 🇮🇹 Italiano -**Fleet Control Console** è una dashboard di comando e controllo (C2) professionale in tempo reale, progettata per le reti di ripetitori radioamatoriali (MMDVM). Questo repository contiene il **Server (Central Hub)**, che fornisce un'interfaccia web centralizzata per monitorare e gestire una flotta di nodi digitali remoti (DMR, NXDN, YSF, P25). +**Fleet Control Console** è una dashboard di comando e controllo (C2) professionale in tempo reale, progettata per le reti di ripetitori radioamatoriali (MMDVM). Questo repository contiene il **Server (Central Hub)**, che fornisce un'interfaccia web centralizzata per monitorare e gestire una flotta di nodi digitali remoti. > ℹ️ **Nota:** Questo è il repository del Server Centrale. Per monitorare i ripetitori, devi installare il [Fleet Control Agent](https://git.arifvg.it/iv3jdv/fleet-node-agent.git) su ciascun nodo remoto. -### 🏗️ Architettura e Tecnologie -Il server agisce da cervello della rete, basato su fondamenta altamente scalabili (v5.0+): -* **Backend Modulare:** Architettura completamente disaccoppiata (`core/`, `services/`, `routes/`) per un'elevata manutenibilità e gestione robusta dei task in background. +### 🏗️ Architettura e Tecnologie (v6.0.0) +* **Backend Modulare:** Architettura completamente disaccoppiata (`core/`, `services/`, `routes/`) per un'elevata manutenibilità e gestione asincrona. * **Motore Core:** Flask (Python) con `gevent` per la gestione ad alta concorrenza dei WebSocket. -* **Database:** SQLite (in modalità WAL) per gestire in sicurezza Utenti, Log operativi e traffico radio. -* **Comunicazione:** MQTT per il routing istantaneo dei dati + WebSockets (SocketIO) per aggiornare la UI a latenza zero. -* **Frontend:** Vanilla JS con layout *Borderless Executive* in stile NOC (Network Operations Center), logica completamente separata (`app.js`, `modals.js`) e supporto nativo **i18n** (internazionalizzazione multilingua dinamica). +* **Database:** SQLite (in modalità WAL) per gestire Utenti, Log Sicurezza, Schedulazioni e traffico radio. +* **Frontend Bilingue:** Vanilla JS con layout *Borderless Executive* in stile NOC. Traduzioni dinamiche (Inglese/Italiano) attivabili in tempo reale. -### ✨ Funzionalità Principali +### ✨ Funzionalità Principali v6.0.0 -#### 🛡️ Diagnostica Proattiva (Watchdog) & Avvisi Globali -* **Monitoraggio Hardware:** Analisi continua delle temperature CPU e della saturazione disco da remoto. Innesca automaticamente notifiche Push prima che si verifichino guasti critici. -* **Rilevamento Anomalie RF:** Monitoraggio in tempo reale del BER (Bit Error Rate) sul traffico RF locale. Rileva il degrado hardware in radiofrequenza avvisando istantaneamente gli amministratori. -* **Propagazione Service Alerts (v5.3+):** Il crash di un demone remoto (es. `SVC KO: MMDVMHOST`) viene segnalato in tempo reale sulla griglia principale e sulla Mappa di Flotta, senza dover ispezionare il singolo nodo. +#### 🗓️ Calendario Pianificazione Profili [NUOVO] +* Schedula i cambi di profilo automatici (es. Net Regionali, Contest, Esercitazioni) su nodi multipli. +* Esecuzione in background: il sistema innesca il `Profilo Target` all'orario di inizio e ripristina automaticamente il `Profilo di Ritorno` alla scadenza della finestra temporale. -#### ⚡ Dashboard Real-Time a Latenza Zero -* **Motore WebSocket:** La dashboard scatta all'istante al passaggio di traffico radio o ai cambi di telemetria. Nessun polling HTTP pesante, nessun refresh della pagina. -* **Stato MQTT Live:** Un badge in tempo reale monitora continuamente la connessione al broker MQTT. -* **PWA Ready:** Installabile su smartphone Android e iOS come Progressive Web App per un'esperienza nativa a schermo intero con cache offline intelligente. +#### 🗺️ Mappa Tattica APRS [NUOVO] +* Mappa GIS in tempo reale che mostra sia i ripetitori fissi che i **passanti APRS in mobilità**. +* Intercetta e formatta istantaneamente i payload APRS dai log dei gateway. +* Include un sistema di pulizia automatica (Garbage Collector) che rimuove i pin mobili dopo 2 ore di inattività. -#### 🔔 Notifiche Web Push -* Ricevi avvisi nativi e immediati su PC o smartphone quando: - * Un nodo va offline o torna operativo. - * Un demone di sistema remoto si blocca (fallimento auto-healing). - * Il Watchdog rileva allarmi termici, disco pieno o anomalie BER. -* Funzionano in modo sicuro anche quando la web app è chiusa o in background. +#### 🛠️ Editor Avanzato & Visual Diff [NUOVO] +* **Editor Config .INI "Macchina del Tempo":** Modifica i file operativi direttamente dal pannello web, con possibilità di ripristinare i backup storici salvati automaticamente nel database. +* **Visual Diff Semantico:** Controlla visivamente le differenze (in verde le aggiunte, in rosso le rimozioni) tra le tue modifiche in bozza e la configurazione attualmente in esecuzione prima di salvare. +* **Interventi Hardware & Servizi:** Avvia/arresta demoni, forza il riavvio del SO o esegui un reset hardware GPIO sulla scheda MMDVM. -#### 🛠️ Controllo Remoto & Manutenzione Avanzata -* **Aggiornamenti Server OTA:** Applica gli aggiornamenti del server tramite Git direttamente dalla dashboard (Over-The-Air) con un clic. Controllo aggiornamenti sincrono e possibilità di bypass della cache di sicurezza. -* **Editor .INI Remoto:** Modifica i file di configurazione (es. MMDVMHost.ini) direttamente dal pannello web. -* **Gestione Demoni:** Avvia, arresta o riavvia i servizi di sistema remoti. -* **Override Globali Scoped:** Cambia i profili operativi simultaneamente su più nodi, filtrati dinamicamente in base ai nodi assegnati all'operatore in uso. -* **Interventi Hardware:** Innesca un riavvio del sistema operativo o un reset fisico (tramite pin GPIO) della scheda MMDVM. - -#### 📊 Monitoraggio & Statistiche -* **Mappa Interattiva di Flotta:** Mappa GIS in tempo reale che mostra la posizione dei ripetitori, stato online/offline, trasmissione attiva (pin lampeggianti) e allarmi diagnostici di servizio in corso. -* **Log Ascolti Live:** Vista unificata in tempo reale del traffico radio di tutta la rete, con traduzione automatica degli ID DMR e NXDN in nominativi. -* **Tracciamento Versioni:** Controlla all'istante le versioni firmware MMDVM e software a bordo di ciascun nodo. -* **Analisi Giornaliera:** Statistiche automatiche su Top Talkgroups, Top Callsign, durata media e numero totale di transiti. +#### 📈 Analitiche Dinamiche & Console Live [NUOVO] +* **Grafici Temporali:** Analizza l'andamento di CPU/Temp e Transiti/BER esplorando finestre temporali dinamiche da 12 Ore fino a 7 Giorni, con rendering fluido via Chart.js. +* **Console WebSocket:** Terminale a latenza zero per analizzare i log dei demoni. +* **Tracciamento Operatori:** Visualizza in tempo reale quali amministratori sono connessi e operativi sulla dashboard. +* **Watchdog Proattivo:** Analisi continua di surriscaldamenti e degrado RF, con avvisi inviati via notifiche Web Push. #### 🔐 Sicurezza e Controllo Accessi -* **Strict Role-Based Access Control (RBAC):** Architettura Zero-Trust reale. La gestione del sistema (System Admin) è nettamente separata dalla gestione dei nodi. -* **Permessi Granulari Ferrei:** Anche un utente `admin` può interagire o configurare *esclusivamente* i nodi che gli sono stati esplicitamente assegnati nella lista `allowed_nodes`, con barriera di sicurezza verificata lato backend ad ogni chiamata API. -* **Audit Trail:** Ogni azione critica (riavvii, modifiche file, gestione demoni) viene registrata con data, ora, utente e nodo di destinazione. +* **Role-Based Access Control (RBAC):** Gestione nodi limitata esclusivamente ai ripetitori assegnati (`allowed_nodes`) per Operatori e `node_admin`. +* **Audit Trail di Sicurezza:** Ogni comando operativo e configurazione viene tracciato con timestamp, utente e obiettivo. ### ⚠️ Sicurezza Richiesta: HTTPS -Si prega di notare che le **Notifiche Web Push** e il **Service Worker** richiedono una connessione sicura per funzionare. Per motivi di sicurezza, i browser moderni abilitano queste funzionalità solo su **HTTPS**. Se accedi alla console via HTTP (al di fuori di `localhost`), il tasto "Push" e la registrazione delle notifiche non saranno attivi. Si consiglia l'uso di un reverse proxy (come Nginx, Caddy o Traefik) con certificato SSL. - -### ⚠️ Configurazione Reverse Proxy & WebSocket -Se esponi la Fleet Console tramite un reverse proxy come **Apache** su IP pubblico (HTTPS), il proxy HTTP standard farà cadere continuamente la connessione in tempo reale di Socket.IO. -Devi abilitare il tunnel WebSocket in Apache: -```bash -sudo a2enmod proxy_wstunnel rewrite headers -``` -E inserire le regole di **Rewrite** *prima* del `ProxyPass` all'interno del tuo blocco ``: -```apache -RewriteEngine On -RewriteCond %{HTTP:Upgrade} =websocket [NC] -RewriteRule /(.*) ws://127.0.0.1:9000/$1 [P,L] -RewriteCond %{HTTP:Upgrade} !=websocket [NC] -RewriteRule /(.*) http://127.0.0.1:9000/$1 [P,L] - -ProxyPass /socket.io/ ws://127.0.0.1:9000/socket.io/ -ProxyPassReverse /socket.io/ ws://127.0.0.1:9000/socket.io/ - -ProxyPass / http://127.0.0.1:9000/ -ProxyPassReverse / http://127.0.0.1:9000/ -``` - -### 🚀 Guida all'Installazione - -#### 0. Privilegi di Root -Tutti i passaggi di installazione devono essere eseguiti come utente `root`. -```bash -apt update -apt install build-essential python3-dev libssl-dev libffi-dev python3-pip python3-venv -``` -#### 1. Clonazione dei Repository -Clona il repository nella cartella /opt per assicurarti che tutti i percorsi dei servizi systemd siano corretti: -```bash -git clone https://git.arifvg.it/iv3jdv/fleet-control-server.git /opt/fleet-control-server -cd /opt/fleet-control-server -``` -#### 2. Setup Ambiente Virtuale (Consigliato) -Per evitare conflitti con i pacchetti di sistema (regola PEP 668), crea una "bolla" isolata: -```bash -cd /opt/fleet-control-server -python3 -m venv venv -source venv/bin/activate -pip install --upgrade pip setuptools wheel -pip install -r requirements.txt -``` - -#### 3. Configurazione Base -1. Copia `config.example.json` in `config.json`. -2. Inserisci le credenziali del broker MQTT. -3. Definisci i ripetitori nel file `clients.json`. -4. Genera le chiavi VAPID su [vapidkeys.com](https://vapidkeys.com/) e inseriscile in `config.json` per attivare le notifiche Push. *(Attenzione: le notifiche Push richiedono obbligatoriamente un certificato HTTPS).* -5. Configura le dimensioni della rotazione dei log (`log_max_mb` e `log_backup_count`) direttamente nel `config.json` per gestire lo spazio su disco. - -#### 4. Esecuzione come Servizio (systemd) -Per eseguire il server in produzione in modo continuo e stabile con Gunicorn: -```bash -cp fleet-console.service /etc/systemd/system/ -systemctl daemon-reload -systemctl enable fleet-console -systemctl start fleet-console -``` -*(Assicurati che il file `.service` punti all'eseguibile `gunicorn` situato all'interno della cartella `venv`).* - ---- -*Created by IV3JDV @ ARIFVG - 2026* +Le **Notifiche Web Push** e il **Service Worker** richiedono obbligatoriamente una connessione HTTPS per funzionare. Si consiglia l'uso di un reverse proxy (come Apache o Nginx) con certificato SSL Let's Encrypt. diff --git a/app.py b/app.py index a71b53e..54dbdbd 100644 --- a/app.py +++ b/app.py @@ -64,9 +64,30 @@ SERVER_COMMIT = get_git_commit() def index(): return render_template('index.html', git_commit=SERVER_COMMIT) +from flask import session + @state.socketio.on('connect') def handle_connect(): + state.connected_web_clients.add(request.sid) + + # Se l'utente è loggato (session), associamo il suo username al SID + user = session.get('user') + if user: + state.active_logged_users[request.sid] = user + emit('mqtt_status', {'connected': mqtt_svc.mqtt_connected_status}) + + # Prepariamo la lista unica degli utenti loggati attivi (togliendo i duplicati se un utente ha più tab aperti) + logged_names = list(set(state.active_logged_users.values())) + state.socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names}) + +@state.socketio.on('disconnect') +def handle_disconnect(): + state.connected_web_clients.discard(request.sid) + state.active_logged_users.pop(request.sid, None) + + logged_names = list(set(state.active_logged_users.values())) + state.socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names}) # --- INIZIALIZZAZIONE SISTEMA & THREAD --- init_db() diff --git a/core/database.py b/core/database.py index 7130f69..72a7387 100644 --- a/core/database.py +++ b/core/database.py @@ -50,6 +50,24 @@ def init_db(): c.execute('''CREATE TABLE IF NOT EXISTS audit_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, username TEXT, client_id TEXT, command TEXT)''') + + c.execute('''CREATE TABLE IF NOT EXISTS config_backups + (id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, client_id TEXT, + service TEXT, config_text TEXT, username TEXT)''') + + c.execute('''CREATE TABLE IF NOT EXISTS telemetry_logs + (id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, client_id TEXT, + cpu REAL, temp REAL, ram REAL, disk REAL)''') + + c.execute("CREATE INDEX IF NOT EXISTS idx_telemetry_logs_client_ts ON telemetry_logs(client_id, timestamp)") + + c.execute('''CREATE TABLE IF NOT EXISTS profile_schedules + (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, target_nodes TEXT, + target_profile TEXT, restore_profile TEXT, start_time DATETIME, + end_time DATETIME, status TEXT DEFAULT 'SCHEDULED', created_by TEXT, + created_at DATETIME DEFAULT (datetime('now', 'localtime')))''') + + c.execute("CREATE INDEX IF NOT EXISTS idx_sched_status_time ON profile_schedules(status, start_time, end_time)") c.execute("CREATE INDEX IF NOT EXISTS idx_radio_logs_ts ON radio_logs(timestamp)") c.execute("CREATE INDEX IF NOT EXISTS idx_radio_logs_client_ts ON radio_logs(client_id, timestamp)") @@ -120,3 +138,12 @@ def prune_old_data(): logger.info(f"🧹 Pulizia DB: {n1} ascolti e {n2} audit rimossi.") except Exception as e: logger.error(f"❌ Errore pulizia DB: {e}") + +def save_telemetry_to_sqlite(client_id, health_data): + try: + with closing(db_connect()) as conn: + conn.execute("INSERT INTO telemetry_logs (timestamp, client_id, cpu, temp, ram, disk) VALUES (datetime('now', 'localtime'), ?, ?, ?, ?, ?)", + (client_id, health_data.get('cpu', 0), health_data.get('temp', 0), health_data.get('ram', 0), health_data.get('disk', 0))) + conn.commit() + except Exception as e: + logger.error(f"Errore salvataggio telemetria: {e}") diff --git a/core/state.py b/core/state.py index 26c1e6e..6e084ad 100644 --- a/core/state.py +++ b/core/state.py @@ -48,6 +48,9 @@ gateway_states = {} active_warnings = {} active_calls = {} operating_modes = {} +node_logs = {} # In-memory circular buffer for live logs +connected_web_clients = set() +active_logged_users = {} # Caricamento iniziale cache telemetria if os.path.exists(CACHE_FILE): diff --git a/install.txt b/install.txt index 0a70297..efa6e36 100644 --- a/install.txt +++ b/install.txt @@ -1,5 +1,5 @@ ============================================================ - INSTALLATION GUIDE - FLEET CONTROL CONSOLE (SERVER) + INSTALLATION GUIDE - FLEET CONTROL CONSOLE (v6.0.0) ============================================================ ------------------------------------------------------------ @@ -74,7 +74,7 @@ Configuration: 4. Start service: systemctl start fleet-console ============================================================ - GUIDA ALL'INSTALLAZIONE - SERVER (ITALIANO) + GUIDA ALL'INSTALLAZIONE - SERVER v6.0.0 (ITALIANO) ============================================================ ------------------------------------------------------------ diff --git a/routes/api_routes.py b/routes/api_routes.py index b92b77a..445f765 100644 --- a/routes/api_routes.py +++ b/routes/api_routes.py @@ -109,7 +109,9 @@ def get_states(): "versions": clean_versions, "gateway_states": enriched_gateway_states, "warnings": state.active_warnings, - "modes": getattr(state, "operating_modes", {}) + "modes": getattr(state, "operating_modes", {}), + "web_users": len(getattr(state, "connected_web_clients", [])), + "logged_users": list(set(getattr(state, "active_logged_users", {}).values())) }) @api_bp.route('/api/stats') @@ -132,7 +134,8 @@ def get_stats(): top_tgs = [{"target": row[0], "count": row[1]} for row in c.fetchall()] c.execute(f"""SELECT source_id, COUNT(*) as cnt FROM radio_logs - WHERE source_id NOT LIKE '倹%' + WHERE source_id NOT LIKE '🌐%' + AND source_id NOT LIKE '%' AND timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter} GROUP BY source_id ORDER BY cnt DESC LIMIT 5""", params) top_calls = [{"call": row[0], "count": row[1]} for row in c.fetchall()] @@ -185,7 +188,8 @@ def cmd(): if not mqtt_publish(f"servizi/{cid}/cmnd", cmd_type): return err("Broker MQTT non raggiungibile - comando non inviato", 503) - audit(auth['username'], cid, cmd_type) + audit_label = f"SWITCH_PROFILE_{cmd_type.upper()}" if cmd_type in known_profile_keys(cid) else cmd_type + audit(auth['username'], cid, audit_label) state.client_telemetry[cid] = {"ts1": "[>] Inviato...", "ts2": "[>] Inviato...", "alt": ""} return jsonify({"success": True}) @@ -221,7 +225,7 @@ def global_cmd(): @api_bp.route('/api/service_control', methods=['POST']) def service_control(): auth = get_auth() - if not auth or auth['role'] != 'admin': + if not auth or (auth['role'] != 'admin' and auth['role'] != 'node_admin'): return err("Non autorizzato", 403) d = json_body() @@ -323,7 +327,7 @@ def save_config_api(): @api_bp.route('/api/config_file//', methods=['GET']) def get_config_file(cid, service): auth = get_auth() - if not auth or auth['role'] != 'admin': + if not auth or (auth['role'] != 'admin' and auth['role'] != 'node_admin'): return err("Non autorizzato", 403) cid = cid.lower() if not node_allowed(auth['role'], auth['allowed_nodes'], cid): @@ -339,7 +343,7 @@ def get_config_file(cid, service): @api_bp.route('/api/config_file', methods=['POST']) def save_config_file(): auth = get_auth() - if not auth or auth['role'] != 'admin': + if not auth or (auth['role'] != 'admin' and auth['role'] != 'node_admin'): return err("Non autorizzato", 403) d = json_body() @@ -359,6 +363,15 @@ def save_config_file(): if not mqtt_publish(f"devices/{cid}/config_set/{service}", json.dumps(new_config)): return err("Broker MQTT non raggiungibile", 503) audit(auth['username'], cid, f"EDIT_CONFIG_{service.upper()}") + + # Salva Backup + try: + with closing(db_connect()) as conn: + conn.execute("INSERT INTO config_backups (timestamp, client_id, service, config_text, username) VALUES (datetime('now', 'localtime'), ?, ?, ?, ?)", + (cid, service, new_config['raw_text'], auth['username'])) + conn.commit() + except Exception as e: + logger.error(f"Errore salvataggio backup config: {e}") if cid not in state.device_configs: state.device_configs[cid] = {} @@ -380,11 +393,14 @@ def get_server_update_status(): # Eseguiamo il controllo sincrono se è passata 1 ora OPPURE se forzato dal client if force_check or (time.time() - LAST_GITEA_CHECK_TIME > 3600): try: - subprocess.run(['git', 'fetch'], timeout=10, cwd=BASE_DIR) - local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip() - remote_hash = subprocess.check_output(['git', 'rev-parse', '@{u}'], cwd=BASE_DIR).decode('utf-8').strip() + # Timeout molto basso per evitare di killare il worker Gunicorn + subprocess.run(['git', 'fetch'], timeout=2, cwd=BASE_DIR) + local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR, timeout=1).decode('utf-8').strip() + remote_hash = subprocess.check_output(['git', 'rev-parse', '@{u}'], cwd=BASE_DIR, timeout=1).decode('utf-8').strip() GLOBAL_SERVER_UPDATE_AVAILABLE = (local_hash != remote_hash) LAST_GITEA_CHECK_TIME = time.time() + except subprocess.TimeoutExpired: + logger.warning("Gitea check andato in timeout, ignorato per non bloccare Gunicorn.") except Exception as e: logger.error(f"Errore controllo Gitea: {e}") @@ -449,3 +465,264 @@ def serve_sw(): @api_bp.route('/icon-512.png') def serve_icon(): return send_from_directory(BASE_DIR, 'icon-512.png') + + +@api_bp.route('/api/logs/', methods=['GET']) +def get_node_logs(cid): + auth = get_auth() + if not auth: + return err("Non autorizzato", 401) + + cid = cid.strip().lower() + if not node_allowed(auth['role'], auth['allowed_nodes'], cid): + return err("Permesso negato per questo nodo", 403) + + logs = list(state.node_logs.get(cid, [])) + return jsonify({"success": True, "logs": logs}) + +@api_bp.route('/api/config_backups//', methods=['GET']) +def get_config_backups(cid, service): + auth = get_auth() + if not auth or auth['role'] != 'admin': + return err("Non autorizzato", 403) + + cid = cid.strip().lower() + if not node_allowed(auth['role'], auth['allowed_nodes'], cid): + return err("Permesso negato per questo nodo", 403) + + try: + with closing(db_connect()) as conn: + c = conn.cursor() + c.execute("SELECT id, timestamp, username FROM config_backups WHERE client_id = ? AND service = ? ORDER BY id DESC LIMIT 20", (cid, service)) + rows = [{"id": r[0], "timestamp": r[1], "username": r[2]} for r in c.fetchall()] + return jsonify({"success": True, "backups": rows}) + except Exception as e: + return err(str(e)) + +@api_bp.route('/api/config_backups/', methods=['GET']) +def get_config_backup_content(backup_id): + auth = get_auth() + if not auth or auth['role'] != 'admin': + return err("Non autorizzato", 403) + + try: + with closing(db_connect()) as conn: + c = conn.cursor() + c.execute("SELECT client_id, config_text FROM config_backups WHERE id = ?", (backup_id,)) + row = c.fetchone() + if not row: + return err("Backup non trovato", 404) + if not node_allowed(auth['role'], auth['allowed_nodes'], row[0]): + return err("Permesso negato", 403) + return jsonify({"success": True, "text": row[1]}) + except Exception as e: + return err(str(e)) + +import zipfile +import io +from flask import send_file + +@api_bp.route('/api/fleet_backup', methods=['GET']) +def get_fleet_backup(): + auth = get_auth() + if not auth or auth['role'] != 'admin': + return err("Non autorizzato", 403) + + memory_file = io.BytesIO() + with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf: + for cid, configs in state.device_configs.items(): + for service, conf in configs.items(): + if isinstance(conf, dict) and 'raw_text' in conf: + zf.writestr(f"{cid}/{service.upper()}.ini", conf['raw_text']) + memory_file.seek(0) + audit(auth['username'], '-', "DOWNLOAD_FLEET_BACKUP") + return send_file(memory_file, download_name=f"fleet_configs_{time.strftime('%Y%m%d')}.zip", as_attachment=True) + +@api_bp.route('/api/analytics/', methods=['GET']) +def get_analytics(cid): + auth = get_auth() + if not auth: + return err("Non autorizzato", 401) + + cid = cid.strip().lower() + if not node_allowed(auth['role'], auth['allowed_nodes'], cid): + return err("Permesso negato per questo nodo", 403) + + try: + hours = int(request.args.get('hours', 24)) + except ValueError: + hours = 24 + + try: + with closing(db_connect()) as conn: + c = conn.cursor() + + # Telemetria: aggreghiamo per ora + c.execute(f"""SELECT strftime('%Y-%m-%d %H:00:00', timestamp) as hr, + AVG(cpu), MAX(temp), AVG(ram) + FROM telemetry_logs + WHERE client_id = ? AND timestamp >= datetime('now', 'localtime', ?) + GROUP BY hr ORDER BY hr""", (cid, f"-{hours} hours")) + telemetry_data = [{"time": r[0], "cpu": round(r[1], 1) if r[1] else 0, "temp": round(r[2], 1) if r[2] else 0, "ram": round(r[3], 1) if r[3] else 0} for r in c.fetchall()] + + # RF BER & Transiti (ignoriamo rete e beacon, prendiamo solo traffico vero locale) + c.execute(f"""SELECT strftime('%Y-%m-%d %H:00:00', timestamp) as hr, + COUNT(*), AVG(ber), AVG(rssi) + FROM radio_logs + WHERE LOWER(client_id) = ? AND timestamp >= datetime('now', 'localtime', ?) + AND source_id NOT LIKE '🌐%' + AND source_id NOT LIKE '%' + AND (LOWER(source_conn) = 'rf' OR source_conn = '') + GROUP BY hr ORDER BY hr""", (cid, f"-{hours} hours")) + rf_data = [{"time": r[0], "count": r[1], "ber": round(r[2], 2) if r[2] else 0, "rssi": round(r[3], 1) if r[3] else 0} for r in c.fetchall()] + + return jsonify({"success": True, "telemetry": telemetry_data, "rf": rf_data}) + except Exception as e: + logger.error(f"Analytics query error: {e}") + return err(str(e)) + +@api_bp.route('/api/audit_logs', methods=['GET']) +def get_audit_logs(): + auth = get_auth() + if not auth or auth['role'] != 'admin': + return err("Non autorizzato", 403) + + try: + with closing(db_connect()) as conn: + c = conn.cursor() + c.execute("SELECT timestamp, username, client_id, command FROM audit_logs ORDER BY id DESC LIMIT 50") + rows = [{"time": r[0], "user": r[1], "node": r[2], "cmd": r[3]} for r in c.fetchall()] + return jsonify({"success": True, "logs": rows}) + except Exception as e: + return err(str(e)) + +@api_bp.route('/api/aprs', methods=['GET']) +def get_aprs(): + auth = get_auth() + if not auth: + return err("Non autorizzato", 401) + msgs = list(getattr(state, 'aprs_msgs', [])) + # msgs è una lista di dizionari dal più vecchio al più nuovo, la restituiamo direttamente + return jsonify(msgs) + +# --- SCHEDULAZIONE PROFILI (CALENDAR SCHEDULER) --- + +@api_bp.route('/api/schedules', methods=['GET']) +def get_schedules(): + auth = get_auth() + if not auth or auth['role'] not in ('admin', 'node_admin'): + return err("Non autorizzato", 403) + + try: + with closing(db_connect(row=True)) as conn: + c = conn.cursor() + c.execute("""SELECT id, title, target_nodes, target_profile, restore_profile, + start_time, end_time, status, created_by, created_at + FROM profile_schedules + ORDER BY id DESC LIMIT 50""") + rows = [dict(r) for r in c.fetchall()] + + # Filtro per node_admin se non ha 'all' + if auth['role'] == 'node_admin' and 'all' not in auth['allowed_nodes'].split(','): + allowed_set = set(x.strip().lower() for x in auth['allowed_nodes'].split(',')) + filtered = [] + for r in rows: + t_nodes = set(x.strip().lower() for x in r['target_nodes'].split(',')) + if t_nodes.issubset(allowed_set): + filtered.append(r) + rows = filtered + + return jsonify({"success": True, "schedules": rows}) + except Exception as e: + logger.error(f"Errore caricamento schedulazioni: {e}") + return err(str(e)) + +@api_bp.route('/api/schedules', methods=['POST']) +def add_schedule(): + auth = get_auth() + if not auth or auth['role'] not in ('admin', 'node_admin'): + return err("Non autorizzato", 403) + + d = json_body() + title = str(d.get('title', '')).strip() + target_nodes = str(d.get('target_nodes', '')).strip().lower() + target_profile = str(d.get('target_profile', '')).strip().upper() + restore_profile = str(d.get('restore_profile', 'NONE')).strip().upper() + start_time = str(d.get('start_time', '')).strip() + end_time = str(d.get('end_time', '')).strip() + + if not title: + return err("Titolo evento obbligatorio") + if not target_nodes: + return err("Nodi target obbligatori") + if not target_profile: + return err("Profilo target obbligatorio") + if not start_time or not end_time: + return err("Date di inizio e fine obbligatorie") + + # Verifica permessi per node_admin + if auth['role'] == 'node_admin': + allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(',')) + if 'all' not in allowed: + if target_nodes == 'all': + return err("Come Node Admin non puoi schedulare su tutta la flotta", 403) + req_nodes = set(x.strip().lower() for x in target_nodes.split(',')) + if not req_nodes.issubset(allowed): + return err("Non hai i permessi per tutti i nodi selezionati", 403) + + # Normalizza formati orari (accetta 'YYYY-MM-DDTHH:MM' o 'YYYY-MM-DD HH:MM') + st_norm = start_time.replace('T', ' ') + if len(st_norm) == 16: st_norm += ':00' + end_norm = end_time.replace('T', ' ') + if len(end_norm) == 16: end_norm += ':00' + + if st_norm >= end_norm: + return err("L'orario di fine deve essere successivo a quello di inizio") + + try: + with closing(db_connect()) as conn: + conn.execute("""INSERT INTO profile_schedules + (title, target_nodes, target_profile, restore_profile, start_time, end_time, status, created_by) + VALUES (?, ?, ?, ?, ?, ?, 'SCHEDULED', ?)""", + (title, target_nodes, target_profile, restore_profile, st_norm, end_norm, auth['username'])) + conn.commit() + audit(auth['username'], target_nodes, f"CREATE_SCHED_{title}_{target_profile}") + return jsonify({"success": True}) + except Exception as e: + logger.error(f"Errore salvataggio schedulazione: {e}") + return err(str(e)) + +@api_bp.route('/api/schedules/', methods=['DELETE']) +def cancel_schedule(sid): + auth = get_auth() + if not auth or auth['role'] not in ('admin', 'node_admin'): + return err("Non autorizzato", 403) + + try: + with closing(db_connect(row=True)) as conn: + c = conn.cursor() + c.execute("SELECT id, title, target_nodes, status, restore_profile FROM profile_schedules WHERE id = ?", (sid,)) + row = c.fetchone() + if not row: + return err("Schedulazione non trovata", 404) + + # Controllo permessi node_admin + if auth['role'] == 'node_admin' and 'all' not in auth['allowed_nodes'].split(','): + allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(',')) + t_nodes = set(x.strip().lower() for x in row['target_nodes'].split(',')) + if not t_nodes.issubset(allowed): + return err("Non autorizzato per questa schedulazione", 403) + + # Se era attiva, ripristina subito il profilo + if row['status'] == 'ACTIVE' and row['restore_profile'] and row['restore_profile'] != 'NONE': + from services.scheduler_service import apply_scheduled_profile + apply_scheduled_profile(row['target_nodes'], row['restore_profile'], "CANCEL_RESTORE") + + conn.execute("UPDATE profile_schedules SET status = 'CANCELLED' WHERE id = ?", (sid,)) + conn.commit() + + audit(auth['username'], row['target_nodes'], f"CANCEL_SCHED_{sid}_{row['title']}") + return jsonify({"success": True}) + except Exception as e: + logger.error(f"Errore annullamento schedulazione: {e}") + return err(str(e)) diff --git a/routes/auth_routes.py b/routes/auth_routes.py index 6b83374..91b481c 100644 --- a/routes/auth_routes.py +++ b/routes/auth_routes.py @@ -12,7 +12,7 @@ from core.database import db_connect, audit auth_bp = Blueprint('auth', __name__) # --- COSTANTI & REGEX VALIDAZIONE --- -VALID_ROLES = ('admin', 'operator') +VALID_ROLES = ('admin', 'node_admin', 'operator') USERNAME_RE = re.compile(r'^[A-Za-z0-9_.@\-]{3,32}$') MIN_PASSWORD_LEN = 8 diff --git a/services/mqtt_service.py b/services/mqtt_service.py index fe28cb8..3a2fd71 100644 --- a/services/mqtt_service.py +++ b/services/mqtt_service.py @@ -1,8 +1,9 @@ import json import re +import time from paho.mqtt import client as mqtt_client from core.config import config, logger -from core.database import save_to_sqlite +from core.database import save_to_sqlite, save_telemetry_to_sqlite import core.state as state from services.push_service import broadcast_push_notification @@ -24,6 +25,9 @@ def on_connect(client, userdata, flags, reason_code, properties=None): topics_list = config.get('mqtt', {}).get('topics', default_topics) subscribe_list = [(topic, 0) for topic in topics_list] subscribe_list.append(("+/+/log", 0)) + subscribe_list.append(("/+/+/log", 0)) + subscribe_list.append(("+/+/Log", 0)) + subscribe_list.append(("/+/+/Log", 0)) client.subscribe(subscribe_list) logger.info(f"Sottoscritto a {len(subscribe_list)} topic MQTT.") @@ -40,7 +44,7 @@ def on_disconnect(client, userdata, disconnect_flags, reason_code, properties=No def on_message(client, userdata, msg): try: - topic = msg.topic + topic = msg.topic.strip('/') payload = msg.payload.decode('utf-8', errors='replace').strip() parts = topic.split('/') if len(parts) < 2: @@ -50,8 +54,26 @@ def on_message(client, userdata, msg): p0 = parts[0].lower().replace('-', '') p2 = parts[2].lower().replace('-', '') if len(parts) > 2 else "" - # --- 1. LOG SOFTWARE & FIRMWARE --- + # --- 1. LOG SOFTWARE, FIRMWARE & LIVE STREAM --- if len(parts) >= 3 and parts[2].lower() == 'log': + svc_name = p0 + + # A) Salva in memoria per il Live Log + if cid not in state.node_logs: + from collections import deque + state.node_logs[cid] = deque(maxlen=100) + + log_entry = { + "time": time.strftime("%H:%M:%S"), + "service": svc_name, + "text": payload + } + state.node_logs[cid].append(log_entry) + + # Inoltra in tempo reale via WebSocket + state.socketio.emit(f"live_log_{cid}", log_entry) + + # B) Parsa le versioni if cid not in state.node_versions: state.node_versions[cid] = {} @@ -84,6 +106,38 @@ def on_message(client, userdata, msg): if "GitID" not in state.node_versions[cid][last_prog]: state.node_versions[cid][last_prog] += f" (GitID #{git_id})" state.notify_update() + + # C) Estrazione APRS/DPRS raw dai log dei Gateway + if ('DPRS' in payload or 'APRS' in payload) and '>' in payload and ':' in payload: + # Es: I: 2026-11-08 12:30:58.615 DPRS IV3JDV /ID51 IV3JDV-9 IV3JDV-9>API51,DSTAR*:/115922h4503.75N/00731.49E[034/002/ + m_aprs = re.search(r'([A-Z0-9\-]{3,9})>([^:]+):(.+)', payload) + if m_aprs: + src_part = m_aprs.group(1).strip() + header_part = m_aprs.group(2).strip() + pld_part = m_aprs.group(3).strip() + + header_tokens = header_part.split(",") + dest_part = header_tokens[0] + path_str = ",".join(header_tokens[1:]) if len(header_tokens) > 1 else "" + + aprs_data = { + "source": src_part, + "dest": dest_part, + "path": path_str, + "payload": pld_part, + "time": time.strftime("%H:%M:%S") + } + + if not hasattr(state, 'aprs_msgs'): + from collections import deque + state.aprs_msgs = deque(maxlen=100) + + state.aprs_msgs.append(aprs_data) + logger.info(f"📍 APRS (da log {svc_name}): {src_part} -> {dest_part}") + state.socketio.emit('aprs_msg', aprs_data) + + # NOTA: Rimosso il return incondizionato qui, perché il log deve completare la sua corsa + # e non bloccare eventuali altre logiche! return # Aggiornamento timestamp last_seen @@ -160,6 +214,16 @@ def on_message(client, userdata, msg): health_changed = state.device_health.get(cid) != new_health state.device_health[cid] = new_health + + # Salvataggio storico nel DB (campionamento max 1 volta ogni 15 minuti) + now_ts = time.time() + last_save = getattr(state, 'last_telemetry_save', {}).get(cid, 0) + if now_ts - last_save >= 900: # 15 minuti (900 secondi) + save_telemetry_to_sqlite(cid, new_health) + if not hasattr(state, 'last_telemetry_save'): + state.last_telemetry_save = {} + state.last_telemetry_save[cid] = now_ts + if health_changed: state.notify_update() @@ -331,6 +395,10 @@ def on_message(client, userdata, msg): logger.warning(f"Formato APRS non decodificato: {payload}") logger.info(f"📍 Inoltro pacchetto APRS al frontend: {data['source']} -> {data['dest']} via [{data['path']}]") + if not hasattr(state, 'aprs_msgs'): + from collections import deque + state.aprs_msgs = deque(maxlen=100) + state.aprs_msgs.append(data) state.socketio.emit('aprs_msg', data) except Exception as e: logger.error(f"Errore parsing APRS: {e}") diff --git a/services/scheduler_service.py b/services/scheduler_service.py index ee339b6..2ab5889 100644 --- a/services/scheduler_service.py +++ b/services/scheduler_service.py @@ -45,6 +45,89 @@ def auto_update_ids(): download_logic() prune_old_data() time.sleep(65) + + # Controllo schedulazioni profili + check_profile_schedules() except Exception as e: - logger.error(f"⚠️ Errore nel thread update: {e}") - time.sleep(30) + logger.error(f"⚠️ Errore nel thread scheduler: {e}") + time.sleep(15) + +from contextlib import closing +from core.database import db_connect, audit + +def apply_scheduled_profile(target_nodes, profile, action_type="SWITCH"): + from services.mqtt_service import mqtt_publish + from core.config import CLIENTS_PATH + import json + import re + + CID_RE = re.compile(r'^[a-z0-9][a-z0-9_\-]{0,63}$') + nodes = [] + if target_nodes.strip().lower() == 'all': + if os.path.exists(CLIENTS_PATH): + try: + with open(CLIENTS_PATH, 'r') as f: + clist = json.load(f) + nodes = [str(c.get('id', '')).lower() for c in clist if CID_RE.match(str(c.get('id', '')).lower())] + except Exception as e: + logger.error(f"Errore lettura clients per schedule: {e}") + else: + nodes = [x.strip().lower() for x in target_nodes.split(',') if CID_RE.match(x.strip().lower())] + + logger.info(f"📅 Scheduler applica profilo [{profile}] su {len(nodes)} nodi ({target_nodes})") + for cid in nodes: + mqtt_publish(f"servizi/{cid}/cmnd", profile) + if cid in state.client_telemetry and isinstance(state.client_telemetry[cid], dict): + state.client_telemetry[cid]["alt"] = f"📅 SCHED: {profile}" + state.notify_update() + +def check_profile_schedules(): + try: + now_str = time.strftime('%Y-%m-%d %H:%M:%S') + with closing(db_connect(row=True)) as conn: + c = conn.cursor() + c.execute("""SELECT id, title, target_nodes, target_profile, restore_profile, + start_time, end_time, status, created_by + FROM profile_schedules + WHERE status IN ('SCHEDULED', 'ACTIVE')""") + rows = c.fetchall() + + for row in rows: + sid = row['id'] + title = row['title'] + nodes = row['target_nodes'] + target_prof = row['target_profile'] + restore_prof = row['restore_profile'] + st_time = row['start_time'] + end_time = row['end_time'] + status = row['status'] + + # Formattiamo le date nel caso abbiano una 'T' (input HTML5 datetime-local) + st_norm = st_time.replace('T', ' ') + if len(st_norm) == 16: st_norm += ':00' + end_norm = end_time.replace('T', ' ') + if len(end_norm) == 16: end_norm += ':00' + + if status == 'SCHEDULED': + if st_norm <= now_str < end_norm: + logger.info(f"▶️ Avvio schedulazione ID {sid} - '{title}' -> Profilo {target_prof}") + apply_scheduled_profile(nodes, target_prof, "START") + conn.execute("UPDATE profile_schedules SET status = 'ACTIVE' WHERE id = ?", (sid,)) + conn.commit() + audit("SCHEDULER", nodes, f"START_SCHED_{sid}_{target_prof}") + elif now_str >= end_norm: + # Scaduta prima di iniziare + logger.warning(f"⌛ Schedulazione ID {sid} - '{title}' scaduta senza esecuzione.") + conn.execute("UPDATE profile_schedules SET status = 'EXPIRED' WHERE id = ?", (sid,)) + conn.commit() + + elif status == 'ACTIVE': + if now_str >= end_norm: + logger.info(f"⏹️ Fine schedulazione ID {sid} - '{title}' -> Ripristino {restore_prof}") + if restore_prof and restore_prof.upper() != 'NONE': + apply_scheduled_profile(nodes, restore_prof, "RESTORE") + conn.execute("UPDATE profile_schedules SET status = 'COMPLETED' WHERE id = ?", (sid,)) + conn.commit() + audit("SCHEDULER", nodes, f"RESTORE_SCHED_{sid}_{restore_prof}") + except Exception as e: + logger.error(f"Errore controllo schedulazioni profili: {e}") diff --git a/static/css/style.css b/static/css/style.css index 4a0ff9f..e927384 100644 --- a/static/css/style.css +++ b/static/css/style.css @@ -31,8 +31,8 @@ body { #top-bar { padding: 12px 20px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 15px; border: 1px solid var(--border-main); width: 100%; max-width: 1400px; background: rgba(6, 36, 111, 0.5); } .title-brand { font-size: 1.2rem; font-weight: 300; letter-spacing: 4px; color: var(--text-main); text-transform: uppercase; white-space: nowrap; flex-shrink: 0; margin-right: 10px;} -.nav-tabs { display: flex; gap: 10px; flex: 1 1 auto; min-width: 250px; flex-wrap: wrap; justify-content: flex-start; margin-left: 0;} -.nav-tab { background: transparent; border: 1px solid transparent; color: var(--text-muted); font-size: 0.85rem; font-weight: 300; letter-spacing: 2px; cursor: pointer; padding: 6px 16px; transition: all 0.2s ease; text-transform: uppercase; white-space: nowrap;} +.nav-tabs { display: flex; gap: 10px; flex-wrap: nowrap; justify-content: flex-start; margin-left: 0;} +.nav-tab { background: transparent; border: 1px solid transparent; color: var(--text-muted); font-size: 0.85rem; font-weight: 300; letter-spacing: 2px; cursor: pointer; padding: 6px 14px; transition: all 0.2s ease; text-transform: uppercase; white-space: nowrap;} .nav-tab:hover { color: var(--text-main); border: 1px solid var(--border-light); } .nav-tab.active { color: var(--text-main); border: 1px solid var(--border-main); } @@ -40,7 +40,7 @@ body { .theme-switch:hover { background: rgba(255,255,255,0.1); } /* Container for right side items (auth and other buttons) */ -.top-bar-right { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: flex-end; flex: 1 1 auto; } +.top-bar-right { display: flex; align-items: center; gap: 8px; flex-wrap: nowrap; justify-content: flex-end; flex: none; } /* FILTRI E CONTROLLI VIEW */ .filter-bar { background: rgba(6, 36, 111, 0.90); border: 1px solid var(--border-main); padding: 10px 20px; display: flex; gap: 15px; flex-wrap: wrap; align-items: center; justify-content: space-between; margin-bottom: 20px; } diff --git a/static/js/app.js b/static/js/app.js index 9dcc6e3..e658b4f 100644 --- a/static/js/app.js +++ b/static/js/app.js @@ -9,7 +9,8 @@ function updateClock() { } // --- VARIABILI GLOBALI E UI VIEW --- -let clients = []; +let clients = []; +let activeLoggedUsers = []; let me = { logged_in: false, user: '', role: '', allowed_nodes: '' }; let isAuthenticated = false; let usersCache = {}; @@ -24,6 +25,7 @@ let searchQuery = ''; let viewMode = localStorage.getItem('fleetViewMode') || 'grid'; let fleetMap = null; let mapMarkers = {}; +let aprsMarkers = {}; let currentFocusedNode = null; let currentMmdvmConfig = ""; @@ -125,7 +127,8 @@ function openNodeFocus(clientId) { } refreshStates(); - refreshLogs(); + refreshLogs(); + setTimeout(loadNodeAnalytics, 300); } function closeNodeFocus() { @@ -148,6 +151,7 @@ window.addEventListener('DOMContentLoaded', () => { checkServerUpdate(); setInterval(checkServerUpdate, 3600000); refreshAprs(); + setInterval(cleanupAprsMarkers, 60000); }); // --- FUNZIONI FILTRO E LAYOUT --- @@ -208,6 +212,16 @@ function applyFilters() { }); } + +function showActiveUsers() { + if (!activeLoggedUsers || activeLoggedUsers.length === 0) { + customAlert("[ USERS ]", "Nessun operatore attualmente loggato."); + return; + } + const html = activeLoggedUsers.map(u => `
🟢 ${esc(u.toUpperCase())}
`).join(''); + customAlert("[ SYS_OPS_ONLINE ]", html); +} + function fmtAge(sec) { sec = Math.max(0, Math.round(sec)); if (sec < 60) return sec + 's'; @@ -533,29 +547,25 @@ async function initUI() { const hasAllNodes = allowedList.includes('all'); const canOverride = hasAllNodes; - let actionBtns = ''; - if (role === 'admin') { - actionBtns += ``; - actionBtns += ``; + // 1. Nella barra principale in alto teniamo SOLO [ SYS_ADM ], UTENTE e CONTROLLI SESSIONE + let topBarAdminBtn = ''; + if (role === 'admin' || role === 'node_admin') { + topBarAdminBtn = ``; } - if (canOverride) { - actionBtns += ``; - } - if (role === 'admin') { - actionBtns += ``; - } - - authContainer.innerHTML = `${actionBtns} - USR: ${esc(String(me.user).toUpperCase())} - - `; + + authContainer.innerHTML = `
+ ${topBarAdminBtn} + USR: ${esc(String(me.user).toUpperCase())} + + +
`; } else { authContainer.innerHTML = ``; } grid.innerHTML = clients.map(c => { let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(c.id.toLowerCase())); - let showReboot = (role === 'admin' && canControl); + let showReboot = (role === 'admin' || role === 'node_admin') && canControl; return `
@@ -619,6 +629,7 @@ async function initUI() { + @@ -742,6 +753,13 @@ function initOrUpdateMap() { fleetMap.fitBounds(bounds, { padding: [40, 40] }); fleetMap._hasFitted = true; } + + // Assicurati che i marker APRS siano renderizzati + for (const [src, data] of Object.entries(aprsMarkers)) { + if (!fleetMap.hasLayer(data.marker)) { + data.marker.addTo(fleetMap); + } + } } async function refreshStates() { @@ -749,6 +767,18 @@ async function refreshStates() { const res = await fetch('/api/states'); const data = await res.json(); latestStatesData = data; globalVersionsData = data.versions || {}; + if (data.web_users !== undefined) { + const uEl = document.getElementById('active-users-count'); + if (uEl) uEl.innerText = data.web_users; + const uBadge = document.getElementById('users-badge'); + if (uBadge) { + uBadge.style.cursor = 'pointer'; + uBadge.onclick = showActiveUsers; + } + } + if (data.logged_users !== undefined) { + activeLoggedUsers = data.logged_users; + } clients.forEach(c => { try { @@ -766,7 +796,7 @@ async function refreshStates() { const role = me.role || ''; const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(c.id.toLowerCase())); - let showReboot = (role === 'admin' && canControl); + let showReboot = (role === 'admin' || role === 'node_admin') && canControl; let isTx = false; let activeModeColor = "var(--primary)"; @@ -1205,6 +1235,7 @@ async function refreshStates() { btnHtml += ``; btnHtml += ``; btnHtml += ``; + btnHtml += ``; btnHtml += ``; btnHtml += ``; let otaColor = (healthObj && healthObj.agent_update_available) ? 'var(--danger)' : 'var(--primary)'; @@ -1242,11 +1273,98 @@ async function refreshAprs() { let html = ""; logs.forEach(msg => { html += formatAprsRow(msg); + plotAprsOnMap(msg); // Popola mappa all'avvio }); tbody.innerHTML = html; } catch (e) { console.error(e); } } + +function parseAprsPosition(payload) { + // Cerca pattern standard APRS (es. 4603.25N/01315.60E) + const posRegex = /([0-9]{2})([0-9]{2}\.[0-9]{1,2})([NS])(.)([0-1][0-9]{2})([0-9]{2}\.[0-9]{1,2})([EOW])/i; + const match = payload.match(posRegex); + if (match) { + let latDeg = parseInt(match[1], 10); + let latMin = parseFloat(match[2]); + let lat = latDeg + (latMin / 60.0); + if (match[3].toUpperCase() === 'S') lat = -lat; + + let lonDeg = parseInt(match[5], 10); + let lonMin = parseFloat(match[6]); + let lon = lonDeg + (lonMin / 60.0); + if (match[7].toUpperCase() === 'W' || match[7].toUpperCase() === 'O') lon = -lon; + + return { lat, lon }; + } + return null; +} + +function plotAprsOnMap(msg) { + const pos = parseAprsPosition(msg.payload); + if (!pos) return; + + const source = msg.source; + const sourceBase = source.split('-')[0].toLowerCase(); + + // Escludiamo dalla mappa i pacchetti provenienti dai nodi della flotta + let isFleetNode = false; + for (let i = 0; i < clients.length; i++) { + let cid = clients[i].id.toLowerCase(); + let cname = (clients[i].name || "").split('-')[0].toLowerCase(); + let ccall = ""; + if (latestStatesData && latestStatesData.general && latestStatesData.general[cid]) { + ccall = (latestStatesData.general[cid].callsign || "").split('-')[0].toLowerCase(); + } + if (sourceBase === cid || sourceBase === cname || (ccall && sourceBase === ccall)) { + isFleetNode = true; + break; + } + } + if (isFleetNode) return; + + if (aprsMarkers[source] && fleetMap) { + fleetMap.removeLayer(aprsMarkers[source].marker); + } + + const customIcon = L.divIcon({ + className: 'custom-div-icon', + html: `
`, + iconSize: [14, 14], + iconAnchor: [7, 7] + }); + + const popupContent = ` +
+
${esc(source)} (APRS)
+
${esc(msg.time)} via ${esc(msg.path.split(',')[0])}
+
${esc(msg.payload)}
+ [ APRS.FI ] +
+ `; + + const marker = L.marker([pos.lat, pos.lon], { icon: customIcon }).bindPopup(popupContent); + + aprsMarkers[source] = { + marker: marker, + timestamp: Date.now() + }; + + if (fleetMap) { + marker.addTo(fleetMap); + } +} + +function cleanupAprsMarkers() { + const now = Date.now(); + for (const [src, data] of Object.entries(aprsMarkers)) { + if (now - data.timestamp > 7200000) { // 2 ore + if (fleetMap) fleetMap.removeLayer(data.marker); + delete aprsMarkers[src]; + } + } +} + function formatAprsRow(msg) { const time = msg.time || new Date().toLocaleTimeString('it-IT', { hour12: false }); const srcHtml = `${esc(msg.source)}`; @@ -1269,6 +1387,7 @@ function addLiveAprs(msg) { if (tbody.children.length > 100) { tbody.removeChild(tbody.lastChild); } + plotAprsOnMap(msg); } async function refreshLogs() { @@ -1410,10 +1529,126 @@ const refreshStatesSoon = debounce(refreshStates, 300); const refreshLogsSoon = debounce(() => { refreshLogs(); refreshStats(); }, 500); if (typeof io !== 'undefined') { - const socket = io(); - socket.on('mqtt_status', function(data) { const badge = document.getElementById('mqtt-badge'); if (badge) { if (data.connected) { badge.innerText = "MQTT: OK"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: ERR"; badge.className = "mqtt-badge mqtt-offline"; } } }); - socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); }); - socket.on('dati_aggiornati', refreshStatesSoon); - socket.on('log_aggiornato', refreshLogsSoon); - socket.on('aprs_msg', function(data) { addLiveAprs(data); }); + window.socket = io(); + window.socket.on('mqtt_status', function(data) { const badge = document.getElementById('mqtt-badge'); if (badge) { if (data.connected) { badge.innerText = "MQTT: OK"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: ERR"; badge.className = "mqtt-badge mqtt-offline"; } } }); + window.socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); }); + window.socket.on('dati_aggiornati', refreshStatesSoon); + window.socket.on('log_aggiornato', refreshLogsSoon); + window.socket.on('aprs_msg', function(data) { addLiveAprs(data); }); + window.socket.on('web_users_count', function(data) { + const el = document.getElementById('active-users-count'); + if (el && data && data.count !== undefined) { + el.innerText = data.count; + } + if (data && data.users) { + activeLoggedUsers = data.users; + } + }); +} + + + +// --- LOGICA ANALYTICS E CHART.JS --- +let hwChart = null; +let rfChart = null; +let currentAnalyticsHours = 24; + +Chart.defaults.color = 'rgba(255, 255, 255, 0.6)'; +Chart.defaults.font.family = "'JetBrains Mono', monospace"; + +function setAnalyticsTimeframe(hours) { + currentAnalyticsHours = hours; + + // Update active class on pills + [12, 24, 48, 168].forEach(h => { + const btn = document.getElementById('btn-ana-' + h); + if (btn) { + if (h === hours) btn.classList.add('active'); + else btn.classList.remove('active'); + } + }); + + // Update label text + const labelEl = document.getElementById('analytics-time-label'); + if (labelEl) { + labelEl.innerText = hours === 168 ? '7D' : hours + 'H'; + } + + // Reload data + loadNodeAnalytics(); +} + +async function loadNodeAnalytics() { + if (!currentFocusedNode) return; + try { + const res = await fetch(`/api/analytics/${currentFocusedNode}?hours=${currentAnalyticsHours}`); + const data = await res.json(); + + if (!data.success) return; + + // Dati Telemetria (Ore o Giorni/Ore) + const formatLabel = (dTime) => { + if (currentAnalyticsHours > 48) { + const parts = dTime.split(' '); + const dateParts = parts[0].split('-'); // YYYY-MM-DD + return `${dateParts[2]}/${dateParts[1]} ${parts[1].substring(0, 5)}`; + } + return dTime.split(' ')[1].substring(0, 5); + }; + const hwLabels = data.telemetry.map(d => formatLabel(d.time)); + const tempD = data.telemetry.map(d => d.temp); + const cpuD = data.telemetry.map(d => d.cpu); + + if (hwChart) hwChart.destroy(); + const ctxHw = document.getElementById('chart-hw').getContext('2d'); + hwChart = new Chart(ctxHw, { + type: 'line', + data: { + labels: hwLabels, + datasets: [ + { label: t('chartTemp'), data: tempD, borderColor: '#ef4444', backgroundColor: 'rgba(239,68,68,0.1)', fill: true, tension: 0.3, yAxisID: 'y' }, + { label: t('chartCpu'), data: cpuD, borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,0.1)', fill: true, tension: 0.3, yAxisID: 'y1' } + ] + }, + options: { + responsive: true, + maintainAspectRatio: false, + plugins: { legend: { display: true, position: 'top' } }, + scales: { + x: { grid: { color: 'rgba(255,255,255,0.05)' } }, + y: { type: 'linear', display: true, position: 'left', grid: { color: 'rgba(255,255,255,0.05)' }, min: 20 }, + y1: { type: 'linear', display: true, position: 'right', grid: { drawOnChartArea: false }, min: 0, max: 100 } + } + } + }); + + // Dati RF + const rfLabels = data.rf.map(d => formatLabel(d.time)); + const countD = data.rf.map(d => d.count); + const berD = data.rf.map(d => d.ber); + + if (rfChart) rfChart.destroy(); + const ctxRf = document.getElementById('chart-rf').getContext('2d'); + rfChart = new Chart(ctxRf, { + type: 'bar', + data: { + labels: rfLabels, + datasets: [ + { label: t('chartTransits'), data: countD, backgroundColor: '#10b981', yAxisID: 'y' }, + { label: t('chartBer'), data: berD, type: 'line', borderColor: '#f59e0b', backgroundColor: 'transparent', tension: 0.3, yAxisID: 'y1' } + ] + }, + options: { + responsive: true, + maintainAspectRatio: false, + plugins: { legend: { display: true, position: 'top' } }, + scales: { + x: { grid: { color: 'rgba(255,255,255,0.05)' } }, + y: { type: 'linear', display: true, position: 'left', grid: { color: 'rgba(255,255,255,0.05)' }, min: 0 }, + y1: { type: 'linear', display: true, position: 'right', grid: { drawOnChartArea: false }, min: 0 } + } + } + }); + + } catch (e) { console.error("Error loading analytics:", e); } } diff --git a/static/js/modals.js b/static/js/modals.js index b76bd6f..b78a8fd 100644 --- a/static/js/modals.js +++ b/static/js/modals.js @@ -2,6 +2,17 @@ const i18n = { en: { lblLogLimit: "Rows:", + btnSched: "SCHED", ttSchedule: "Calendar Profile Scheduler", schedTitle: "CALENDAR PROFILE SCHEDULER", + schedNew: "NEW SCHEDULED EVENT", lblSchedTitle: "Event Name:", lblSchedNodes: "Target Nodes:", + lblSchedTargetProf: "Target Profile:", lblSchedRestoreProf: "Restore Profile:", + lblSchedStart: "Start Date/Time:", lblSchedEnd: "End Date/Time:", btnAddSched: "CREATE SCHEDULE", + thSchedTitle: "Title", thSchedNodes: "Nodes", thSchedProf: "Profile", thSchedStart: "Start", + thSchedEnd: "End", thSchedStatus: "Status", thSchedActs: "Actions", + statusScheduled: "SCHEDULED", statusActive: "ACTIVE", statusCompleted: "COMPLETED", statusCancelled: "CANCELLED", statusExpired: "EXPIRED", + confCancelSched: "Cancel this scheduled event?", msgSchedCreated: "SCHEDULE CREATED", msgSchedCancelled: "SCHEDULE CANCELLED", + errSchedDates: "End date must be after start date!", errMissingSchedData: "Please fill all required fields!", + optAllNodes: "ALL NODES (FLEET)", optNone: "NONE (Leave current)", + lastTransits: "Lastheard", loginTitle: "SYSTEM_LOGIN", thTime: "Time", thRep: "Repeater", thMode: "Mode", thCall: "Callsign", thDur: "Duration", thUser: "User", thRole: "Role", thNodes: "Nodes", thActs: "Actions", @@ -44,6 +55,17 @@ const i18n = { }, it: { lblLogLimit: "Righe:", + btnSched: "SCHED", ttSchedule: "Pianificazione Calendario Profili", schedTitle: "CALENDARIO PIANIFICAZIONE PROFILI", + schedNew: "NUOVO EVENTO PROGRAMMATO", lblSchedTitle: "Nome Evento:", lblSchedNodes: "Nodi Coinvolti:", + lblSchedTargetProf: "Profilo Attivazione:", lblSchedRestoreProf: "Profilo Ripristino:", + lblSchedStart: "Data/Ora Inizio:", lblSchedEnd: "Data/Ora Fine:", btnAddSched: "CREA PIANIFICAZIONE", + thSchedTitle: "Titolo", thSchedNodes: "Nodi", thSchedProf: "Profilo", thSchedStart: "Inizio", + thSchedEnd: "Fine", thSchedStatus: "Stato", thSchedActs: "Azioni", + statusScheduled: "PROGRAMMATO", statusActive: "ATTIVO", statusCompleted: "COMPLETATO", statusCancelled: "ANNULLATO", statusExpired: "SCADUTO", + confCancelSched: "Annullare questo evento programmato?", msgSchedCreated: "PIANIFICAZIONE CREATA", msgSchedCancelled: "PIANIFICAZIONE ANNULLATA", + errSchedDates: "La data di fine deve essere successiva a quella di inizio!", errMissingSchedData: "Compilare tutti i campi obbligatori!", + optAllNodes: "TUTTI I NODI (FLOTTA)", optNone: "NESSUNO (Mantieni attivo)", + lastTransits: "Ultimi ascolti", loginTitle: "ACCESSO SISTEMA", thTime: "Ora", thRep: "Ripetitore", thMode: "Modo", thCall: "Nominativo", thDur: "Durata", thUser: "Utente", thRole: "Ruolo", thNodes: "Nodi", thActs: "Azioni", @@ -82,7 +104,9 @@ const i18n = { lblSysUptime: "Tempo di attività sistema", lblSwVersions: "Versioni Software", lblOtaUpdate: "Aggiornamento OTA", waitConfig: "IN ATTESA DELLA CONFIGURAZIONE...", noDaemonData: "NESSUN DATO DAL DEMONE. RETENTATIVO...", cfgEmpty: "[!] MEMORIA CFG VUOTA", netError: "ERRORE DI RETE", noModesFound: "NESSUN MODO TROVATO NELLA CONFIGURAZIONE", accessDenied: "[ ACCESSO NEGATO ]", savingRestart: "⏳ SALVATAGGIO & RIAVVIO IN CORSO...", stateUpdated: "✅ STATO AGGIORNATO CON SUCCESSO!", - phSearch: "CERCA ID/CALL...", btnGrid: "[ GRIGLIA ]", btnList: "[ LISTA ]" + phSearch: "CERCA ID/CALL...", btnGrid: "[ GRIGLIA ]", btnList: "[ LISTA ]", + liveLogTitle: "[ LIVE_LOG: ", filterAll: "TUTTI I DEMONI", btnScrollOn: "SCROLL: ON", btnScrollOff: "SCROLL: OFF", btnClear: "PULISCI", + logConnWait: "Connessione in corso... In attesa dei log per ", logNoData: "Nessun log recente in memoria per ", logApplyFilter: "Applicazione filtro...", btnDownloadZip: "[ SCARICA_TUTTI_CFG_ZIP ]", lblHistory: "STORICO:", optCurrentUnsaved: "Attuale (Non salvata)", btnPreviewDiff: "[ ANTEPRIMA_DIFF ]", btnCancelDiff: "ANNULLA", titleAuditLogs: "[ LOG_SICUREZZA_AUDIT ]", btnRefresh: "AGGIORNA", btnRefreshBracket: "[ AGGIORNA ]", waitLoading: "In attesa di caricamento...", titleAnalytics: "[ ANALITICHE_NODO ]", msgNoAudit: "Nessun log di sicurezza presente.", msgNoModifications: "[ NESSUNA MODIFICA RILEVATA RISPETTO ALLA CONFIGURAZIONE ATTIVA ]", warnUnverifiedDiff: "Non hai verificato il Diff visivo. Sicuro di voler sovrascrivere?", chartTemp: "Temp °C", chartCpu: "CPU %", chartTransits: "Transiti", chartBer: "BER Medio %" } }; @@ -177,7 +201,44 @@ async function executeUpdateRequest() { } // --- MODALE ADMIN & UTENTI --- -async function openAdmin() { document.getElementById('admin-modal').style.display = 'flex'; loadUsers(); loadSettings(); cancelEdit(); } +async function openAdmin() { + document.getElementById('admin-modal').style.display = 'flex'; + + // Inietto i bottoni operativi dentro l'header del pannello admin + let adminBtnsHtml = ''; + const role = me.role || ''; + const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); + const hasAllNodes = allowedList.includes('all'); + const canOverride = hasAllNodes; + + if (role === 'admin') { + adminBtnsHtml += ``; + adminBtnsHtml += ``; + } + if (role === 'admin' || role === 'node_admin') { + adminBtnsHtml += ``; + } + if (canOverride) { + adminBtnsHtml += ``; + } + + const adminActionDiv = document.getElementById('admin-action-btns'); + if (adminActionDiv) { + adminActionDiv.innerHTML = adminBtnsHtml; + // Se siamo admin eseguiamo anche un check per l'update del server per mostrare/nascondere il tasto + if (role === 'admin' && typeof GLOBAL_SERVER_UPDATE_AVAILABLE !== 'undefined' && GLOBAL_SERVER_UPDATE_AVAILABLE) { + const upBtn = document.getElementById('server-update-btn-modal'); + if(upBtn) upBtn.style.display = 'inline-block'; + } + } + + if (me.role === 'admin') { + loadUsers(); + loadSettings(); + cancelEdit(); + } + loadAuditLogs(); +} function closeAdmin() { document.getElementById('admin-modal').style.display = 'none'; cancelEdit(); } async function loadUsers() { @@ -354,16 +415,29 @@ function controlService(clientId, service, action) { }); } -// --- MODALE EDITOR INI --- -let currentEditClient = ""; let currentEditService = ""; +// --- MODALE EDITOR INI E BACKUP HISTORY --- +let currentEditClient = ""; let currentEditService = ""; let currentOriginalConfig = ""; let isDiffMode = false; +let historyConfigs = {}; // Cache per i backup + async function openEditorModal(clientId, service) { - currentEditClient = clientId; currentEditService = service; document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`; - document.getElementById('config-textarea').value = "AWAITING_STREAM..."; document.getElementById('editor-status').innerText = ""; document.getElementById('editor-modal').style.display = 'flex'; + currentEditClient = clientId; currentEditService = service; isDiffMode = false; + document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`; + document.getElementById('config-textarea').value = "AWAITING_STREAM..."; + document.getElementById('config-textarea').style.display = 'block'; + document.getElementById('diff-view').style.display = 'none'; + document.getElementById('btn-cancel-diff').style.display = 'none'; + document.getElementById('editor-status').innerText = ""; + document.getElementById('editor-modal').style.display = 'flex'; + document.getElementById('config-history-select').innerHTML = ``; + historyConfigs = {}; + try { const res = await fetch(`/api/config_file/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`); const data = await res.json(); if (data.success) { - document.getElementById('config-textarea').value = data.data.raw_text || "EMPTY"; + currentOriginalConfig = data.data.raw_text || ""; + document.getElementById('config-textarea').value = currentOriginalConfig; + fetchConfigHistory(clientId, service); } else { document.getElementById('config-textarea').value = "ERR:\n" + data.error; } @@ -371,18 +445,118 @@ async function openEditorModal(clientId, service) { document.getElementById('config-textarea').value = "NET_ERR"; } } + +async function fetchConfigHistory(clientId, service) { + try { + const res = await fetch(`/api/config_backups/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`); + const data = await res.json(); + if (data.success && data.backups.length > 0) { + const select = document.getElementById('config-history-select'); + data.backups.forEach(b => { + const opt = document.createElement('option'); + opt.value = b.id; + opt.text = `${b.timestamp} (${b.username})`; + select.appendChild(opt); + }); + } + } catch(e) { console.error("History fetch error:", e); } +} + +async function loadHistoryConfig() { + const val = document.getElementById('config-history-select').value; + if (!val) { + // Ripristina testualmente la versione corrente se scelgono "Attuale" + document.getElementById('config-textarea').value = currentOriginalConfig; + return; + } + + if (historyConfigs[val]) { + document.getElementById('config-textarea').value = historyConfigs[val]; + return; + } + + try { + const res = await fetch(`/api/config_backups/${val}`); + const data = await res.json(); + if (data.success) { + historyConfigs[val] = data.text; + document.getElementById('config-textarea').value = data.text; + } + } catch (e) { console.error(e); } +} + +function previewConfigDiff() { + const newText = document.getElementById('config-textarea').value; + const diffView = document.getElementById('diff-view'); + const textarea = document.getElementById('config-textarea'); + + if (isDiffMode) { + // Torna all'editor + textarea.style.display = 'block'; + diffView.style.display = 'none'; + document.getElementById('btn-cancel-diff').style.display = 'none'; + isDiffMode = false; + return; + } + + // Calcola il diff visivo + const dmp = new diff_match_patch(); + const diffs = dmp.diff_main(currentOriginalConfig, newText); + dmp.diff_cleanupSemantic(diffs); + + let html = ""; + diffs.forEach(part => { + const type = part[0]; // -1 rimossa, 1 aggiunta, 0 uguale + const text = esc(part[1]); + if (type === 1) html += `${text}`; + else if (type === -1) html += `${text}`; + else html += `${text}`; + }); + + if (diffs.length === 1 && diffs[0][0] === 0) { + html = `${t('msgNoModifications')}\n\n` + html; + } + + diffView.innerHTML = html; + textarea.style.display = 'none'; + diffView.style.display = 'block'; + document.getElementById('btn-cancel-diff').style.display = 'block'; + isDiffMode = true; +} + +function cancelDiff() { + document.getElementById('config-textarea').style.display = 'block'; + document.getElementById('diff-view').style.display = 'none'; + document.getElementById('btn-cancel-diff').style.display = 'none'; + isDiffMode = false; +} + function closeEditorModal() { document.getElementById('editor-modal').style.display = 'none'; } function saveConfig() { - const textValue = document.getElementById('config-textarea').value; const statusSpan = document.getElementById('editor-status'); - customConfirm(t('titleSave'), `${t('confOvr')}${currentEditClient.toUpperCase()}?`, "var(--danger)", async () => { - statusSpan.innerText = "WRITING..."; statusSpan.style.color = "var(--success)"; - try { - const res = await fetch('/api/config_file', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: currentEditClient, service: currentEditService, config_data: { "raw_text": textValue } }) }); - const data = await res.json(); - if (data.success) { customAlert(t('titleSuccess'), "FILE_WRITTEN"); closeEditorModal(); } else { customAlert(t('titleError'), "ERR: " + esc(data.error), true); statusSpan.innerText = "ERR"; } - } catch(e) { customAlert(t('titleError'), t('msgNetErr'), true); statusSpan.innerText = "NET_ERR"; } - }); + const textValue = document.getElementById('config-textarea').value; + const statusSpan = document.getElementById('editor-status'); + + if (!isDiffMode && textValue !== currentOriginalConfig) { + customConfirm(t('titleSave'), t('warnUnverifiedDiff'), "var(--accent)", () => executeSave(textValue, statusSpan)); + } else { + customConfirm(t('titleSave'), `${t('confOvr')}${currentEditClient.toUpperCase()}?`, "var(--danger)", () => executeSave(textValue, statusSpan)); + } +} + +async function executeSave(textValue, statusSpan) { + statusSpan.innerText = "WRITING..."; statusSpan.style.color = "var(--success)"; + try { + const res = await fetch('/api/config_file', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: currentEditClient, service: currentEditService, config_data: { "raw_text": textValue } }) }); + const data = await res.json(); + if (data.success) { + customAlert(t('titleSuccess'), "FILE_WRITTEN"); + currentOriginalConfig = textValue; // Aggiorna l'originale corrente + closeEditorModal(); + } else { + customAlert(t('titleError'), "ERR: " + esc(data.error), true); statusSpan.innerText = "ERR"; + } + } catch(e) { customAlert(t('titleError'), t('msgNetErr'), true); statusSpan.innerText = "NET_ERR"; } } // --- MODALE VERSIONI SOFTWARE --- @@ -393,3 +567,403 @@ function openVersionsModal(clientId) { document.getElementById('versions-modal').style.display = 'flex'; } function closeVersionsModal() { document.getElementById('versions-modal').style.display = 'none'; } + + +// -------------------- LIVE LOG MODAL -------------------- +let currentLogClientId = null; + +function openLogModal(clientId) { + currentLogClientId = clientId.toLowerCase(); + document.getElementById('log-modal-title').innerText = clientId.toUpperCase(); + document.getElementById('log-console').innerHTML = `${t('logConnWait')} ${clientId.toUpperCase()}...\n`; + document.getElementById('log-modal').style.display = 'flex'; + document.getElementById('log-service-filter').value = 'ALL'; + + // 1. Fetch initial logs + fetch(`/api/logs/${clientId}`) + .then(res => res.json()) + .then(data => { + if (data.success && data.logs.length > 0) { + document.getElementById('log-console').innerHTML = ''; + data.logs.forEach(log => appendLog(log)); + } else { + document.getElementById('log-console').innerHTML = `${t('logNoData')} ${clientId.toUpperCase()}.\n`; + } + }) + .catch(err => console.error("Errore fetch logs:", err)); + + // 2. Subscribe WebSocket + window.socket.on('live_log_' + currentLogClientId, function(logEntry) { + appendLog(logEntry); + }); +} + +function closeLogModal() { + document.getElementById('log-modal').style.display = 'none'; + if (currentLogClientId) { + window.socket.off('live_log_' + currentLogClientId); + } + currentLogClientId = null; +} + +let autoScroll = true; + +function toggleAutoScroll() { + autoScroll = !autoScroll; + const btn = document.getElementById('btn-autoscroll'); + if (autoScroll) { + btn.innerText = t('btnScrollOn') || 'SCROLL: ON'; + btn.style.borderColor = 'var(--accent)'; + btn.style.setProperty('color', 'var(--accent)', 'important'); + scrollToBottom(); + } else { + btn.innerText = t('btnScrollOff') || 'SCROLL: OFF'; + btn.style.borderColor = 'var(--text-muted)'; + btn.style.setProperty('color', 'var(--text-muted)', 'important'); + } +} + +function clearLogs() { + document.getElementById('log-console').innerHTML = ''; +} + +function scrollToBottom() { + const box = document.getElementById('log-console'); + box.scrollTop = box.scrollHeight; +} + +function appendLog(log) { + const filter = document.getElementById('log-service-filter').value.toLowerCase(); + const logSvc = log.service.toLowerCase(); + if (filter !== 'all' && !logSvc.includes(filter)) { + return; + } + + const box = document.getElementById('log-console'); + + let color = '#c9d1d9'; + let prefix = log.service.toLowerCase(); + + if (prefix.includes('mmdvm')) color = '#58a6ff'; + else if (prefix.includes('dmr')) color = '#3fb950'; + else if (prefix.includes('ysf')) color = '#8b5cf6'; // Violetto per YSF + else if (prefix.includes('dstar') || prefix.includes('d-star')) color = '#f97316'; // Arancio per D-Star + else if (prefix.includes('nxdn')) color = '#10b981'; // Verde NXDN + else if (prefix.includes('p25')) color = '#ffcc00'; // Giallo P25 + + const span = document.createElement('div'); + span.style.marginBottom = '2px'; + + const timeSpan = `[${log.time}]`; + const svcSpan = `[${log.service}]`; + + span.innerHTML = `${timeSpan} ${svcSpan} ${escapeHtml(log.text)}`; + + // Remove default "Connessione in corso..." if present + if (box.innerHTML.includes(t('logConnWait'))) { + box.innerHTML = ''; + } + + box.appendChild(span); + + // Keep max 1000 lines in DOM to prevent lag + if (box.childElementCount > 1000) { + box.removeChild(box.firstChild); + } + + if (autoScroll) scrollToBottom(); +} + +function escapeHtml(unsafe) { + return unsafe + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function renderLogs() { + // When filter changes, we just clear and wait for new logs, or we could refetch. + // For simplicity, we clear the console and fetch again from server. + if (currentLogClientId) { + document.getElementById('log-console').innerHTML = `${t('logApplyFilter')}\n`; + fetch(`/api/logs/${currentLogClientId}`) + .then(res => res.json()) + .then(data => { + document.getElementById('log-console').innerHTML = ''; + if (data.success) { + data.logs.forEach(log => appendLog(log)); + } + }); + } +} + + +// --- SECURITY AUDIT LOGS --- +async function loadAuditLogs() { + try { + const res = await fetch('/api/audit_logs'); + const data = await res.json(); + const container = document.getElementById('audit-logs-container'); + if (data.success && data.logs) { + if (data.logs.length === 0) { + container.innerHTML = `${t('msgNoAudit')}`; + return; + } + let html = ''; + data.logs.forEach(log => { + html += `
+ [${log.time}] + ${esc(log.user.toUpperCase())} + ${esc(log.node.toUpperCase())} + ${esc(log.cmd)} +
`; + }); + container.innerHTML = html; + } + } catch(e) { console.error("Error loading audit logs:", e); } +} + + +// --- MODALE CALENDARIO SCHEDULAZIONE PROFILI --- +async function openScheduleModal() { + document.getElementById('schedule-modal').style.display = 'flex'; + populateScheduleNodeOptions(); + loadSchedules(); + + // Inizializza le date con orari coerenti (Inizio: adesso + 5 min, Fine: adesso + 2 ore) + const now = new Date(); + const in5m = new Date(now.getTime() + 5 * 60000); + const in2h = new Date(now.getTime() + 125 * 60000); + + const toLocalISO = (d) => { + const pad = (n) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; + }; + + document.getElementById('sched-start').value = toLocalISO(in5m); + document.getElementById('sched-end').value = toLocalISO(in2h); +} + +function closeScheduleModal() { + document.getElementById('schedule-modal').style.display = 'none'; +} + +function updateScheduleProfileOptions() { + const selNodes = document.getElementById('sched-nodes-select'); + const selTarget = document.getElementById('sched-target-prof'); + const selRestore = document.getElementById('sched-restore-prof'); + if (!selNodes || !selTarget || !selRestore) return; + + // Proviamo a estrarre i nomi dei profili dal primo nodo selezionato + const selectedCid = selNodes.value; + let profiles = { "A": "Profilo A", "B": "Profilo B" }; // Default + + if (selectedCid !== 'all' && globalHealthData[selectedCid] && globalHealthData[selectedCid].profiles) { + profiles = globalHealthData[selectedCid].profiles; + } else { + // Se è 'all', cerchiamo il primo nodo disponibile che abbia i profili valorizzati + for (let cid in globalHealthData) { + if (globalHealthData[cid] && globalHealthData[cid].profiles && Object.keys(globalHealthData[cid].profiles).length > 0) { + profiles = globalHealthData[cid].profiles; + break; + } + } + } + + // Aggiorniamo le select + let htmlTarget = ""; + let htmlRestore = ""; + + for (const [pKey, pLabel] of Object.entries(profiles)) { + htmlTarget += ``; + htmlRestore += ``; + } + htmlRestore += ``; + + // Salviamo i valori attuali se possibile per non resettarli + const currTarget = selTarget.value; + const currRestore = selRestore.value; + + selTarget.innerHTML = htmlTarget; + selRestore.innerHTML = htmlRestore; + + if(currTarget && [...selTarget.options].some(o => o.value === currTarget)) selTarget.value = currTarget; + if(currRestore && [...selRestore.options].some(o => o.value === currRestore)) selRestore.value = currRestore; + + // Riapplichiamo le traduzioni per l'opzione NONE se in italiano + if (currentLang === 'it') { + const noneOpt = selRestore.querySelector('option[value="NONE"]'); + if(noneOpt) noneOpt.innerText = "NESSUNO (Mantieni attivo)"; + } +} + +function populateScheduleNodeOptions() { + const sel = document.getElementById('sched-nodes-select'); + if (!sel) return; + + const role = me.role || ''; + const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); + const hasAll = allowedList.includes('all'); + + let html = ''; + if (hasAll || role === 'admin') { + html += ``; + } + + clients.forEach(c => { + if (hasAll || allowedList.includes(c.id.toLowerCase())) { + html += ``; + } + }); + + sel.innerHTML = html; + sel.addEventListener('change', updateScheduleProfileOptions); + updateScheduleProfileOptions(); +} + +async function loadSchedules() { + const tbody = document.getElementById('schedules-table-body'); + if (!tbody) return; + + try { + const res = await fetch('/api/schedules'); + const data = await res.json(); + + if (!data.success || !data.schedules || data.schedules.length === 0) { + tbody.innerHTML = `NO_SCHEDULES_FOUND`; + return; + } + + tbody.innerHTML = data.schedules.map(s => { + let statusColor = "var(--text-muted)"; + let statusClass = ""; + let statusText = s.status; + + if (s.status === 'SCHEDULED') { + statusColor = "#f59e0b"; + statusText = t('statusScheduled'); + } else if (s.status === 'ACTIVE') { + statusColor = "var(--success)"; + statusClass = "blink"; + statusText = t('statusActive'); + } else if (s.status === 'COMPLETED') { + statusColor = "var(--text-muted)"; + statusText = t('statusCompleted'); + } else if (s.status === 'CANCELLED') { + statusColor = "var(--danger)"; + statusText = t('statusCancelled'); + } else if (s.status === 'EXPIRED') { + statusColor = "var(--text-muted)"; + statusText = t('statusExpired'); + } + + const isFinished = ['COMPLETED', 'CANCELLED', 'EXPIRED'].includes(s.status); + + + // Tentativo di dedurre il profilo di partenza dal primo nodo o dai nodi target + let startProf = "?"; + let cids = s.target_nodes.toLowerCase() === 'all' ? Object.keys(globalHealthData) : s.target_nodes.toLowerCase().split(','); + for (let i = 0; i < cids.length; i++) { + let cid = cids[i].trim(); + let card = document.getElementById(`card-${cid}`); + if (card && card.dataset.lastMode) { + startProf = card.dataset.lastMode; + // Se leggiamo DMR o D-STAR non è un nome di profilo. Dobbiamo guardare se nel telemetry c'è una hint + let tel = latestStatesData && latestStatesData.telemetry && latestStatesData.telemetry[cid] ? latestStatesData.telemetry[cid] : {}; + if(tel.alt && tel.alt.includes('SCHED:')) { + startProf = tel.alt.split(':')[1].trim(); + } + break; + } + } + if (startProf === "?" || startProf.length > 5) startProf = "CURR"; // Current + + let profDisplay = `${esc(startProf)} ➔ ${esc(s.target_profile)}`; + if (s.restore_profile !== 'NONE') { + profDisplay += ` ➔ ${esc(s.restore_profile)}`; + } + + return ` + ${esc(s.title)} + ${esc(s.target_nodes.toUpperCase())} + ${profDisplay} + ${esc(s.start_time.substring(5, 16))} + ${esc(s.end_time.substring(5, 16))} + [ ${statusText} ] + + ${!isFinished ? `` : '—'} + + `; + }).join(''); + + } catch(e) { + console.error("Error loading schedules:", e); + tbody.innerHTML = `NET_ERR`; + } +} + +async function submitSchedule() { + const title = document.getElementById('sched-title').value.trim(); + const targetNodes = document.getElementById('sched-nodes-select').value; + const targetProf = document.getElementById('sched-target-prof').value.trim().toUpperCase(); + const restoreProf = document.getElementById('sched-restore-prof').value.trim().toUpperCase(); + const startTime = document.getElementById('sched-start').value; + const endTime = document.getElementById('sched-end').value; + + if (!title || !targetNodes || !targetProf || !startTime || !endTime) { + return customAlert(t('titleError'), t('errMissingSchedData'), true); + } + + if (startTime >= endTime) { + return customAlert(t('titleError'), t('errSchedDates'), true); + } + + const payload = { + title: title, + target_nodes: targetNodes, + target_profile: targetProf, + restore_profile: restoreProf, + start_time: startTime, + end_time: endTime + }; + + try { + const res = await fetch('/api/schedules', { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify(payload) + }); + const data = await res.json(); + + if (data.success) { + customAlert(t('titleSuccess'), t('msgSchedCreated')); + document.getElementById('sched-title').value = ''; + loadSchedules(); + } else { + customAlert(t('titleError'), esc(data.error), true); + } + } catch(e) { + console.error(e); + customAlert(t('titleError'), t('msgNetErr'), true); + } +} + +function cancelSchedule(sid) { + customConfirm(t('titleAction'), t('confCancelSched'), "var(--danger)", async () => { + try { + const res = await fetch(`/api/schedules/${sid}`, { method: 'DELETE' }); + const data = await res.json(); + if (data.success) { + customAlert(t('titleSuccess'), t('msgSchedCancelled')); + loadSchedules(); + } else { + customAlert(t('titleError'), esc(data.error), true); + } + } catch(e) { + console.error(e); + customAlert(t('titleError'), t('msgNetErr'), true); + } + }); +} diff --git a/templates/index.html b/templates/index.html index 74834c7..2d1aa15 100644 --- a/templates/index.html +++ b/templates/index.html @@ -25,18 +25,18 @@ -
-
+
+
- - + +
+
+

+ [ NODE_ANALYTICS ] 24H +

+
+ + + + +
+ +
+
+ +
+ +
+ +
+ +
+ +
+
+
+ -