Compare commits

..
89 Commits
Author SHA1 Message Date
iv3jdv 311c4053f0 Security fix 2026-11-08 16:20:23 +01:00
iv3jdv 93fc177911 feat(release): v6.0.0 - Major C2 platform evolution
- Calendar Profile Scheduler: pianificazione temporizzata con switch automatico e rollback del profilo a fine evento
- Tactical APRS Map: tracciamento stazioni in mobilità, filtro dei nodi di flotta e garbage collection dopo 2h
- Dynamic Timeframe Analytics: filtri temporali 12H, 24H, 48H, 7D sui grafici Chart.js con etichette intelligenti
- Time Machine & Visual Diff: storico backup configurazioni .ini con visualizzatore differenze semantico
- Header UX Refactor: riorganizzazione a tre righe compatte con integrazione badge operatori online in tempo reale
- Complete i18n: allineamento del dizionario bilingue (IT/EN) su tutta la piattaforma
2026-11-08 15:27:42 +01:00
iv3jdv c7c95d877c fix 2026-11-07 10:46:39 +01:00
iv3jdv a06e5cd7b7 update README.md 2026-11-03 20:33:16 +01:00
iv3jdv e7bbd080b0 Release v5.3.7: Implementato bypass cache per check aggiornamenti 2026-11-03 20:02:33 +01:00
iv3jdv 019e518534 Release v5.3.6: Strict RBAC e separazione permessi Admin/Nodi 2026-11-03 19:45:38 +01:00
iv3jdv e199fb8f29 Release v5.3.4: Ripristino permessi Global Override per Operator 2026-11-03 18:30:17 +01:00
iv3jdv 43e0e77790 Release v5.3.3: Sync fix per il controllo aggiornamenti backend 2026-11-03 18:14:57 +01:00
iv3jdv 1bb1c2cc99 Release v5.3.2: Fix propagazione Service Alerts e completamento UI i18n 2026-11-03 17:56:10 +01:00
iv3jdv 5fabe68944 Release v5.3.1: Hotfix API server update e prevenzione SyntaxError JSON 2026-11-03 16:56:34 +01:00
iv3jdv 3064dc035f Release v5.3.0: The Borderless Executive Update ed espansione i18n 2026-11-03 16:47:02 +01:00
iv3jdv 8fc08f1c23 reaorganize home header 2026-11-03 15:04:19 +01:00
iv3jdv 66cd63a181 feat(ui,api): layout mini-card fisso, nominativo tx pulito, cache-busting index e check Gitea asincrono 2026-11-03 13:03:55 +01:00
iv3jdv 36def1e201 fix mini-card width v2 2026-11-02 22:52:27 +01:00
iv3jdv a6c24244bd fix mini-card width 2026-11-02 22:43:47 +01:00
iv3jdv 502dcc2f65 Restyling badge 2026-11-02 22:31:44 +01:00
iv3jdv d4e83364e2 add time/date 2026-11-02 22:01:51 +01:00
iv3jdv fa4b3d8df2 fix mode spacing 2026-11-01 20:09:40 +01:00
iv3jdv a67ddd582c feat(ui): aggiunto supporto per i modi FM e M17 nei toggle operativi 2026-11-01 18:57:06 +01:00
iv3jdv 7ee7b00b37 fix(ui): restyling chip gateway ad alto contrasto e parsing aprs raw 2026-11-01 14:28:25 +01:00
iv3jdv ebaefeeedf fix(aprs): parsing stringhe raw ax25 e mapping colonna path 2026-11-01 11:41:45 +01:00
iv3jdv 2e8b75c384 feat(ui): implementazione multi-layout (Blueprint, Tactical, Light, Glass) e fix visivi 2026-11-01 10:52:20 +01:00
iv3jdv a56da30330 restored interactive map 2026-11-01 09:42:44 +01:00
iv3jdv 9b7c76c801 fix(telemetry): allineamento stati hangtime e risoluzione falsi positivi sui beacon
- Backend (mqtt_service.py): Aggiunta logica per intercettare i pacchetti beacon in assenza di traffico voce. Il sistema ora pulisce la memoria dei modi alternativi (es. D-Star/YSF) se il beacon è DMR, prevenendo il blocco dell'interfaccia su un vecchio protocollo.
- Frontend (app.js): La memorizzazione del colore e del modo per la gestione dell'hangtime (Hold) ora scatta con la condizione `!isIdle` anziché solo con il PTT voce (`isTx`).
- I badge della dashboard Home ora mostrano coerentemente il protocollo corretto per tutta la durata dell'hangtime, sia dopo un passaggio voce che dopo un beacon di rete.
2026-11-01 09:31:40 +01:00
iv3jdv bf4a669446 fix badge color 2026-10-31 21:42:26 +01:00
iv3jdv e92a37f02a fix(modes): visibilità pannello admin e sincronizzazione hangtime MQTT
- Nascosto il pannello "Operating Modes" per gli utenti non autenticati o senza permessi admin, risolvendo l'errore 403 e il falso allarme "CFG MEMORY EMPTY".
- Risolto il bug dell'hangtime RF (Hold) a fine trasmissione: rimosso il timer asincrono locale lato frontend.
- La UI ora legge lo stato di hold sincronizzandosi esclusivamente col flag "idle" in arrivo dal broker MQTT (MMDVMHost).
- Mantenimento corretto a schermo dell'ultimo modo operativo utilizzato (es. [ DMR ] o [ NXDN ]) durante l'intera durata della coda del ponte.
2026-10-31 21:18:33 +01:00
iv3jdv 2456f462fe fix secure mode change 2026-10-31 20:49:05 +01:00
iv3jdv 34180df506 feat(modes): controllo interattivo modi operativi MMDVM e sync gateway
- Aggiunti pulsanti toggle interattivi per DMR, YSF, D-Star, NXDN e P25 nella vista Focus
- Aggiornamento automatico e persistenza del file di configurazione MMDVMHost
- Sincronizzazione automatica start/stop dei relativi demoni Gateway al cambio modo
- Aggiornamento ottimistico dell'interfaccia utente con feedback visivo immediato
- Allineamento immediato della cache backend in memoria al salvataggio config
2026-10-31 20:27:16 +01:00
iv3jdv 99c5d4f431 fix enable/disable mode 2026-10-31 16:45:20 +01:00
iv3jdv c47377a22c add enable/disable mode 2026-10-31 16:32:31 +01:00
iv3jdv b684976665 fix get data 2026-10-31 15:50:40 +01:00
iv3jdv 77edeef8ac fix dstar mode tx 2026-10-31 15:20:08 +01:00
iv3jdv 68fe4f9d61 fix header badge align 2026-10-31 15:03:23 +01:00
iv3jdv eea2fae2d4 remove backdrop-filter: blur() 2026-10-31 14:50:27 +01:00
iv3jdv ea505f22aa restore hangtime/idle 2026-10-31 14:40:36 +01:00
iv3jdv 5a21cf8eb9 add color tx mode badge 2026-10-31 14:31:17 +01:00
iv3jdv 793b06b4e3 feat: aggiunta Focus Mode e tab decodifica traffico APRS 2026-10-31 13:58:04 +01:00
iv3jdv 2ed2ea58ea feat: implementato nuovo layout Blueprint CAD 2026-10-31 12:32:59 +01:00
iv3jdv 35f1598393 feat(ui): feedback visivo TX sui mini-badge della home
Implementato il riconoscimento dello stato di trasmissione nei mini-badge della schermata principale. I badge ora si illuminano mostrando '🎙️ TX' con bordo e ombreggiatura dinamica abbinata al colore del modo digitale attivo (DMR, YSF, NXDN, ecc.), prioritizzando la visibilità del transito.
2026-10-25 15:52:10 +01:00
iv3jdv 9a4dc1eea7 feat(mqtt): supporto coordinate e info da DMRGateway
Aggiunto 'dmrgateway' ai topic validi per il recupero dei dati di geolocalizzazione (Lat, Lon, Loc). Implementato il merge incrementale dei parametri per permettere a MMDVMHost e DMRGateway di popolare le info del nodo senza sovrascriversi a vicenda, in previsione della deprecazione della sezione [Info] su MMDVM.
2026-10-25 15:22:51 +01:00
iv3jdv be0cbbb64b fix scroll home 2026-10-25 12:42:55 +01:00
iv3jdv 6d11c355df fix(watchdog): ridotta finestra temporale alert BER a 5 minuti
Aggiornata la query di analisi diagnostica nel watchdog per calcolare la media del BER sugli ultimi 5 minuti (invece di 2 ore). Ridotto il numero minimo di transiti necessari per l'innesco, garantendo un feedback immediato nella dashboard e la scomparsa rapida dell'allarme in assenza di traffico degradato.
2026-10-25 12:28:20 +01:00
iv3jdv efca23c64f feat(logs): limite configurabile e selettore righe Last Heard con i18n
Aggiunto il supporto per definire il numero di righe del Last Heard tramite configurazione (config.json) e query string (?limit=). Inserito nel frontend un selettore a tendina con persistenza in localStorage ed etichetta bilingue (IT/EN).
2026-10-25 11:54:20 +01:00
iv3jdv 69308c4580 fix(mqtt): parsing intelligente stati gateway YSF e NXDN" -m "Risolto il problema di visualizzazione dei badge YSF e NXDN nella dashboard. Aggiunto il parsing testuale dei messaggi MQTT per intercettare correttamente le connessioni ('Linked to', 'Switched to reflector') e le disconnessioni ('stopping'), ignorando i messaggi di heartbeat ed evitando che la fase di avvio cancelli lo stato del reflector appena agganciato 2026-10-25 11:14:09 +01:00
iv3jdv a39389fe1a docs: aggiornamento finale README dopo sincronizzazione 2026-10-25 09:14:27 +01:00
iv3jdv a934a53898 feat(ui): aggiunti link a qrz.com per i nominativi nel last heard
Resi cliccabili i nominativi radio nella tabella dei log. Cliccando su un callsign si apre automaticamente la relativa pagina di ricerca su QRZ.com in una nuova scheda, filtrando in automatico gli ID di rete o puramente numerici.
2026-10-25 09:13:03 +01:00
iv3jdv 81eff4300d Update README.md 2026-10-24 19:26:58 +02:00
iv3jdv b6f1993e26 update CSS 2026-10-24 18:55:05 +02:00
iv3jdv 164525e035 add HANG_TIME 2026-10-24 18:16:46 +02:00
iv3jdv 21f971b205 Refactor v5.0: Architettura modulare backend/frontend e PWA v6 2026-10-24 17:58:56 +02:00
iv3jdv 86899aebb9 fix Badge alignment 2026-10-24 16:12:25 +02:00
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
iv3jdv 951396563a Release 3.0: Nuovo design Soft UI, Fleet Status centrato e fix vari 2026-10-24 12:25:27 +02:00
iv3jdv 000ac4f530 fix badge 2026-10-23 00:06:58 +02:00
iv3jdv 891c995cc0 fix hash client display 2026-10-22 23:53:18 +02:00
iv3jdv a3031ce33f update 2026-10-22 23:17:29 +02:00
iv3jdv 47b4bed21f update 2026-10-22 22:54:30 +02:00
iv3jdv 7a9008de78 update 2026-10-22 22:53:42 +02:00
iv3jdv dad1a656fe update 2026-10-22 22:35:51 +02:00
iv3jdv b33d495474 add agent version 2026-10-22 21:47:57 +02:00
iv3jdv 38f7efce6b add OTAcClient update signal 2026-10-22 18:59:09 +02:00
iv3jdv 24c81c1abb update CCS class 2026-10-22 14:01:58 +02:00
iv3jdv 126ad8cdaf add update logging 2026-10-22 13:21:19 +02:00
iv3jdv 2f0abdc9bf add Server OTA Update 2026-10-22 13:11:46 +02:00
iv3jdv a1449eedfb add Telemetry node Uptime 2026-10-22 12:52:10 +02:00
iv3jdv 2fa1b476c4 feat(ui): mostrato hash e messaggio dell'ultimo commit nel footer tramite subprocess 2026-10-22 01:36:35 +02:00
iv3jdv 8ce2ed243d fix/feat: stabilizzazione dashboard in tempo reale e log dinamici
- Modificato app.py per leggere i parametri del RotatingFileHandler dal config.json, permettendo la regolazione dello spazio su disco senza toccare il codice.
- Identificato e risolto il bug degli azzeramenti della tabella Lastheard (causato da un fallback continuo di Socket.IO a causa della mancata direttiva Upgrade nei reverse proxy)
2026-10-20 21:37:18 +02:00
iv3jdv 8ee2958b8e fix(dmr): risolto campo source mancante nei log
- MMDVMHost omette il campo source nel payload JSON dell'azione end per il DMR.
- Aggiunto il salvataggio in RAM di  e  (su active_calls) durante l'evento start.
- Ripristinata l'iniezione di questi dati prima della scrittura nel DB SQLite.
- Ora i badge RF/NET e la telemetria estesa funzionano correttamente anche sul DMR
2026-10-20 17:53:55 +02:00
iv3jdv 298478e36d feat(dashboard): estensione filtro nodo globale sulla UI
- Aggiunto  all'evento onchange del menu a tendina.
- Implementata logica lato client in index.html per filtrare dinamicamente i transiti.
- Ora la selezione di un singolo nodo isola sia i widget statistici che lo storico dei log sottostante, senza interferire con i log grezzi della vista NODES
2026-10-20 17:39:22 +02:00
iv3jdv 502244dff4 feat(dashboard): aggiunte colonne Source e YSF Mode, fix visibilità CQCQCQ per D-STAR e DG-ID per C4FM 2026-10-20 17:17:48 +02:00
iv3jdv c5dcacefd1 fix(mqtt): previene eccezione di decodifica su payload sporchi
- Aggiunto  alla decodifica dei messaggi MQTT in app.py.
- Evita che errori come UnicodeDecodeError (es. byte 0xb2) scartino interi pacchetti validi.
- Ora gli alias radio o i beacon con caratteri speciali/obsoleti vengono gestiti senza bloccare la visualizzazione del transito sulla dashboard
2026-10-20 15:34:46 +02:00
iv3jdv cae5c4ea83 fix(dashboard): refactoring colonne Target e REF/SLOT
- Separata la destinazione radio (Target) dall'infrastruttura di rete (REF/SLOT).
- Risolto il bug dei moduli D-STAR troncati causato dai beacon INFO locali di MMDVMHost.
- La colonna Target ora mostra l'UR CALL reale, mentre REF/SLOT usa in modo esclusivo la memoria di linking iniziale.
- Aggiornati index.html (nuova UI) e la logica di parsing/salvataggio in app.py.
2026-10-20 14:27:47 +02:00
iv3jdv 445cc5e97d refactor: rimossa etichetta Network dai Time Slot nell'interfaccia
Rimossa l'estrazione MQTT in app.py e la visualizzazione frontend (es. [BM]) accanto a TS1 e TS2. Il mapping esclusivo non è più coerente quando si utilizzano configurazioni multi-network con politiche di TGRewrite avanzate.
2026-10-19 22:49:42 +02:00
iv3jdv c502da2dfb update 2026-10-19 21:22:21 +02:00
iv3jdv 3b45c14ded frequency precision display 2026-10-18 13:49:21 +02:00
iv3jdv 255066eefa Delete system_monitor.py 2026-10-17 18:50:35 +02:00
iv3jdv 74d7910fec Upload files to "/" 2026-10-17 18:48:51 +02:00
iv3jdv bcb885c878 Merge pull request 'update' (#6) from develop into main
Reviewed-on: #6
2026-10-17 18:36:45 +02:00
iv3jdv 3f59b905c7 update 2026-10-17 18:35:22 +02:00
iv3jdv 869b09f8a9 Merge pull request 'update index.html' (#5) from develop into main
Reviewed-on: #5
2026-10-16 23:49:36 +02:00
iv3jdv bdfc4043f8 update index.html 2026-10-16 23:48:27 +02:00
iv3jdv caf77819a2 Merge pull request 'update index.html' (#4) from develop into main
Reviewed-on: #4
2026-10-16 21:01:30 +02:00
iv3jdv 47e51e10f0 update index.html 2026-10-16 21:00:21 +02:00
iv3jdv d56d3d6b5b Merge pull request 'update index.html' (#3) from develop into main
Reviewed-on: #3
2026-10-16 20:48:43 +02:00
iv3jdv cd2960d00b update index.html 2026-10-16 20:45:13 +02:00
iv3jdv 95b5dd4cbc update index.html 2026-10-16 20:41:36 +02:00
iv3jdv 74d7c41b93 enhanceded RSSI 2026-10-16 20:31:23 +02:00
iv3jdv cf4dd93c06 Merge pull request 'add RSSI data' (#2) from develop into main
Reviewed-on: #2
2026-10-16 19:51:12 +02:00
iv3jdv 9fb0b01f30 add RSSI data 2026-10-16 19:39:58 +02:00
28 changed files with 6236 additions and 2657 deletions
+41
View File
@@ -0,0 +1,41 @@
# Modifiche di sicurezza e correzioni / Security fixes & changes
Tutte le modifiche mantengono il comportamento precedente **per default**; ciò che cambia
visibilmente è indicato esplicitamente. / Every change keeps the previous behaviour **by default**;
visible differences are listed explicitly.
## Correzioni attive subito / Active immediately
| # | Modifica | Effetto visibile |
|---|----------|------------------|
| 1 | **Scheduler**: i profili/comandi vengono validati come in `/api/command`. `REBOOT`, `RESET_HAT`, `UPDATE_AGENT` possono essere schedulati solo da un `admin` (controllo al salvataggio **e** all'esecuzione). I nodi target vengono validati. | Un `node_admin` non può più programmare comandi riservati agli admin. Schedulazioni già presenti create da non-admin con quei comandi non vengono più eseguite (warning nel log). |
| 2 | **WebSocket `live_log_<nodo>`**: inviato solo ai socket con sessione valida **e** autorizzati su quel nodo (ruolo/`allowed_nodes` rivalidati ogni 2 min). | Nessuno per l'uso normale: la console log già richiedeva il login via `/api/logs/<nodo>`. Chi non è loggato non riceve più i log in diretta. |
| 3 | **Rate limit login dietro reverse proxy**: se la richiesta arriva da loopback con `X-Forwarded-For`, si usa l'IP reale (ultimo valore, aggiunto dal proxy). Con `trust_proxy: true` il comportamento è invariato. | Un utente che sbaglia la password non blocca più il login a tutti gli altri. |
| 4 | **Scheduler su thread dedicato**: non è più ritardato dal download degli ID DMR/NXDN. | Le schedulazioni partono puntuali anche durante i download. |
| 5 | **Pruning**: `telemetry_logs` (default 90 giorni) e `config_backups` (ultimi 100 per nodo/servizio) ora vengono potati. | Dati più vecchi di quelle soglie vengono eliminati; configurabile (0 = disattiva). |
| 6 | `save_to_sqlite` chiude sempre la connessione; `__main__` usa `web.port`; emoji corrotta nel log; `test-push.py` funzionante; nomi file in `install.txt` corretti; `chart.js` fissato alla versione 4.4.1. | Nessuno. |
## Opzioni nuove (tutte disattivate / invariate di default) / New opt-in options
Nel blocco `web` di `config.json` (vedi `config.json.example`):
* `require_login_for_read: true` – richiede il login per `/api/states`, `/api/logs`, `/api/stats`, `/api/clients` e limita `aprs_msg` ai soli utenti loggati. **Attenzione:** la vista pubblica della dashboard resterà vuota finché non si fa il login.
* `cors_origins: "https://tuo.dominio"` – restringe le origini ammesse per Socket.IO (default `"*"`, invariato).
* `ota_enabled: false` – disabilita l'aggiornamento OTA da interfaccia (`git pull` + riavvio).
* `trust_proxy`, `cookie_secure` (consigliato `true` dietro HTTPS), `session_hours`.
Nel blocco `mqtt`: `"tls": true` (+ `"ca_certs"`, porta tipicamente 8883) per cifrare la connessione al broker.
Altre chiavi: `telemetry_retention_days`, `config_backups_keep`.
## Non modificato di proposito / Deliberately left as is
* **Servizio come root e bind su 0.0.0.0**: cambiarlo di default romperebbe le installazioni esistenti
(permessi su cartella/log, accesso diretto alla porta 9000). È incluso
`systemd/fleet-console.hardened.service.example` con utente dedicato e hardening, da adottare quando vuoi.
* **CSP e SRI**: la UI usa molti stili e handler inline, quindi una CSP rigida la romperebbe; l'SRI richiede
gli hash delle librerie (calcolabili con `curl -s URL | openssl dgst -sha384 -binary | openssl base64 -A`).
* **Broker MQTT**: l'autenticazione dei messaggi e le ACL per nodo si configurano sul broker (es. Mosquitto
`acl_file`), non nel server.
* **Backup di config in chiaro**: i file `.ini` salvati in `config_backups` possono contenere password di rete.
Proteggere `monitor.db` con permessi `600`.
* **Schedulazioni sovrapposte** sugli stessi nodi e ripristino del "profilo precedente": non gestiti.
+72 -142
View File
@@ -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,173 +14,103 @@
> ℹ️ **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:
* **Backend:** Flask (Python) with `gevent` for high-concurrency handling.
* **Database:** SQLite (WAL mode) for robust User Management, Audit Logs, and Radio Traffic storage.
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, 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* NOC (Network Operations Center) design.
* **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)
#### ⚡ 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, instantly alerting you if the backend loses connectivity.
* **PWA Ready:** Install the dashboard as a Progressive Web App on iOS/Android for a native, full-screen mobile experience.
#### 🗓️ 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.
#### 🔔 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).
* Works securely even when the web app is closed or in the background.
#### 🗺️ 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.
#### 🛠️ 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.
#### 📈 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.
#### 🔐 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.
**Pro Tip:** You can use Let's Encrypt to get a free SSL certificate for your domain.
**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.
#### 🛠️ Advanced Remote Control & Maintenance
* **Remote .INI Editor:** Edit daemon configuration files (e.g., MMDVMHost.ini) directly from the web interface without SSH access.
* **Service Management:** Start, Stop, or Restart remote system daemons with a single click.
* **Global Overrides:** Switch profiles (e.g., Profile A/B) or force updates simultaneously on all nodes in the fleet.
* **Hardware Interventions:** Trigger a physical OS reboot or a hard GPIO reset of the MMDVM HAT directly from the web panel.
#### 📊 Unified Monitoring & Statistics
* **Live Heard Log:** A centralized view of radio traffic across the entire network, auto-resolving DMR and NXDN IDs into callsigns.
* **Real-Time Telemetry:** Monitor CPU, RAM, Disk, and Temperature for every connected node.
* **Daily Analytics:** Automatically tracks Top Talkgroups, Top Callsigns, Average duration, and daily transit counts.
#### 🔐 Security & Access Control
* **Role-Based Access Control (RBAC):** Create `admin` and `operator` accounts.
* **Granular Permissions:** Restrict operators to view/control only specific repeaters.
* **Audit Trail:** Every critical action (reboots, config edits, daemon restarts) is logged with the username, timestamp, and target node.
### 🚀 Installation Guide
#### 0. Root Privileges
All installation steps must be executed as the `root` user. Before starting, elevate your privileges by running:
### ⚠️ Reverse Proxy & WebSocket Configuration
If using a reverse proxy like **Apache** on HTTPS, you must enable WebSocket tunneling:
```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://tuo-gitea.com/utente/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
sudo a2enmod proxy_wstunnel rewrite headers
```
Insert the **Rewrite** rules *before* the `ProxyPass` directives in your `<VirtualHost *:443>`:
```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]
#### 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).*
ProxyPass /socket.io/ ws://127.0.0.1:9000/socket.io/
ProxyPassReverse /socket.io/ ws://127.0.0.1:9000/socket.io/
#### 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
ProxyPass / http://127.0.0.1:9000/
ProxyPassReverse / http://127.0.0.1:9000/
```
*(Ensure the `.service` file points to the `gunicorn` executable inside your `venv`)*.
---
<a name="italiano"></a>
## 🇮🇹 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:
* **Backend:** Flask (Python) con `gevent` per la gestione ad alta concorrenza.
* **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 un moderno design *Glassmorphism* in stile NOC (Network Operations Center).
### 🏗️ 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 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
#### ⚡ 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, avvisandoti istantaneamente in caso di problemi di rete.
* **PWA Ready:** Installabile su smartphone Android e iOS come Progressive Web App per un'esperienza nativa a schermo intero.
#### 🗓️ 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.
#### 🔔 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).
* Funzionano in modo sicuro anche quando la web app è chiusa o in background.
#### 🗺️ 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à.
### ⚠️ 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.
**Suggerimento:** Puoi usare Let's Encrypt per ottenere un certificato SSL gratuito per il tuo dominio.
#### 🛠️ 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
* **Editor .INI Remoto:** Modifica i file di configurazione (es. MMDVMHost.ini) direttamente dal pannello web, senza bisogno di accessi SSH.
* **Gestione Demoni:** Avvia, arresta o riavvia i servizi di sistema remoti con un clic.
* **Override Globali:** Cambia i profili operativi (es. Profilo A/B) simultaneamente su tutta la rete.
* **Interventi Hardware:** Innesca un riavvio del sistema operativo o un reset fisico (tramite pin GPIO) della scheda MMDVM direttamente dall'interfaccia web.
#### 📊 Monitoraggio & Statistiche
* **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.
* **Telemetria in Diretta:** Monitora l'utilizzo di CPU, RAM, Disco e le Temperature per ogni nodo connesso.
* **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
* **Gestione Ruoli (RBAC):** Creazione di account `admin` e `operator`.
* **Permessi Granulari:** Limita un operatore al controllo e alla visualizzazione di specifici ripetitori.
* **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.
### 🚀 Guida all'Installazione
#### 0. Privilegi di Root
Tutti i passaggi di installazione devono essere eseguiti come utente `root`. Prima di iniziare, eleva i tuoi privilegi eseguendo:
```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://tuo-gitea.com/utente/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).*
#### 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*
### ⚠️ Sicurezza Richiesta: HTTPS
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.
+93 -1349
View File
File diff suppressed because it is too large Load Diff
+21 -3
View File
@@ -15,8 +15,10 @@
"dstar-gateway/+/json",
"mmdvm/+/json",
"devices/#",
"data/#"
]
"data/#",
"aprs-gateway/aprs"
],
"tls": false
},
"web_admin": {
"default_user": "admin",
@@ -37,5 +39,21 @@
"id_urls": {
"dmr": "https://radioid.net/static/dmrid.dat",
"nxdn": "https://radioid.net/static/nxdn.csv"
}
},
"log_max_mb": 50,
"log_backup_count": 10,
"last_heard_limit": 60,
"web": {
"port": 9000,
"cookie_secure": false,
"session_hours": 12,
"trust_proxy": false,
"cors_origins": "*",
"require_login_for_read": false,
"ota_enabled": true
},
"retention_days": 90,
"audit_retention_days": 365,
"telemetry_retention_days": 90,
"config_backups_keep": 100
}
View File
+70
View File
@@ -0,0 +1,70 @@
import os
import json
import secrets
import logging
import threading
from logging.handlers import RotatingFileHandler
# --- PERCORSI DINAMICI ---
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DB_PATH = os.path.join(BASE_DIR, 'monitor.db')
CACHE_FILE = os.path.join(BASE_DIR, 'telemetry_cache.json')
CONFIG_PATH = os.path.join(BASE_DIR, 'config.json')
DMR_IDS_PATH = os.path.join(BASE_DIR, 'dmrid.dat')
NXDN_IDS_PATH = os.path.join(BASE_DIR, 'nxdn.csv')
CLIENTS_PATH = os.path.join(BASE_DIR, 'clients.json')
LOG_FILE = os.path.join(BASE_DIR, 'fleet_console.log')
# --- CONFIG LOADER ---
config_lock = threading.Lock()
def read_config():
try:
with open(CONFIG_PATH, 'r') as f:
return json.load(f)
except Exception:
return {}
def write_config(cfg):
tmp = CONFIG_PATH + '.tmp'
with config_lock:
with open(tmp, 'w') as f:
json.dump(cfg, f, indent=4)
try:
os.chmod(tmp, os.stat(CONFIG_PATH).st_mode & 0o777)
except OSError:
pass
os.replace(tmp, CONFIG_PATH)
config = read_config()
web_cfg = config.get('web', {})
# --- LOGGING ROTATIVO ---
log_max_mb = int(config.get('log_max_mb', 50))
log_backup_count = int(config.get('log_backup_count', 10))
max_bytes_val = log_max_mb * 1024 * 1024 if log_max_mb > 0 else 0
logging.basicConfig(
handlers=[
RotatingFileHandler(LOG_FILE, maxBytes=max_bytes_val, backupCount=log_backup_count),
logging.StreamHandler()
],
level=logging.INFO,
format='[%(asctime)s] %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger("FleetHub")
logging.getLogger('werkzeug').setLevel(logging.ERROR)
def get_secret_key():
key = os.environ.get('FLEET_SECRET_KEY') or config.get('secret_key')
if not key or key == 'ari_fvg_secret_ultra_secure':
key = secrets.token_hex(32)
config['secret_key'] = key
try:
write_config(config)
logger.warning("🔑 Nuova secret_key generata e salvata in config.json.")
except Exception as e:
logger.error(f"Impossibile salvare la secret_key in config.json ({e}).")
return key
+168
View File
@@ -0,0 +1,168 @@
import sqlite3
import secrets
from contextlib import closing
from werkzeug.security import generate_password_hash
from core.config import DB_PATH, config, read_config, logger
from core.state import notify_update
def db_connect(row=False):
conn = sqlite3.connect(DB_PATH, timeout=10)
if row:
conn.row_factory = sqlite3.Row
return conn
def init_db():
conn = sqlite3.connect(DB_PATH, timeout=10)
c = conn.cursor()
c.execute('PRAGMA journal_mode=WAL;')
c.execute('''CREATE TABLE IF NOT EXISTS radio_logs
(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, client_id TEXT,
source_id TEXT, target TEXT, slot INTEGER, duration REAL, ber REAL, loss REAL)''')
try:
c.execute("ALTER TABLE radio_logs ADD COLUMN protocol TEXT DEFAULT 'DMR'")
except sqlite3.OperationalError: pass
try:
c.execute("ALTER TABLE radio_logs ADD COLUMN source_ext TEXT DEFAULT ''")
except sqlite3.OperationalError: pass
try:
c.execute("ALTER TABLE radio_logs ADD COLUMN rssi REAL DEFAULT 0")
except sqlite3.OperationalError: pass
try:
c.execute("ALTER TABLE radio_logs ADD COLUMN source_conn TEXT DEFAULT ''")
except sqlite3.OperationalError: pass
try:
c.execute("ALTER TABLE radio_logs ADD COLUMN ysf_mode TEXT DEFAULT ''")
except sqlite3.OperationalError: pass
c.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password_hash TEXT,
role TEXT, allowed_nodes TEXT)''')
c.execute('''CREATE TABLE IF NOT EXISTS push_subscriptions
(id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, subscription TEXT UNIQUE)''')
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)")
c.execute("CREATE INDEX IF NOT EXISTS idx_audit_logs_ts ON audit_logs(timestamp)")
c.execute("SELECT COUNT(*) FROM users")
if c.fetchone()[0] == 0:
adm_cfg = config.get("web_admin", {})
def_user = adm_cfg.get("default_user", "admin")
def_pass = adm_cfg.get("default_pass", "")
generated = False
if not def_pass or def_pass == "admin123":
def_pass = secrets.token_urlsafe(9)
generated = True
c.execute("INSERT INTO users (username, password_hash, role, allowed_nodes) VALUES (?,?,?,?)",
(def_user, generate_password_hash(def_pass), 'admin', 'all'))
if generated:
logger.warning(f">>> DEFAULT USER CREATED - User: {def_user} | Temporary password: {def_pass} | CHANGE IT NOW <<<")
else:
logger.info(f">>> DEFAULT USER CREATED - User: {def_user} (password from config.json) <<<")
conn.commit()
conn.close()
def save_to_sqlite(client_id, data, protocol="DMR"):
conn = sqlite3.connect(DB_PATH, timeout=10)
try:
_save_to_sqlite(conn, client_id, data, protocol)
finally:
conn.close()
notify_update('log_aggiornato')
def _save_to_sqlite(conn, client_id, data, protocol):
c = conn.cursor()
rssi_val = 0
if 'rssi' in data and isinstance(data['rssi'], dict):
rssi_val = data['rssi'].get('ave', 0)
elif 'rssi' in data:
rssi_val = data['rssi']
c.execute("""INSERT INTO radio_logs
(timestamp, client_id, protocol, source_id, target, slot, duration, ber, source_ext, rssi, source_conn, ysf_mode)
VALUES (datetime('now', 'localtime'), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(client_id, protocol, str(data.get('src_id', '---')), str(data.get('dst_id', '---')),
data.get('slot', 0), round(data.get('duration', 0), 1), round(data.get('ber', 0), 2),
str(data.get('src_ext', '')), rssi_val, str(data.get('source', '')), str(data.get('mode', ''))))
conn.commit()
def audit(username, client_id, command):
try:
with closing(db_connect()) as conn:
conn.execute("INSERT INTO audit_logs (timestamp, username, client_id, command) VALUES (datetime('now','localtime'), ?, ?, ?)",
(username, client_id, command))
conn.commit()
except Exception as e:
logger.error(f"Audit log error: {e}")
def prune_old_data():
try:
cfg = read_config()
radio_days = int(cfg.get("retention_days", 90))
audit_days = int(cfg.get("audit_retention_days", 365))
with closing(db_connect()) as conn:
c = conn.cursor()
c.execute("DELETE FROM radio_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{radio_days} days",))
n1 = c.rowcount
c.execute("DELETE FROM audit_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{audit_days} days",))
n2 = c.rowcount
# Telemetria e backup config non venivano mai potati (default generosi, configurabili)
tele_days = int(cfg.get("telemetry_retention_days", 90))
n3 = 0
if tele_days > 0:
c.execute("DELETE FROM telemetry_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{tele_days} days",))
n3 = c.rowcount
keep = int(cfg.get("config_backups_keep", 100))
n4 = 0
if keep > 0:
c.execute("""DELETE FROM config_backups WHERE id NOT IN (
SELECT id FROM config_backups b
WHERE b.client_id = config_backups.client_id AND b.service = config_backups.service
ORDER BY id DESC LIMIT ?)""", (keep,))
n4 = c.rowcount
conn.commit()
if n1 or n2 or n3 or n4:
logger.info(f"🧹 Pulizia DB: {n1} ascolti, {n2} audit, {n3} telemetrie e {n4} backup config 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}")
+10
View File
@@ -0,0 +1,10 @@
"""Controllo permessi sui nodi, condiviso da API, push e WebSocket (nessuna dipendenza interna)."""
def node_allowed(role, allowed_nodes, cid):
if role == 'admin':
return True
allowed = (allowed_nodes or '').strip().lower()
if allowed == 'all':
return True
return cid in [x.strip().lower() for x in allowed.split(',') if x.strip()]
+169
View File
@@ -0,0 +1,169 @@
import os
import json
import time
import threading
import sqlite3
from contextlib import closing
from flask_socketio import SocketIO
from core.config import CACHE_FILE, DB_PATH, DMR_IDS_PATH, NXDN_IDS_PATH, logger, web_cfg
from core.permissions import node_allowed
# --- WEBSOCKET SOCKETIO ---
socketio = SocketIO(cors_allowed_origins=web_cfg.get('cors_origins', '*'))
# --- NOTIFICHE WEBSOCKET ---
NOTIFY_DELAY = 0.3
_notify_lock = threading.Lock()
_notify_pending = set()
def notify_update(event='dati_aggiornati'):
with _notify_lock:
if event in _notify_pending:
return
_notify_pending.add(event)
def _fire():
with _notify_lock:
_notify_pending.discard(event)
try:
socketio.emit(event)
except Exception as e:
logger.error(f"Errore emit WebSocket '{event}': {e}")
timer = threading.Timer(NOTIFY_DELAY, _fire)
timer.daemon = True
timer.start()
# --- STATI GLOBALI IN MEMORIA ---
START_TIME = time.time()
client_states = {}
device_configs = {}
client_telemetry = {}
last_notified_errors = {}
device_health = {}
last_seen_reflector = {}
node_info = {}
node_general = {}
node_versions = {}
gateway_states = {}
active_warnings = {}
active_calls = {}
operating_modes = {}
node_logs = {} # In-memory circular buffer for live logs
connected_web_clients = set()
active_logged_users = {}
socket_auth = {} # sid -> {"username","role","allowed_nodes","ts"} (solo socket con sessione valida)
auth_lookup = None # impostato da app.py: username -> dict auth aggiornato oppure None
AUTH_REFRESH_SEC = 120
def emit_to_authorized(event, data, cid=None):
"""Invia l'evento solo ai socket autenticati (e, se cid e' dato, autorizzati su quel nodo)."""
now = time.time()
for sid, a in list(socket_auth.items()):
try:
# Rilegge periodicamente ruolo/nodi: utenti rimossi o declassati perdono l'accesso live
if auth_lookup and now - a.get('ts', 0) > AUTH_REFRESH_SEC:
fresh = auth_lookup(a['username'])
if not fresh:
socket_auth.pop(sid, None)
continue
a.update(fresh)
a['ts'] = now
if cid is None or node_allowed(a.get('role'), a.get('allowed_nodes'), cid):
socketio.emit(event, data, to=sid)
except Exception as e:
logger.error(f"emit_to_authorized '{event}': {e}")
def emit_aprs(data):
"""APRS live: broadcast come prima, oppure solo utenti loggati se web.require_login_for_read."""
if web_cfg.get('require_login_for_read'):
emit_to_authorized('aprs_msg', data)
else:
socketio.emit('aprs_msg', data)
# Caricamento iniziale cache telemetria
if os.path.exists(CACHE_FILE):
try:
with open(CACHE_FILE, 'r') as f:
client_telemetry = json.load(f)
except Exception:
client_telemetry = {}
def save_cache(data):
try:
tmp = CACHE_FILE + '.tmp'
with open(tmp, 'w') as f:
json.dump(data, f)
os.replace(tmp, CACHE_FILE)
except Exception as e:
logger.error(f"Errore salvataggio cache telemetria: {e}")
notify_update()
# --- GESTIONE LAST SEEN ---
last_seen = {}
last_seen_lock = threading.Lock()
def touch_seen(cid, kind):
with last_seen_lock:
last_seen.setdefault(cid, {})[kind] = time.time()
def seen_ages():
now = time.time()
with last_seen_lock:
return {cid: {k: round(now - ts, 1) for k, ts in kinds.items()} for cid, kinds in last_seen.items()}
def seed_last_seen():
try:
with closing(sqlite3.connect(DB_PATH, timeout=10)) as conn:
rows = conn.execute("""SELECT LOWER(client_id), MAX(timestamp) FROM radio_logs
WHERE source_id NOT LIKE '🌐%' GROUP BY LOWER(client_id)""").fetchall()
for cid, ts in rows:
try:
parsed = time.mktime(time.strptime(ts, '%Y-%m-%d %H:%M:%S'))
except (TypeError, ValueError):
continue
with last_seen_lock:
last_seen.setdefault(cid, {}).setdefault('mmdvm', parsed)
except Exception as e:
logger.error(f"seed_last_seen: {e}")
# --- DATABASE ID DMR / NXDN ---
user_db = {}
nxdn_db = {}
def load_ids():
global user_db, nxdn_db
new_dmr, new_nxdn = {}, {}
if os.path.exists(DMR_IDS_PATH):
with open(DMR_IDS_PATH, 'r', encoding='utf-8', errors='ignore') as f:
for l in f:
l = l.replace('"', '')
if ',' in l: p = l.strip().split(',')
elif '\t' in l: p = l.strip().split('\t')
elif ';' in l: p = l.strip().split(';')
else: p = l.strip().split()
if len(p) >= 2 and p[0].strip().isdigit():
new_dmr[p[0].strip()] = p[1].strip()
if os.path.exists(NXDN_IDS_PATH):
with open(NXDN_IDS_PATH, 'r', encoding='utf-8', errors='ignore') as f:
for l in f:
sep = '\t' if '\t' in l else (',' if ',' in l else ';')
p = l.strip().split(sep)
if len(p) >= 2 and p[0].strip().isdigit():
new_nxdn[p[0].strip()] = p[1].strip()
if new_dmr: user_db = new_dmr
if new_nxdn: nxdn_db = new_nxdn
def get_call(id_val, proto="DMR"):
sid = str(id_val)
if proto == "NXDN":
return nxdn_db.get(sid, sid)
return user_db.get(sid, sid)
# Inizializzazione automatica ID
load_ids()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 34 KiB

+6 -6
View File
@@ -1,5 +1,5 @@
============================================================
INSTALLATION GUIDE - FLEET CONTROL CONSOLE (SERVER)
INSTALLATION GUIDE - FLEET CONTROL CONSOLE (v6.0.0)
============================================================
------------------------------------------------------------
@@ -36,7 +36,7 @@ Install project requirements:
The server handles the web interface and user permissions.
Steps:
1. Configure 'config.json' using 'config.example.json'.
1. Configure 'config.json' using 'config.json.example'.
2. Enter MQTT credentials and VAPID keys.
3. Define repeaters in the 'clients.json' file.
4. Install production WSGI server packages (if not in requirements):
@@ -59,7 +59,7 @@ They will NOT work over standard HTTP.
4. RUNNING AS A SERVICE (SYSTEMD)
------------------------------------------------------------
⚠️ IMPORTANT (VENV USERS): Before copying the service file,
open 'fleet-control.service' and ensure the paths point to your
open 'fleet-console.service' and ensure the paths point to your
virtual environment.
Example:
@@ -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)
============================================================
------------------------------------------------------------
@@ -110,7 +110,7 @@ Installa i requisiti del progetto:
2. SETUP DEL SERVER
------------------------------------------------------------
Passaggi:
1. Configura 'config.json' partendo da 'config.example.json'.
1. Configura 'config.json' partendo da 'config.json.example'.
2. Inserisci credenziali MQTT e chiavi VAPID.
3. Definisci i ripetitori in 'clients.json'.
4. Avvia il server di produzione:
@@ -128,7 +128,7 @@ Passaggi:
4. ESECUZIONE COME SERVIZIO (SYSTEMD)
------------------------------------------------------------
⚠️ IMPORTANTE (PER UTENTI VENV): Prima di copiare il file di
servizio, apri 'fleet-control.service' e assicurati che i percorsi
servizio, apri 'fleet-console.service' e assicurati che i percorsi
puntino al tuo ambiente virtuale!
Esempio:
View File
+748
View File
@@ -0,0 +1,748 @@
import os
import re
import json
import time
import sqlite3
import subprocess
from contextlib import closing
from flask import Blueprint, request, jsonify, send_from_directory
from core.config import (
BASE_DIR, CLIENTS_PATH, DB_PATH, config, read_config, write_config, logger
)
from core.database import db_connect, audit
import core.state as state
from services.mqtt_service import mqtt_publish
from services.push_service import node_allowed
from routes.auth_routes import get_auth, json_body, err
from services.scheduler_service import PRIVILEGED_COMMANDS as SCHED_PRIVILEGED
# --- AGGIUNTE PER GITEA BACKGROUND CHECK ---
GLOBAL_SERVER_UPDATE_AVAILABLE = False
LAST_GITEA_CHECK_TIME = 0
api_bp = Blueprint('api', __name__)
# --- REGEX & COSTANTI COMANDI ---
CID_RE = re.compile(r'^[a-z0-9][a-z0-9_\-]{0,63}$')
SERVICE_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.@\-]{0,63}$')
PROFILE_KEY_RE = re.compile(r'^[A-Za-z0-9_\-]{1,32}$')
TIME_RE = re.compile(r'^([01]\d|2[0-3]):[0-5]\d$')
SIMPLE_COMMANDS = {'TG:ON', 'TG:OFF'}
PRIVILEGED_COMMANDS = {'REBOOT', 'RESET_HAT', 'UPDATE_AGENT'}
SERVICE_ACTIONS = {'start', 'stop', 'restart'}
def known_profile_keys(cid=None):
keys = {'A', 'B'}
healths = [state.device_health.get(cid)] if cid else list(state.device_health.values())
for h in healths:
profiles = (h or {}).get('profiles') or {}
if isinstance(profiles, dict):
keys.update(str(k) for k in profiles.keys() if PROFILE_KEY_RE.match(str(k)))
return keys - PRIVILEGED_COMMANDS - SIMPLE_COMMANDS
# --- ROTTE DATI GENERALI & LOGS ---
@api_bp.route('/api/clients')
def get_clients():
if os.path.exists(CLIENTS_PATH):
with open(CLIENTS_PATH, 'r') as f:
return jsonify(json.load(f))
return jsonify([])
@api_bp.route('/api/logs')
def get_logs():
# 1. Recupera il valore da config.json (default: 60)
cfg_limit = config.get("last_heard_limit", 60)
# 2. Se il client passa ?limit=, usa quello (validato tra 10 e 300 righe)
try:
limit = int(request.args.get('limit', cfg_limit))
limit = max(10, min(limit, 300))
except (ValueError, TypeError):
limit = cfg_limit
conn = sqlite3.connect(DB_PATH, timeout=10)
c = conn.cursor()
c.execute("""SELECT timestamp, client_id, protocol, source_id, target, slot, duration, ber, source_ext, rssi, source_conn, ysf_mode
FROM radio_logs ORDER BY id DESC LIMIT ?""", (limit,))
logs = c.fetchall()
conn.close()
return jsonify(logs)
@api_bp.route('/api/states', methods=['GET'])
def get_states():
clean_versions = {}
for c, d in state.node_versions.items():
clean_versions[c] = {k: v for k, v in d.items() if not k.startswith('_')}
enriched_gateway_states = dict(state.gateway_states)
for cid, confs in state.device_configs.items():
if 'dmrgateway' in confs:
dmr_conf = confs['dmrgateway']
if isinstance(dmr_conf, dict) and 'raw_text' in dmr_conf:
raw = dmr_conf['raw_text']
active_dmr_nets = []
for i in range(1, 6):
section_name = f"[DMR Network {i}]"
if section_name in raw:
block = raw.split(section_name)[1].split('[')[0]
if re.search(r'^Enabled\s*=\s*1', block, re.MULTILINE | re.IGNORECASE):
m_name = re.search(r'^Name\s*=\s*(.+)', block, re.MULTILINE | re.IGNORECASE)
net_name = m_name.group(1).strip() if m_name else f"Net {i}"
active_dmr_nets.append(net_name)
if active_dmr_nets:
if cid not in enriched_gateway_states:
enriched_gateway_states[cid] = {}
enriched_gateway_states[cid]['DMR_NETS'] = active_dmr_nets
return jsonify({
"states": state.client_states,
"telemetry": state.client_telemetry,
"health": state.device_health,
"info": state.node_info,
"general": state.node_general,
"last_seen": state.seen_ages(),
"uptime": int(time.time() - state.START_TIME),
"versions": clean_versions,
"gateway_states": enriched_gateway_states,
"warnings": state.active_warnings,
"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')
def get_stats():
node = request.args.get('node', 'all').lower()
conn = sqlite3.connect(DB_PATH, timeout=10)
c = conn.cursor()
node_filter = ""
params = []
if node != 'all':
node_filter = " AND LOWER(client_id) = ?"
params.append(node)
c.execute(f"""SELECT target, COUNT(*) as cnt FROM radio_logs
WHERE target NOT IN ('---', 'NET', '')
AND timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter}
GROUP BY target ORDER BY cnt DESC LIMIT 5""", params)
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 '🌐%'
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()]
c.execute(f"""SELECT AVG(duration) FROM radio_logs
WHERE duration > 0.5
AND timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter}""", params)
avg_dur = c.fetchone()[0]
avg_dur = round(avg_dur, 1) if avg_dur else 0
c.execute(f"SELECT COUNT(*) FROM radio_logs WHERE timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter}", params)
today_tx = c.fetchone()[0]
conn.close()
return jsonify({
"top_tgs": top_tgs,
"top_calls": top_calls,
"avg_duration": avg_dur,
"today_tx": today_tx
})
# --- COMANDI NODO & RETE ---
@api_bp.route('/api/command', methods=['POST'])
def cmd():
auth = get_auth()
if not auth:
return err("Non autenticato", 403)
d = json_body()
cid = str(d.get('clientId', '')).strip().lower()
cmd_type = str(d.get('type', '')).strip()
if not CID_RE.match(cid):
return err("ID nodo non valido")
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo.", 403)
if cmd_type in PRIVILEGED_COMMANDS:
if auth['role'] != 'admin':
return err("Solo gli amministratori possono eseguire questo comando.", 403)
elif cmd_type in SIMPLE_COMMANDS:
pass
elif cmd_type in known_profile_keys(cid):
pass
else:
logger.warning(f"Comando non consentito da {auth['username']}: {cmd_type[:40]!r} -> {cid}")
return err("Comando sconosciuto")
if not mqtt_publish(f"servizi/{cid}/cmnd", cmd_type):
return err("Broker MQTT non raggiungibile - comando non inviato", 503)
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})
@api_bp.route('/api/global_command', methods=['POST'])
def global_cmd():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Azione riservata agli amministratori!", 403)
cmd_type = str(json_body().get('type', '')).strip()
if cmd_type not in known_profile_keys():
return err("Profilo sconosciuto")
clients_list = []
if os.path.exists(CLIENTS_PATH):
with open(CLIENTS_PATH, 'r') as f:
clients_list = json.load(f)
sent, failed = 0, 0
for client in clients_list:
cid = str(client.get('id', '')).lower()
if not CID_RE.match(cid):
continue
if mqtt_publish(f"servizi/{cid}/cmnd", cmd_type):
audit(auth['username'], cid, f"GLOBAL_OVERRIDE_{cmd_type}")
sent += 1
else:
failed += 1
if failed and not sent:
return err("Broker MQTT non raggiungibile", 503)
return jsonify({"success": True, "sent": sent, "failed": failed})
@api_bp.route('/api/service_control', methods=['POST'])
def service_control():
auth = get_auth()
if not auth or (auth['role'] != 'admin' and auth['role'] != 'node_admin'):
return err("Non autorizzato", 403)
d = json_body()
cid = str(d.get('clientId', '')).strip().lower()
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo", 403)
action = str(d.get('action', '')).strip().lower()
service = str(d.get('service', '')).strip()
if not CID_RE.match(cid):
return err("ID nodo non valido")
if action not in SERVICE_ACTIONS:
return err("Azione servizio non valida")
if not SERVICE_RE.match(service):
return err("Nome servizio non valido")
if not mqtt_publish(f"devices/{cid}/control", f"{action}:{service}"):
return err("Broker MQTT non raggiungibile", 503)
audit(auth['username'], cid, f"SVC_{action.upper()}_{service}")
return jsonify({"success": True})
@api_bp.route('/api/update_nodes', methods=['POST'])
def update_nodes():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
if not mqtt_publish("devices/control/request", "update"):
return err("Broker MQTT non raggiungibile", 503)
logger.info(f"🔄 REQ CONFIG inviata a tutta la flotta da {auth['username']}")
audit(auth['username'], '*', 'REQ_CONFIG_ALL')
return jsonify({"success": True})
# --- CONFIGURAZIONI & FILE .INI ---
@api_bp.route('/api/ui_config', methods=['GET'])
def get_ui_config():
try:
cfg = read_config()
ui_cfg = cfg.get("ui", {
"profileA_Name": "PROFILE A",
"profileA_Color": "#3498db",
"profileB_Name": "PROFILE B",
"profileB_Color": "#9b59b6"
})
return jsonify(ui_cfg)
except Exception as e:
logger.error(f"ui_config error: {e}")
return jsonify({"error": "Configurazione non disponibile"}), 500
@api_bp.route('/api/config', methods=['GET'])
def get_config_api():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
cfg = read_config()
return jsonify({
"update_schedule": cfg.get("update_schedule", "03:00"),
"url_dmr": cfg.get("id_urls", {}).get("dmr", ""),
"url_nxdn": cfg.get("id_urls", {}).get("nxdn", ""),
"log_max_mb": cfg.get("log_max_mb", 50),
"log_backup_count": cfg.get("log_backup_count", 10)
})
@api_bp.route('/api/config', methods=['POST'])
def save_config_api():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
d = json_body()
schedule = str(d.get("update_schedule", "03:00")).strip()
url_dmr = str(d.get("url_dmr", "")).strip()
url_nxdn = str(d.get("url_nxdn", "")).strip()
try:
log_max_mb = int(d.get("log_max_mb", 50))
log_backup_count = int(d.get("log_backup_count", 10))
except ValueError:
return err("Parametri di rotazione log non validi")
if not TIME_RE.match(schedule):
return err("Formato orario non valido (usa HH:MM)")
for u in (url_dmr, url_nxdn):
if not u.lower().startswith(('http://', 'https://')):
return err("Gli URL devono iniziare con http:// o https://")
cfg = read_config()
cfg["update_schedule"] = schedule
cfg.setdefault("id_urls", {})
cfg["id_urls"]["dmr"] = url_dmr
cfg["id_urls"]["nxdn"] = url_nxdn
cfg["log_max_mb"] = log_max_mb
cfg["log_backup_count"] = log_backup_count
write_config(cfg)
audit(auth['username'], '-', 'EDIT_SERVER_CONFIG')
return jsonify({"success": True})
@api_bp.route('/api/config_file/<cid>/<service>', methods=['GET'])
def get_config_file(cid, service):
auth = get_auth()
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):
return err("Permesso negato per questo nodo", 403)
service = service.lower()
if not CID_RE.match(cid) or not SERVICE_RE.match(service):
return err("Parametri non validi")
config_data = state.device_configs.get(cid, {}).get(service)
if not config_data:
return err("Configurazione non ancora ricevuta. Invia un comando di richiesta aggiornamento.", 404)
return jsonify({"success": True, "data": config_data})
@api_bp.route('/api/config_file', methods=['POST'])
def save_config_file():
auth = get_auth()
if not auth or (auth['role'] != 'admin' and auth['role'] != 'node_admin'):
return err("Non autorizzato", 403)
d = json_body()
cid = str(d.get('clientId', '')).strip().lower()
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo", 403)
service = str(d.get('service', '')).strip().lower()
new_config = d.get('config_data')
if not CID_RE.match(cid) or not SERVICE_RE.match(service):
return err("Parametri non validi")
if not isinstance(new_config, dict) or not isinstance(new_config.get('raw_text'), str):
return err("Payload configurazione non valido")
if len(new_config['raw_text']) > 65536:
return err("File di configurazione troppo grande (max 64 KB)")
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] = {}
state.device_configs[cid][service] = new_config
return jsonify({"success": True})
# --- AGGIORNAMENTO SERVER OTA ---
@api_bp.route('/api/server_update/check', methods=['GET'])
def get_server_update_status():
global LAST_GITEA_CHECK_TIME, GLOBAL_SERVER_UPDATE_AVAILABLE
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
force_check = request.args.get('force') == '1'
# 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:
# 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}")
return jsonify({"success": True, "update_available": GLOBAL_SERVER_UPDATE_AVAILABLE})
@api_bp.route('/api/server_update/apply', methods=['POST'])
def apply_server_update():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
if read_config().get('web', {}).get('ota_enabled', True) is False:
return err("Aggiornamento OTA disabilitato dalla configurazione", 403)
try:
audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE')
subprocess.run(['git', 'pull', '--ff-only'], timeout=30, cwd=BASE_DIR, check=True)
def restart_server():
time.sleep(2)
os._exit(1)
import threading
threading.Thread(target=restart_server, daemon=True).start()
return jsonify({"success": True})
except subprocess.CalledProcessError as e:
logger.error(f"Errore durante git pull: {e}")
return err("Conflitto o errore durante il git pull.")
except Exception as e:
logger.error(f"Errore aggiornamento server: {e}")
return err(str(e))
# --- NOTIFICHE WEBPUSH VAPID ---
@api_bp.route('/api/vapid_public_key')
def get_vapid_key():
return jsonify({"public_key": config.get('webpush', {}).get('vapid_public_key', '')})
@api_bp.route('/api/subscribe', methods=['POST'])
def subscribe_push():
auth = get_auth()
if not auth:
return err("Non autorizzato", 403)
sub_data = json_body()
if not sub_data.get('endpoint'):
return err("Sottoscrizione non valida")
with closing(db_connect()) as conn:
conn.execute("""INSERT INTO push_subscriptions (username, subscription) VALUES (?, ?)
ON CONFLICT(subscription) DO UPDATE SET username = excluded.username""",
(auth['username'], json.dumps(sub_data)))
conn.commit()
return jsonify({"success": True})
# --- ASSET PWA / OFFLINE ---
@api_bp.route('/manifest.json')
def serve_manifest():
return send_from_directory(BASE_DIR, 'manifest.json')
@api_bp.route('/sw.js')
def serve_sw():
resp = send_from_directory(BASE_DIR, 'sw.js', mimetype='application/javascript')
resp.headers['Cache-Control'] = 'no-cache'
resp.headers['Service-Worker-Allowed'] = '/'
return resp
@api_bp.route('/icon-512.png')
def serve_icon():
return send_from_directory(BASE_DIR, 'icon-512.png')
@api_bp.route('/api/logs/<cid>', 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/<cid>/<service>', 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/<int:backup_id>', 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/<cid>', 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")
# Validazione profili: stessa logica di /api/command (i comandi privilegiati solo per admin)
profiles_to_check = [target_profile] + ([restore_profile] if restore_profile != 'NONE' else [])
for prof in profiles_to_check:
if prof in SCHED_PRIVILEGED:
if auth['role'] != 'admin':
return err("Solo gli amministratori possono schedulare questo comando.", 403)
elif not (PROFILE_KEY_RE.match(prof) or prof in SIMPLE_COMMANDS):
return err("Profilo non valido")
# Validazione nodi target
if target_nodes != 'all':
node_list = [x.strip() for x in target_nodes.split(',') if x.strip()]
if not node_list or not all(CID_RE.match(x) for x in node_list):
return err("ID nodo non valido")
target_nodes = ','.join(node_list)
# 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/<int:sid>', 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, created_by 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, _is_admin
apply_scheduled_profile(row['target_nodes'], row['restore_profile'], "CANCEL_RESTORE",
allow_privileged=_is_admin(conn, row['created_by']))
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))
+261
View File
@@ -0,0 +1,261 @@
import re
import time
import hashlib
import threading
import sqlite3
from contextlib import closing
from flask import Blueprint, request, session, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from core.config import config, logger
from core.database import db_connect, audit
auth_bp = Blueprint('auth', __name__)
# --- COSTANTI & REGEX VALIDAZIONE ---
VALID_ROLES = ('admin', 'node_admin', 'operator')
USERNAME_RE = re.compile(r'^[A-Za-z0-9_.@\-]{3,32}$')
MIN_PASSWORD_LEN = 8
def json_body():
d = request.get_json(silent=True)
return d if isinstance(d, dict) else {}
def err(msg, code=400):
return jsonify({"success": False, "error": msg}), code
def pw_fingerprint(password_hash):
return hashlib.sha256(password_hash.encode()).hexdigest()[:16]
def get_auth():
username = session.get('user')
if not session.get('logged_in') or not username:
return None
with closing(db_connect(row=True)) as conn:
row = conn.execute("SELECT username, password_hash, role, allowed_nodes FROM users WHERE username = ?",
(username,)).fetchone()
if not row or session.get('pv') != pw_fingerprint(row['password_hash']):
session.clear()
return None
return {"username": row['username'], "role": row['role'], "allowed_nodes": row['allowed_nodes'] or ''}
def count_admins(cursor, exclude_id=None):
if exclude_id is None:
cursor.execute("SELECT COUNT(*) FROM users WHERE role = 'admin'")
else:
cursor.execute("SELECT COUNT(*) FROM users WHERE role = 'admin' AND id != ?", (exclude_id,))
return cursor.fetchone()[0]
def normalize_nodes(value):
value = (value or '').strip().lower()
if not value or value == 'all':
return 'all'
return ','.join(x.strip() for x in value.split(',') if x.strip())
# --- RATE LIMITING / BRUTE FORCE PROTECTION ---
LOGIN_MAX_FAILS = 5
LOGIN_WINDOW_SEC = 300
login_attempts = {}
login_lock = threading.Lock()
LOOPBACK_ADDRS = ('127.0.0.1', '::1')
def client_ip():
fwd = request.headers.get('X-Forwarded-For', '')
if config.get('web', {}).get('trust_proxy'):
if fwd:
return fwd.split(',')[0].strip()
elif fwd and request.remote_addr in LOOPBACK_ADDRS:
# Connessione dal proxy locale: solo lui puo' avere remote_addr loopback, quindi
# fidarsi dell'ultimo valore (quello aggiunto dal proxy) e' sicuro e evita che
# tutti gli utenti condividano 127.0.0.1 (lockout globale del login).
last = fwd.split(',')[-1].strip()
if last:
return last
return request.remote_addr or 'unknown'
def login_blocked(ip):
now = time.time()
with login_lock:
fails = [x for x in login_attempts.get(ip, []) if now - x < LOGIN_WINDOW_SEC]
if fails:
login_attempts[ip] = fails
else:
login_attempts.pop(ip, None)
return len(fails) >= LOGIN_MAX_FAILS
def login_register_fail(ip):
with login_lock:
login_attempts.setdefault(ip, []).append(time.time())
def login_reset(ip):
with login_lock:
login_attempts.pop(ip, None)
# --- ROTTE AUTENTICAZIONE ---
@auth_bp.route('/api/login', methods=['POST'])
def login():
d = json_body()
username, password = d.get('user'), d.get('pass')
if not isinstance(username, str) or not isinstance(password, str) or not username or not password:
return err("Credenziali mancanti", 400)
ip = client_ip()
if login_blocked(ip):
logger.warning(f"Login bloccato (troppi tentativi) da {ip}")
return err("Troppi tentativi falliti. Riprova tra qualche minuto.", 429)
with closing(db_connect(row=True)) as conn:
user = conn.execute("SELECT * FROM users WHERE username = ?", (username,)).fetchone()
if user and check_password_hash(user['password_hash'], password):
login_reset(ip)
session.clear()
session.permanent = True
session['logged_in'] = True
session['user'] = user['username']
session['pv'] = pw_fingerprint(user['password_hash'])
logger.info(f"Login OK: {user['username']} da {ip}")
return jsonify({"success": True, "role": user['role'], "allowed_nodes": user['allowed_nodes']})
login_register_fail(ip)
logger.warning(f"Login fallito per {username[:32]!r} da {ip}")
return jsonify({"success": False}), 401
@auth_bp.route('/api/logout', methods=['POST'])
def logout():
session.clear()
return jsonify({"success": True})
@auth_bp.route('/api/me')
def me():
auth = get_auth()
if not auth:
return jsonify({"logged_in": False})
return jsonify({"logged_in": True, "user": auth['username'], "role": auth['role'],
"allowed_nodes": auth['allowed_nodes']})
@auth_bp.route('/api/change_password', methods=['POST'])
def change_password():
auth = get_auth()
if not auth:
return err("Non autenticato", 403)
d = json_body()
new_pass = d.get('new_password')
user_to_change = d.get('username') or auth['username']
if auth['role'] != 'admin' and auth['username'] != user_to_change:
return err("Non autorizzato", 403)
if not new_pass or not isinstance(new_pass, str):
return err("La password non può essere vuota")
if len(new_pass) < MIN_PASSWORD_LEN:
return err(f"La password deve contenere almeno {MIN_PASSWORD_LEN} caratteri")
with closing(db_connect()) as conn:
cur = conn.execute("UPDATE users SET password_hash = ? WHERE username = ?",
(generate_password_hash(new_pass), user_to_change))
conn.commit()
if cur.rowcount == 0:
return err("Utente non trovato", 404)
audit(auth['username'], '-', f"PASSWORD_CHANGE_{user_to_change}")
return jsonify({"success": True})
# --- GESTIONE UTENTI (ADMIN ONLY) ---
@auth_bp.route('/api/users', methods=['GET'])
def get_users():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
with closing(db_connect(row=True)) as conn:
users = [dict(r) for r in conn.execute("SELECT id, username, role, allowed_nodes FROM users")]
return jsonify(users)
@auth_bp.route('/api/users', methods=['POST'])
def add_user():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
d = json_body()
username = str(d.get('username', '')).strip()
password = d.get('password')
role = d.get('role', 'operator')
allowed = normalize_nodes(d.get('allowed_nodes', 'all'))
if not username or not password:
return err("Dati mancanti")
if not USERNAME_RE.match(username):
return err("Username non valido (3-32 caratteri: lettere, numeri, . _ @ -)")
if not isinstance(password, str) or len(password) < MIN_PASSWORD_LEN:
return err(f"La password deve contenere almeno {MIN_PASSWORD_LEN} caratteri")
if role not in VALID_ROLES:
return err("Ruolo non valido")
try:
with closing(db_connect()) as conn:
conn.execute("INSERT INTO users (username, password_hash, role, allowed_nodes) VALUES (?,?,?,?)",
(username, generate_password_hash(password), role, allowed))
conn.commit()
except sqlite3.IntegrityError:
return err("Username già esistente")
audit(auth['username'], '-', f"USER_ADD_{username}_{role}")
return jsonify({"success": True})
@auth_bp.route('/api/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
d = json_body()
password = d.get('password')
if password is not None and not isinstance(password, str):
return err("Password non valida")
with closing(db_connect()) as conn:
c = conn.cursor()
c.execute("SELECT username, role, allowed_nodes FROM users WHERE id = ?", (user_id,))
existing = c.fetchone()
if not existing:
return err("Utente non trovato", 404)
role = d.get('role', existing[1])
allowed = normalize_nodes(d.get('allowed_nodes', existing[2]))
if role not in VALID_ROLES:
return err("Ruolo non valido")
if existing[1] == 'admin' and role != 'admin' and count_admins(c, exclude_id=user_id) == 0:
return err("Impossibile degradare l'ultimo amministratore rimasto!")
if password and password.strip() != "":
if len(password) < MIN_PASSWORD_LEN:
return err(f"La password deve contenere almeno {MIN_PASSWORD_LEN} caratteri")
c.execute("UPDATE users SET password_hash=?, role=?, allowed_nodes=? WHERE id=?",
(generate_password_hash(password), role, allowed, user_id))
else:
c.execute("UPDATE users SET role=?, allowed_nodes=? WHERE id=?", (role, allowed, user_id))
conn.commit()
audit(auth['username'], '-', f"USER_EDIT_{existing[0]}")
return jsonify({"success": True})
@auth_bp.route('/api/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
with closing(db_connect()) as conn:
c = conn.cursor()
c.execute("SELECT username, role FROM users WHERE id = ?", (user_id,))
u = c.fetchone()
if not u:
return err("Utente non trovato", 404)
if u[0] == auth['username']:
return err("Non puoi eliminare il tuo stesso account!")
if u[1] == 'admin' and count_admins(c, exclude_id=user_id) == 0:
return err("Impossibile eliminare l'ultimo amministratore rimasto!")
c.execute("DELETE FROM users WHERE id = ?", (user_id,))
c.execute("DELETE FROM push_subscriptions WHERE username = ?", (u[0],))
conn.commit()
audit(auth['username'], '-', f"USER_DEL_{u[0]}")
return jsonify({"success": True})
View File
+569
View File
@@ -0,0 +1,569 @@
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, save_telemetry_to_sqlite
import core.state as state
from services.push_service import broadcast_push_notification
mqtt_connected_status = False
def on_connect(client, userdata, flags, reason_code, properties=None):
global mqtt_connected_status
if reason_code == 0:
mqtt_connected_status = True
logger.info("✅ Connessione al broker MQTT riuscita! Sottoscrizione ai topic...")
state.socketio.emit('mqtt_status', {'connected': True})
default_topics = [
"servizi/+/stat", "dmr-gateway/+/json", "devices/+/services",
"nxdn-gateway/+/json", "ysf-gateway/+/json", "p25-gateway/+/json",
"dstar-gateway/+/json", "mmdvm/+/json", "data/#"
]
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.")
else:
mqtt_connected_status = False
state.socketio.emit('mqtt_status', {'connected': False})
logger.error(f"❌ Errore connessione MQTT. Reason code: {reason_code}")
def on_disconnect(client, userdata, disconnect_flags, reason_code, properties=None):
global mqtt_connected_status
mqtt_connected_status = False
state.socketio.emit('mqtt_status', {'connected': False})
logger.warning(f"⚠️ Disconnessione MQTT rilevata! Codice: {reason_code}. Riconnessione automatica...")
def on_message(client, userdata, msg):
try:
topic = msg.topic.strip('/')
payload = msg.payload.decode('utf-8', errors='replace').strip()
parts = topic.split('/')
if len(parts) < 2:
return
cid = parts[1].lower()
p0 = parts[0].lower().replace('-', '')
p2 = parts[2].lower().replace('-', '') if len(parts) > 2 else ""
# --- 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.emit_to_authorized(f"live_log_{cid}", log_entry, cid=cid)
# B) Parsa le versioni
if cid not in state.node_versions:
state.node_versions[cid] = {}
m_fw = re.search(r'description:\s*(MMDVM[^\n\r]+)', payload, re.IGNORECASE)
if m_fw:
state.node_versions[cid]["Firmware MMDVM"] = m_fw.group(1).strip()
state.notify_update()
m_sw1 = re.search(r'([A-Za-z0-9_]+)-([a-zA-Z0-9.\-]+)\s+is starting', payload, re.IGNORECASE)
if m_sw1:
prog = m_sw1.group(1)
state.node_versions[cid][prog] = m_sw1.group(2).strip()
state.node_versions[cid]["_last_prog"] = prog
state.notify_update()
m_sw2 = re.search(r'([A-Za-z0-9_]+)\s+version\s+([a-zA-Z0-9.\-\s#]+)', payload, re.IGNORECASE)
if m_sw2:
prog = m_sw2.group(1)
if prog.lower() not in ['protocol', 'firmware', 'mmdvm firmware']:
ver = m_sw2.group(2).replace("is starting", "").strip()
state.node_versions[cid][prog] = ver
state.node_versions[cid]["_last_prog"] = prog
state.notify_update()
m_git = re.search(r'Built .*?\(GitID #([0-9a-fA-F]+)\)', payload, re.IGNORECASE)
if m_git:
git_id = m_git.group(1)
last_prog = state.node_versions[cid].get("_last_prog")
if last_prog and last_prog in state.node_versions[cid]:
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.emit_aprs(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
if p0 == 'mmdvm':
state.touch_seen(cid, 'mmdvm')
elif p0 in ('dmrgateway', 'nxdngateway', 'ysfgateway', 'p25gateway', 'dstargateway'):
state.touch_seen(cid, 'gateway')
elif p0 == 'devices' and p2 == 'services':
state.touch_seen(cid, 'health')
# --- 2. FILE CONFIGURAZIONE ---
if p0 == 'data' and len(parts) >= 4 and parts[3].lower() == 'full_config':
cid_conf = parts[1].lower()
svc_name = parts[2].lower()
if cid_conf not in state.device_configs:
state.device_configs[cid_conf] = {}
try:
state.device_configs[cid_conf][svc_name] = json.loads(payload)
logger.debug(f"Configurazione salvata per {cid_conf} -> {svc_name}")
except Exception as e:
logger.error(f"Errore parsing config JSON: {e}")
# --- 3. STATO NODO (ONLINE / OFFLINE) ---
elif p0 == 'servizi':
state.client_states[cid] = payload
state.notify_update()
state_up = payload.upper()
if state_up.startswith('OFFLINE'):
if not msg.retain and state.last_notified_errors.get(f"{cid}_NODE") != 'OFFLINE':
broadcast_push_notification(f"💀 NODE OFFLINE: {cid.upper()}", "Connessione persa con il broker.", cid=cid)
state.last_notified_errors[f"{cid}_NODE"] = 'OFFLINE'
elif state_up.startswith('ONLINE'):
if state.last_notified_errors.get(f"{cid}_NODE") == 'OFFLINE':
broadcast_push_notification(f"🌤️ NODE ONLINE: {cid.upper()}", "Nodo nuovamente online.", cid=cid)
del state.last_notified_errors[f"{cid}_NODE"]
if not state_up.startswith('OFF') and state_up != '':
tel = state.client_telemetry.get(cid, {})
if isinstance(tel, dict) and '🔄' in str(tel.get('ts1', '')):
state.client_telemetry[cid] = {"ts1": "Waiting...", "ts2": "Waiting...", "alt": ""}
state.save_cache(state.client_telemetry)
# --- 4. TELEMETRIA AGENT & DEMONI ---
elif p0 == 'devices' and len(parts) >= 3 and p2 == 'services':
try:
data = json.loads(payload)
new_health = {
"cpu": round(data.get("cpu_usage_percent", 0), 1),
"temp": round(data.get("cpu_temp", 0), 1),
"ram": round(data.get("memory_usage_percent", 0), 1),
"disk": round(data.get("disk_usage_percent", 0), 1),
"processes": data.get("processes", {}),
"files": data.get("files", data.get("config_files", [])),
"file_names": data.get("file_names", []),
"profiles": data.get("profiles", {"A": "PROFILE A", "B": "PROFILE B"}),
"interval": data.get("update_interval"),
"uptime": data.get("uptime_seconds", 0),
"agent_version": data.get("agent_version", "1.0"),
"agent_update_available": data.get("agent_update_available", False)
}
bin_versions = data.get("versions", {})
if bin_versions:
if cid not in state.node_versions:
state.node_versions[cid] = {}
keys_to_remove = [k for k in state.node_versions[cid].keys()
if k not in bin_versions and k not in ["Firmware MMDVM", "_last_prog"]]
for k in keys_to_remove:
del state.node_versions[cid][k]
for prog_name, prog_ver in bin_versions.items():
state.node_versions[cid][prog_name] = prog_ver
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()
processes = data.get("processes", {})
for svc_name, svc_status in processes.items():
status_key = f"{cid}_{svc_name}"
s_lower = svc_status.lower()
if s_lower in ["error", "stopped", "failed"]:
if state.last_notified_errors.get(status_key) != s_lower:
msg_err = f"Servizio {svc_name} KO ({svc_status})"
if s_lower == "error":
msg_err += " - Auto-healing fallito! ⚠️"
broadcast_push_notification(f"🚨 ALLARME: {cid.upper()}", msg_err, cid=cid)
state.last_notified_errors[status_key] = s_lower
elif s_lower == "online" and status_key in state.last_notified_errors:
broadcast_push_notification(f"✅ RIPRISTINATO: {cid.upper()}", f"Servizio {svc_name} tornato ONLINE.", cid=cid)
del state.last_notified_errors[status_key]
except Exception as e:
logger.error(f"Errore parsing telemetria agent: {e}")
# --- 5. INFO FREQUENZE E GEOLOCALIZZAZIONE ---
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost', 'dmrgateway') and parts[3].lower() == 'info':
try:
cid = parts[1].lower()
data = json.loads(payload)
def format_freq(f):
if str(f).isdigit() and int(f) > 0:
hz = int(f)
mhz, frac = divmod(hz, 1000000)
dec = f"{frac:06d}"
if dec.endswith("0"):
dec = dec[:-1]
return f"{mhz}.{dec} MHz"
return str(f)
# Inizializza il dizionario se il nodo è nuovo
if cid not in state.node_info:
state.node_info[cid] = {"tx": "0", "rx": "0", "lat": "0.0", "lon": "0.0", "loc": "Sconosciuta"}
# Aggiorna solo i campi effettivamente presenti nel payload per fondere i dati di MMDVM e DMRGateway
if "TXFrequency" in data:
state.node_info[cid]["tx"] = format_freq(data["TXFrequency"])
if "RXFrequency" in data:
state.node_info[cid]["rx"] = format_freq(data["RXFrequency"])
if "Latitude" in data:
state.node_info[cid]["lat"] = data["Latitude"]
if "Longitude" in data:
state.node_info[cid]["lon"] = data["Longitude"]
if "Location" in data:
state.node_info[cid]["loc"] = data["Location"]
state.notify_update()
except Exception as e:
logger.error(f"Errore parsing info (MMDVM/DMRGateway) per {cid}: {e}")
# --- 6. INFO GENERALI (CALLSIGN & RADIO ID) ---
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost') and parts[3].lower() == 'general':
try:
cid = parts[1].lower()
data = json.loads(payload)
callsign = data.get("Callsign", "")
radio_id = data.get("Id", "")
duplex = data.get("Duplex", "1")
if callsign:
state.node_general[cid] = {"callsign": callsign, "radio_id": radio_id, "duplex": str(duplex)}
state.notify_update()
except Exception as e:
logger.error(f"Errore parsing MMDVMHost general per {cid}: {e}")
# --- 7. EVENTI GATEWAY (LINKING / UNLINKING) ---
elif p0 in ['dmrgateway', 'nxdngateway', 'ysfgateway', 'p25gateway', 'dstargateway']:
data = json.loads(payload)
proto = "DMR"
if "nxdn" in p0: proto = "NXDN"
elif "ysf" in p0: proto = "YSF"
elif "p25" in p0: proto = "P25"
elif "dstar" in p0: proto = "D-STAR"
if cid not in state.gateway_states:
state.gateway_states[cid] = {}
m = "" # Variabile per il log di sistema
# 1. Parsing strutturato (usato per il messaggio "Link IT-YSF-FVG")
if 'link' in data:
l = data['link']
g_dest = str(l.get('reflector') or l.get('talkgroup') or '---').strip()
g_action = l.get('action', '')
state.gateway_states[cid][proto] = {"action": g_action, "dest": g_dest}
state.notify_update()
if g_action == 'linking':
state.last_seen_reflector[f"{cid}_{proto}"] = g_dest
elif g_action == 'unlinking':
state.last_seen_reflector[f"{cid}_{proto}"] = "---"
m = f"{'Link' if g_action=='linking' else 'Unlinked'} {g_dest}"
# 2. Parsing testuale (usato per gli status testuali)
elif 'status' in data:
raw_msg = str(data['status'].get('message', 'IDLE'))
msg_lower = raw_msg.lower()
m = raw_msg
# A. NXDN: Connessione tramite RF
if "switched to reflector" in msg_lower:
match = re.search(r'switched to reflector (\w+)', msg_lower)
if match:
state.gateway_states[cid][proto] = {"action": "linked", "dest": match.group(1).upper()}
state.notify_update()
# B. YSF/NXDN: Connessione standard
elif "linked to" in msg_lower:
idx = msg_lower.find("linked to")
dest = raw_msg[idx + 9:].strip()
state.gateway_states[cid][proto] = {"action": "linked", "dest": dest}
state.notify_update()
# C. Connessione in corso
elif "linking to" in msg_lower:
idx = msg_lower.find("linking to")
dest = raw_msg[idx + 10:].strip()
state.gateway_states[cid][proto] = {"action": "linking", "dest": dest}
state.notify_update()
# D. Disconnessione o arresto del demone (Azzera la memoria)
elif "unlinked" in msg_lower or "disconnected" in msg_lower or "not linked" in msg_lower or "failed" in msg_lower or "stopping" in msg_lower:
state.gateway_states[cid][proto] = {"action": "unlinked", "dest": ""}
state.notify_update()
# E. Avvio del demone
elif "starting" in msg_lower or "opening" in msg_lower or "idle" in msg_lower:
# Azzera il badge SOLO se non è appena stato registrato un "Link" fulmineo
current_act = state.gateway_states.get(cid, {}).get(proto, {}).get("action")
if current_act not in ["linked", "linking"]:
state.gateway_states[cid][proto] = {"action": "idle", "dest": ""}
state.notify_update()
# Salvataggio nel DB per la console log
if m and "running" not in m.lower():
save_to_sqlite(cid, {'src_id': f"🌐 {m}", 'dst_id': 'NET'}, protocol=proto)
# --- 7.5 EVENTI APRS ---
elif p0 == 'aprsgateway' and len(parts) >= 2 and parts[1].lower() == 'aprs':
try:
if not payload:
return
# Payload RAW APRS: CALLSIGN>DEST,PATH:PAYLOAD
data = {"source": "---", "dest": "---", "path": "", "payload": payload, "time": ""}
if ">" in payload and ":" in payload:
src_part, rest = payload.split(">", 1)
header_part, pld_part = rest.split(":", 1)
header_tokens = header_part.split(",")
dest_part = header_tokens[0]
path_str = ",".join(header_tokens[1:]) if len(header_tokens) > 1 else ""
data["source"] = src_part.strip()
data["dest"] = dest_part.strip()
data["path"] = path_str.strip()
data["payload"] = pld_part.strip()
else:
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.emit_aprs(data)
except Exception as e:
logger.error(f"Errore parsing APRS: {e}")
# --- MODI OPERATIVI MMDVM ---
elif len(parts) == 3 and p0 == 'data' and p2 == 'mmdvm':
try:
cid = parts[1].lower()
state.operating_modes[cid] = json.loads(payload)
state.notify_update()
except Exception as e:
logger.error(f"Errore parsing MMDVM modes per {cid}: {e}")
# --- 8. TRAFFICO VOCE MMDVM (DMR & MODI DIGITALI) ---
elif parts[0] == 'mmdvm':
data = json.loads(payload)
if cid not in state.active_calls:
state.active_calls[cid] = {}
if cid not in state.client_telemetry or not isinstance(state.client_telemetry.get(cid), dict):
state.client_telemetry[cid] = {"ts1": "Waiting...", "ts2": "Waiting...", "alt": "", "idle": True}
if 'MMDVM' in data and data['MMDVM'].get('mode') == 'idle':
state.client_telemetry[cid]["idle"] = True
state.save_cache(state.client_telemetry)
return
state.client_telemetry[cid]["idle"] = False
# --- ALLINEAMENTO MODI PER BEACON ---
curr_mode = data.get('MMDVM', {}).get('mode', '')
if curr_mode:
if curr_mode.upper() == 'DMR':
state.client_telemetry[cid]["alt"] = ""
else:
old_alt = state.client_telemetry[cid].get("alt", "")
if not any(i in old_alt for i in ['🟢','🟣','🔵','🟠']):
state.client_telemetry[cid]["alt"] = f"📡 {curr_mode.upper()} BEACON"
if 'DMR' in data:
d = data['DMR']
act = d.get('action')
sk = f"ts{d.get('slot', 1)}"
if act in ['start', 'late_entry']:
src = state.get_call(d.get('src_id'))
dst = str(d.get('dst_id'))
state.active_calls[cid][sk] = {
'src': src,
'dst': dst,
'slot': d.get('slot', 1),
'ext': str(d.get('src_ext', '')),
'source': str(d.get('source', '')),
'mode': str(d.get('mode', ''))
}
state.client_telemetry[cid]["alt"] = ""
state.client_telemetry[cid][sk] = f"🎙️ {src} ➔ TG {dst}"
state.notify_update()
elif act in ['end', 'lost']:
info = state.active_calls[cid].get(sk, {'src': '---', 'dst': '---', 'slot': d.get('slot', 1), 'ext': '', 'source': '', 'mode': ''})
d.update({
'src_id': info['src'],
'dst_id': info['dst'],
'slot': info['slot'],
'src_ext': info['ext'],
'source': info['source'],
'mode': info['mode']
})
save_to_sqlite(cid, d, protocol="DMR")
state.client_telemetry[cid][sk] = f"{'✅' if act=='end' else '⚠️'} {info['src']}"
state.save_cache(state.client_telemetry)
if sk in state.active_calls[cid]:
del state.active_calls[cid][sk]
else:
for k, ico, name in [('NXDN','🟢','NXDN'),('YSF','🟣','YSF'),('P25','🟠','P25'),('D-Star','🔵','D-STAR')]:
if k in data:
p = data[k]
act = p.get('action')
if act == 'start':
if k == 'NXDN':
src = state.get_call(p.get('src_id', '---'), 'NXDN')
elif k == 'P25':
src = state.get_call(p.get('src_id', '---'), 'DMR')
else:
src = str(p.get('Callsign', p.get('src_callsign', p.get('src_info', p.get('src_id', '---')))))
raw_target = str(p.get('dst_callsign', p.get('dst_id', ''))).strip()
if name == 'D-STAR':
target = raw_target if raw_target else "---"
else:
target = raw_target if raw_target not in ['', '0', 'ALL'] else "---"
if name == 'YSF' and 'dg-id' in p:
dg_id = str(p.get('dg-id')).strip()
if dg_id:
target = f"DG-ID {dg_id}" if target == "---" else f"{target} (DG {dg_id})"
mem_ref = state.last_seen_reflector.get(f"{cid}_{name}", "---")
pack_ref = str(p.get('reflector', '')).strip()
ref_slot = mem_ref if mem_ref != "---" else (pack_ref if pack_ref else "---")
state.active_calls[cid][k] = {'src': src, 'dst': target, 'slot': ref_slot, 'ext': str(p.get('src_ext', '')), 'source': str(p.get('source', '')), 'mode': str(p.get('mode', ''))}
target_str = target if target != "---" else "NET"
state.client_telemetry[cid].update({"ts1":"","ts2":"","alt": f"{ico} {name}: {src} ➔ {target_str} ({ref_slot})"})
state.notify_update()
elif act in ['end', 'lost']:
info = state.active_calls[cid].get(k, {'src': '---', 'dst': '---', 'slot': '---', 'ext': '', 'source': '', 'mode': ''})
p.update({'src_id': info['src'], 'dst_id': info['dst'], 'slot': info['slot'], 'src_ext': info['ext'], 'source': info['source'], 'mode': info['mode']})
save_to_sqlite(cid, p, protocol=name)
state.client_telemetry[cid]["alt"] = f"{'✅' if act=='end' else '⚠️'} {name}: {info['src']}"
state.save_cache(state.client_telemetry)
if k in state.active_calls[cid]:
del state.active_calls[cid][k]
except Exception as e:
logger.error(f"MQTT MSG ERROR: {e}")
# Inizializzazione Client MQTT
mqtt_id = config.get('mqtt', {}).get('client_id', 'flask_backend_generic')
mqtt_backend = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, mqtt_id)
mqtt_backend.username_pw_set(config.get('mqtt', {}).get('user', ''), config.get('mqtt', {}).get('password', ''))
# TLS opzionale (default: disattivato, comportamento invariato). In config.json:
# "mqtt": { ..., "port": 8883, "tls": true, "ca_certs": "/etc/ssl/certs/ca-certificates.crt" }
if config.get('mqtt', {}).get('tls'):
import ssl
try:
mqtt_backend.tls_set(ca_certs=config.get('mqtt', {}).get('ca_certs') or None,
cert_reqs=ssl.CERT_REQUIRED)
logger.info("🔒 MQTT: TLS abilitato")
except Exception as e:
logger.error(f"MQTT TLS non configurabile: {e}")
mqtt_backend.on_connect = on_connect
mqtt_backend.on_disconnect = on_disconnect
mqtt_backend.on_message = on_message
def is_connected():
return mqtt_connected_status
def start_mqtt():
try:
broker = config.get('mqtt', {}).get('broker', 'localhost')
port = config.get('mqtt', {}).get('port', 1883)
mqtt_backend.connect_async(broker, port)
mqtt_backend.loop_start()
logger.info(f"Avvio connessione MQTT asincrona verso {broker}:{port}...")
except Exception as e:
logger.error(f"Errore critico nell'inizializzazione MQTT: {e}")
def mqtt_publish(topic, payload, qos=1):
if not mqtt_connected_status:
logger.warning(f"MQTT offline: pubblicazione su {topic} annullata")
return False
try:
info = mqtt_backend.publish(topic, payload, qos=qos)
if info.rc != mqtt_client.MQTT_ERR_SUCCESS:
logger.warning(f"MQTT publish fallita su {topic} (rc={info.rc})")
return False
return True
except Exception as e:
logger.error(f"MQTT publish error su {topic}: {e}")
return False
+63
View File
@@ -0,0 +1,63 @@
import json
import queue
from contextlib import closing
from pywebpush import webpush, WebPushException
from core.config import config, logger
from core.database import db_connect
from core.permissions import node_allowed # noqa: F401 (re-export per compatibilita')
push_queue = queue.Queue(maxsize=200)
def broadcast_push_notification(title, body, cid=None):
if not config.get('webpush'):
return
try:
push_queue.put_nowait((title, body, cid))
except queue.Full:
logger.warning("Push queue piena: notifica scartata")
def _send_push(title, body, cid):
wp_config = config.get('webpush')
if not wp_config:
return
payload = json.dumps({"title": title, "body": body, "tag": cid or "fleet-alert"})
dead = []
with closing(db_connect()) as conn:
rows = conn.execute("""SELECT p.id, p.subscription, u.role, u.allowed_nodes
FROM push_subscriptions p
LEFT JOIN users u ON u.username = p.username""").fetchall()
for sub_id, sub_json, role, allowed in rows:
if role is None:
dead.append(sub_id)
continue
if cid and not node_allowed(role, allowed, cid):
continue
try:
webpush(
subscription_info=json.loads(sub_json),
data=payload,
vapid_private_key=wp_config['vapid_private_key'],
vapid_claims={"sub": wp_config['vapid_claim_email']},
timeout=10
)
except WebPushException as ex:
status = getattr(getattr(ex, 'response', None), 'status_code', None)
if status in (404, 410):
dead.append(sub_id)
else:
logger.warning(f"Push error (status {status}): {ex}")
except Exception as e:
logger.error(f"Generic Push Error: {e}")
for sub_id in dead:
conn.execute("DELETE FROM push_subscriptions WHERE id = ?", (sub_id,))
if dead:
conn.commit()
def push_worker():
while True:
title, body, cid = push_queue.get()
try:
_send_push(title, body, cid)
except Exception as e:
logger.error(f"Push worker error: {e}")
+149
View File
@@ -0,0 +1,149 @@
import os
import time
import urllib.request
from core.config import DMR_IDS_PATH, NXDN_IDS_PATH, read_config, logger
from core.database import prune_old_data
import core.state as state
def download_file(url, dest):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=60) as response:
data = response.read()
if len(data) < 1024:
raise ValueError(f"file scaricato troppo piccolo ({len(data)} byte) da {url}")
tmp = dest + '.tmp'
with open(tmp, 'wb') as out_file:
out_file.write(data)
os.replace(tmp, dest)
def download_logic():
try:
urls = read_config().get("id_urls") or {}
url_dmr = urls.get("dmr") or "https://radioid.net/static/users.csv"
url_nxdn = urls.get("nxdn") or "https://radioid.net/static/nxdn.csv"
logger.info("📡 Inizio download database ID (DMR e NXDN)...")
download_file(url_dmr, DMR_IDS_PATH)
download_file(url_nxdn, NXDN_IDS_PATH)
state.load_ids()
logger.info(f"✅ Aggiornamento completato ({len(state.user_db)} ID DMR, {len(state.nxdn_db)} ID NXDN).")
except Exception as e:
logger.error(f"❌ Errore durante il download: {e}")
def auto_update_ids():
if not os.path.exists(DMR_IDS_PATH) or not os.path.exists(NXDN_IDS_PATH):
logger.info("🔍 File ID mancanti. Avvio download immediato...")
download_logic()
prune_old_data()
while True:
try:
now = time.strftime("%H:%M")
target_time = read_config().get("update_schedule", "03:00")
if now == target_time:
logger.info(f"⏰ Orario programmato ({target_time}) raggiunto. Aggiorno...")
download_logic()
prune_old_data()
time.sleep(65)
except Exception as e:
logger.error(f"⚠️ Errore nel thread aggiornamento ID: {e}")
time.sleep(15)
def schedule_loop():
"""Thread dedicato alle schedulazioni: non e' piu' bloccato dai download degli ID."""
while True:
try:
check_profile_schedules()
except Exception as e:
logger.error(f"⚠️ Errore nel thread schedulazioni: {e}")
time.sleep(15)
from contextlib import closing
from core.database import db_connect, audit
# Comandi che le API riservano agli admin: una schedulazione li puo' inviare solo se creata da un admin.
PRIVILEGED_COMMANDS = {'REBOOT', 'RESET_HAT', 'UPDATE_AGENT'}
def _is_admin(conn, username):
row = conn.execute("SELECT role FROM users WHERE username = ?", (username,)).fetchone()
return bool(row) and row[0] == 'admin'
def apply_scheduled_profile(target_nodes, profile, action_type="SWITCH", allow_privileged=False):
if str(profile).strip().upper() in PRIVILEGED_COMMANDS and not allow_privileged:
logger.warning(f"🚫 Scheduler: comando privilegiato '{profile}' ignorato (schedulazione non creata da un admin)")
return
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", allow_privileged=_is_admin(conn, row['created_by']))
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", allow_privileged=_is_admin(conn, row['created_by']))
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}")
+88
View File
@@ -0,0 +1,88 @@
import time
import sqlite3
from contextlib import closing
from core.config import DB_PATH, logger
import core.state as state
from services.push_service import broadcast_push_notification
watchdog_notified = {}
def run_diagnostics():
new_warnings = {}
# 1. Analisi Hardware (Temperatura e Spazio Disco)
for cid, health in list(state.device_health.items()):
node_warns = []
state_up = str(state.client_states.get(cid, '')).upper()
if 'OFF' in state_up or state_up == '':
continue
temp = health.get('temp', 0)
disk = health.get('disk', 0)
# Allarme Temperatura CPU (Soglia 75°C, rientro 68°C)
key_temp = f"{cid}_TEMP"
if temp >= 75.0:
node_warns.append(f"🌡️ Alta Temperatura ({temp}°C)")
if not watchdog_notified.get(key_temp):
broadcast_push_notification(f"🌡️ ALLARME TERMICO: {cid.upper()}", f"CPU surriscaldata a {temp}°C! Verificare ventilazione.", cid=cid)
watchdog_notified[key_temp] = True
elif temp < 68.0 and watchdog_notified.get(key_temp):
broadcast_push_notification(f"✅ TEMPERATURA OK: {cid.upper()}", f"Temperatura CPU rientrata a {temp}°C.", cid=cid)
del watchdog_notified[key_temp]
# Allarme Spazio Disco (Soglia 90%, rientro 85%)
key_disk = f"{cid}_DISK"
if disk >= 90.0:
node_warns.append(f"💾 Spazio Disco Quasi Pieno ({disk}%)")
if not watchdog_notified.get(key_disk):
broadcast_push_notification(f"💾 DISCO CRITICO: {cid.upper()}", f"Utilizzo disco al {disk}%. Rischio blocco log MMDVM.", cid=cid)
watchdog_notified[key_disk] = True
elif disk < 85.0 and watchdog_notified.get(key_disk):
del watchdog_notified[key_disk]
if node_warns:
new_warnings.setdefault(cid, []).extend(node_warns)
# 2. Analisi Radio RF (Media BER sulle ultime 2 ore, solo transiti RF locali)
try:
with closing(sqlite3.connect(DB_PATH, timeout=10)) as conn:
cur = conn.cursor()
cur.execute("""
SELECT LOWER(client_id), AVG(ber), COUNT(*)
FROM radio_logs
WHERE timestamp >= datetime('now', 'localtime', '-5 minutes')
AND source_id NOT LIKE '🌐%'
AND (source_conn IS NULL OR LOWER(source_conn) != 'network')
GROUP BY LOWER(client_id)
""")
rows = cur.fetchall()
for cid, avg_ber, cnt in rows:
key_ber = f"{cid}_BER"
if cnt >= 2 and avg_ber is not None and avg_ber >= 5.0:
new_warnings.setdefault(cid, []).append(f"⚠️ Alto BER RF ({avg_ber:.1f}%)")
if not watchdog_notified.get(key_ber):
broadcast_push_notification(f"⚠️ ANOMALIA RF: {cid.upper()}", f"Rilevato BER medio del {avg_ber:.1f}% negli ultimi {cnt} passaggi RF.", cid=cid)
watchdog_notified[key_ber] = True
elif avg_ber is not None and avg_ber < 3.0:
if watchdog_notified.get(key_ber):
del watchdog_notified[key_ber]
except Exception as e:
logger.error(f"Errore diagnostica BER Watchdog: {e}")
# Aggiorna il dizionario globale condiviso preservando i riferimenti in memoria
changed = new_warnings != state.active_warnings
state.active_warnings.clear()
state.active_warnings.update(new_warnings)
if changed:
state.notify_update()
def watchdog_loop():
time.sleep(15) # Attesa iniziale all'avvio
while True:
try:
run_diagnostics()
except Exception as e:
logger.error(f"Errore nel loop del Watchdog: {e}")
time.sleep(60)
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+279
View File
@@ -0,0 +1,279 @@
/* =========================================
LAYOUT 2: TACTICAL (Ispirato alla versione dark/ambra)
========================================= */
body.layout-tactical {
--bg-main: #111318;
--card-bg: #1c2128;
--primary: #f5b041; /* Giallo/Ambra */
--accent: #c0392b; /* Rosso scuro */
--success: #2ecc71; /* Verde */
--danger: #e74c3c;
--text-main: #e6edf3;
--text-muted: #7d8590;
--border-main: #444c56;
--border-light: #30363d;
background-color: var(--bg-main);
}
body.layout-tactical .card, body.layout-tactical .modal-content {
background: var(--card-bg) !important;
border: 1px solid var(--border-light) !important;
border-radius: 4px !important;
box-shadow: 0 4px 10px rgba(0,0,0,0.4) !important;
}
body.layout-tactical .title-brand {
color: var(--primary);
}
body.layout-tactical .tactical-led {
border-radius: 2px !important; /* LED quadrati e rigidi */
}
body.layout-tactical .terminal-log {
background: #0d1117;
border-color: var(--border-light);
}
/* =========================================
LAYOUT 3: LIGHT (Clean & Bright - Modalità diurna)
========================================= */
body.layout-light {
--bg-main: #f8fafc;
--card-bg: #ffffff;
--primary: #0ea5e9; /* Azzurro pulito */
--accent: #8b5cf6;
--success: #10b981;
--danger: #ef4444;
--text-main: #1e293b;
--text-muted: #64748b;
--border-main: #cbd5e1;
--border-light: #e2e8f0;
background-color: var(--bg-main) !important;
background-image: none !important; /* Rimozione della griglia blueprint! */
color: var(--text-main);
}
/* --- Override for the main layout grid from original style.css --- */
body.layout-light div.card,
body.layout-light div.modal-content,
body.layout-light div.mini-card {
background: #ffffff !important;
border: 1px solid var(--border-main) !important;
border-radius: 8px !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.04) !important;
}
body.layout-light .filter-bar {
background: #ffffff !important;
border: 1px solid var(--border-main) !important;
}
body.layout-light .filter-pill {
color: var(--text-muted) !important;
border-color: var(--border-main) !important;
}
body.layout-light .filter-pill.active {
color: var(--primary) !important;
border-color: var(--primary) !important;
background: #f0f9ff !important;
}
body.layout-light .filter-pill:hover {
background: #f8fafc !important;
}
/* Fix per la mappa */
body.layout-light .dark-tiles {
filter: none !important;
-webkit-filter: none !important;
}
body.layout-light .custom-map-pin.pin-online {
background: var(--success);
border-color: #059669;
box-shadow: 0 0 10px rgba(16, 185, 129, 0.4);
color: white;
}
body.layout-light .custom-map-pin.pin-offline {
background: var(--danger);
border-color: #b91c1c;
box-shadow: 0 0 10px rgba(239, 68, 68, 0.4);
color: white;
}
/* --- Top Bar --- */
body.layout-light #top-bar-container,
body.layout-light #top-bar {
background: #ffffff !important;
border-bottom: 1px solid var(--border-main) !important;
box-shadow: 0 2px 10px rgba(0,0,0,0.03);
}
body.layout-light .title-brand {
color: var(--primary) !important;
text-shadow: none !important;
}
/* Testi scuri sulle mini card */
body.layout-light .mini-card-name {
color: var(--text-main) !important;
font-weight: 600;
}
body.layout-light .mini-card[style*="grayscale"] {
opacity: 0.5 !important;
background: #f1f5f9 !important;
}
/* Bottoni, Tab e Navigazione */
body.layout-light .nav-tab { color: var(--text-muted); }
body.layout-light .nav-tab.active {
color: var(--primary) !important;
border-bottom: 2px solid var(--primary) !important;
background: transparent !important;
}
body.layout-light .theme-switch {
border: 1px solid var(--border-main) !important;
color: var(--text-muted) !important;
background: transparent !important;
}
body.layout-light .btn-cmd {
color: var(--text-main) !important;
border-color: var(--border-main) !important;
background: #ffffff;
}
body.layout-light .btn-cmd:hover {
background: #f1f5f9;
}
/* Fix per i pannelli informativi a bordo */
body.layout-light .freq-bar,
body.layout-light .node-meta,
body.layout-light .health-bar {
border-color: var(--border-light) !important;
color: var(--text-muted) !important;
}
body.layout-light .health-bar span {
border-right-color: var(--border-light) !important;
}
body.layout-light .seen-bar {
border-color: var(--border-light) !important;
}
/* Testo interno delle Card dei Nodi */
body.layout-light .client-name {
color: var(--text-main) !important;
}
body.layout-light .badge-id {
color: var(--text-muted) !important;
}
body.layout-light .type-badge.type-repeater {
color: var(--primary) !important;
border-color: var(--primary) !important;
background: transparent;
}
body.layout-light .status-display {
color: var(--text-main) !important;
border-color: var(--border-light) !important;
}
/* Fix tabelle */
body.layout-light table { background: transparent; }
body.layout-light thead th, body.layout-light thead tr {
background: #f1f5f9 !important;
color: var(--text-muted) !important;
border-bottom: 2px solid var(--border-main) !important;
font-weight: 600;
}
body.layout-light tbody tr, body.layout-light td {
background: #ffffff !important;
border-bottom: 1px solid var(--border-light) !important;
color: var(--text-main) !important;
}
body.layout-light tbody tr:nth-child(even), body.layout-light tbody tr:nth-child(even) td {
background: #f8fafc !important;
}
body.layout-light tbody tr:hover, body.layout-light tbody tr:hover td {
background: #f1f5f9 !important;
}
/* Input */
body.layout-light select, body.layout-light input, body.layout-light textarea {
background: #ffffff !important;
color: var(--text-main) !important;
border: 1px solid var(--border-main) !important;
}
body.layout-light .terminal-log {
background: #f1f5f9 !important;
color: #334155 !important;
border-color: var(--border-main) !important;
}
/* Fix visibilità dei pin mappa nel tema chiaro */
body.layout-light .custom-map-pin {
color: #ffffff !important;
font-weight: bold !important;
font-size: 16px !important;
line-height: 24px !important;
}
body.layout-light .custom-map-pin.pin-online {
background-color: var(--success) !important;
border: 2px solid #059669 !important;
box-shadow: 0 0 12px rgba(16, 185, 129, 0.6) !important;
}
body.layout-light .custom-map-pin.pin-offline {
background-color: var(--danger) !important;
border: 2px solid #b91c1c !important;
box-shadow: 0 0 12px rgba(239, 68, 68, 0.6) !important;
}
body.layout-light .custom-map-pin.pin-tx {
background-color: var(--primary) !important;
border: 2px solid #0284c7 !important;
box-shadow: 0 0 15px rgba(2, 132, 199, 0.8) !important;
}
body.layout-light .custom-map-pin.pin-warn {
background-color: var(--accent) !important;
border: 2px solid #7c3aed !important;
}
/* Fix per i container delle popup di Leaflet */
body.layout-light .leaflet-popup-content-wrapper,
body.layout-light .leaflet-popup-tip {
background: #ffffff !important;
color: var(--text-main) !important;
box-shadow: 0 4px 15px rgba(0,0,0,0.1) !important;
}
body.layout-light .leaflet-popup-content div {
color: var(--text-main);
}
/* =========================================
LAYOUT 4: GLASSMORPHISM & NEON
Layout moderno, traslucido con sfocature
========================================= */
body.layout-glass {
--bg-main: #0f172a;
--primary: #38bdf8;
--accent: #c084fc;
--success: #34d399;
--danger: #fb7185;
--card-bg: rgba(255, 255, 255, 0.03);
--border-light: rgba(255,255,255,0.1);
background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
background-attachment: fixed;
}
body.layout-glass .card, body.layout-glass .modal-content {
background: var(--card-bg) !important;
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255,255,255,0.08) !important;
border-radius: 24px !important;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5) !important;
}
body.layout-glass .btn-cmd, body.layout-glass .filter-pill {
border-radius: 12px;
}
body.layout-glass .card-header {
border-bottom: 1px solid rgba(255,255,255,0.05);
padding-bottom: 15px;
}
body.layout-glass input, body.layout-glass select, body.layout-glass textarea {
background: rgba(0,0,0,0.3);
border-radius: 8px;
border: 1px solid rgba(255,255,255,0.1);
}
+188
View File
@@ -0,0 +1,188 @@
/* --- TEMA SCHEMATIC / BLUEPRINT (Disegno Tecnico CAD) --- */
:root {
--bg-base: #06246f;
--grid-color: rgba(123, 198, 255, 0.15);
--border-main: #7bc6ff;
--border-light: rgba(123, 198, 255, 0.4);
--primary: #7bc6ff;
--success: #00ffcc;
--danger: #ff3366;
--accent: #ffcc00;
--text-main: #ffffff;
--text-muted: rgba(255, 255, 255, 0.6);
}
* { box-sizing: border-box; }
body {
font-family: 'Inter', sans-serif;
background-color: var(--bg-base);
background-image:
linear-gradient(var(--grid-color) 1px, transparent 1px),
linear-gradient(90deg, var(--grid-color) 1px, transparent 1px);
background-size: 20px 20px;
margin: 0; padding: 0; color: var(--text-main); min-height: 100vh;
}
/* TOP BAR - OTTIMIZZATA RIMUOVENDO BACKDROP-FILTER E RISOLVENDO WRAP */
#top-bar-container { position: sticky; top: 0; z-index: 100; padding: 15px 20px; display: flex; justify-content: center; background: rgba(6, 36, 111, 0.95); border-bottom: 1px solid var(--border-main); margin-bottom: 30px; }
#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-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); }
.theme-switch { background: transparent; border: 1px dashed var(--border-main); color: var(--text-main); padding: 6px 14px; cursor: pointer; font-weight: 300; font-size: 0.75rem; letter-spacing: 1px; transition: all 0.2s ease; text-transform: uppercase; white-space: nowrap;}
.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: 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; }
.filter-pill { background: transparent; border: 1px dashed var(--border-light); color: var(--text-muted); padding: 6px 14px; font-size: 0.75rem; font-weight: 300; letter-spacing: 1px; cursor: pointer; transition: all 0.2s ease; text-transform: uppercase; font-family: 'JetBrains Mono', monospace; }
.filter-pill:hover { border-style: solid; border-color: var(--border-main); color: var(--text-main); }
.filter-pill.active { background: rgba(123, 198, 255, 0.15); color: var(--text-main); border: 1px solid var(--text-main); }
.filter-pill.pill-warn { color: var(--accent); border-color: rgba(255, 204, 0, 0.4); }
.filter-pill.pill-warn.active { background: rgba(255, 204, 0, 0.15); border: 1px solid var(--accent); color: var(--accent); }
/* GRIGLIA E LISTA */
.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; }
/* CARDS - OTTIMIZZATE RIMUOVENDO BACKDROP-FILTER */
.card { background: rgba(6, 36, 111, 0.90) !important; padding: 20px; border: 1px solid var(--border-main) !important; display: flex; flex-direction: column; transition: all 0.3s ease; box-shadow: none !important; border-radius: 0; }
.card:hover { border-color: #fff !important; }
/* HEADER FISSO SU 2 RIGHE ALLINEATO A SINISTRA */
.card-header { display: flex; flex-direction: column; justify-content: flex-start; align-items: flex-start; gap: 8px; margin-bottom: 15px; border-bottom: 1px dashed var(--border-main); padding-bottom: 12px; }
.client-name { font-size: 1.6rem; font-weight: 300; letter-spacing: -1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%; line-height: 1.2; padding-top: 2px; }
.header-badges { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; justify-content: flex-start; width: 100%; }
.badge-id { font-size: 0.75rem; font-family: 'JetBrains Mono', monospace; background: transparent; padding: 0; border: none; color: var(--border-main); }
.type-badge { font-size: 0.65rem; padding: 2px 6px; border: 1px solid var(--primary); background: transparent; color: var(--primary); font-weight: 400; text-transform: uppercase; display: inline-block; vertical-align: middle; }
/* DATI STRUTTURALI */
.health-bar { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.75rem; font-weight: 300; background: transparent; padding: 10px; margin-bottom: 15px; border: 1px solid var(--border-light); font-family: 'JetBrains Mono', monospace; text-align: left; }
.health-bar > span { background: transparent; padding: 4px; border: 1px dashed rgba(255,255,255,0.1); }
.freq-bar { display: flex; justify-content: space-between; font-size: 0.8rem; font-weight: 400; background: transparent; padding: 8px 10px; margin-bottom: 10px; border: 1px dashed var(--border-light); font-family: 'JetBrains Mono', monospace; }
.freq-tx { color: var(--danger); } .freq-rx { color: var(--success); }
.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; text-transform: uppercase; }
.seen-item b { font-weight: 400; }
.seen-item.ok b { color: var(--success); }
.seen-item.warn, .seen-item.warn b { color: var(--accent); font-weight: 400; }
.node-meta { font-size: 0.75rem; color: var(--border-main); text-align: left; margin-bottom: 10px; line-height: 1.4; font-family: 'JetBrains Mono', monospace; }
.node-meta-item { display: block; }
.status-display { text-align: center; font-family: 'Inter', sans-serif; font-size: 0.85rem; font-weight: 300; letter-spacing: 2px; padding: 8px; background: transparent; border: 1px solid var(--border-light); margin-bottom: 10px; color: var(--text-muted); text-transform: uppercase; transition: all 0.3s ease;}
.card.online .status-display { color: var(--success); border-color: var(--success); }
.status-offline { color: var(--danger) !important; border-color: var(--danger) !important; }
.gateway-bar { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 15px; justify-content: flex-start; min-height: 20px;}
.ts-container { display: flex; flex-direction: column; gap: 6px; margin-bottom: 15px; }
.dmr-info { font-size: 0.85rem; font-weight: 400; font-family: 'JetBrains Mono', monospace; padding: 8px 12px; background: transparent !important; border: 1px solid var(--border-light); color: var(--text-muted) !important; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: all 0.3s; text-align: left; }
.terminal-log { background: rgba(0,0,0,0.3); color: var(--border-main); font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; padding: 10px; max-height: 90px; overflow-y: auto; border: 1px dashed var(--border-light); line-height: 1.4; margin-bottom: 15px; scrollbar-width: thin; scrollbar-color: var(--border-light) transparent; }
.actions { display: none; gap: 8px; flex-wrap: wrap; margin-top: auto; }
.btn-cmd { flex: 1; padding: 8px 10px; background: transparent !important; border: 1px solid var(--border-main); color: var(--text-main) !important; font-weight: 300; font-size: 0.75rem; cursor: pointer; font-family: 'Inter', sans-serif; letter-spacing: 1px; transition: all 0.2s ease; text-transform: uppercase; display: flex; align-items: center; justify-content: center; gap: 5px; white-space: nowrap;}
.btn-cmd:hover { background: rgba(255,255,255,0.1) !important; border-color: #fff; }
details.admin-dropdown summary { list-style: none; display: flex; justify-content: center; align-items: center; border: 1px dashed var(--border-main) !important; }
details.admin-dropdown summary::-webkit-details-marker { display: none; }
.mqtt-badge { padding: 4px 10px; font-size: 0.75rem; font-weight: 400; font-family: 'JetBrains Mono', monospace; transition: all 0.3s ease; border: 1px solid var(--border-main); display: flex; align-items: center; justify-content: center; height: 30px; white-space: nowrap;}
.mqtt-online { background: transparent; color: var(--success); border-color: var(--success); }
.mqtt-offline { background: transparent; color: var(--danger); border-color: var(--danger); animation: danger-glow 2s infinite; }
.table-container { background: rgba(6, 36, 111, 0.90); border: 1px solid var(--border-main); overflow-x: auto; overflow-y: auto; max-height: 500px; margin: 0 20px 40px 20px; -webkit-overflow-scrolling: touch; }
thead th { position: sticky; top: 0; z-index: 10; background: var(--bg-base); border-bottom: 1px dashed var(--border-main); font-weight: 400; letter-spacing: 1px; color: var(--border-main); }
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-light); line-height: 1.6; vertical-align: middle; }
th { text-transform: uppercase; font-size: 0.75rem; }
tbody tr:hover { background-color: rgba(123, 198, 255, 0.1); }
@keyframes soft-glow { 0% { box-shadow: inset 0 0 5px var(--pulse-color, var(--primary)); border-color: var(--border-color); } 50% { box-shadow: inset 0 0 15px var(--pulse-color, var(--primary)); border-color: var(--pulse-color, var(--primary)); } 100% { box-shadow: inset 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: 1px solid var(--pulse-color, var(--primary)) !important; }
@keyframes danger-glow { 0% { box-shadow: inset 0 0 5px var(--danger); border-color: var(--border-light); } 50% { box-shadow: inset 0 0 15px var(--danger); border-color: var(--danger); } 100% { box-shadow: inset 0 0 5px var(--danger); border-color: var(--border-light); } }
.blink { animation: danger-glow 1.5s infinite; color: var(--danger) !important; border: 1px solid var(--danger) !important; }
/* MODALS - OTTIMIZZATE */
.modal-overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(6, 36, 111, 0.85); z-index:1000; align-items:center; justify-content:center; backdrop-filter: blur(8px); }
.modal-top { z-index: 5000 !important; }
.modal-content { background: var(--bg-base); border: 1px solid var(--border-main); padding: 25px; max-height: 90vh; overflow-y: auto; width: 90%; }
.auth-btn { background: transparent; color: var(--text-main); border: 1px solid var(--border-main); padding: 6px 12px; font-weight: 300; cursor: pointer; font-size: 0.8rem; font-family: 'Inter', sans-serif; transition: all 0.2s; letter-spacing: 1px; text-transform: uppercase; white-space: nowrap;}
.auth-btn:hover { background: rgba(255,255,255,0.1); border-color: #fff; }
input, select { background: transparent; border: 1px dashed var(--border-main); color: var(--text-main); padding: 8px 12px; font-family: 'JetBrains Mono', monospace; outline: none; }
input:focus, select:focus { border-color: #fff; border-style: solid; }
input:disabled { opacity: 0.5; cursor: not-allowed; }
option { background: var(--bg-base); color: var(--text-main); }
/* MINI CARD - OTTIMIZZATA */
.mini-card { background: rgba(6, 36, 111, 0.90); border: 1px solid var(--border-main); padding: 15px 10px; display: flex; flex-direction: column; align-items: center; justify-content: space-between; text-align: center; transition: all 0.2s ease; cursor: pointer; height: 105px; width: 160px; overflow: hidden; }
.mini-card:hover { background: rgba(123, 198, 255, 0.15); border-color: #fff; }
.mini-card-content { width: 100%; overflow: hidden; }
.mini-card-name { font-weight: 300; font-size: 1.1rem; width: 100%; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; letter-spacing: -0.5px; }
.mini-card-status { font-size: 0.65rem; font-weight: 400; padding: 4px; border: 1px dashed var(--border-light); width: 100%; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; letter-spacing: 1px; margin-top: 5px; transition: all 0.3s ease;}
/* --- STILI FLEET MAP & DIAGNOSTICA --- */
#map-container { max-width: 1400px; height: calc(100vh - 200px); min-height: 550px; margin: 0 auto; border: 1px solid var(--border-main); overflow: hidden; }
/* Filtro CAD per la mappa */
.dark-tiles { filter: invert(1) sepia(1) hue-rotate(180deg) saturate(3) brightness(0.8) contrast(1.2); }
.custom-map-pin { display: flex; align-items: center; justify-content: center; border-radius: 50%; border: 1px solid white; font-size: 0.9rem; background: transparent; font-family: 'JetBrains Mono', monospace; font-weight: normal; transition: all 0.3s ease;}
.pin-online { border-color: var(--success); color: var(--success); }
.pin-offline { border-color: var(--text-muted); color: var(--text-muted); border-style: dashed; }
.pin-warn { border-color: var(--accent) !important; color: var(--accent) !important; }
.pin-tx { border-color: var(--primary) !important; color: var(--primary) !important; box-shadow: inset 0 0 8px var(--primary); border-width: 2px; }
.leaflet-popup-content-wrapper { background: var(--bg-base) !important; color: var(--text-main) !important; border-radius: 0 !important; border: 1px solid var(--border-main) !important; box-shadow: none !important; }
.leaflet-popup-tip { background: var(--border-main) !important; }
/* Responsive rules */
@media (max-width: 1200px) {
#top-bar { flex-direction: column; align-items: stretch;}
.title-brand { text-align: center; margin-bottom: 10px; margin-right: 0;}
.nav-tabs { justify-content: center; margin-left: 0; margin-bottom: 10px;}
.top-bar-right { justify-content: center;}
}
@media (max-width: 768px) {
#top-bar-container { top: 0; padding: 10px; margin-bottom: 15px; border-bottom: 1px solid var(--border-main); }
#top-bar { padding: 15px; gap: 12px; }
.title-brand { font-size: 1.1rem; text-align: center; width: 100%; margin-right: 0;}
.top-bar-right { 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 dashed var(--border-main); margin-top: 5px;}
#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(--bg-base); border-top: 1px solid var(--border-main); margin: 0; padding: 10px 0; justify-content: space-around; z-index: 1000; flex-direction: row; gap: 0; padding-bottom: env(safe-area-bottom, 10px); }
.nav-tab { font-size: 0.85rem; padding: 10px; flex: 1; text-align: center; }
body { padding-bottom: 70px; }
.filter-bar { flex-direction: column; clip-path: none; border: 1px solid var(--border-light); margin-bottom: 10px;}
.list-view .card { flex-direction: column; align-items: stretch; clip-path: none;}
#map-container { height: calc(100vh - 220px); min-height: 400px; margin: 0 10px; clip-path: none;}
.table-container { clip-path: none; border: 1px solid var(--border-light); margin: 0 10px 20px 10px; }
.table-container table, .table-container thead, .table-container tbody, .table-container th, .table-container td, .table-container tr { display: block; width: 100%; }
.table-container thead tr { position: absolute; top: -9999px; left: -9999px; }
.table-container tr { border-bottom: 2px dashed var(--border-light); margin-bottom: 15px; background: var(--bg-base); padding: 10px; }
.table-container td { border: none; position: relative; padding-left: 40%; text-align: left; min-height: 30px; display: flex; align-items: center; }
.table-container td:before { position: absolute; top: 50%; transform: translateY(-50%); left: 10px; width: 35%; padding-right: 10px; font-weight: 800; color: var(--accent); content: attr(data-label); font-size: 0.75rem; }
}
+1654
View File
File diff suppressed because it is too large Load Diff
+969
View File
@@ -0,0 +1,969 @@
// --- SISTEMA TRADUZIONI (i18n) & HELPERS ---
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",
btnReqCfg: "REQ_CFG", btnGlobal: "GBL_OVR", btnAdmin: "SYS_ADM", btnPass: "CHG_PWD", btnLogout: "LOGOUT",
btnSvc: "SVC", btnFile: "CFG", btnBoot: "REBOOT", btnAdd: "ADD",
waitNet: "> Waiting network...", waitData: "Waiting for node data...", forceUpdate: "FORCE_UPD",
adminTitle: "SYS_ADMIN", adminDBSync: "DB_SYNC_CFG", adminTime: "Daily Update Time:", adminSave: "SAVE_CFG", roleOp: "Operator",
modSvcTitle: "DAEMONS:", modFileTitle: "CFG_FILES", modEditTitle: "EDIT:",
warnEdit: "[WARN] DIRECT EDIT ACTIVE",
btnEdit: "EDIT", btnStart: "START", btnRestart: "RST", btnStop: "STOP", btnSave: "WRITE_FILE",
btnHat: "RST_HAT", confHat: "PHYSICAL RESET MMDVM ON: ",
confOta: "EXECUTE GIT PULL 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: "[WARN] DAEMON OFFLINE",
promptOvr: "GLOBAL OVERRIDE", promptOvrConfirm: "Confirm sending to ENTIRE network?",
modUpdateTitle: "GBL_UPDATE", confUpdate: "Do you want to request updated data and configuration files from all nodes in the fleet?", alertUpdateOk: "ACK",
btnConfReset: "CONFIRM", btnCancel: "ABORT", promptPass: "NEW PWD:",
titleError: "ERR", titleSuccess: "OK", titleAction: "CONFIRM", titleDelete: "DEL_USR", titleSave: "SAVE", titleGlobal: "GBL_OVR",
btnYes: "EXECUTE", msgDelUser: "DELETE USER?", msgPassOk: "PWD_UPDATED", msgPassErr: "PWD_ERR", msgLoginFail: "AUTH_FAIL",
msgConfigSaved: "CFG_SAVED", msgConfigErr: "CFG_ERR", msgNetErr: "NET_ERR", msgOvrSel: "SELECT_PROF:",
msgOvrOk: "CMD_BROADCASTED", msgMissUser: "MISSING_USR", msgMissPass: "MISSING_PWD", btnSvcKo: "DAEMON_ERR",
phNewPass: "NEW_PWD (EMPTY=KEEP)", phPass: "PWD",
titleSwitch: "SW_PROF", confSwitch: "SWITCH TO ", titleBoot: "SYS_REBOOT", confBoot: "REBOOT NODE ",
ttReqCfg: "REQ_DATA", ttGlobal: "GBL_OVR", ttAdmin: "ADMIN", ttPass: "CHG_PWD", ttLogout: "LOGOUT",
ttProfA: "PROF_A", ttProfB: "PROF_B", ttTgOn: "TG_ON", ttTgOff: "TG_OFF", ttSvc: "DAEMONS", ttFile: "FILES", ttHat: "RST_HAT", ttBoot: "REBOOT",
ttSwitchTo: "SW_TO: ", ttSvcStart: "START", ttSvcRestart: "RST", ttSvcEdit: "EDIT", ttSvcStop: "STOP", ttLang: "LANG",
statTopTG: "TOP_TG", statTopCall: "TOP_CALL", statLoading: "LOADING...", statAvgDur: "AVG_DUR", statTodayTx: "TX_TODAY", statNoData: "NO_DATA",
statTitle: "DAILY_STATS", statAllNodes: "ALL_NODES", modVersions: "SW_VERSIONS",
filtAll: "ALL_NODES", filtOnline: "ONLINE", filtOffline: "OFFLINE", filtAlerts: "ALERTS",
fleetStatus: "[ FLEET_STATUS ]", aprsTraffic: "[ APRS_TRAFFIC ]", btnClear: "[ CLEAR ]", btnReturn: "[ < RETURN TO OVERVIEW ]",
hwTelemetry: "[ HARDWARE_TELEMETRY ]", rfConfig: "[ RF_CONFIGURATION ]", opModes: "[ OPERATING_MODES ]", actGateways: "[ ACTIVE_GATEWAYS ]",
tsModes: "[ TIMESLOTS_MODES ]", liveTerminal: "[ LIVE_TERMINAL ]", nodeLastheard: "[ NODE_LASTHEARD ]", adminControls: "[ ADMIN_CONTROLS ]",
cpuLoad: "CPU_LOAD:", sysTemp: "SYS_TEMP:", ramUsage: "RAM_USAGE:", diskSpace: "DISK_SPACE:", sysUptime: "UPTIME:",
txFreq: "TX_FREQ:", rxFreq: "RX_FREQ:", nodeLoc: "LOCATION:",
statusOffline: "OFFLINE", statusAlert: "(!) ALERT", awaitingStream: "> AWAITING_STREAM...", focusNode: "FOCUS_NODE", noActiveGw: "NO_ACTIVE_GATEWAYS",
lblSysUptime: "System Uptime", lblSwVersions: "Software Versions", lblOtaUpdate: "OTA Update", waitConfig: "WAITING FOR CONFIG...",
noDaemonData: "NO DAEMON DATA YET. RETRYING...", cfgEmpty: "[!] CFG MEMORY EMPTY", netError: "NETWORK ERROR", noModesFound: "NO MODES FOUND IN CONFIG",
accessDenied: "[ ACCESS DENIED ]", savingRestart: "⏳ SAVING & RESTARTING...", stateUpdated: "✅ STATE UPDATED SUCCESSFULLY!",
phSearch: "SEARCH ID/CALL...", btnGrid: "[ GRID ]", btnList: "[ LIST ]"
},
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",
btnReqCfg: "REQ_CFG", btnGlobal: "GBL_OVR", btnAdmin: "SYS_ADM", btnPass: "CHG_PWD", btnLogout: "ESCI",
btnSvc: "SERVIZI", btnFile: "CFG", btnBoot: "RIAVVIA", btnAdd: "AGGIUNGI",
waitNet: "> Attesa rete...", waitData: "In attesa dei dati dal nodo...", forceUpdate: "FORZA AGGIORNAMENTO",
adminTitle: "AMMINISTRAZIONE SISTEMA", adminDBSync: "SINCRONIZZAZIONE DB", adminTime: "Orario Aggiornamento:", adminSave: "SALVA CONFIG", roleOp: "Operatore",
modSvcTitle: "DEMONI:", modFileTitle: "FILE CONFIGURAZIONE", modEditTitle: "MODIFICA:",
warnEdit: "[ATTENZIONE] MODIFICA DIRETTA ATTIVA",
btnEdit: "MODIFICA", btnStart: "AVVIA", btnRestart: "RIAVVIA", btnStop: "FERMA", btnSave: "SALVA FILE",
btnHat: "RESET HAT", confHat: "Reset hardware modem MMDVM su: ",
confOta: "Eseguire git pull 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: "[ATTENZIONE] DEMONE OFFLINE",
promptOvr: "OVERRIDE GLOBALE", promptOvrConfirm: "Confermi l'invio a TUTTA la rete?",
modUpdateTitle: "AGGIORNAMENTO FLOTTA", confUpdate: "Vuoi richiedere i dati e i file di configurazione aggiornati a tutti i nodi della flotta?", alertUpdateOk: "CONFERMATO",
btnConfReset: "CONFERMA", btnCancel: "ANNULLA", promptPass: "NUOVA PASSWORD:",
titleError: "ERRORE", titleSuccess: "OK", titleAction: "CONFERMA", titleDelete: "ELIMINA UTENTE", titleSave: "SALVA", titleGlobal: "OVERRIDE GLOBALE",
btnYes: "ESEGUI", msgDelUser: "Eliminare definitivamente l'utente?", msgPassOk: "PASSWORD AGGIORNATA", msgPassErr: "ERRORE AGGIORNAMENTO PASSWORD", msgLoginFail: "CREDENZIALI NON VALIDE",
msgConfigSaved: "CONFIGURAZIONE SALVATA", msgConfigErr: "ERRORE SALVATAGGIO CONFIG", msgNetErr: "ERRORE DI RETE", msgOvrSel: "SELEZIONA PROFILO:",
msgOvrOk: "COMANDO INVIATO ALLA RETE", msgMissUser: "SPECIFICARE NOME UTENTE", msgMissPass: "SPECIFICARE PASSWORD", btnSvcKo: "ERRORE DEMONE",
phNewPass: "NUOVA PWD (VUOTA = INVARIATA)", phPass: "PASSWORD",
titleSwitch: "CAMBIO PROFILO", confSwitch: "Passa al profilo ", titleBoot: "RIAVVIO NODO", confBoot: "Riavviare il nodo ",
ttReqCfg: "Richiedi dati nodi", ttGlobal: "Override globale profili", ttAdmin: "Pannello amministrazione", ttPass: "Cambia 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 a: ", ttSvcStart: "Avvia demone", ttSvcRestart: "Riavvia demone", ttSvcEdit: "Modifica configurazione", ttSvcStop: "Arresta demone", ttLang: "Lingua",
statTopTG: "TOP TALKGROUP", statTopCall: "TOP NOMINATIVI", statLoading: "CARICAMENTO...", statAvgDur: "DURATA MEDIA", statTodayTx: "PASSAGGI OGGI", statNoData: "NESSUN DATO",
statTitle: "STATISTICHE GIORNALIERE", statAllNodes: "TUTTI I NODI", modVersions: "VERSIONI SOFTWARE",
filtAll: "TUTTI I NODI", filtOnline: "ONLINE", filtOffline: "OFFLINE", filtAlerts: "AVVISI",
fleetStatus: "[ STATO FLOTTA ]", aprsTraffic: "[ TRAFFICO APRS ]", btnClear: "[ PULISCI ]", btnReturn: "[ < TORNA ALLA DASHBOARD ]",
hwTelemetry: "[ TELEMETRIA HARDWARE ]", rfConfig: "[ CONFIGURAZIONE RF ]", opModes: "[ MODI OPERATIVI ]", actGateways: "[ GATEWAY ATTIVI ]",
tsModes: "[ TIMESLOT E MODI ]", liveTerminal: "[ TERMINALE LIVE ]", nodeLastheard: "[ ULTIMI ASCOLTI NODO ]", adminControls: "[ CONTROLLI AMMINISTRATORE ]",
cpuLoad: "CARICO CPU:", sysTemp: "TEMP. SIS:", ramUsage: "UTILIZZO RAM:", diskSpace: "SPAZIO DISCO:", sysUptime: "ATTIVITÀ:",
txFreq: "FREQ. TX:", rxFreq: "FREQ. RX:", nodeLoc: "POSIZIONE:",
statusOffline: "OFFLINE", statusAlert: "(!) AVVISO", awaitingStream: "> IN ATTESA DI FLUSSO DATI...", focusNode: "DETTAGLI NODO", noActiveGw: "NESSUN GATEWAY ATTIVO",
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 ]",
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 %"
}
};
let currentLang = localStorage.getItem('lang') || 'en';
function t(key) { return i18n[currentLang][key] || key; }
function toggleLang() { currentLang = currentLang === 'it' ? 'en' : 'it'; localStorage.setItem('lang', currentLang); location.reload(); }
function applyTranslations() {
const langBtn = document.getElementById('lang-btn');
if (langBtn) langBtn.innerText = currentLang === 'it' ? "ENG" : "ITA";
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
if (i18n[currentLang][key]) el.innerHTML = i18n[currentLang][key];
});
document.querySelectorAll('[data-i18n-title]').forEach(el => {
const key = el.getAttribute('data-i18n-title');
if (i18n[currentLang][key]) el.title = i18n[currentLang][key];
});
const newPassInput = document.getElementById('new-pass');
if (newPassInput && typeof editingUserId !== 'undefined' && editingUserId) newPassInput.placeholder = t('phNewPass');
else if (newPassInput) newPassInput.placeholder = t('phPass');
const searchInput = document.getElementById('node-search');
if (searchInput) searchInput.placeholder = t('phSearch') || 'SEARCH ID/CALL...';
if (typeof applyViewMode === 'function') applyViewMode();
}
function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
function q(s) { return esc(JSON.stringify(String(s ?? ''))); }
// --- DIALOGHI ALERT & CONFIRM ---
function customAlert(title, desc, isError = false) {
const color = isError ? 'var(--danger)' : 'var(--success)';
document.getElementById('alert-title').innerHTML = '> ' + title;
document.getElementById('alert-title').style.color = color;
document.getElementById('alert-box').style.borderTopColor = color;
document.getElementById('alert-desc').innerHTML = desc;
document.getElementById('alert-modal').style.display = 'flex';
}
function customConfirm(title, desc, color, callback) {
document.getElementById('confirm-title').innerHTML = '> ' + title;
document.getElementById('confirm-title').style.color = color;
document.getElementById('confirm-box').style.borderTopColor = color;
document.getElementById('confirm-desc').innerHTML = desc;
document.getElementById('confirm-yes-btn').style.borderColor = color;
document.getElementById('confirm-yes-btn').style.color = color;
document.getElementById('confirm-yes-btn').innerText = t('btnYes');
document.getElementById('confirm-cancel-btn').innerText = t('btnCancel');
confirmActionCallback = callback;
document.getElementById('confirm-modal').style.display = 'flex';
}
function executeConfirmAction() {
document.getElementById('confirm-modal').style.display = 'none';
if (confirmActionCallback) { confirmActionCallback(); confirmActionCallback = null; }
}
// --- MODALE LOGIN ---
function openLoginModal() { document.getElementById('login-modal').style.display = 'flex'; setTimeout(() => document.getElementById('modal-username').focus(), 100); }
function closeLoginModal() { document.getElementById('login-modal').style.display = 'none'; document.getElementById('modal-username').value = ''; document.getElementById('modal-password').value = ''; }
function handleLoginEnter(e) { if (e.key === 'Enter') performLogin(); }
// --- MODALE RESET HAT ---
function confirmHatReset(id) {
currentResetHatId = id;
document.getElementById('reset-hat-desc').innerText = `${t('confHat')}${id.toUpperCase()}?`;
document.getElementById('reset-hat-modal').style.display = 'flex';
}
function closeHatResetModal() { document.getElementById('reset-hat-modal').style.display = 'none'; currentResetHatId = null; }
async function executeHatReset() {
if (!currentResetHatId) return;
const clientId = currentResetHatId; closeHatResetModal();
try {
const res = await fetch('/api/command', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: clientId, type: 'RESET_HAT' }) });
const data = await res.json();
if(!data.success) { customAlert(t('titleError'), esc(data.error), true); }
refreshStates();
} catch (e) { console.error(e); }
}
// --- MODALE GLOBAL UPDATE ---
function sendGlobalUpdate() { document.getElementById('update-modal').style.display = 'flex'; }
function closeUpdateModal() { document.getElementById('update-modal').style.display = 'none'; }
async function executeUpdateRequest() {
closeUpdateModal();
try { await fetch('/api/update_nodes', { method: 'POST' }); customAlert(t('titleSuccess'), t('alertUpdateOk')); }
catch (e) { console.error(e); }
}
// --- MODALE ADMIN & UTENTI ---
async function openAdmin() {
document.getElementById('admin-modal').style.display = 'flex';
// Inietto i bottoni operativi dentro l'header del pannello admin
let adminBtnsHtml = '';
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAllNodes = allowedList.includes('all');
const canOverride = hasAllNodes;
if (role === 'admin') {
adminBtnsHtml += `<button id="server-update-btn-modal" onclick="confirmServerUpdate(); closeAdmin();" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; display:none; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ UPD_SERVER ]</button>`;
adminBtnsHtml += `<button onclick="sendGlobalUpdate(); closeAdmin();" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ REQ_CFG ]</button>`;
}
if (role === 'admin' || role === 'node_admin') {
adminBtnsHtml += `<button onclick="openScheduleModal(); closeAdmin();" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ SCHED ]</button>`;
}
if (canOverride) {
adminBtnsHtml += `<button onclick="triggerGlobalEmergency(); closeAdmin();" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ GBL_OVR ]</button>`;
}
const adminActionDiv = document.getElementById('admin-action-btns');
if (adminActionDiv) {
adminActionDiv.innerHTML = adminBtnsHtml;
// Se siamo admin eseguiamo anche un check per l'update del server per mostrare/nascondere il tasto
if (role === 'admin' && typeof GLOBAL_SERVER_UPDATE_AVAILABLE !== 'undefined' && GLOBAL_SERVER_UPDATE_AVAILABLE) {
const upBtn = document.getElementById('server-update-btn-modal');
if(upBtn) upBtn.style.display = 'inline-block';
}
}
if (me.role === 'admin') {
loadUsers();
loadSettings();
cancelEdit();
}
loadAuditLogs();
}
function closeAdmin() { document.getElementById('admin-modal').style.display = 'none'; cancelEdit(); }
async function loadUsers() {
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>[ ${esc(String(u.role).toUpperCase())} ]</td><td>${esc(u.allowed_nodes)}</td>
<td style="text-align:right; min-width: 130px; white-space: nowrap;">
<button onclick="startEditUser(${Number(u.id)})" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; display:inline-block; width: 60px; flex: 0 0 60px; margin-right:5px; padding: 6px;">EDIT</button>
<button onclick="deleteUser(${u.id})" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; display:inline-block; width: 60px; flex: 0 0 60px; padding: 6px;">DEL</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 = "UPDATE"; btnSubmit.style.borderColor = "var(--accent)"; btnSubmit.style.color = "var(--accent) !important"; 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 = "ADD"; btnSubmit.style.borderColor = "var(--success)"; btnSubmit.style.color = "var(--success) !important"; 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(); }); }
// --- CONFIGURAZIONE SYNC / DB ---
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); }
}
// --- GLOBAL OVERRIDE ---
function triggerGlobalEmergency() {
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAll = allowedList.includes('all');
let uniqueProfiles = {};
for (const id in globalHealthData) {
if (!hasAll && !allowedList.includes(id.toLowerCase())) continue;
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)", "#00ffcc", "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="border-color:${col}; color:${col} !important;">${esc(v)}</button>`;
idx++;
}
if (Object.keys(uniqueProfiles).length === 0) { html = `<p style="color:var(--danger); font-weight:400; font-family:'JetBrains Mono',monospace;">NO_PROFS_FOUND</p>`; }
container.innerHTML = html;
const descText = hasAll ? t('msgOvrSel') : (currentLang === 'it' ? `SELEZIONA PROFILO (NODI ASSEGNATI: ${allowedList.length}):` : `SELECT PROFILE (NODES: ${allowedList.length}):`);
document.getElementById('override-desc').innerText = descText;
document.getElementById('override-modal').style.display = 'flex';
}
function sendGlobalAction(action) {
document.getElementById('override-modal').style.display = 'none';
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAll = allowedList.includes('all');
const confirmMsg = hasAll
? t('promptOvrConfirm')
: (currentLang === 'it'
? `Confermi l'invio ai tuoi nodi autorizzati (${allowedList.map(n => n.toUpperCase()).join(', ')})?`
: `Confirm sending to your authorized nodes (${allowedList.map(n => n.toUpperCase()).join(', ')})?`);
customConfirm(t('titleGlobal'), confirmMsg, "var(--danger)", async () => {
try {
const res = await fetch('/api/global_command', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({type: action})
});
const d = await res.json();
if(d.success) customAlert(t('titleSuccess'), t('msgOvrOk'));
else customAlert(t('titleError'), esc(d.error), true);
refreshStates();
} catch(e) { console.error(e); }
});
}
// --- CAMBIO PASSWORD ---
function changeMyPassword() { document.getElementById('new-password-input').value = ''; document.getElementById('password-modal').style.display = 'flex'; setTimeout(() => document.getElementById('new-password-input').focus(), 100); }
function closePasswordModal() { document.getElementById('password-modal').style.display = 'none'; }
async function executePasswordChange() {
const p = document.getElementById('new-password-input').value; if (!p) return; closePasswordModal();
try { const res = await fetch('/api/change_password', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username: me.user, new_password: p}) });
if ((await res.json()).success) { customAlert(t('titleSuccess'), t('msgPassOk')); setTimeout(() => logout(), 1500); } else { customAlert(t('titleError'), t('msgPassErr'), true); }
} catch(e) { console.error(e); }
}
// --- MODALE FILE CONFIGURAZIONE ---
function fileLabel(stem, names) {
const key = String(stem).toLowerCase(); const full = (names || []).find(n => String(n).replace(/\.[^.]*$/, '').toLowerCase() === key);
if (full) { const m = String(full).match(/^(.*?)(\.[^.]*)?$/); return String(m[1]).toUpperCase() + (m[2] || ''); }
return String(stem).toUpperCase() + '.INI';
}
function openConfigsModal(clientId) {
const data = globalHealthData[clientId.toLowerCase()];
const listDiv = document.getElementById('configs-list');
let listaFile = data ? (data.config_files || data.files || []) : [];
const fileNames = (data && data.file_names) || [];
if (listaFile.length === 0) {
listDiv.innerHTML = `<p>${t('waitData')}</p><button onclick="sendGlobalUpdate(); closeConfigsModal();" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important;">${t('forceUpdate')}</button>`;
} else {
listDiv.innerHTML = listaFile.map(f => `<div style="display:flex; justify-content:space-between; align-items:center; padding:10px 0; border-bottom:1px dashed var(--border-light); width:100%;">
<span style="font-weight:400; font-family:'JetBrains Mono',monospace; flex: 1; text-align: left; overflow:hidden; text-overflow:ellipsis; padding-right:20px;">${esc(fileLabel(f, fileNames))}</span>
<button onclick="closeConfigsModal(); openEditorModal(${q(clientId)}, ${q(f)})" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width: 80px; flex: 0 0 80px; padding: 6px;">${t('btnEdit')}</button>
</div>`).join('');
}
document.getElementById('configs-modal').style.display = 'flex';
}
function closeConfigsModal() { document.getElementById('configs-modal').style.display = 'none'; }
// --- MODALE GESTIONE DEMONI/SERVIZI ---
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>NO_DATA</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:10px 0; border-bottom:1px dashed var(--border-light); width: 100%;">
<div style="font-weight:400; color:${statusColor}; font-family:'JetBrains Mono',monospace; flex: 1; text-align: left; overflow:hidden; text-overflow:ellipsis; padding-right:20px;">${esc(name)} [${esc(String(status).toUpperCase())}]</div>
<div style="display:flex; gap:8px; flex: 0 0 auto; justify-content: flex-end;">
${!isOnline ? `<button onclick="controlService(${q(clientId)},${q(name)}, 'start')" class="btn-cmd" style="border-color:var(--success); color:var(--success) !important; width: 70px; flex: 0 0 70px; padding: 6px 0;">START</button>` : ''}
<button onclick="controlService(${q(clientId)}, ${q(name)}, 'restart')" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width: 70px; flex: 0 0 70px; padding: 6px 0;">RST</button>
<button onclick="openEditorModal(${q(clientId)}, ${q(name)})" class="btn-cmd" style="width: 70px; flex: 0 0 70px; padding: 6px 0;">EDIT</button>
${isOnline ? `<button onclick="controlService(${q(clientId)},${q(name)}, 'stop')" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; width: 70px; flex: 0 0 70px; padding: 6px 0;">STOP</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'), "ERR: " + esc(data.error), true);
} catch(e) { console.error(e); }
});
}
// --- 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; isDiffMode = false;
document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`;
document.getElementById('config-textarea').value = "AWAITING_STREAM...";
document.getElementById('config-textarea').style.display = 'block';
document.getElementById('diff-view').style.display = 'none';
document.getElementById('btn-cancel-diff').style.display = 'none';
document.getElementById('editor-status').innerText = "";
document.getElementById('editor-modal').style.display = 'flex';
document.getElementById('config-history-select').innerHTML = `<option value="">${t('optCurrentUnsaved')}</option>`;
historyConfigs = {};
try {
const res = await fetch(`/api/config_file/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`);
const data = await res.json();
if (data.success) {
currentOriginalConfig = data.data.raw_text || "";
document.getElementById('config-textarea').value = currentOriginalConfig;
fetchConfigHistory(clientId, service);
} else {
document.getElementById('config-textarea').value = "ERR:\n" + data.error;
}
} catch(e) {
document.getElementById('config-textarea').value = "NET_ERR";
}
}
async function fetchConfigHistory(clientId, service) {
try {
const res = await fetch(`/api/config_backups/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`);
const data = await res.json();
if (data.success && data.backups.length > 0) {
const select = document.getElementById('config-history-select');
data.backups.forEach(b => {
const opt = document.createElement('option');
opt.value = b.id;
opt.text = `${b.timestamp} (${b.username})`;
select.appendChild(opt);
});
}
} catch(e) { console.error("History fetch error:", e); }
}
async function loadHistoryConfig() {
const val = document.getElementById('config-history-select').value;
if (!val) {
// Ripristina testualmente la versione corrente se scelgono "Attuale"
document.getElementById('config-textarea').value = currentOriginalConfig;
return;
}
if (historyConfigs[val]) {
document.getElementById('config-textarea').value = historyConfigs[val];
return;
}
try {
const res = await fetch(`/api/config_backups/${val}`);
const data = await res.json();
if (data.success) {
historyConfigs[val] = data.text;
document.getElementById('config-textarea').value = data.text;
}
} catch (e) { console.error(e); }
}
function previewConfigDiff() {
const newText = document.getElementById('config-textarea').value;
const diffView = document.getElementById('diff-view');
const textarea = document.getElementById('config-textarea');
if (isDiffMode) {
// Torna all'editor
textarea.style.display = 'block';
diffView.style.display = 'none';
document.getElementById('btn-cancel-diff').style.display = 'none';
isDiffMode = false;
return;
}
// Calcola il diff visivo
const dmp = new diff_match_patch();
const diffs = dmp.diff_main(currentOriginalConfig, newText);
dmp.diff_cleanupSemantic(diffs);
let html = "";
diffs.forEach(part => {
const type = part[0]; // -1 rimossa, 1 aggiunta, 0 uguale
const text = esc(part[1]);
if (type === 1) html += `<span style="background-color: rgba(46, 204, 113, 0.2); color: #2ecc71;">${text}</span>`;
else if (type === -1) html += `<span style="background-color: rgba(231, 76, 60, 0.2); color: #e74c3c; text-decoration: line-through;">${text}</span>`;
else html += `<span style="color: var(--text-muted); opacity: 0.8;">${text}</span>`;
});
if (diffs.length === 1 && diffs[0][0] === 0) {
html = `<span style="color: var(--success); font-weight: bold;">${t('msgNoModifications')}</span>\n\n` + html;
}
diffView.innerHTML = html;
textarea.style.display = 'none';
diffView.style.display = 'block';
document.getElementById('btn-cancel-diff').style.display = 'block';
isDiffMode = true;
}
function cancelDiff() {
document.getElementById('config-textarea').style.display = 'block';
document.getElementById('diff-view').style.display = 'none';
document.getElementById('btn-cancel-diff').style.display = 'none';
isDiffMode = false;
}
function closeEditorModal() { document.getElementById('editor-modal').style.display = 'none'; }
function saveConfig() {
const textValue = document.getElementById('config-textarea').value;
const statusSpan = document.getElementById('editor-status');
if (!isDiffMode && textValue !== currentOriginalConfig) {
customConfirm(t('titleSave'), t('warnUnverifiedDiff'), "var(--accent)", () => executeSave(textValue, statusSpan));
} else {
customConfirm(t('titleSave'), `${t('confOvr')}<b>${currentEditClient.toUpperCase()}</b>?`, "var(--danger)", () => executeSave(textValue, statusSpan));
}
}
async function executeSave(textValue, statusSpan) {
statusSpan.innerText = "WRITING..."; statusSpan.style.color = "var(--success)";
try {
const res = await fetch('/api/config_file', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: currentEditClient, service: currentEditService, config_data: { "raw_text": textValue } }) });
const data = await res.json();
if (data.success) {
customAlert(t('titleSuccess'), "FILE_WRITTEN");
currentOriginalConfig = textValue; // Aggiorna l'originale corrente
closeEditorModal();
} else {
customAlert(t('titleError'), "ERR: " + esc(data.error), true); statusSpan.innerText = "ERR";
}
} catch(e) { customAlert(t('titleError'), t('msgNetErr'), true); statusSpan.innerText = "NET_ERR"; }
}
// --- MODALE VERSIONI SOFTWARE ---
function openVersionsModal(clientId) {
const versions = globalVersionsData[clientId.toLowerCase()]; const listDiv = document.getElementById('versions-list');
if (!versions || Object.keys(versions).length === 0) { listDiv.innerHTML = "<p style='font-family:\"JetBrains Mono\",monospace;'>NO_DATA. RESTART SVCS TO PUSH LOGS.</p>"; }
else { let html = ""; for (const [software, version] of Object.entries(versions)) { html += `<div style="border-bottom:1px dashed var(--border-light); padding:5px 0;"><strong style="color: var(--primary); display: inline-block; width: 140px;">${esc(software)}:</strong> <span style="color: var(--success); font-weight: 400;">${esc(version)}</span></div>`; } listDiv.innerHTML = html; }
document.getElementById('versions-modal').style.display = 'flex';
}
function closeVersionsModal() { document.getElementById('versions-modal').style.display = 'none'; }
// -------------------- LIVE LOG MODAL --------------------
let currentLogClientId = null;
function openLogModal(clientId) {
currentLogClientId = clientId.toLowerCase();
document.getElementById('log-modal-title').innerText = clientId.toUpperCase();
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logConnWait')} ${clientId.toUpperCase()}...</span>\n`;
document.getElementById('log-modal').style.display = 'flex';
document.getElementById('log-service-filter').value = 'ALL';
// 1. Fetch initial logs
fetch(`/api/logs/${clientId}`)
.then(res => res.json())
.then(data => {
if (data.success && data.logs.length > 0) {
document.getElementById('log-console').innerHTML = '';
data.logs.forEach(log => appendLog(log));
} else {
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logNoData')} ${clientId.toUpperCase()}.</span>\n`;
}
})
.catch(err => console.error("Errore fetch logs:", err));
// 2. Subscribe WebSocket
window.socket.on('live_log_' + currentLogClientId, function(logEntry) {
appendLog(logEntry);
});
}
function closeLogModal() {
document.getElementById('log-modal').style.display = 'none';
if (currentLogClientId) {
window.socket.off('live_log_' + currentLogClientId);
}
currentLogClientId = null;
}
let autoScroll = true;
function toggleAutoScroll() {
autoScroll = !autoScroll;
const btn = document.getElementById('btn-autoscroll');
if (autoScroll) {
btn.innerText = t('btnScrollOn') || 'SCROLL: ON';
btn.style.borderColor = 'var(--accent)';
btn.style.setProperty('color', 'var(--accent)', 'important');
scrollToBottom();
} else {
btn.innerText = t('btnScrollOff') || 'SCROLL: OFF';
btn.style.borderColor = 'var(--text-muted)';
btn.style.setProperty('color', 'var(--text-muted)', 'important');
}
}
function clearLogs() {
document.getElementById('log-console').innerHTML = '';
}
function scrollToBottom() {
const box = document.getElementById('log-console');
box.scrollTop = box.scrollHeight;
}
function appendLog(log) {
const filter = document.getElementById('log-service-filter').value.toLowerCase();
const logSvc = log.service.toLowerCase();
if (filter !== 'all' && !logSvc.includes(filter)) {
return;
}
const box = document.getElementById('log-console');
let color = '#c9d1d9';
let prefix = log.service.toLowerCase();
if (prefix.includes('mmdvm')) color = '#58a6ff';
else if (prefix.includes('dmr')) color = '#3fb950';
else if (prefix.includes('ysf')) color = '#8b5cf6'; // Violetto per YSF
else if (prefix.includes('dstar') || prefix.includes('d-star')) color = '#f97316'; // Arancio per D-Star
else if (prefix.includes('nxdn')) color = '#10b981'; // Verde NXDN
else if (prefix.includes('p25')) color = '#ffcc00'; // Giallo P25
const span = document.createElement('div');
span.style.marginBottom = '2px';
const timeSpan = `<span style="color: #8b949e;">[${log.time}]</span>`;
const svcSpan = `<span style="color: ${color}; font-weight: bold;">[${log.service}]</span>`;
span.innerHTML = `${timeSpan} ${svcSpan} ${escapeHtml(log.text)}`;
// Remove default "Connessione in corso..." if present
if (box.innerHTML.includes(t('logConnWait'))) {
box.innerHTML = '';
}
box.appendChild(span);
// Keep max 1000 lines in DOM to prevent lag
if (box.childElementCount > 1000) {
box.removeChild(box.firstChild);
}
if (autoScroll) scrollToBottom();
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
function renderLogs() {
// When filter changes, we just clear and wait for new logs, or we could refetch.
// For simplicity, we clear the console and fetch again from server.
if (currentLogClientId) {
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logApplyFilter')}</span>\n`;
fetch(`/api/logs/${currentLogClientId}`)
.then(res => res.json())
.then(data => {
document.getElementById('log-console').innerHTML = '';
if (data.success) {
data.logs.forEach(log => appendLog(log));
}
});
}
}
// --- SECURITY AUDIT LOGS ---
async function loadAuditLogs() {
try {
const res = await fetch('/api/audit_logs');
const data = await res.json();
const container = document.getElementById('audit-logs-container');
if (data.success && data.logs) {
if (data.logs.length === 0) {
container.innerHTML = `<span style="color: var(--text-muted);">${t('msgNoAudit')}</span>`;
return;
}
let html = '';
data.logs.forEach(log => {
html += `<div style="border-bottom: 1px dashed var(--border-light); padding: 4px 0; display: flex; gap: 15px;">
<span style="color: var(--text-muted); flex: 0 0 140px;">[${log.time}]</span>
<span style="color: var(--primary); flex: 0 0 100px;">${esc(log.user.toUpperCase())}</span>
<span style="color: var(--success); flex: 0 0 80px;">${esc(log.node.toUpperCase())}</span>
<span style="color: var(--text-main); flex: 1;">${esc(log.cmd)}</span>
</div>`;
});
container.innerHTML = html;
}
} catch(e) { console.error("Error loading audit logs:", e); }
}
// --- MODALE CALENDARIO SCHEDULAZIONE PROFILI ---
async function openScheduleModal() {
document.getElementById('schedule-modal').style.display = 'flex';
populateScheduleNodeOptions();
loadSchedules();
// Inizializza le date con orari coerenti (Inizio: adesso + 5 min, Fine: adesso + 2 ore)
const now = new Date();
const in5m = new Date(now.getTime() + 5 * 60000);
const in2h = new Date(now.getTime() + 125 * 60000);
const toLocalISO = (d) => {
const pad = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
document.getElementById('sched-start').value = toLocalISO(in5m);
document.getElementById('sched-end').value = toLocalISO(in2h);
}
function closeScheduleModal() {
document.getElementById('schedule-modal').style.display = 'none';
}
function updateScheduleProfileOptions() {
const selNodes = document.getElementById('sched-nodes-select');
const selTarget = document.getElementById('sched-target-prof');
const selRestore = document.getElementById('sched-restore-prof');
if (!selNodes || !selTarget || !selRestore) return;
// Proviamo a estrarre i nomi dei profili dal primo nodo selezionato
const selectedCid = selNodes.value;
let profiles = { "A": "Profilo A", "B": "Profilo B" }; // Default
if (selectedCid !== 'all' && globalHealthData[selectedCid] && globalHealthData[selectedCid].profiles) {
profiles = globalHealthData[selectedCid].profiles;
} else {
// Se è 'all', cerchiamo il primo nodo disponibile che abbia i profili valorizzati
for (let cid in globalHealthData) {
if (globalHealthData[cid] && globalHealthData[cid].profiles && Object.keys(globalHealthData[cid].profiles).length > 0) {
profiles = globalHealthData[cid].profiles;
break;
}
}
}
// Aggiorniamo le select
let htmlTarget = "";
let htmlRestore = "";
for (const [pKey, pLabel] of Object.entries(profiles)) {
htmlTarget += `<option value="${pKey}">${pKey} (${esc(pLabel)})</option>`;
htmlRestore += `<option value="${pKey}">${pKey} (${esc(pLabel)})</option>`;
}
htmlRestore += `<option value="NONE" data-i18n="optNone">NONE (Leave active)</option>`;
// Salviamo i valori attuali se possibile per non resettarli
const currTarget = selTarget.value;
const currRestore = selRestore.value;
selTarget.innerHTML = htmlTarget;
selRestore.innerHTML = htmlRestore;
if(currTarget && [...selTarget.options].some(o => o.value === currTarget)) selTarget.value = currTarget;
if(currRestore && [...selRestore.options].some(o => o.value === currRestore)) selRestore.value = currRestore;
// Riapplichiamo le traduzioni per l'opzione NONE se in italiano
if (currentLang === 'it') {
const noneOpt = selRestore.querySelector('option[value="NONE"]');
if(noneOpt) noneOpt.innerText = "NESSUNO (Mantieni attivo)";
}
}
function populateScheduleNodeOptions() {
const sel = document.getElementById('sched-nodes-select');
if (!sel) return;
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAll = allowedList.includes('all');
let html = '';
if (hasAll || role === 'admin') {
html += `<option value="all">${t('optAllNodes')}</option>`;
}
clients.forEach(c => {
if (hasAll || allowedList.includes(c.id.toLowerCase())) {
html += `<option value="${c.id}">${esc(c.name)} (${c.id.toUpperCase()})</option>`;
}
});
sel.innerHTML = html;
sel.addEventListener('change', updateScheduleProfileOptions);
updateScheduleProfileOptions();
}
async function loadSchedules() {
const tbody = document.getElementById('schedules-table-body');
if (!tbody) return;
try {
const res = await fetch('/api/schedules');
const data = await res.json();
if (!data.success || !data.schedules || data.schedules.length === 0) {
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:15px;">NO_SCHEDULES_FOUND</td></tr>`;
return;
}
tbody.innerHTML = data.schedules.map(s => {
let statusColor = "var(--text-muted)";
let statusClass = "";
let statusText = s.status;
if (s.status === 'SCHEDULED') {
statusColor = "#f59e0b";
statusText = t('statusScheduled');
} else if (s.status === 'ACTIVE') {
statusColor = "var(--success)";
statusClass = "blink";
statusText = t('statusActive');
} else if (s.status === 'COMPLETED') {
statusColor = "var(--text-muted)";
statusText = t('statusCompleted');
} else if (s.status === 'CANCELLED') {
statusColor = "var(--danger)";
statusText = t('statusCancelled');
} else if (s.status === 'EXPIRED') {
statusColor = "var(--text-muted)";
statusText = t('statusExpired');
}
const isFinished = ['COMPLETED', 'CANCELLED', 'EXPIRED'].includes(s.status);
// Tentativo di dedurre il profilo di partenza dal primo nodo o dai nodi target
let startProf = "?";
let cids = s.target_nodes.toLowerCase() === 'all' ? Object.keys(globalHealthData) : s.target_nodes.toLowerCase().split(',');
for (let i = 0; i < cids.length; i++) {
let cid = cids[i].trim();
let card = document.getElementById(`card-${cid}`);
if (card && card.dataset.lastMode) {
startProf = card.dataset.lastMode;
// Se leggiamo DMR o D-STAR non è un nome di profilo. Dobbiamo guardare se nel telemetry c'è una hint
let tel = latestStatesData && latestStatesData.telemetry && latestStatesData.telemetry[cid] ? latestStatesData.telemetry[cid] : {};
if(tel.alt && tel.alt.includes('SCHED:')) {
startProf = tel.alt.split(':')[1].trim();
}
break;
}
}
if (startProf === "?" || startProf.length > 5) startProf = "CURR"; // Current
let profDisplay = `<span style="color:var(--text-muted);">${esc(startProf)}</span> ➔ <b style="color:var(--accent);">${esc(s.target_profile)}</b>`;
if (s.restore_profile !== 'NONE') {
profDisplay += ` ➔ <span style="color:var(--success);">${esc(s.restore_profile)}</span>`;
}
return `<tr>
<td style="font-weight:bold; color:var(--text-main);">${esc(s.title)}</td>
<td><span style="color:var(--primary); font-family:'JetBrains Mono',monospace;">${esc(s.target_nodes.toUpperCase())}</span></td>
<td style="font-family:'JetBrains Mono',monospace;">${profDisplay}</td>
<td style="font-size:0.8rem; color:var(--text-muted);">${esc(s.start_time.substring(5, 16))}</td>
<td style="font-size:0.8rem; color:var(--text-muted);">${esc(s.end_time.substring(5, 16))}</td>
<td><span class="${statusClass}" style="color:${statusColor}; font-weight:bold; font-size:0.8rem;">[ ${statusText} ]</span></td>
<td style="text-align:right;">
${!isFinished ? `<button onclick="cancelSchedule(${s.id})" class="btn-cmd" style="border-color:var(--danger); color:var(--danger)!important; padding:4px 8px; font-size:0.75rem; width:auto; flex:none;">DEL</button>` : '—'}
</td>
</tr>`;
}).join('');
} catch(e) {
console.error("Error loading schedules:", e);
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; color:var(--danger); padding:15px;">NET_ERR</td></tr>`;
}
}
async function submitSchedule() {
const title = document.getElementById('sched-title').value.trim();
const targetNodes = document.getElementById('sched-nodes-select').value;
const targetProf = document.getElementById('sched-target-prof').value.trim().toUpperCase();
const restoreProf = document.getElementById('sched-restore-prof').value.trim().toUpperCase();
const startTime = document.getElementById('sched-start').value;
const endTime = document.getElementById('sched-end').value;
if (!title || !targetNodes || !targetProf || !startTime || !endTime) {
return customAlert(t('titleError'), t('errMissingSchedData'), true);
}
if (startTime >= endTime) {
return customAlert(t('titleError'), t('errSchedDates'), true);
}
const payload = {
title: title,
target_nodes: targetNodes,
target_profile: targetProf,
restore_profile: restoreProf,
start_time: startTime,
end_time: endTime
};
try {
const res = await fetch('/api/schedules', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
});
const data = await res.json();
if (data.success) {
customAlert(t('titleSuccess'), t('msgSchedCreated'));
document.getElementById('sched-title').value = '';
loadSchedules();
} else {
customAlert(t('titleError'), esc(data.error), true);
}
} catch(e) {
console.error(e);
customAlert(t('titleError'), t('msgNetErr'), true);
}
}
function cancelSchedule(sid) {
customConfirm(t('titleAction'), t('confCancelSched'), "var(--danger)", async () => {
try {
const res = await fetch(`/api/schedules/${sid}`, { method: 'DELETE' });
const data = await res.json();
if (data.success) {
customAlert(t('titleSuccess'), t('msgSchedCancelled'));
loadSchedules();
} else {
customAlert(t('titleError'), esc(data.error), true);
}
} catch(e) {
console.error(e);
customAlert(t('titleError'), t('msgNetErr'), true);
}
});
}
+4 -9
View File
@@ -1,13 +1,14 @@
const CACHE_NAME = 'fleet-c2-v3'; // incrementare a ogni modifica degli asset precaricati
const CACHE_NAME = 'fleet-c2-v6';
const PRECACHE_URLS = [
'/',
'/static/css/style.css',
'/static/js/modals.js',
'/static/js/app.js',
'/manifest.json',
'/icon-512.png'
];
// --- 1. INSTALL: precache "best effort" -------------------------------------
// Se un file manca (es. icona non ancora caricata) l'installazione NON fallisce:
// un SW che non si installa significa niente notifiche push.
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
@@ -26,8 +27,6 @@ self.addEventListener('activate', event => {
});
// --- 3. FETCH: network-first, cache come ripiego offline ---------------------
// Gestiamo solo le GET della nostra origine. API e WebSocket (socket.io) passano
// sempre direttamente dalla rete: i dati della flotta non vanno mai serviti "vecchi".
self.addEventListener('fetch', event => {
const req = event.request;
if (req.method !== 'GET') return;
@@ -80,8 +79,6 @@ self.addEventListener('push', event => {
icon: '/icon-512.png',
badge: '/icon-512.png',
vibrate: [200, 100, 200],
// Stesso tag = la nuova notifica dello stesso nodo sostituisce la precedente
// (invece di accumulare 10 notifiche) e rifà vibrare/suonare.
tag: data.tag || 'fleet-alert',
renotify: true,
data: {
@@ -100,8 +97,6 @@ self.addEventListener('push', event => {
});
// --- 5. CLICK SULLA NOTIFICA -------------------------------------------------
// Click sul corpo O su "Apri Dashboard": porta in primo piano la finestra già aperta,
// altrimenti ne apre una nuova. "Chiudi" chiude soltanto.
self.addEventListener('notificationclick', event => {
event.notification.close();
if (event.action === 'close') return;
@@ -0,0 +1,37 @@
# VERSIONE PIU' SICURA (opzionale) del servizio. Il file fleet-console.service originale resta invariato.
#
# Preparazione (una tantum, da root):
# useradd --system --home /opt/fleet-control-server --shell /usr/sbin/nologin fleet
# chown -R fleet:fleet /opt/fleet-control-server
# cp systemd/fleet-console.hardened.service.example /etc/systemd/system/fleet-console.service
# systemctl daemon-reload && systemctl restart fleet-console
#
# Se usi un reverse proxy (consigliato) cambia anche il bind in 127.0.0.1:9000 qui sotto.
# L'aggiornamento OTA (git pull) continua a funzionare perche' l'utente "fleet" possiede la cartella.
[Unit]
Description=Fleet Control Console - Central Hub
After=network.target
[Service]
Type=simple
User=fleet
Group=fleet
WorkingDirectory=/opt/fleet-control-server
ExecStart=/opt/fleet-control-server/venv/bin/gunicorn -k "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" -w 1 --graceful-timeout 2 --bind 0.0.0.0:9000 app:app
TimeoutStopSec=3
Restart=always
RestartSec=5
# Hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=true
ReadWritePaths=/opt/fleet-control-server
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=fleet-console
[Install]
WantedBy=multi-user.target
+509 -1080
View File
File diff suppressed because it is too large Load Diff
+8 -8
View File
@@ -1,11 +1,11 @@
import sqlite3
import json
from app import broadcast_push_notification, init_db
"""Invia una notifica push di prova a tutti gli iscritti, senza avviare MQTT e i thread dell'app.
# Proviamo a inviare una notifica a tutti gli iscritti nel DB
Uso (dalla cartella del progetto, con il venv attivo): python test-push.py
"""
from core.database import init_db
from services.push_service import _send_push
init_db()
print("🚀 Starting notification test...")
broadcast_push_notification(
"⚠️ ALLERTA FLOTTA",
"Test Push Notification: System Online!"
)
_send_push("⚠️ ALLERTA FLOTTA", "Test Push Notification: System Online!", None)
print("✅ Command sent.")