Compare commits
17
Commits
v2.2.0
...
47b4bed21f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47b4bed21f | ||
|
|
7a9008de78 | ||
|
|
dad1a656fe | ||
|
|
b33d495474 | ||
|
|
38f7efce6b | ||
|
|
24c81c1abb | ||
|
|
126ad8cdaf | ||
|
|
2f0abdc9bf | ||
|
|
a1449eedfb | ||
|
|
2fa1b476c4 | ||
|
|
8ce2ed243d | ||
|
|
8ee2958b8e | ||
|
|
298478e36d | ||
|
|
502244dff4 | ||
|
|
c5dcacefd1 | ||
|
|
cae5c4ea83 | ||
|
|
445cc5e97d |
@@ -37,6 +37,27 @@ The server acts as the brain of the network:
|
||||
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.
|
||||
|
||||
### ⚠️ Reverse Proxy & WebSocket Configuration
|
||||
If you expose the Fleet Console through a reverse proxy like **Apache** on a public IP (HTTPS), standard HTTP proxying will drop Socket.IO real-time connections, causing the dashboard's tables to randomly clear or flash.
|
||||
You must enable the WebSocket tunnel in Apache:
|
||||
```bash
|
||||
sudo a2enmod proxy_wstunnel rewrite headers
|
||||
```
|
||||
And insert the **Rewrite** rules *before* the `ProxyPass` directives inside your `<VirtualHost *:443>` block:
|
||||
```apache
|
||||
RewriteEngine On
|
||||
RewriteCond %{HTTP:Upgrade} =websocket [NC]
|
||||
RewriteRule /(.*) ws://127.0.0.1:9000/$1 [P,L]
|
||||
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
|
||||
RewriteRule /(.*) http://127.0.0.1:9000/$1 [P,L]
|
||||
|
||||
ProxyPass /socket.io/ ws://127.0.0.1:9000/socket.io/
|
||||
ProxyPassReverse /socket.io/ ws://127.0.0.1:9000/socket.io/
|
||||
|
||||
ProxyPass / http://127.0.0.1:9000/
|
||||
ProxyPassReverse / http://127.0.0.1:9000/
|
||||
```
|
||||
|
||||
#### 🛠️ 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.
|
||||
@@ -82,6 +103,7 @@ pip install -r requirements.txt
|
||||
2. Configure your MQTT broker credentials.
|
||||
3. Define your repeaters in `clients.json`.
|
||||
4. Generate VAPID keys at [vapidkeys.com](https://vapidkeys.com/) and add them to `config.json` to enable Web Push notifications. *(Note: Push notifications require HTTPS).*
|
||||
5. Configure dynamic log rotation sizes (`log_max_mb` and `log_backup_count`) directly in `config.json` to manage disk space.
|
||||
|
||||
#### 4. Running as a Service
|
||||
To run the server continuously in production using Gunicorn:
|
||||
@@ -126,6 +148,27 @@ Il server agisce da cervello della rete:
|
||||
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.
|
||||
|
||||
### ⚠️ Configurazione Reverse Proxy & WebSocket
|
||||
Se esponi la Fleet Console tramite un reverse proxy come **Apache** su IP pubblico (HTTPS), il proxy HTTP standard farà cadere continuamente la connessione in tempo reale di Socket.IO, causando fastidiosi "azzeramenti" o lampeggiamenti della dashboard.
|
||||
Devi abilitare il tunnel WebSocket in Apache:
|
||||
```bash
|
||||
sudo a2enmod proxy_wstunnel rewrite headers
|
||||
```
|
||||
E inserire le regole di **Rewrite** *prima* del `ProxyPass` all'interno del tuo blocco `<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]
|
||||
|
||||
ProxyPass /socket.io/ ws://127.0.0.1:9000/socket.io/
|
||||
ProxyPassReverse /socket.io/ ws://127.0.0.1:9000/socket.io/
|
||||
|
||||
ProxyPass / http://127.0.0.1:9000/
|
||||
ProxyPassReverse / http://127.0.0.1:9000/
|
||||
```
|
||||
|
||||
#### 🛠️ 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.
|
||||
@@ -171,6 +214,7 @@ pip install -r requirements.txt
|
||||
2. Inserisci le credenziali del broker MQTT.
|
||||
3. Definisci i ripetitori nel file `clients.json`.
|
||||
4. Genera le chiavi VAPID su [vapidkeys.com](https://vapidkeys.com/) e inseriscile in `config.json` per attivare le notifiche Push. *(Attenzione: le notifiche Push richiedono obbligatoriamente un certificato HTTPS).*
|
||||
5. Configura le dimensioni della rotazione dei log (`log_max_mb` e `log_backup_count`) direttamente nel `config.json` per gestire lo spazio su disco.
|
||||
|
||||
#### 4. Esecuzione come Servizio (systemd)
|
||||
Per eseguire il server in produzione in modo continuo e stabile con Gunicorn:
|
||||
|
||||
@@ -12,6 +12,7 @@ import re
|
||||
import queue
|
||||
import hashlib
|
||||
import secrets
|
||||
import subprocess
|
||||
from contextlib import closing
|
||||
from pywebpush import webpush, WebPushException
|
||||
from logging.handlers import RotatingFileHandler
|
||||
@@ -29,25 +30,15 @@ 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')
|
||||
|
||||
# --- LOGGING CONFIGURATION ---
|
||||
logging.basicConfig(
|
||||
handlers=[
|
||||
RotatingFileHandler(LOG_FILE, maxBytes=10000000, backupCount=3),
|
||||
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)
|
||||
|
||||
# --- CONFIG ---
|
||||
# --- CONFIG LOADER (INIZIALE PER IL LOGGING) ---
|
||||
config_lock = threading.Lock()
|
||||
|
||||
def read_config():
|
||||
with open(CONFIG_PATH, 'r') as f:
|
||||
return json.load(f)
|
||||
try:
|
||||
with open(CONFIG_PATH, 'r') as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def write_config(cfg):
|
||||
tmp = CONFIG_PATH + '.tmp'
|
||||
@@ -63,6 +54,23 @@ def write_config(cfg):
|
||||
config = read_config()
|
||||
web_cfg = config.get('web', {})
|
||||
|
||||
# --- LOGGING CONFIGURATION DINAMICA ---
|
||||
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':
|
||||
@@ -96,6 +104,14 @@ def init_db():
|
||||
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)''')
|
||||
@@ -190,8 +206,8 @@ def save_to_sqlite(client_id, data, protocol="DMR"):
|
||||
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) 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))
|
||||
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()
|
||||
conn.close()
|
||||
notify_update('log_aggiornato')
|
||||
@@ -235,7 +251,6 @@ client_telemetry = {}
|
||||
last_notified_errors = {}
|
||||
device_health = {}
|
||||
last_seen_reflector = {}
|
||||
network_mapping = {}
|
||||
node_info = {}
|
||||
node_general = {}
|
||||
node_versions = {}
|
||||
@@ -317,7 +332,7 @@ def handle_connect():
|
||||
def on_message(client, userdata, msg):
|
||||
try:
|
||||
topic = msg.topic
|
||||
payload = msg.payload.decode().strip()
|
||||
payload = msg.payload.decode('utf-8', errors='replace').strip()
|
||||
parts = topic.split('/')
|
||||
if len(parts) < 2: return
|
||||
|
||||
@@ -325,38 +340,32 @@ def on_message(client, userdata, msg):
|
||||
p0 = parts[0].lower().replace('-', '')
|
||||
p2 = parts[2].lower().replace('-', '') if len(parts) > 2 else ""
|
||||
|
||||
# --- LOG MANAGEMENT (ESTRAZIONE VERSIONI E GIT ID) ---
|
||||
# --- LOG MANAGEMENT (ESTRAZIONE VERSIONI E GIT ID) ---
|
||||
if len(parts) >= 3 and parts[2].lower() == 'log':
|
||||
if cid not in node_versions:
|
||||
node_versions[cid] = {}
|
||||
|
||||
# 1. Cattura il Firmware MMDVM (es. "... description: MMDVM 20260424 19.2000 Mhz GitID #57e692a")
|
||||
m_fw = re.search(r'description:\s*(MMDVM[^\n\r]+)', payload, re.IGNORECASE)
|
||||
if m_fw:
|
||||
node_versions[cid]["Firmware MMDVM"] = m_fw.group(1).strip()
|
||||
notify_update()
|
||||
|
||||
# 2. Cattura le versioni dei demoni Formato A (es. "YSFGateway-20260323 is starting")
|
||||
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)
|
||||
node_versions[cid][prog] = m_sw1.group(2).strip()
|
||||
node_versions[cid]["_last_prog"] = prog # Per il GitID della riga dopo
|
||||
node_versions[cid]["_last_prog"] = prog
|
||||
notify_update()
|
||||
|
||||
# 3. Cattura le versioni dei demoni Formato B (es. "MMDVMHost version 20250419 git #65ebb55")
|
||||
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)
|
||||
# Ignoriamo i falsi positivi dei log (es. "protocol version", "firmware version")
|
||||
if prog.lower() not in ['protocol', 'firmware', 'mmdvm firmware']:
|
||||
# Puliamo un eventuale "is starting" finale, se presente
|
||||
ver = m_sw2.group(2).replace("is starting", "").strip()
|
||||
node_versions[cid][prog] = ver
|
||||
node_versions[cid]["_last_prog"] = prog
|
||||
notify_update()
|
||||
|
||||
# 4. Cattura il GitID della riga successiva per i demoni di Formato A
|
||||
m_git = re.search(r'Built .*?\(GitID #([0-9a-fA-F]+)\)', payload, re.IGNORECASE)
|
||||
if m_git:
|
||||
git_id = m_git.group(1)
|
||||
@@ -417,25 +426,24 @@ def on_message(client, userdata, msg):
|
||||
"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")
|
||||
"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)
|
||||
}
|
||||
# --- AGGIUNTA E PULIZIA: SALVA LE VERSIONI DEI BINARI ---
|
||||
bin_versions = data.get("versions", {})
|
||||
if bin_versions:
|
||||
if cid not in node_versions:
|
||||
node_versions[cid] = {}
|
||||
|
||||
# Rimuove le vecchie versioni binarie che il nodo non trasmette più
|
||||
# (proteggendo però il "Firmware MMDVM" e le chiavi interne che derivano dai log)
|
||||
keys_to_remove = [k for k in 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 node_versions[cid][k]
|
||||
|
||||
# Aggiorna o aggiunge le versioni attuali
|
||||
for prog_name, prog_ver in bin_versions.items():
|
||||
node_versions[cid][prog_name] = prog_ver
|
||||
# ----------------------------------------------
|
||||
|
||||
health_changed = device_health.get(cid) != new_health
|
||||
device_health[cid] = new_health
|
||||
if health_changed:
|
||||
@@ -458,32 +466,6 @@ def on_message(client, userdata, msg):
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing health data: {e}")
|
||||
|
||||
elif len(parts) >= 4 and p0 == 'data' and p2 == 'dmrgateway' and (parts[3].upper().startswith('NETWORK') or parts[3].upper().startswith('DMR NETWORK')):
|
||||
try:
|
||||
cid = parts[1].lower()
|
||||
data = json.loads(payload)
|
||||
|
||||
if cid not in network_mapping:
|
||||
network_mapping[cid] = {"ts1": "", "ts2": ""}
|
||||
|
||||
if str(data.get("Enabled")) == "1":
|
||||
net_name = data.get("Name", "Net").upper()
|
||||
is_ts1 = False
|
||||
is_ts2 = False
|
||||
|
||||
keys_to_check = ["PassAllTG", "PassAllPC", "TGRewrite", "PCRewrite", "TypeRewrite", "SrcRewrite"]
|
||||
for k in keys_to_check:
|
||||
val = str(data.get(k, "")).strip()
|
||||
if val.startswith("1"): is_ts1 = True
|
||||
if val.startswith("2"): is_ts2 = True
|
||||
|
||||
if is_ts1: network_mapping[cid]["ts1"] = net_name
|
||||
if is_ts2: network_mapping[cid]["ts2"] = net_name
|
||||
notify_update()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing DMRGateway for {cid}: {e}")
|
||||
|
||||
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost') and parts[3].lower() == 'info':
|
||||
try:
|
||||
cid = parts[1].lower()
|
||||
@@ -571,18 +553,36 @@ def on_message(client, userdata, msg):
|
||||
if act in ['start', 'late_entry']:
|
||||
src = get_call(d.get('src_id'))
|
||||
dst = str(d.get('dst_id'))
|
||||
active_calls[cid][sk] = {'src': src, 'dst': dst}
|
||||
|
||||
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', ''))
|
||||
}
|
||||
|
||||
client_telemetry[cid]["alt"] = ""
|
||||
client_telemetry[cid][sk] = f"🎙️ {src} ➔ TG {dst}"
|
||||
notify_update()
|
||||
|
||||
elif act in ['end', 'lost']:
|
||||
info = active_calls[cid].get(sk, {'src': '---', 'dst': '---'})
|
||||
d['src_id'], d['dst_id'] = info['src'], info['dst']
|
||||
info = 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")
|
||||
client_telemetry[cid][sk] = f"{'✅' if act=='end' else '⚠️'} {info['src']}"
|
||||
save_cache(client_telemetry)
|
||||
if sk in active_calls[cid]: del active_calls[cid][sk]
|
||||
|
||||
else:
|
||||
for k, ico, name in [('NXDN','🟢','NXDN'),('YSF','🟣','YSF'),('P25','🟠','P25'),('D-Star','🔵','D-STAR')]:
|
||||
if k in data:
|
||||
@@ -594,21 +594,33 @@ def on_message(client, userdata, msg):
|
||||
elif k == 'P25': src = 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', '---')))))
|
||||
|
||||
t_list = [p.get('reflector'), p.get('dst_callsign'), p.get('dst_id')]
|
||||
current_target = next((str(x).strip() for x in t_list if x and str(x).strip() not in ['', '---', '0', 'CQCQCQ']), None)
|
||||
raw_target = str(p.get('dst_callsign', p.get('dst_id', ''))).strip()
|
||||
|
||||
if not current_target or current_target == cid.upper():
|
||||
target = last_seen_reflector.get(f"{cid}_{name}", "---")
|
||||
if name == 'D-STAR':
|
||||
target = raw_target if raw_target else "---"
|
||||
else:
|
||||
target = current_target
|
||||
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})"
|
||||
|
||||
active_calls[cid][k] = {'src': src, 'dst': target, 'ext': str(p.get('src_ext', ''))}
|
||||
client_telemetry[cid].update({"ts1":"","ts2":"","alt": f"{ico} {name}: {src} ➔ {target}"})
|
||||
mem_ref = 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 "---")
|
||||
|
||||
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"
|
||||
client_telemetry[cid].update({"ts1":"","ts2":"","alt": f"{ico} {name}: {src} ➔ {target_str} ({ref_slot})"})
|
||||
notify_update()
|
||||
|
||||
elif act in ['end', 'lost']:
|
||||
info = active_calls[cid].get(k, {'src': '---', 'dst': '---', 'ext': ''})
|
||||
p.update({'src_id': info['src'], 'dst_id': info['dst'], 'src_ext': info['ext']})
|
||||
info = 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)
|
||||
client_telemetry[cid]["alt"] = f"{'✅' if act=='end' else '⚠️'} {name}: {info['src']}"
|
||||
save_cache(client_telemetry)
|
||||
@@ -616,16 +628,16 @@ def on_message(client, userdata, msg):
|
||||
except Exception as e:
|
||||
logger.error(f"MQTT MSG ERROR: {e}")
|
||||
|
||||
mqtt_id = config['mqtt'].get('client_id', 'flask_backend_generic')
|
||||
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['mqtt']['user'], config['mqtt']['password'])
|
||||
mqtt_backend.username_pw_set(config.get('mqtt', {}).get('user', ''), config.get('mqtt', {}).get('password', ''))
|
||||
mqtt_backend.on_connect = on_connect
|
||||
mqtt_backend.on_disconnect = on_disconnect
|
||||
mqtt_backend.on_message = on_message
|
||||
try:
|
||||
mqtt_backend.connect_async(config['mqtt']['broker'], config['mqtt']['port'])
|
||||
mqtt_backend.connect_async(config.get('mqtt', {}).get('broker', 'localhost'), config.get('mqtt', {}).get('port', 1883))
|
||||
mqtt_backend.loop_start()
|
||||
logger.info(f"Avvio connessione MQTT asincrona verso {config['mqtt']['broker']}...")
|
||||
logger.info(f"Avvio connessione MQTT asincrona verso {config.get('mqtt', {}).get('broker')}...")
|
||||
except Exception as e:
|
||||
logger.error(f"Errore critico nell'inizializzazione MQTT: {e}")
|
||||
|
||||
@@ -652,8 +664,18 @@ def add_security_headers(resp):
|
||||
resp.headers['Cache-Control'] = 'no-store'
|
||||
return resp
|
||||
|
||||
def get_git_commit():
|
||||
try:
|
||||
# Legge i primi 7 caratteri dell'hash del commit corrente
|
||||
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').strip()
|
||||
except Exception:
|
||||
return "sconosciuta"
|
||||
|
||||
SERVER_COMMIT = get_git_commit()
|
||||
|
||||
@app.route('/')
|
||||
def index(): return render_template('index.html')
|
||||
def index():
|
||||
return render_template('index.html', git_commit=SERVER_COMMIT)
|
||||
|
||||
@app.route('/api/clients')
|
||||
def get_clients():
|
||||
@@ -665,14 +687,13 @@ def get_clients():
|
||||
def get_logs():
|
||||
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 FROM radio_logs ORDER BY id DESC LIMIT 60")
|
||||
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 60")
|
||||
logs = c.fetchall()
|
||||
conn.close()
|
||||
return jsonify(logs)
|
||||
|
||||
@app.route('/api/states', methods=['GET'])
|
||||
def get_states():
|
||||
# Filtriamo le chiavi di servizio (come '_last_prog') per non mandarle all'interfaccia
|
||||
clean_versions = {}
|
||||
for c, d in node_versions.items():
|
||||
clean_versions[c] = {k: v for k, v in d.items() if not k.startswith('_')}
|
||||
@@ -681,7 +702,6 @@ def get_states():
|
||||
"states": client_states,
|
||||
"telemetry": client_telemetry,
|
||||
"health": device_health,
|
||||
"networks": network_mapping,
|
||||
"info": node_info,
|
||||
"general": node_general,
|
||||
"last_seen": seen_ages(),
|
||||
@@ -1188,7 +1208,9 @@ def get_config_api():
|
||||
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", "")
|
||||
"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)
|
||||
})
|
||||
|
||||
@app.route('/api/config', methods=['POST'])
|
||||
@@ -1201,6 +1223,13 @@ def save_config_api():
|
||||
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("Invalid log rotation settings")
|
||||
|
||||
if not TIME_RE.match(schedule):
|
||||
return err("Invalid time (use HH:MM)")
|
||||
for u in (url_dmr, url_nxdn):
|
||||
@@ -1212,6 +1241,9 @@ def save_config_api():
|
||||
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})
|
||||
@@ -1252,6 +1284,58 @@ def save_config_file():
|
||||
audit(auth['username'], cid, f"EDIT_CONFIG_{service.upper()}")
|
||||
return jsonify({"success": True})
|
||||
|
||||
@app.route('/api/server_update/check', methods=['GET'])
|
||||
def check_server_update():
|
||||
auth = get_auth()
|
||||
if not auth or auth['role'] != 'admin':
|
||||
return err("Unauthorized", 403)
|
||||
|
||||
try:
|
||||
# Aggiorna le informazioni dal remote senza unire i file
|
||||
subprocess.run(['git', 'fetch'], timeout=10, cwd=BASE_DIR)
|
||||
|
||||
# Confronta il commit locale con quello remoto
|
||||
local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip()
|
||||
remote_hash = subprocess.check_output(['git', 'rev-parse', '@{u}'], cwd=BASE_DIR).decode('utf-8').strip()
|
||||
|
||||
update_available = local_hash != remote_hash
|
||||
|
||||
# --- LOG DI DEBUG ---
|
||||
logger.info(f"🔍 Controllo OTA: Local={local_hash[:7]} | Remote={remote_hash[:7]} | Update={update_available}")
|
||||
# --------------------
|
||||
|
||||
return jsonify({"success": True, "update_available": update_available})
|
||||
except Exception as e:
|
||||
logger.error(f"Errore controllo aggiornamenti server: {e}")
|
||||
return jsonify({"success": False, "error": "Impossibile verificare aggiornamenti"})
|
||||
|
||||
@app.route('/api/server_update/apply', methods=['POST'])
|
||||
def apply_server_update():
|
||||
auth = get_auth()
|
||||
if not auth or auth['role'] != 'admin':
|
||||
return err("Unauthorized", 403)
|
||||
|
||||
try:
|
||||
audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE')
|
||||
logger.warning(f"🔄 Aggiornamento OTA del server avviato da {auth['username']}")
|
||||
|
||||
# Esegue il pull
|
||||
subprocess.run(['git', 'pull', '--ff-only'], timeout=30, cwd=BASE_DIR, check=True)
|
||||
|
||||
# Programma il riavvio (esce dal processo, systemd lo farà ripartire)
|
||||
def restart_server():
|
||||
time.sleep(2)
|
||||
os._exit(1)
|
||||
|
||||
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))
|
||||
|
||||
@app.route('/manifest.json')
|
||||
def serve_manifest():
|
||||
return send_from_directory(BASE_DIR, 'manifest.json')
|
||||
|
||||
+3
-1
@@ -37,5 +37,7 @@
|
||||
"id_urls": {
|
||||
"dmr": "https://radioid.net/static/dmrid.dat",
|
||||
"nxdn": "https://radioid.net/static/nxdn.csv"
|
||||
}
|
||||
},
|
||||
"log_max_mb": 50,
|
||||
"log_backup_count": 10
|
||||
}
|
||||
|
||||
+102
-12
@@ -196,7 +196,7 @@
|
||||
<h3 style="margin: 0; font-weight: 800; display: flex; align-items: center; gap: 10px; color: var(--text-main);">
|
||||
<span style="font-size: 1.5rem;">📊</span> <span data-i18n="statTitle">DAILY STATISTICS</span>
|
||||
</h3>
|
||||
<select id="stat-node-filter" onchange="refreshStats()" style="background: var(--card-bg); border: 1px solid var(--border-color); color: var(--text-main); padding: 8px 15px; border-radius: 6px; font-family: 'JetBrains Mono', monospace; font-weight: bold; cursor: pointer; outline: none;">
|
||||
<select id="stat-node-filter" onchange="refreshStats(); refreshLogs();" style="background: var(--card-bg); border: 1px solid var(--border-color); color: var(--text-main); padding: 8px 15px; border-radius: 6px; font-family: 'JetBrains Mono', monospace; font-weight: bold; cursor: pointer; outline: none;">
|
||||
<option value="all">🌐 ALL NODES</option>
|
||||
</select>
|
||||
</div>
|
||||
@@ -236,7 +236,9 @@
|
||||
<th data-i18n="thTime">Time</th>
|
||||
<th data-i18n="thRep">Repeater</th>
|
||||
<th data-i18n="thMode">Mode</th>
|
||||
<th style="text-align: center;">Slot</th>
|
||||
<th style="text-align: center;">YSF Mode</th>
|
||||
<th style="text-align: center;">Source</th>
|
||||
<th style="text-align: center;">REF / SLOT</th>
|
||||
<th data-i18n="thCall">Callsign</th>
|
||||
<th>Target / TG</th>
|
||||
<th data-i18n="thDur">Duration</th>
|
||||
@@ -264,10 +266,11 @@
|
||||
<span>GitHub Mirror</span>
|
||||
</a>
|
||||
<span style="opacity: 0.5;">|</span>
|
||||
<span style="font-family: 'JetBrains Mono', monospace; color: var(--accent);">Rev: {{ git_commit }}</span>
|
||||
<span style="opacity: 0.5;">|</span>
|
||||
<span id="last-update">Sync: --:--</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<div id="login-modal" class="modal-overlay">
|
||||
<div class="modal-content" style="width:90%; max-width:400px;">
|
||||
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border-color); padding-bottom:15px; margin-bottom:20px;">
|
||||
@@ -464,7 +467,7 @@
|
||||
ttReqCfg: "Request immediate data update", ttGlobal: "Force profile switch on network", ttAdmin: "User and system management", ttPass: "Change your password", ttLogout: "Log out",
|
||||
ttProfA: "Switch to Profile A", ttProfB: "Switch to Profile B", ttTgOn: "Enable Telegram notifications", ttTgOff: "Disable Telegram notifications", ttSvc: "Manage system daemons", ttFile: "Edit .ini configuration files", ttHat: "Send physical reset to modem", ttBoot: "Reboot node operating system",
|
||||
ttSwitchTo: "Switch to profile: ", ttSvcStart: "Start service", ttSvcRestart: "Restart service", ttSvcEdit: "Edit configuration", ttSvcStop: "Stop service", ttLang: "Change language",
|
||||
statTopTG: "🎯 TOP TALKGROUPS", statTopCall: "🗣️ TOP CALLSIGNS", statLoading: "Loading...", statAvgDur: "⏱️ AVERAGE DURATION", statTodayTx: "📡 TRANSITS TODAY", statNoData: "No data",
|
||||
statTopTG: "🎯 TOP TALKGROUPS", statTopCall: "🗣️ TOP CALLSIGNS", statLoading: "Loading...", statAvgDur: "⏱️ AVERAGE DURATION", statTodayTx: "📡 TRANSITI TODAY", statNoData: "No data",
|
||||
statTitle: "DAILY STATISTICS", statAllNodes: "ALL NODES", modVersions: "Software & Firmware"
|
||||
},
|
||||
it: {
|
||||
@@ -715,8 +718,9 @@
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
|
||||
if (isAuthenticated) {
|
||||
if (isAuthenticated) {
|
||||
let adminBtn = role === 'admin' ? `
|
||||
<button id="server-update-btn" onclick="confirmServerUpdate()" class="auth-btn" style="background:var(--danger); color:white !important; display:none; border: 2px solid white; animation: pulse-red 1.5s infinite;" title="Aggiornamento Server Disponibile">🔄 UPDATE SERVER</button>
|
||||
<button onclick="sendGlobalUpdate()" class="auth-btn" style="background:#f59e0b; color:white;" data-i18n-title="ttReqCfg" title="${t('ttReqCfg')}">${t('btnReqCfg')}</button>
|
||||
<button onclick="triggerGlobalEmergency()" class="auth-btn" style="background:#ef4444; color:white;" data-i18n-title="ttGlobal" title="${t('ttGlobal')}">${t('btnGlobal')}</button>
|
||||
<button onclick="openAdmin()" class="auth-btn" style="background:var(--accent); color:white;" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">${t('btnAdmin')}</button>` : '';
|
||||
@@ -739,6 +743,7 @@
|
||||
<span class="client-name" title="${esc(c.name)}">${esc(c.name)}</span>
|
||||
<div style="display: flex; align-items: center;">
|
||||
<span class="badge-id">ID: ${c.id.toUpperCase()}</span>
|
||||
<span class="badge-id" id="agent-badge-${c.id}" style="display: none; margin-left: 6px; color: #38bdf8; border-color: rgba(56, 189, 248, 0.4); background: rgba(56, 189, 248, 0.1);" title="Versione Node Agent"></span>
|
||||
<div id="type-badge-${c.id}" class="type-badge" style="display: none;"></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -755,6 +760,7 @@
|
||||
<span>🌡️ <span id="temp-${c.id}">--</span>°C</span>
|
||||
<span>🧠 <span id="ram-${c.id}">--</span>%</span>
|
||||
<span>💾 <span id="disk-${c.id}">--</span>%</span>
|
||||
<span title="System Uptime">⏱️ <span id="up-${c.id}">--</span></span>
|
||||
</div>
|
||||
<div class="seen-bar" id="seen-${c.id}" style="display: none;"></div>
|
||||
|
||||
@@ -789,7 +795,7 @@
|
||||
<button class="btn-cmd" style="background: var(--danger); padding: 8px 4px;" title="${t('ttBoot')}" onclick="confirmReboot('${c.id}')">${t('btnBoot')}</button>
|
||||
</div>
|
||||
<div style="width: 100%; display: flex; gap: 8px;">
|
||||
<button class="btn-cmd" style="background: #2563eb; padding: 8px 4px;" title="Scarica l'ultima versione da Gitea" onclick="confirmUpdateAgent('${c.id}')">⬇️ UPDATE OTA</button>
|
||||
<button id="btn-ota-${c.id}" class="btn-cmd" style="background: #2563eb; padding: 8px 4px;" title="Scarica l'ultima versione da Gitea" onclick="confirmUpdateAgent('${c.id}')">⬇️ UPDATE OTA</button>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>`;
|
||||
@@ -889,7 +895,6 @@
|
||||
if (altDiv) altDiv.style.display = "none";
|
||||
if (tsContainer) tsContainer.style.display = "flex";
|
||||
|
||||
let netObj = data.networks && data.networks[c.id.toLowerCase()] ? data.networks[c.id.toLowerCase()] : {ts1: "", ts2: ""};
|
||||
activeModeColor = "var(--primary)";
|
||||
|
||||
if (ts1Div && ts2Div) {
|
||||
@@ -899,8 +904,8 @@
|
||||
[ts1Div, ts2Div].forEach((div, idx) => {
|
||||
if (isSimplex && idx === 0) return;
|
||||
|
||||
const val = String((idx === 0 ? telemetryObj.ts1 : telemetryObj.ts2) ?? ''); const netName = idx === 0 ? netObj.ts1 : netObj.ts2;
|
||||
const fullLabel = netName ? `TS${idx + 1} [${netName}]` : `TS${idx + 1}`;
|
||||
const val = String((idx === 0 ? telemetryObj.ts1 : telemetryObj.ts2) ?? '');
|
||||
const fullLabel = `TS${idx + 1}`;
|
||||
div.innerText = `${fullLabel}: ${val}`;
|
||||
div.style.setProperty('--pulse-color', activeModeColor);
|
||||
|
||||
@@ -945,6 +950,15 @@
|
||||
let tempVal = healthObj.temp; tempSpan.innerText = tempVal; tempSpan.style.color = tempVal < 55 ? 'var(--success)' : (tempVal < 70 ? '#f59e0b' : 'var(--danger)');
|
||||
ramSpan.innerText = healthObj.ram; let d = healthObj.disk; diskSpan.innerText = d; diskSpan.style.color = d < 85 ? 'inherit' : (d < 95 ? '#f59e0b' : 'var(--danger)');
|
||||
|
||||
let upSpan = document.getElementById(`up-${c.id}`);
|
||||
if (upSpan && healthObj.uptime) {
|
||||
upSpan.innerText = fmtAge(healthObj.uptime);
|
||||
}
|
||||
let agentBadge = document.getElementById(`agent-badge-${c.id}`);
|
||||
if (agentBadge && healthObj.agent_version) {
|
||||
agentBadge.innerText = `Agent v${healthObj.agent_version}`;
|
||||
agentBadge.style.display = 'inline-block';
|
||||
}
|
||||
const profBtnsDiv = document.getElementById(`prof-btns-${c.id}`);
|
||||
const profKeys = JSON.stringify(healthObj.profiles || {});
|
||||
|
||||
@@ -967,7 +981,11 @@
|
||||
}
|
||||
}
|
||||
|
||||
} else { if (healthContainer) healthContainer.style.display = 'none'; }
|
||||
} else {
|
||||
if (healthContainer) healthContainer.style.display = 'none';
|
||||
let agentBadge = document.getElementById(`agent-badge-${c.id}`);
|
||||
if (agentBadge) agentBadge.style.display = 'none';
|
||||
}
|
||||
|
||||
globalHealthData[c.id.toLowerCase()] = healthObj;
|
||||
|
||||
@@ -983,6 +1001,19 @@
|
||||
else { btnSvc.style.background = '#334155'; btnSvc.classList.remove('blink'); btnSvc.innerHTML = t('btnSvc'); }
|
||||
}
|
||||
|
||||
let btnOta = document.getElementById(`btn-ota-${c.id}`);
|
||||
if (btnOta) {
|
||||
if (healthObj && healthObj.agent_update_available) {
|
||||
btnOta.style.setProperty('background', 'var(--danger)', 'important');
|
||||
btnOta.style.setProperty('color', 'white', 'important');
|
||||
btnOta.style.animation = 'pulse-red 1.5s infinite';
|
||||
} else {
|
||||
btnOta.style.setProperty('background', '#2563eb', 'important');
|
||||
btnOta.style.setProperty('color', 'white', 'important');
|
||||
btnOta.style.animation = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
if (isOnline) {
|
||||
cardDiv.classList.add('online'); statusDiv.classList.remove('status-offline'); cardDiv.style.opacity = "1"; cardDiv.style.filter = "none";
|
||||
|
||||
@@ -1018,13 +1049,36 @@
|
||||
const clientId = row[1]; const protocol = row[2] || "DMR"; let source = row[3] || "---"; const target = row[4] || "---";
|
||||
const rawSlot = row[5]; const source_ext = row[8];
|
||||
const rawRssi = row[9];
|
||||
const sourceConn = row[10];
|
||||
const ysfMode = row[11];
|
||||
|
||||
let sourceHtml = esc(source);
|
||||
if (source_ext && source_ext.trim() !== "") { sourceHtml += ` <span style="font-size:0.8em; color:#94a3b8; font-family:'JetBrains Mono', monospace;">/${esc(source_ext)}</span>`; }
|
||||
|
||||
const slotDisplay = protocol === "DMR" ? `TS${rawSlot}` : "--";
|
||||
let slotDisplay = "---";
|
||||
if (rawSlot && String(rawSlot).trim() !== "" && rawSlot !== "undefined") {
|
||||
if (protocol === "DMR" && !String(rawSlot).toUpperCase().startsWith("TS")) {
|
||||
slotDisplay = `TS${rawSlot}`;
|
||||
} else {
|
||||
slotDisplay = rawSlot;
|
||||
}
|
||||
}
|
||||
let protoColor = "#3b82f6"; if (protocol === "NXDN") protoColor = "#10b981"; else if (protocol === "YSF") protoColor = "#8b5cf6"; else if (protocol === "D-STAR") protoColor = "#06b6d4"; else if (protocol === "P25") protoColor = "#f59e0b";
|
||||
|
||||
// Formatta il Source (RF o NET)
|
||||
let sourceBadge = "---";
|
||||
if (sourceConn) {
|
||||
if (sourceConn.toLowerCase() === 'rf') sourceBadge = '<span style="color:#f87171; font-weight:800;">RF</span>';
|
||||
else if (sourceConn.toLowerCase() === 'network') sourceBadge = '<span style="color:#38bdf8; font-weight:800;">NET</span>';
|
||||
else sourceBadge = `<span style="font-weight:800; color:var(--text-muted);">${esc(sourceConn).toUpperCase()}</span>`;
|
||||
}
|
||||
|
||||
// Formatta l'YSF Mode
|
||||
let modeDisplay = "---";
|
||||
if (ysfMode && ysfMode.trim() !== "") {
|
||||
modeDisplay = `<span style="font-size:0.7rem; color:#a78bfa; border: 1px solid #a78bfa; padding: 2px 4px; border-radius: 4px;">${esc(ysfMode).toUpperCase()}</span>`;
|
||||
}
|
||||
|
||||
// Formatta l'RSSI con S-Meter grafico a segmenti
|
||||
let rssiDisplay = '---';
|
||||
if (rawRssi && rawRssi !== 0) {
|
||||
@@ -1076,7 +1130,11 @@
|
||||
if (!networkLogs[clientId]) networkLogs[clientId] = "";
|
||||
networkLogs[clientId] += `<div style="border-bottom:1px solid rgba(255,255,255,0.1); padding:4px 0;"><span style="color:#64748b;">[${esc(time)}]</span> <span style="color:${protoColor}; font-weight:bold;">[${esc(protocol)}]</span> <span style="color:#cbd5e1;">${esc(source.replace("🌐", "").trim())}</span></div>`;
|
||||
} else {
|
||||
tableHTML += `<tr><td>${esc(time)}</td><td><b style="color:var(--text-main);">${esc(String(clientId).toUpperCase())}</b></td><td><span style="background:${protoColor}; color:white; padding:3px 8px; border-radius:8px; font-size:0.7rem; font-weight:800;">${esc(protocol)}</span></td><td style="font-family:'JetBrains Mono', monospace; font-weight:bold; text-align:center;">${esc(slotDisplay)}</td><td style="color:var(--accent); font-weight:800;">${sourceHtml}</td><td style="font-family:'JetBrains Mono', monospace;">${esc(target.trim())}</td><td>${esc(row[6])}s</td><td>${esc(row[7])}%</td><td style="font-family:'JetBrains Mono', monospace;">${rssiDisplay}</td></tr>`;
|
||||
// FILTRO TENDINA: Controlla il nodo selezionato prima di aggiungere la riga
|
||||
const selectedFilter = document.getElementById('stat-node-filter').value;
|
||||
if (selectedFilter === 'all' || String(clientId).toLowerCase() === selectedFilter) {
|
||||
tableHTML += `<tr><td>${esc(time)}</td><td><b style="color:var(--text-main);">${esc(String(clientId).toUpperCase())}</b></td><td><span style="background:${protoColor}; color:white; padding:3px 8px; border-radius:8px; font-size:0.7rem; font-weight:800;">${esc(protocol)}</span></td><td style="text-align:center;">${modeDisplay}</td><td style="text-align:center; font-family:'JetBrains Mono', monospace;">${sourceBadge}</td><td style="font-family:'JetBrains Mono', monospace; font-weight:bold; text-align:center;">${esc(slotDisplay)}</td><td style="color:var(--accent); font-weight:800;">${sourceHtml}</td><td style="font-family:'JetBrains Mono', monospace;">${esc(target.trim())}</td><td>${esc(row[6])}s</td><td>${esc(row[7])}%</td><td style="font-family:'JetBrains Mono', monospace;">${rssiDisplay}</td></tr>`;
|
||||
}
|
||||
}
|
||||
});
|
||||
tbody.innerHTML = tableHTML;
|
||||
@@ -1307,6 +1365,38 @@
|
||||
}
|
||||
function urlB64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i); return outputArray; }
|
||||
|
||||
async function checkServerUpdate() {
|
||||
if (!isAuthenticated || me.role !== 'admin') return;
|
||||
try {
|
||||
const res = await fetch('/api/server_update/check');
|
||||
const data = await res.json();
|
||||
const btn = document.getElementById('server-update-btn');
|
||||
if (btn) {
|
||||
btn.style.display = data.update_available ? 'inline-block' : 'none';
|
||||
}
|
||||
} catch (e) { console.error("Errore check update server:", e); }
|
||||
}
|
||||
|
||||
function confirmServerUpdate() {
|
||||
customConfirm("🔄 UPDATE SERVER", "Vuoi scaricare l'ultima versione del server da Gitea/GitHub e riavviare il servizio backend?", "var(--danger)", async () => {
|
||||
try {
|
||||
const res = await fetch('/api/server_update/apply', { method: 'POST' });
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
customAlert("✅ SUCCESS", "Aggiornamento in corso. La pagina si ricaricherà a breve.");
|
||||
setTimeout(() => location.reload(), 5000); // Ricarica dopo 5 secondi
|
||||
} else {
|
||||
customAlert("❌ ERRORE", esc(data.error), true);
|
||||
}
|
||||
} catch (e) { console.error(e); customAlert("❌ ERRORE", "Errore di rete.", true); }
|
||||
});
|
||||
}
|
||||
|
||||
// Controlla gli aggiornamenti ogni ora
|
||||
setInterval(checkServerUpdate, 3600000);
|
||||
// Effettua un controllo 5 secondi dopo l'avvio della UI
|
||||
setTimeout(checkServerUpdate, 5000);
|
||||
|
||||
initUI();
|
||||
checkPushStatus();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user