diff --git a/app.py b/app.py index 9cd6fa3..a71b53e 100644 --- a/app.py +++ b/app.py @@ -1,222 +1,32 @@ import gevent.monkey gevent.monkey.patch_all() -from flask import Flask, render_template, request, session, jsonify, send_from_directory -from paho.mqtt import client as mqtt_client -from werkzeug.security import generate_password_hash, check_password_hash -import json import os -import sqlite3 -import urllib.request -import threading -import time -import logging -import re -import queue -import hashlib -import secrets import subprocess -from contextlib import closing -from pywebpush import webpush, WebPushException -from logging.handlers import RotatingFileHandler -from flask_socketio import SocketIO, emit +import threading +from flask import Flask, render_template, request +from flask_socketio import emit -# --- DYNAMIC BASE PATH --- -BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +# --- IMPORT MODULI CORE --- +from core.config import BASE_DIR, get_secret_key, web_cfg, logger +from core.database import init_db +import core.state as state -# --- PATHS --- -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') +# --- IMPORT SERVIZI --- +from services.push_service import push_worker +from services.watchdog_service import watchdog_loop +from services.scheduler_service import auto_update_ids +import services.mqtt_service as mqtt_svc -# --- CONFIG LOADER (INIZIALE PER IL LOGGING) --- -config_lock = threading.Lock() +# --- IMPORT ROTTE / BLUEPRINTS --- +from routes.auth_routes import auth_bp +from routes.api_routes import api_bp -def read_config(): - try: - with open(CONFIG_PATH, 'r') as f: - return json.load(f) - except Exception: - return {} +# Inizializzazione Flask +template_dir = os.path.join(BASE_DIR, 'templates') if os.path.isdir(os.path.join(BASE_DIR, 'templates')) else BASE_DIR +app = Flask(__name__, template_folder=template_dir) -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 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': - key = secrets.token_hex(32) - config['secret_key'] = key - try: - write_config(config) - logger.warning("🔑 Nuova secret_key generata e salvata in config.json (le sessioni esistenti sono state invalidate).") - except Exception as e: - logger.error(f"Impossibile salvare la secret_key in config.json ({e}): sarà valida solo fino al riavvio.") - return key - -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 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() - -init_db() - -# --- ID DATABASE LOADING --- -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 - -load_ids() - -def get_call(id, proto="DMR"): - sid = str(id) - if proto == "NXDN": return nxdn_db.get(sid, sid) - return user_db.get(sid, sid) - -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() - -def save_to_sqlite(client_id, data, protocol="DMR"): - conn = sqlite3.connect(DB_PATH, timeout=10) - 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() - conn.close() - notify_update('log_aggiornato') - -app = Flask(__name__) -socketio = SocketIO(app, cors_allowed_origins=web_cfg.get('cors_origins', '*')) +# Configurazione Sicurezza Sessioni app.secret_key = get_secret_key() app.config.update( SESSION_COOKIE_HTTPONLY=True, @@ -225,452 +35,14 @@ app.config.update( PERMANENT_SESSION_LIFETIME=int(web_cfg.get('session_hours', 12)) * 3600, ) -# --- NOTIFICHE WEBSOCKET --- -NOTIFY_DELAY = 0.3 -_notify_lock = threading.Lock() -_notify_pending = set() +# Collegamento SocketIO +state.socketio.init_app(app) -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() - -client_states = {} -device_configs = {} -client_telemetry = {} -last_notified_errors = {} -device_health = {} -last_seen_reflector = {} -node_info = {} -node_general = {} -node_versions = {} -gateway_states = {} - -if os.path.exists(CACHE_FILE): - try: - with open(CACHE_FILE, 'r') as f: client_telemetry = json.load(f) - except: client_telemetry = {} - -active_calls = {} - -START_TIME = time.time() -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}") - -seed_last_seen() - -# --- MQTT CALLBACKS --- -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("✅ Successfully connected to MQTT Broker! Subscribing to topics...") - 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)) - - client.subscribe(subscribe_list) - logger.info(f"Subscribed to {len(subscribe_list)} MQTT topics.") - else: - mqtt_connected_status = False - socketio.emit('mqtt_status', {'connected': False}) - logger.error(f"❌ MQTT Connection Error. Reason code: {reason_code}") - -def on_disconnect(client, userdata, disconnect_flags, reason_code, properties=None): - global mqtt_connected_status - mqtt_connected_status = False - socketio.emit('mqtt_status', {'connected': False}) - logger.warning(f"⚠️ MQTT Disconnection detected! Reason code: {reason_code}. Attempting automatic reconnection...") - -@socketio.on('connect') -def handle_connect(): - emit('mqtt_status', {'connected': mqtt_connected_status}) - -def on_message(client, userdata, msg): - try: - topic = msg.topic - 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 "" - - if len(parts) >= 3 and parts[2].lower() == 'log': - if cid not in node_versions: - node_versions[cid] = {} - - 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() - - 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 - 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() - node_versions[cid][prog] = ver - node_versions[cid]["_last_prog"] = prog - 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 = node_versions[cid].get("_last_prog") - if last_prog and last_prog in node_versions[cid]: - if "GitID" not in node_versions[cid][last_prog]: - node_versions[cid][last_prog] += f" (GitID #{git_id})" - notify_update() - return - - if p0 == 'mmdvm': - touch_seen(cid, 'mmdvm') - elif p0 in ('dmrgateway', 'nxdngateway', 'ysfgateway', 'p25gateway', 'dstargateway'): - touch_seen(cid, 'gateway') - elif p0 == 'devices' and p2 == 'services': - touch_seen(cid, 'health') - - 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 device_configs: - device_configs[cid_conf] = {} - try: - device_configs[cid_conf][svc_name] = json.loads(payload) - logger.debug(f"Configuration saved for {cid_conf} -> {svc_name}") - except Exception as e: - logger.error(f"Error parsing config JSON: {e}") - - elif p0 == 'servizi': - client_states[cid] = payload - notify_update() - - state_up = payload.upper() - if state_up.startswith('OFFLINE'): - if not msg.retain and last_notified_errors.get(f"{cid}_NODE") != 'OFFLINE': - broadcast_push_notification(f"💀 NODE OFFLINE: {cid.upper()}", "Connection lost with broker.", cid=cid) - last_notified_errors[f"{cid}_NODE"] = 'OFFLINE' - elif state_up.startswith('ONLINE'): - if last_notified_errors.get(f"{cid}_NODE") == 'OFFLINE': - broadcast_push_notification(f"🌤️ NODE ONLINE: {cid.upper()}", "Node is back online.", cid=cid) - del last_notified_errors[f"{cid}_NODE"] - - if not state_up.startswith('OFF') and state_up != '': - tel = client_telemetry.get(cid, {}) - if isinstance(tel, dict) and '🔄' in str(tel.get('ts1', '')): - client_telemetry[cid] = {"ts1": "Waiting...", "ts2": "Waiting...", "alt": ""} - save_cache(client_telemetry) - - 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 node_versions: - node_versions[cid] = {} - - 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] - - 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: - 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 last_notified_errors.get(status_key) != s_lower: - msg_err = f"Service {svc_name} KO ({svc_status})" - if s_lower == "error": msg_err += " - Auto-healing failed! ⚠️" - broadcast_push_notification(f"🚨 ALARM: {cid.upper()}", msg_err, cid=cid) - last_notified_errors[status_key] = s_lower - elif s_lower == "online" and status_key in last_notified_errors: - broadcast_push_notification(f"✅ RESTORED: {cid.upper()}", f"Service {svc_name} back ONLINE.", cid=cid) - del last_notified_errors[status_key] - - except Exception as e: - logger.error(f"Error parsing health data: {e}") - - elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost') and parts[3].lower() == 'info': - try: - cid = parts[1].lower() - data = json.loads(payload) - - tx = data.get("TXFrequency", "0") - rx = data.get("RXFrequency", "0") - lat = data.get("Latitude", "0.0") - lon = data.get("Longitude", "0.0") - loc = data.get("Location", "Sconosciuta") - - 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) - - node_info[cid] = { - "tx": format_freq(tx), - "rx": format_freq(rx), - "lat": lat, - "lon": lon, - "loc": loc - } - notify_update() - except Exception as e: - logger.error(f"Error parsing MMDVMHost info for {cid}: {e}") - - 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: - node_general[cid] = {"callsign": callsign, "radio_id": radio_id, "duplex": str(duplex)} - notify_update() - except Exception as e: - logger.error(f"Error parsing MMDVMHost general for {cid}: {e}") - - 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 gateway_states: - gateway_states[cid] = {} - - if 'status' in data: - gateway_states[cid][proto] = {"action": "status", "dest": data['status'].get('message', 'IDLE')} - notify_update() - elif 'link' in data: - l = data['link'] - g_dest = str(l.get('reflector') or l.get('talkgroup') or '---').strip() - g_action = l.get('action', '') - gateway_states[cid][proto] = {"action": g_action, "dest": g_dest} - notify_update() - - m = "" - if 'status' in data: - m = data['status'].get('message', '') - elif 'link' in data: - l = data['link'] - dest = str(l.get('reflector') or l.get('talkgroup') or '---').strip() - action = l.get('action') - if action == 'linking': last_seen_reflector[f"{cid}_{proto}"] = dest - elif action == 'unlinking': last_seen_reflector[f"{cid}_{proto}"] = "---" - m = f"{'Link' if action=='linking' else 'Unlinked'} {dest}" - - if m: save_to_sqlite(cid, {'src_id': "🌐 " + m, 'dst_id': 'NET'}, protocol=proto) - - elif parts[0] == 'mmdvm': - data = json.loads(payload) - if cid not in active_calls: active_calls[cid] = {} - if cid not in client_telemetry or not isinstance(client_telemetry.get(cid), dict): - client_telemetry[cid] = {"ts1": "Waiting...", "ts2": "Waiting...", "alt": "", "idle": True} - - if 'MMDVM' in data and data['MMDVM'].get('mode') == 'idle': - client_telemetry[cid]["idle"] = True - save_cache(client_telemetry) - return - - client_telemetry[cid]["idle"] = False - - 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 = get_call(d.get('src_id')) - dst = str(d.get('dst_id')) - - 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': '---', '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: - p = data[k] - act = p.get('action') - - if act == 'start': - if k == 'NXDN': src = get_call(p.get('src_id', '---'), 'NXDN') - 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', '---'))))) - - 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 = 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': '---', '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) - if k in active_calls[cid]: del active_calls[cid][k] - except Exception as e: - logger.error(f"MQTT MSG ERROR: {e}") - -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', '')) -mqtt_backend.on_connect = on_connect -mqtt_backend.on_disconnect = on_disconnect -mqtt_backend.on_message = on_message -try: - 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.get('mqtt', {}).get('broker')}...") -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 +# Registrazione Blueprint +app.register_blueprint(auth_bp) +app.register_blueprint(api_bp) +# Security Headers @app.after_request def add_security_headers(resp): resp.headers.setdefault('X-Content-Type-Options', 'nosniff') @@ -682,7 +54,7 @@ def add_security_headers(resp): def get_git_commit(): try: - return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').strip() + return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip() except Exception: return "sconosciuta" @@ -692,772 +64,21 @@ SERVER_COMMIT = get_git_commit() def index(): return render_template('index.html', git_commit=SERVER_COMMIT) -@app.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([]) - -@app.route('/api/logs') -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, 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(): - clean_versions = {} - for c, d in node_versions.items(): - clean_versions[c] = {k: v for k, v in d.items() if not k.startswith('_')} - - # --- INIEZIONE DMR NETWORKS DA CONFIGURAZIONE (Versione 4.0) --- - enriched_gateway_states = dict(gateway_states) - - for cid, confs in 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 = [] - - # Cerca le sezioni [DMR Network 1] fino a [DMR Network 5] - for i in range(1, 6): - section_name = f"[DMR Network {i}]" - if section_name in raw: - # Estrai blocco della sezione - block = raw.split(section_name)[1].split('[')[0] - # Cerca Enabled=1 - if re.search(r'^Enabled\s*=\s*1', block, re.MULTILINE | re.IGNORECASE): - # Cerca Name= (es. Name=BM_2222) - 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": client_states, - "telemetry": client_telemetry, - "health": device_health, - "info": node_info, - "general": node_general, - "last_seen": seen_ages(), - "uptime": int(time.time() - START_TIME), - "versions": clean_versions, - "gateway_states": enriched_gateway_states - }) - -@app.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 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 - }) - -# ===================================================================== -# AUTENTICAZIONE / VALIDAZIONE -# ===================================================================== -VALID_ROLES = ('admin', 'operator') -USERNAME_RE = re.compile(r'^[A-Za-z0-9_.@\-]{3,32}$') -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$') -MIN_PASSWORD_LEN = 8 - -SIMPLE_COMMANDS = {'TG:ON', 'TG:OFF'} -PRIVILEGED_COMMANDS = {'REBOOT', 'RESET_HAT', 'UPDATE_AGENT'} -SERVICE_ACTIONS = {'start', 'stop', 'restart'} - -def db_connect(row=False): - conn = sqlite3.connect(DB_PATH, timeout=10) - if row: - conn.row_factory = sqlite3.Row - return conn - -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 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()] - -def known_profile_keys(cid=None): - keys = {'A', 'B'} - healths = [device_health.get(cid)] if cid else list(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 - -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 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()) - -LOGIN_MAX_FAILS = 5 -LOGIN_WINDOW_SEC = 300 -login_attempts = {} -login_lock = threading.Lock() - -def client_ip(): - if config.get('web', {}).get('trust_proxy'): - fwd = request.headers.get('X-Forwarded-For', '') - if fwd: - return fwd.split(',')[0].strip() - 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) - -@app.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("Missing credentials", 400) - - ip = client_ip() - if login_blocked(ip): - logger.warning(f"Login bloccato (troppi tentativi) da {ip}") - return err("Too many failed attempts. Try again in a few minutes.", 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 - -@app.route('/api/logout', methods=['POST']) -def logout(): - session.clear() - return jsonify({"success": True}) - -@app.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']}) - -@app.route('/api/command', methods=['POST']) -def cmd(): - auth = get_auth() - if not auth: - return err("Not authenticated", 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("Invalid node id") - if not node_allowed(auth['role'], auth['allowed_nodes'], cid): - return err("You do not have permission for this node.", 403) - - if cmd_type in PRIVILEGED_COMMANDS: - if auth['role'] != 'admin': - return err("Only Admins can run this command.", 403) - elif cmd_type in SIMPLE_COMMANDS: - pass - elif cmd_type in known_profile_keys(cid): - pass - else: - logger.warning(f"Comando non ammesso da {auth['username']}: {cmd_type[:40]!r} -> {cid}") - return err("Unknown command") - - if not mqtt_publish(f"servizi/{cid}/cmnd", cmd_type): - return err("MQTT broker offline - command not sent", 503) - - audit(auth['username'], cid, cmd_type) - client_telemetry[cid] = {"ts1": "🔄 Sent...", "ts2": "🔄 Sent...", "alt": ""} - return jsonify({"success": True}) - -@app.route('/api/global_command', methods=['POST']) -def global_cmd(): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Admin action only!", 403) - - cmd_type = str(json_body().get('type', '')).strip() - if cmd_type not in known_profile_keys(): - return err("Unknown profile") - - 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("MQTT broker offline - command not sent", 503) - return jsonify({"success": True, "sent": sent, "failed": failed}) - -@app.route('/api/service_control', methods=['POST']) -def service_control(): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 403) - - d = json_body() - cid = str(d.get('clientId', '')).strip().lower() - action = str(d.get('action', '')).strip().lower() - service = str(d.get('service', '')).strip() - if not CID_RE.match(cid): - return err("Invalid node id") - if action not in SERVICE_ACTIONS: - return err("Invalid action") - if not SERVICE_RE.match(service): - return err("Invalid service name") - - if not mqtt_publish(f"devices/{cid}/control", f"{action}:{service}"): - return err("MQTT broker offline - command not sent", 503) - audit(auth['username'], cid, f"SVC_{action.upper()}_{service}") - return jsonify({"success": True}) - -@app.route('/api/update_nodes', methods=['POST']) -def update_nodes(): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 403) - if not mqtt_publish("devices/control/request", "update"): - return err("MQTT broker offline - command not sent", 503) - logger.info(f"📢 REQ CONFIG inviata a tutta la flotta da {auth['username']}") - audit(auth['username'], '*', 'REQ_CONFIG_ALL') - return jsonify({"success": True}) - -@app.route('/api/users', methods=['GET']) -def get_users(): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 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) - -@app.route('/api/users', methods=['POST']) -def add_user(): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 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("Missing data") - if not USERNAME_RE.match(username): - return err("Invalid username (3-32 chars: letters, digits, . _ @ -)") - if not isinstance(password, str) or len(password) < MIN_PASSWORD_LEN: - return err(f"Password must be at least {MIN_PASSWORD_LEN} characters") - if role not in VALID_ROLES: - return err("Invalid role") - - 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 already exists") - audit(auth['username'], '-', f"USER_ADD_{username}_{role}") - return jsonify({"success": True}) - -@app.route('/api/users/', methods=['DELETE']) -def delete_user(user_id): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 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("User not found", 404) - if u[0] == auth['username']: - return err("You cannot delete yourself!") - if u[1] == 'admin' and count_admins(c, exclude_id=user_id) == 0: - return err("You cannot delete the last admin!") - 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}) - -@app.route('/api/users/', methods=['PUT']) -def update_user(user_id): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 403) - - d = json_body() - password = d.get('password') - if password is not None and not isinstance(password, str): - return err("Invalid password") - - 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("User not found", 404) - - role = d.get('role', existing[1]) - allowed = normalize_nodes(d.get('allowed_nodes', existing[2])) - if role not in VALID_ROLES: - return err("Invalid role") - if existing[1] == 'admin' and role != 'admin' and count_admins(c, exclude_id=user_id) == 0: - return err("You cannot demote the last admin!") - - if password and password.strip() != "": - if len(password) < MIN_PASSWORD_LEN: - return err(f"Password must be at least {MIN_PASSWORD_LEN} characters") - 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}) - -@app.route('/api/change_password', methods=['POST']) -def change_password(): - auth = get_auth() - if not auth: - return err("Not authenticated", 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("Unauthorized", 403) - if not new_pass or not isinstance(new_pass, str): - return err("Password cannot be empty") - if len(new_pass) < MIN_PASSWORD_LEN: - return err(f"Password must be at least {MIN_PASSWORD_LEN} characters") - - 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("User not found", 404) - audit(auth['username'], '-', f"PASSWORD_CHANGE_{user_to_change}") - return jsonify({"success": True}) - -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 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 - conn.commit() - if n1 or n2: - logger.info(f"🧹 Pulizia DB: {n1} ascolti e {n2} audit rimossi.") - except Exception as e: - logger.error(f"❌ Errore pulizia DB: {e}") - -def auto_update_ids(): - 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) - load_ids() - logger.info(f"✅ Aggiornamento completato ({len(user_db)} ID DMR, {len(nxdn_db)} ID NXDN).") - except Exception as e: - logger.error(f"❌ Errore durante il download: {e}") - - 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 update: {e}") - time.sleep(30) - -@app.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": "Configuration unavailable"}), 500 - -@app.route('/api/config', methods=['GET']) -def get_config_api(): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 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) - }) - -@app.route('/api/config', methods=['POST']) -def save_config_api(): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 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("Invalid log rotation settings") - - if not TIME_RE.match(schedule): - return err("Invalid time (use HH:MM)") - for u in (url_dmr, url_nxdn): - if not u.lower().startswith(('http://', 'https://')): - return err("URLs must start with http:// or 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}) - -@app.route('/api/config_file//', methods=['GET']) -def get_config_file(cid, service): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 403) - cid = cid.lower() - service = service.lower() - if not CID_RE.match(cid) or not SERVICE_RE.match(service): - return err("Invalid parameters") - config_data = device_configs.get(cid, {}).get(service) - if not config_data: - return err("Configuration not received yet. Wait or send an UPDATE command.", 404) - return jsonify({"success": True, "data": config_data}) - -@app.route('/api/config_file', methods=['POST']) -def save_config_file(): - auth = get_auth() - if not auth or auth['role'] != 'admin': - return err("Unauthorized", 403) - - d = json_body() - cid = str(d.get('clientId', '')).strip().lower() - 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("Invalid parameters") - if not isinstance(new_config, dict) or not isinstance(new_config.get('raw_text'), str): - return err("Invalid configuration payload") - if len(new_config['raw_text']) > 65536: - return err("Configuration too large (max 64 KB)") - - if not mqtt_publish(f"devices/{cid}/config_set/{service}", json.dumps(new_config)): - return err("MQTT broker offline - configuration not sent", 503) - 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: - subprocess.run(['git', 'fetch'], timeout=10, cwd=BASE_DIR) - local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip() - remote_hash = subprocess.check_output(['git', 'rev-parse', '@{u}'], cwd=BASE_DIR).decode('utf-8').strip() - update_available = local_hash != remote_hash - 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') - subprocess.run(['git', 'pull', '--ff-only'], timeout=30, cwd=BASE_DIR, check=True) - 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') - -@app.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 - -@app.route('/icon-512.png') -def serve_icon(): - return send_from_directory(BASE_DIR, 'icon-512.png') - -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}") - -@app.route('/api/vapid_public_key') -def get_vapid_key(): - return jsonify({"public_key": config.get('webpush', {}).get('vapid_public_key', '')}) - -@app.route('/api/subscribe', methods=['POST']) -def subscribe_push(): - auth = get_auth() - if not auth: - return err("Unauthorized", 403) - sub_data = json_body() - if not sub_data.get('endpoint'): - return err("Invalid subscription") - 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}) +@state.socketio.on('connect') +def handle_connect(): + emit('mqtt_status', {'connected': mqtt_svc.mqtt_connected_status}) + +# --- INIZIALIZZAZIONE SISTEMA & THREAD --- +init_db() +state.seed_last_seen() +mqtt_svc.start_mqtt() threading.Thread(target=auto_update_ids, daemon=True).start() threading.Thread(target=push_worker, daemon=True).start() +threading.Thread(target=watchdog_loop, daemon=True).start() + +logger.info(f"🚀 Fleet Control Console modulare pronta (Git Rev: {SERVER_COMMIT})") if __name__ == '__main__': - socketio.run(app, host='0.0.0.0', port=9000) + port = int(config.get('web', {}).get('port', 9000)) if 'config' in locals() else 9000 + state.socketio.run(app, host='0.0.0.0', port=port) diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/config.py b/core/config.py new file mode 100644 index 0000000..4a585a4 --- /dev/null +++ b/core/config.py @@ -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 diff --git a/core/database.py b/core/database.py new file mode 100644 index 0000000..7130f69 --- /dev/null +++ b/core/database.py @@ -0,0 +1,122 @@ +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 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) + 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() + conn.close() + notify_update('log_aggiornato') + +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 + conn.commit() + if n1 or n2: + logger.info(f"🧹 Pulizia DB: {n1} ascolti e {n2} audit rimossi.") + except Exception as e: + logger.error(f"❌ Errore pulizia DB: {e}") diff --git a/core/state.py b/core/state.py new file mode 100644 index 0000000..b70048d --- /dev/null +++ b/core/state.py @@ -0,0 +1,135 @@ +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 + +# --- 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 = {} + +# 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() diff --git a/routes/__init__.py b/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/routes/api_routes.py b/routes/api_routes.py new file mode 100644 index 0000000..4807152 --- /dev/null +++ b/routes/api_routes.py @@ -0,0 +1,417 @@ +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 + +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(): + 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 60""") + 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 + }) + +@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 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(auth['username'], cid, cmd_type) + 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': + return err("Non autorizzato", 403) + + d = json_body() + cid = str(d.get('clientId', '')).strip().lower() + 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//', methods=['GET']) +def get_config_file(cid, service): + auth = get_auth() + if not auth or auth['role'] != 'admin': + return err("Non autorizzato", 403) + cid = cid.lower() + 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': + return err("Non autorizzato", 403) + + d = json_body() + cid = str(d.get('clientId', '')).strip().lower() + 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()}") + return jsonify({"success": True}) + +# --- AGGIORNAMENTO SERVER OTA --- + +@api_bp.route('/api/server_update/check', methods=['GET']) +def check_server_update(): + auth = get_auth() + if not auth or auth['role'] != 'admin': + return err("Non autorizzato", 403) + + try: + subprocess.run(['git', 'fetch'], timeout=10, cwd=BASE_DIR) + local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip() + remote_hash = subprocess.check_output(['git', 'rev-parse', '@{u}'], cwd=BASE_DIR).decode('utf-8').strip() + update_available = local_hash != remote_hash + 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"}) + +@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) + + 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') diff --git a/routes/auth_routes.py b/routes/auth_routes.py new file mode 100644 index 0000000..6b83374 --- /dev/null +++ b/routes/auth_routes.py @@ -0,0 +1,252 @@ +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', '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() + +def client_ip(): + if config.get('web', {}).get('trust_proxy'): + fwd = request.headers.get('X-Forwarded-For', '') + if fwd: + return fwd.split(',')[0].strip() + 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/', 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/', 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}) diff --git a/services/__init__.py b/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/services/mqtt_service.py b/services/mqtt_service.py new file mode 100644 index 0000000..98de991 --- /dev/null +++ b/services/mqtt_service.py @@ -0,0 +1,404 @@ +import json +import re +from paho.mqtt import client as mqtt_client +from core.config import config, logger +from core.database import save_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)) + + 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 + 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 --- + if len(parts) >= 3 and parts[2].lower() == 'log': + 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() + 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 + 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') and parts[3].lower() == 'info': + try: + cid = parts[1].lower() + data = json.loads(payload) + + tx = data.get("TXFrequency", "0") + rx = data.get("RXFrequency", "0") + lat = data.get("Latitude", "0.0") + lon = data.get("Longitude", "0.0") + loc = data.get("Location", "Sconosciuta") + + 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) + + state.node_info[cid] = { + "tx": format_freq(tx), + "rx": format_freq(rx), + "lat": lat, + "lon": lon, + "loc": loc + } + state.notify_update() + except Exception as e: + logger.error(f"Errore parsing MMDVMHost info 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] = {} + + if 'status' in data: + state.gateway_states[cid][proto] = {"action": "status", "dest": data['status'].get('message', 'IDLE')} + state.notify_update() + elif '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() + + m = "" + if 'status' in data: + m = data['status'].get('message', '') + elif 'link' in data: + l = data['link'] + dest = str(l.get('reflector') or l.get('talkgroup') or '---').strip() + action = l.get('action') + if action == 'linking': + state.last_seen_reflector[f"{cid}_{proto}"] = dest + elif action == 'unlinking': + state.last_seen_reflector[f"{cid}_{proto}"] = "---" + m = f"{'Link' if action=='linking' else 'Unlinked'} {dest}" + + if m: + save_to_sqlite(cid, {'src_id': "🌐 " + m, 'dst_id': 'NET'}, protocol=proto) + + # --- 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 + + 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', '')) +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 diff --git a/services/push_service.py b/services/push_service.py new file mode 100644 index 0000000..2d2a9de --- /dev/null +++ b/services/push_service.py @@ -0,0 +1,70 @@ +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 + +push_queue = queue.Queue(maxsize=200) + +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()] + +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}") diff --git a/services/scheduler_service.py b/services/scheduler_service.py new file mode 100644 index 0000000..ee339b6 --- /dev/null +++ b/services/scheduler_service.py @@ -0,0 +1,50 @@ +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 update: {e}") + time.sleep(30) diff --git a/services/watchdog_service.py b/services/watchdog_service.py new file mode 100644 index 0000000..60ea3c7 --- /dev/null +++ b/services/watchdog_service.py @@ -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', '-2 hours') + 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 >= 5 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) diff --git a/static/css/style.css b/static/css/style.css new file mode 100644 index 0000000..0ff6aaf --- /dev/null +++ b/static/css/style.css @@ -0,0 +1,152 @@ +/* --- TEMA MODERNO (Soft UI / Tailwind inspired) --- */ +:root { + --primary: #3b82f6; --success: #10b981; --danger: #ef4444; --accent: #8b5cf6; + --bg-gradient: #0f172a; + --card-bg: #1e293b; + --border-color: rgba(255, 255, 255, 0.1); + --text-main: #f8fafc; + --text-muted: #94a3b8; + --topbar-bg: #1e293b; +} + +* { box-sizing: border-box; } +body { font-family: 'Inter', sans-serif; background: var(--bg-gradient); margin: 0; padding: 0; color: var(--text-main); min-height: 100vh; } + +#top-bar-container { position: sticky; top: 0; z-index: 100; padding: 15px 20px; display: flex; justify-content: center; background: rgba(15, 23, 42, 0.85); backdrop-filter: blur(10px); margin-bottom: 30px; } +#top-bar { background: var(--topbar-bg); padding: 12px 30px; display: flex; justify-content: space-between; align-items: center; border-radius: 12px; border: 1px solid var(--border-color); width: 100%; max-width: 1400px; box-shadow: 0 4px 15px rgba(0,0,0,0.3); } +.title-brand { font-size: 1.2rem; font-weight: 800; letter-spacing: 2px; color: var(--text-main); font-family: 'JetBrains Mono', monospace; } + +.nav-tabs { display: flex; gap: 15px; margin-left: 30px; flex: 1; } +.nav-tab { background: transparent; border: none; color: var(--text-muted); font-size: 0.95rem; font-weight: 800; cursor: pointer; padding: 8px 16px; border-radius: 8px; transition: all 0.2s ease; font-family: 'Inter', sans-serif; letter-spacing: 1px; } +.nav-tab:hover { color: var(--text-main); background: rgba(255,255,255,0.05); } +.nav-tab.active { color: var(--primary); background: rgba(59, 130, 246, 0.1); } + +.theme-switch { background: transparent; border: 1px solid var(--border-color); color: var(--text-muted); padding: 6px 14px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem; font-family: 'Inter', sans-serif; transition: all 0.2s; } +.theme-switch:hover { color: var(--text-main); border-color: var(--text-main); } + +/* FILTRI E CONTROLLI VIEW */ +.filter-bar { background: var(--topbar-bg); border-radius: 12px; border: 1px solid var(--border-color); padding: 10px 20px; display: flex; gap: 15px; flex-wrap: wrap; align-items: center; justify-content: space-between; box-shadow: 0 4px 12px rgba(0,0,0,0.2); margin-bottom: 20px; } +.filter-pill { background: transparent; border: 1px solid var(--border-color); color: var(--text-muted); padding: 6px 14px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; cursor: pointer; transition: all 0.2s ease; } +.filter-pill:hover { background: rgba(255,255,255,0.05); color: var(--text-main); } +.filter-pill.active { background: rgba(59, 130, 246, 0.15); color: var(--primary); border-color: var(--primary); } +.filter-pill.pill-warn { color: #f59e0b; border-color: rgba(245, 158, 11, 0.3); } +.filter-pill.pill-warn.active { background: rgba(245, 158, 11, 0.15); border-color: #f59e0b; color: #f59e0b; } + +/* 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; } + +.card { background: var(--card-bg) !important; border-radius: 12px; padding: 20px; border: 1px solid var(--border-color); border-top: 3px solid var(--border-color) !important; display: flex; flex-direction: column; box-shadow: 0 4px 12px rgba(0,0,0,0.2) !important; filter: none !important; opacity: 1 !important; transition: all 0.3s ease; } + +/* HEADER FISSO SU 2 RIGHE ALLINEATO A SINISTRA */ +.card-header { display: flex; flex-direction: column; justify-content: flex-start; align-items: flex-start; gap: 10px; margin-bottom: 15px; border-bottom: 1px solid var(--border-color); padding-bottom: 12px; } +.client-name { font-size: 1.2rem; font-weight: 800; 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: rgba(0,0,0,0.3); padding: 4px 8px; border-radius: 6px; border: 1px solid var(--border-color); color: var(--text-muted); } + +.health-bar { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.75rem; font-weight: 600; background: rgba(0,0,0,0.2); padding: 10px; border-radius: 8px; margin-bottom: 15px; border: 1px solid var(--border-color); font-family: 'JetBrains Mono', monospace; text-align: center; } +.health-bar > span { background: rgba(255,255,255,0.03); padding: 6px; border-radius: 6px; } + +.freq-bar { display: flex; justify-content: space-around; font-size: 0.8rem; font-weight: 800; background: rgba(0,0,0,0.2); padding: 8px 10px; border-radius: 8px; margin-bottom: 10px; border: 1px dashed var(--border-color); font-family: 'JetBrains Mono', monospace; } +.freq-tx { color: #f87171; } .freq-rx { color: #4ade80; } + +.seen-bar { display: flex; flex-wrap: wrap; justify-content: center; gap: 4px 14px; font-size: 0.7rem; font-family: 'JetBrains Mono', monospace; color: var(--text-muted); margin: -6px 0 12px 0; } +.seen-item b { font-weight: 700; } +.seen-item.ok b { color: var(--success); } +.seen-item.warn, .seen-item.warn b { color: #f59e0b; font-weight: 700; } + +.node-meta { font-size: 0.75rem; color: #8b949e; text-align: center; margin-bottom: 10px; line-height: 1.4; } +.node-meta-item { display: block; } + +.type-badge { font-size: 0.65rem; padding: 4px 8px; border-radius: 6px; font-weight: 700; text-transform: uppercase; display: inline-block; margin-left: 0; vertical-align: middle; } +.type-repeater { background: rgba(59, 130, 246, 0.15); color: var(--primary); border: 1px solid var(--primary); } +.type-hotspot { background: rgba(139, 92, 246, 0.15); color: var(--accent); border: 1px solid var(--accent); } + +.status-display { text-align: center; font-family: 'Inter', sans-serif; font-size: 0.9rem; font-weight: 700; padding: 8px; border-radius: 6px; background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); margin-bottom: 10px; color: var(--text-muted); } +.card.online .status-display { color: var(--success); border-color: rgba(16, 185, 129, 0.4); background: rgba(16, 185, 129, 0.1); } +.status-offline { color: var(--danger) !important; border-color: rgba(239, 68, 68, 0.4) !important; } + +.gateway-bar { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 15px; justify-content: center; } + +.ts-container { display: flex; flex-direction: column; gap: 6px; margin-bottom: 15px; } +.dmr-info { font-size: 0.85rem; font-weight: 600; font-family: 'JetBrains Mono', monospace; padding: 8px 12px; border-radius: 6px; background: rgba(0,0,0,0.2) !important; border: 1px solid var(--border-color); border-left: 4px solid var(--border-color) !important; color: var(--text-muted) !important; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: all 0.3s; } + +.terminal-log { background: #010409; color: var(--text-muted); font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; border-radius: 6px; padding: 10px; max-height: 90px; overflow-y: auto; border: 1px solid var(--border-color); line-height: 1.4; margin-bottom: 15px; box-shadow: inset 0 2px 5px rgba(0,0,0,0.5); scrollbar-width: thin; scrollbar-color: var(--border-color) transparent; } + +.actions { display: none; gap: 8px; flex-wrap: wrap; margin-top: auto; } +.btn-cmd { flex: 1; padding: 8px 10px; border: 1px solid transparent; background: rgba(255,255,255,0.05) !important; border-radius: 6px; font-weight: 600; font-size: 0.75rem; cursor: pointer; color: var(--text-main) !important; font-family: 'Inter', sans-serif; transition: all 0.2s ease; display: flex; align-items: center; justify-content: center; gap: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.2) !important; } +.btn-cmd:hover { filter: brightness(1.2); } + +details.admin-dropdown summary { list-style: none; display: flex; justify-content: center; align-items: center; } +details.admin-dropdown summary::-webkit-details-marker { display: none; } + +.mqtt-badge { padding: 4px 10px; border-radius: 6px; font-size: 0.75rem; font-weight: 800; font-family: 'JetBrains Mono', monospace; transition: all 0.3s ease; border: 1px solid var(--border-color); display: flex; align-items: center; justify-content: center; height: 30px;} +.mqtt-online { background: rgba(16, 185, 129, 0.1); color: var(--success); border-color: var(--success); } +.mqtt-offline { background: rgba(239, 68, 68, 0.1); color: var(--danger); border-color: var(--danger); animation: danger-glow 2s infinite; } + +.table-container { background: var(--card-bg); border-radius: 12px; border: 1px solid var(--border-color); overflow-x: auto; overflow-y: auto; max-height: 500px; margin: 0 20px 40px 20px; -webkit-overflow-scrolling: touch; box-shadow: 0 4px 12px rgba(0,0,0,0.2); } +thead th { position: sticky; top: 0; z-index: 10; background: #0f172a; border-bottom: 2px solid var(--primary); } +table { width: 100%; min-width: 100%; border-collapse: collapse; text-align: left; font-size: 0.85rem; font-family: 'Inter', sans-serif; white-space: nowrap; } +th, td { padding: 12px 16px; border-bottom: 1px solid var(--border-color); line-height: 1.6; vertical-align: middle; } +th { background-color: rgba(255, 255, 255, 0.02); font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; font-size: 0.75rem; color: var(--text-muted); } +tbody tr:nth-child(even) { background-color: rgba(255, 255, 255, 0.015); } + +@keyframes soft-glow { 0% { box-shadow: 0 0 5px var(--pulse-color, var(--primary)); border-color: var(--border-color); } 50% { box-shadow: 0 0 15px var(--pulse-color, var(--primary)); border-color: var(--pulse-color, var(--primary)); } 100% { box-shadow: 0 0 5px var(--pulse-color, var(--primary)); border-color: var(--border-color); } } +.tx-active-unified { animation: soft-glow 2s infinite !important; color: var(--text-main) !important; background: rgba(0,0,0,0.3) !important; border-left: 4px solid var(--pulse-color, var(--primary)) !important; } + +@keyframes danger-glow { 0% { box-shadow: 0 0 5px var(--danger); border-color: var(--border-color); } 50% { box-shadow: 0 0 15px var(--danger); border-color: var(--danger); } 100% { box-shadow: 0 0 5px var(--danger); border-color: var(--border-color); } } +.blink { animation: danger-glow 1.5s infinite; color: var(--danger) !important; border: 1px solid var(--danger) !important; } + +.modal-overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(15, 23, 42, 0.9); z-index:1000; align-items:center; justify-content:center; backdrop-filter: blur(5px); } +.modal-top { z-index: 5000 !important; } +.modal-content { background:var(--card-bg); border:1px solid var(--border-color); padding:25px; border-radius:12px; max-height: 90vh; overflow-y: auto; box-shadow: 0 10px 40px rgba(0,0,0,0.5); } + +.auth-btn { background: rgba(255,255,255,0.05); color: var(--text-main); border: 1px solid var(--border-color); padding: 6px 12px; border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.8rem; font-family: 'Inter', sans-serif; transition: all 0.2s; } +.auth-btn:hover { border-color: var(--text-main); background: rgba(255,255,255,0.1); } +input, select { background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); color: var(--text-main); padding: 8px 12px; border-radius: 6px; font-family: 'Inter', sans-serif; outline: none; } +input:focus, select:focus { border-color: var(--primary); } +input:disabled { opacity: 0.5; cursor: not-allowed; } +option { background: var(--card-bg); color: var(--text-main); } + +.mini-card { background: var(--card-bg); border-radius: 10px; border: 1px solid var(--border-color); padding: 15px 10px; display: flex; flex-direction: column; align-items: center; justify-content: space-between; text-align: center; transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease; cursor: pointer; box-shadow: 0 4px 6px rgba(0,0,0,0.1); height: 105px; width: 160px; overflow: hidden; } +.mini-card:hover { transform: translateY(-4px); box-shadow: 0 8px 15px rgba(0,0,0,0.3); } +.mini-card-content { width: 100%; overflow: hidden; } +.mini-card-name { font-weight: 800; font-size: 0.95rem; width: 100%; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.mini-card-status { font-size: 0.65rem; font-weight: 800; padding: 4px 6px; border-radius: 6px; width: 100%; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + +/* --- STILI FLEET MAP & DIAGNOSTICA --- */ +#map-container { max-width: 1400px; height: calc(100vh - 200px); min-height: 550px; margin: 0 auto; border-radius: 12px; border: 1px solid var(--border-color); overflow: hidden; box-shadow: 0 8px 25px rgba(0,0,0,0.4); } +.dark-tiles { filter: brightness(0.6) invert(1) contrast(3) hue-rotate(200deg) saturate(0.3) brightness(0.7); } +.custom-map-pin { display: flex; align-items: center; justify-content: center; border-radius: 50%; border: 2px solid white; font-size: 1rem; color: white; box-shadow: 0 0 10px rgba(0,0,0,0.5); transition: all 0.3s ease; } +.pin-online { background: var(--success); border-color: rgba(255,255,255,0.8); } +.pin-offline { background: #64748b; border-color: rgba(255,255,255,0.3); opacity: 0.7; } +.pin-warn { background: #f59e0b !important; border-color: #fbbf24 !important; animation: danger-glow 2s infinite !important; } +.pin-tx { background: var(--primary) !important; animation: soft-glow 1.5s infinite !important; transform: scale(1.15); } +.leaflet-popup-content-wrapper { background: var(--card-bg) !important; color: var(--text-main) !important; border-radius: 10px !important; border: 1px solid var(--border-color) !important; box-shadow: 0 6px 20px rgba(0,0,0,0.6) !important; } +.leaflet-popup-tip { background: var(--card-bg) !important; } + +@media (max-width: 768px) { + #top-bar-container { top: 0; padding: 10px; margin-bottom: 15px; } + #top-bar { flex-direction: column; padding: 15px; gap: 12px; border-radius: 12px; } + .title-brand { font-size: 1.1rem; text-align: center; width: 100%; } + #top-bar > div { width: 100%; flex-wrap: wrap; justify-content: center; gap: 8px !important; } + #auth-container { width: 100%; justify-content: center; flex-wrap: wrap; padding-top: 12px; border-top: 1px solid var(--border-color); } + #auth-container > span { width: 100%; text-align: center; margin-bottom: 8px; font-family: 'Inter', sans-serif; } + .auth-btn, .theme-switch { flex: 1 1 auto; text-align: center; } + .nav-tabs { position: fixed; bottom: 0; left: 0; width: 100%; background: var(--topbar-bg); border-top: 1px solid var(--border-color); margin: 0; padding: 10px 0; justify-content: space-around; z-index: 1000; flex-direction: row; gap: 0; padding-bottom: env(safe-area-inset-bottom, 10px); box-shadow: 0 -4px 15px rgba(0,0,0,0.3); } + .nav-tab { font-size: 0.95rem; padding: 10px; flex: 1; text-align: center; border-radius: 0; } + body { padding-bottom: 70px; } + .filter-bar { flex-direction: column; } + .list-view .card { flex-direction: column; align-items: stretch; } + #map-container { height: calc(100vh - 220px); min-height: 400px; margin: 0 10px; } +} diff --git a/static/js/app.js b/static/js/app.js new file mode 100644 index 0000000..4bef380 --- /dev/null +++ b/static/js/app.js @@ -0,0 +1,848 @@ +// --- VARIABILI GLOBALI E UI VIEW --- +let clients = []; +let me = { logged_in: false, user: '', role: '', allowed_nodes: '' }; +let isAuthenticated = false; +let usersCache = {}; +let globalHealthData = {}; +let globalVersionsData = {}; +let editingUserId = null; +let currentResetHatId = null; +let confirmActionCallback = null; + +let currentFilter = 'all'; +let searchQuery = ''; +let viewMode = localStorage.getItem('fleetViewMode') || 'grid'; +let fleetMap = null; +let mapMarkers = {}; + +function switchView(viewName) { + document.getElementById('view-home').style.display = 'none'; + document.getElementById('view-nodes').style.display = 'none'; + document.getElementById('view-map').style.display = 'none'; + document.getElementById('tab-home').classList.remove('active'); + document.getElementById('tab-nodes').classList.remove('active'); + document.getElementById('tab-map').classList.remove('active'); + + document.getElementById(`view-${viewName}`).style.display = 'block'; + document.getElementById(`tab-${viewName}`).classList.add('active'); + localStorage.setItem('fleetDefaultView', viewName); + + if (viewName === 'nodes') { applyViewMode(); } + else if (viewName === 'map') { + setTimeout(() => { + initOrUpdateMap(); + }, 100); + } +} + +window.addEventListener('DOMContentLoaded', () => { + const savedView = localStorage.getItem('fleetDefaultView') || 'home'; + switchView(savedView); + initUI(); + checkPushStatus(); + setInterval(refreshStates, 15000); + setInterval(() => { refreshLogs(); refreshStats(); }, 60000); + checkServerUpdate(); + setInterval(checkServerUpdate, 3600000); +}); + +// --- FUNZIONI FILTRO E LAYOUT --- +function setFilter(filter) { + currentFilter = filter; + document.querySelectorAll('.filter-pill').forEach(btn => { + if (btn.getAttribute('onclick') === `setFilter('${filter}')`) btn.classList.add('active'); + else btn.classList.remove('active'); + }); + applyFilters(); +} + +function toggleViewMode() { + viewMode = viewMode === 'grid' ? 'list' : 'grid'; + localStorage.setItem('fleetViewMode', viewMode); + applyViewMode(); +} + +function applyViewMode() { + const gridDiv = document.getElementById('client-grid'); + const btnToggle = document.getElementById('view-toggle-btn'); + if (viewMode === 'list') { + gridDiv.className = 'list-view'; + btnToggle.innerText = '📄 LIST'; + } else { + gridDiv.className = 'grid'; + btnToggle.innerText = '🔲 GRID'; + } +} + +function applyFilters() { + const searchEl = document.getElementById('node-search'); + if(!searchEl) return; + searchQuery = searchEl.value.toLowerCase(); + + clients.forEach(c => { + const card = document.getElementById(`card-${c.id}`); + if (!card) return; + + let show = true; + let status = card.dataset.status || 'offline'; + let gatewaysStr = card.dataset.gateways || ''; + let hasAlert = card.dataset.hasWarn === 'true'; + + if (currentFilter === 'online' && status !== 'online') show = false; + if (currentFilter === 'offline' && status === 'online') show = false; + if (currentFilter === 'alerts' && !hasAlert) show = false; + if (['dmr', 'ysf', 'd-star', 'nxdn'].includes(currentFilter)) { + if (!gatewaysStr.includes(currentFilter)) show = false; + } + + if (searchQuery !== '') { + const searchStr = `${c.id.toLowerCase()} ${c.name.toLowerCase()} ${(card.dataset.loc || '').toLowerCase()}`; + if (!searchStr.includes(searchQuery)) show = false; + } + + card.style.display = show ? 'flex' : 'none'; + }); +} + +function fmtAge(sec) { + sec = Math.max(0, Math.round(sec)); + if (sec < 60) return sec + 's'; + if (sec < 3600) return Math.floor(sec / 60) + 'm'; + if (sec < 86400) return Math.floor(sec / 3600) + 'h'; + return Math.floor(sec / 86400) + 'd'; +} + +function seenItem(label, age, tip, warn) { + const cls = warn ? 'warn' : (age !== undefined && age < 300 ? 'ok' : 'idle'); + const txt = age === undefined ? '—' : fmtAge(age); + return `${warn ? '⚠ ' : ''}${label} ${txt}`; +} + +function renderSeen(c, data, isOnline) { + const div = document.getElementById(`seen-${c.id}`); + if (!div) return; + const it = currentLang === 'it'; + const ages = (data.last_seen && data.last_seen[c.id.toLowerCase()]) || {}; + const upSec = data.uptime || 0; + let html = ''; + + const warnM = ages.mmdvm === undefined && isOnline && upSec > 600; + const tipM = it ? `Ultimo evento dal topic mmdvm/${c.id}/json (TX, cambio modo...). Su un nodo tranquillo può passare molto tempo.` + : `Last event from topic mmdvm/${c.id}/json (TX, mode change...). It can be a long time on a quiet node.`; + const tipMW = it ? `Nessun evento MMDVM ricevuto da quando il server è attivo (${fmtAge(upSec)}): controlla che MMDVMHost sia connesso al broker.` + : `No MMDVM event received since the server started (${fmtAge(upSec)}): check that MMDVMHost is connected to the broker.`; + html += seenItem('MMDVM', ages.mmdvm, warnM ? tipMW : tipM, warnM); + + if (ages.gateway !== undefined) { + html += seenItem('GW', ages.gateway, it ? 'Ultimo evento dai gateway (DMR/NXDN/YSF/P25/D-Star)' : 'Last event from the gateways (DMR/NXDN/YSF/P25/D-Star)', false); + } + + const hObj = (data.health && data.health[c.id.toLowerCase()]) || {}; + const iv = Number(hObj.interval) > 0 ? Number(hObj.interval) : 60; + const warnA = isOnline && (ages.health === undefined ? upSec > Math.max(300, iv * 5) : ages.health > Math.max(180, iv * 3)); + const tipA = warnA + ? (it ? 'L\'agent del nodo non invia più lo stato (devices//services): connessione bloccata?' : 'The node agent stopped sending its status (devices//services): stuck connection?') + : (it ? 'Ultimo stato ricevuto dall\'agent del nodo (devices//services)' : 'Last status received from the node agent (devices//services)'); + html += seenItem('AGENT', ages.health, tipA, warnA); + + div.innerHTML = html; + div.style.display = 'flex'; +} + +function sendCommand(clientId, type, customTitle, customMsg, customColor) { + const title = customTitle || t('titleAction'); + const msg = customMsg || `${t('confOp')}${clientId.toUpperCase()}?`; + const color = customColor || "var(--primary)"; + customConfirm(title, msg, color, async () => { + try { + const res = await fetch('/api/command', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId, type }) }); + const data = await res.json(); + if(!data.success) { customAlert(t('titleError'), esc(data.error), true); } + refreshStates(); + } catch (e) { console.error(e); } + }); +} + +function confirmSwitch(id, mode) { + const data = globalHealthData[id.toLowerCase()]; + let profileName = mode === 'A' ? "PROFILE A" : "PROFILE B"; + if (data && data.profiles && data.profiles[mode]) profileName = data.profiles[mode]; + const title = `🔄 ${t('titleSwitch')}`; + const msg = `${t('confSwitch')} ${esc(profileName)} -> ${id.toUpperCase()}?`; + const color = mode === 'A' ? "var(--accent)" : "#eab308"; + sendCommand(id, mode, title, msg, color); +} + +function confirmReboot(id) { sendCommand(id, 'REBOOT', `🔄 ${t('titleBoot')}`, `${t('confBoot')}${id.toUpperCase()}?`, "var(--danger)"); } +function confirmUpdateAgent(id) { sendCommand(id, 'UPDATE_AGENT', `⬇️ UPDATE OTA`, `Confermi l'aggiornamento dello script tramite git pull sul nodo ${id.toUpperCase()}?`, "#2563eb"); } + +function sendTgCommand(clientId, comando) { + const msg = (comando === 'TG:ON') ? t('confTgOn') : t('confTgOff'); + customConfirm("💬 TELEGRAM", `${msg}${clientId.toUpperCase()}?`, "var(--primary)", async () => { + try { + const res = await fetch('/api/command', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: clientId, type: comando }) }); + const data = await res.json(); + if(!data.success) { customAlert(t('titleError'), esc(data.error), true); } + refreshStates(); + } catch (e) { console.error(e); } + }); +} + +async function initUI() { + applyTranslations(); + try { + try { const meRes = await fetch('/api/me'); if (meRes.ok) me = await meRes.json(); } catch (e) { console.error(e); } + isAuthenticated = !!me.logged_in; + + const response = await fetch('/api/clients'); + clients = await response.json(); + clients = clients.filter(c => /^[A-Za-z0-9_\-]+$/.test(String(c.id))); + + const statSelect = document.getElementById('stat-node-filter'); + if (statSelect) { + let opts = ``; + clients.forEach(c => { opts += ``; }); + statSelect.innerHTML = opts; + } + + const grid = document.getElementById('client-grid'); + const authContainer = document.getElementById('auth-container'); + const role = me.role || ''; + const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); + + if (isAuthenticated) { + let adminBtn = role === 'admin' ? ` + + + + ` : ''; + + authContainer.innerHTML = `${adminBtn} + 👤 ${esc(String(me.user).toUpperCase())} + + `; + } else { + authContainer.innerHTML = ``; + } + + grid.innerHTML = clients.map(c => { + let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(c.id.toLowerCase())); + let showReboot = (role === 'admin'); + + return ` +
+
+ ${esc(c.name)} +
+ ID: ${c.id.toUpperCase()} + + +
+
+ +
+ + + + + + + +
Offline
+ + + +
+
TS1: ...
+
TS2: ...
+
+ + +
${t('waitNet')}
+ + + + ${canControl ? ` + +
+ + +
+ ` : ''} + + ${showReboot ? ` +
+ ⚙️ Admin Tools +
+ + + + + + +
+
+ ` : ''} +
`; + }).join(''); + + const miniGrid = document.getElementById('home-mini-nodes'); + if (miniGrid) { + miniGrid.innerHTML = clients.map(c => ` +
+
+
${esc(c.name)}
+
ID: ${c.id.toUpperCase()}
+
+
OFFLINE
+
+ `).join(''); + } + + refreshStates(); refreshLogs(); refreshStats(); + } catch (e) { console.error(e); } +} + +async function performLogin() { + const user = document.getElementById('modal-username').value; const pass = document.getElementById('modal-password').value; + if (!user || !pass) return; + const res = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user, pass }) }); + const data = await res.json(); + if (res.ok) { location.reload(); } + else if (res.status === 429) { customAlert(t('titleError'), esc(data.error || t('msgLoginFail')), true); } + else { customAlert(t('titleError'), t('msgLoginFail'), true); } +} +async function logout() { try { await fetch('/api/logout', { method: 'POST' }); } catch (e) { console.error(e); } sessionStorage.clear(); location.reload(); } + +// --- LOGICA FLEET MAP V5.0 --- +let latestStatesData = null; +function initOrUpdateMap() { + if (!fleetMap) { + fleetMap = L.map('map-container').setView([46.06, 13.23], 9); + L.tileLayer('https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', { + attribution: '© OpenStreetMap France | © OpenStreetMap', + maxZoom: 19, + className: 'dark-tiles' + }).addTo(fleetMap); + } else { + fleetMap.invalidateSize(); + } + + if (!latestStatesData) return; + + let bounds = []; + clients.forEach(c => { + const cid = c.id.toLowerCase(); + const info = latestStatesData.info && latestStatesData.info[cid]; + const gen = latestStatesData.general && latestStatesData.general[cid]; + const state = latestStatesData.states[cid] || "OFFLINE"; + const isOnline = !state.toUpperCase().includes("OFF") && state !== ""; + const health = latestStatesData.health && latestStatesData.health[cid]; + const card = document.getElementById(`card-${c.id}`); + const isTx = card && card.dataset.lastTx && (Date.now() - parseInt(card.dataset.lastTx) < 3000); + const warns = (latestStatesData.warnings && latestStatesData.warnings[cid]) || []; + + if (info && info.lat && info.lon && parseFloat(info.lat) !== 0 && parseFloat(info.lon) !== 0) { + const lat = parseFloat(info.lat); + const lon = parseFloat(info.lon); + bounds.push([lat, lon]); + + let pinClass = isOnline ? (warns.length > 0 ? 'pin-warn' : 'pin-online') : 'pin-offline'; + if (isTx) pinClass += ' pin-tx'; + + let iconSymbol = (gen && gen.duplex === "0") ? "📻" : "📡"; + if (warns.length > 0 && !isTx) iconSymbol = "⚠️"; + + const customIcon = L.divIcon({ + className: 'custom-div-icon', + html: `
${iconSymbol}
`, + iconSize: [32, 32], + iconAnchor: [16, 16] + }); + + const call = (gen && gen.callsign) ? gen.callsign : c.name; + const warnsHtml = warns.length > 0 ? ` +
+ ${warns.map(w => esc(w)).join('
')} +
+ ` : ''; + + const popupContent = ` +
+
${esc(call)}
+
ID: ${c.id.toUpperCase()} | ${isOnline ? 'ONLINE' : 'OFFLINE'}
+ ${warnsHtml} +
📍 ${esc(info.loc)}
+
TX: ${esc(info.tx)}
+
RX: ${esc(info.rx)}
+ ${health ? `
🌡️ Temp: ${health.temp}°C | CPU: ${health.cpu}%
` : ''} + +
+ `; + + if (!mapMarkers[cid]) { + mapMarkers[cid] = L.marker([lat, lon], { icon: customIcon }).addTo(fleetMap).bindPopup(popupContent); + } else { + mapMarkers[cid].setLatLng([lat, lon]); + mapMarkers[cid].setIcon(customIcon); + mapMarkers[cid].setPopupContent(popupContent); + } + } + }); + + if (bounds.length > 0 && !fleetMap._hasFitted) { + fleetMap.fitBounds(bounds, { padding: [40, 40] }); + fleetMap._hasFitted = true; + } +} + +async function refreshStates() { + try { + const res = await fetch('/api/states'); const data = await res.json(); + latestStatesData = data; + globalVersionsData = data.versions || {}; + + clients.forEach(c => { + const statusDiv = document.getElementById(`status-${c.id}`); const cardDiv = document.getElementById(`card-${c.id}`); + if (!statusDiv || !cardDiv) return; + + let stateValue = data.states[c.id.toLowerCase()] || data.states[c.id] || "OFFLINE"; + stateValue = String(stateValue).trim().toUpperCase(); statusDiv.innerText = stateValue; + const isOnline = !stateValue.includes("OFF") && stateValue !== ""; + cardDiv.dataset.status = isOnline ? 'online' : 'offline'; + renderSeen(c, data, isOnline); + + const warns = (data.warnings && data.warnings[c.id.toLowerCase()]) || []; + const diagDiv = document.getElementById(`diag-warn-${c.id}`); + cardDiv.dataset.hasWarn = (warns.length > 0) ? 'true' : 'false'; + + if (diagDiv) { + if (warns.length > 0 && isOnline) { + diagDiv.style.display = 'block'; + diagDiv.innerHTML = warns.map(w => `
${esc(w)}
`).join(''); + } else { + diagDiv.style.display = 'none'; + diagDiv.innerHTML = ''; + } + } + + let genObj = data.general && data.general[c.id.toLowerCase()]; + const nameSpan = cardDiv.querySelector('.client-name'); + const idBadge = cardDiv.querySelector('.badge-id'); + const typeBadge = document.getElementById(`type-badge-${c.id}`); + + if (genObj && isOnline) { + nameSpan.innerText = genObj.callsign; + idBadge.innerText = `ID: ${genObj.radio_id}`; + idBadge.style.background = "var(--primary)"; idBadge.style.color = "#ffffff"; idBadge.style.borderColor = "var(--primary)"; + + if (typeBadge && genObj.duplex !== undefined) { + typeBadge.style.display = 'inline-block'; + if (genObj.duplex === "1") { typeBadge.innerText = "REPEATER"; typeBadge.className = "type-badge type-repeater"; } + else { typeBadge.innerText = "HOTSPOT"; typeBadge.className = "type-badge type-hotspot"; } + } + } else { + nameSpan.innerText = c.name; + idBadge.innerText = `ID: ${c.id.toUpperCase()}`; + idBadge.style.background = "rgba(255,255,255,0.1)"; idBadge.style.color = "var(--text-muted)"; idBadge.style.borderColor = "var(--border-color)"; + if (typeBadge) typeBadge.style.display = 'none'; + } + + let telemetryObj = data.telemetry[c.id.toLowerCase()] || data.telemetry[c.id] || { ts1: "...", ts2: "...", alt: "", idle: true }; + if (typeof telemetryObj === 'string') telemetryObj = { ts1: telemetryObj, ts2: "...", alt: "", idle: true }; + + const tsContainer = document.getElementById(`ts-container-${c.id}`); const ts1Div = document.getElementById(`dmr-ts1-${c.id}`); const ts2Div = document.getElementById(`dmr-ts2-${c.id}`); const altDiv = document.getElementById(`dmr-alt-${c.id}`); + + let isTx = false; let activeModeColor = "var(--success)"; let isIdle = telemetryObj.idle === true; + + if (telemetryObj.alt && telemetryObj.alt !== "") { + if (tsContainer) tsContainer.style.display = "none"; + if (altDiv) { + altDiv.style.display = "block"; altDiv.innerText = telemetryObj.alt; let altText = telemetryObj.alt.toUpperCase(); + + if (altText.includes("NXDN")) activeModeColor = "#10b981"; else if (altText.includes("YSF")) activeModeColor = "#8b5cf6"; else if (altText.includes("D-STAR")) activeModeColor = "#06b6d4"; else if (altText.includes("P25")) activeModeColor = "#f59e0b"; + isTx = altText.includes("🟢") || altText.includes("🟣") || altText.includes("🔵") || altText.includes("🟠"); + altDiv.style.setProperty('--pulse-color', activeModeColor); + if (isTx) { altDiv.classList.add('tx-active-unified'); } else { altDiv.classList.remove('tx-active-unified'); altDiv.style.setProperty('color', 'var(--text-muted)', 'important'); altDiv.style.setProperty('border-left', `4px solid var(--border-color)`, 'important'); } + } + } else { + if (altDiv) altDiv.style.display = "none"; + if (tsContainer) tsContainer.style.display = "flex"; + activeModeColor = "var(--primary)"; + if (ts1Div && ts2Div) { + let isSimplex = (genObj && genObj.duplex === "0"); + ts1Div.style.display = isSimplex ? 'none' : 'block'; + [ts1Div, ts2Div].forEach((div, idx) => { + if (isSimplex && idx === 0) return; + const val = String((idx === 0 ? telemetryObj.ts1 : telemetryObj.ts2) ?? ''); + const fullLabel = `TS${idx + 1}`; + div.innerText = `${fullLabel}: ${val}`; + div.style.setProperty('--pulse-color', activeModeColor); + if (val.includes("🎙️")) { isTx = true; div.classList.add('tx-active-unified'); } + else { div.classList.remove('tx-active-unified'); div.style.setProperty('color', 'var(--text-muted)', 'important'); div.style.setProperty('border-left', '4px solid var(--border-color)', 'important'); } + }); + } + } + + let healthObj = data.health && data.health[c.id.toLowerCase()]; + let infoObj = data.info && data.info[c.id.toLowerCase()]; + const freqContainer = document.getElementById(`freq-container-${c.id}`); const freqTx = document.getElementById(`freq-tx-${c.id}`); const freqRx = document.getElementById(`freq-rx-${c.id}`); + const metaContainer = document.getElementById(`meta-container-${c.id}`); + const locSpan = document.getElementById(`loc-${c.id}`); + const latSpan = document.getElementById(`lat-${c.id}`); + const lonSpan = document.getElementById(`lon-${c.id}`); + + if (infoObj && isOnline) { + if (freqContainer) { freqContainer.style.display = 'flex'; freqTx.innerText = infoObj.tx; freqRx.innerText = infoObj.rx; } + if (metaContainer) { + metaContainer.style.display = 'block'; + locSpan.innerText = infoObj.loc; + cardDiv.dataset.loc = infoObj.loc; + if(latSpan) latSpan.innerText = infoObj.lat; + if(lonSpan) lonSpan.innerText = infoObj.lon; + } + } else { + if (freqContainer) freqContainer.style.display = 'none'; + if (metaContainer) metaContainer.style.display = 'none'; + } + + const healthContainer = document.getElementById(`health-${c.id}`); const cpuSpan = document.getElementById(`cpu-${c.id}`); const tempSpan = document.getElementById(`temp-${c.id}`); const ramSpan = document.getElementById(`ram-${c.id}`); const diskSpan = document.getElementById(`disk-${c.id}`); + + const gwBar = document.getElementById(`gw-bar-${c.id}`); + if (gwBar && healthObj) { + let gwHtml = ""; + let gwData = data.gateway_states && data.gateway_states[c.id.toLowerCase()] ? data.gateway_states[c.id.toLowerCase()] : {}; + let processes = healthObj.processes || {}; + let activeGatewaysStr = ""; + + const gwMap = [ + { id: 'dmrgateway', label: 'DMR', color: '#3b82f6', tint: 'rgba(59, 130, 246, 0.15)', proto: 'DMR' }, + { id: 'ysfgateway', label: 'YSF', color: '#8b5cf6', tint: 'rgba(139, 92, 246, 0.15)', proto: 'YSF' }, + { id: 'dstargateway', label: 'D-STAR', color: '#06b6d4', tint: 'rgba(6, 182, 212, 0.15)', proto: 'D-STAR' }, + { id: 'nxdngateway', label: 'NXDN', color: '#10b981', tint: 'rgba(16, 185, 129, 0.15)', proto: 'NXDN' }, + { id: 'p25gateway', label: 'P25', color: '#f59e0b', tint: 'rgba(245, 158, 11, 0.15)', proto: 'P25' } + ]; + + if (isOnline) { + gwMap.forEach(gw => { + let isActiveProc = processes[gw.id] && processes[gw.id].toLowerCase() === 'online'; + if (isActiveProc) { + activeGatewaysStr += gw.proto.toLowerCase() + ","; + let stateInfo = gwData[gw.proto] || { action: 'IDLE', dest: '---' }; + let action = (stateInfo.action || 'IDLE').toLowerCase(); + let dest = stateInfo.dest && stateInfo.dest !== '---' ? stateInfo.dest : ''; + + let badgeBg, badgeColor, badgeBorder, suffix = '', extraClass = ''; + + if (action === 'linking' || action === 'linked' || (dest !== '' && action !== 'unlinked' && action !== 'failed')) { + badgeBg = gw.color; + badgeColor = 'white'; + badgeBorder = gw.color; + if (dest) suffix = `: ${dest}`; + else suffix = ` [LINKING]`; + } else if (action === 'failed') { + badgeBg = 'var(--danger)'; + badgeColor = 'white'; + badgeBorder = 'var(--danger)'; + suffix = ' [FAILED]'; + extraClass = 'blink'; + } else if (action === 'unlinked') { + badgeBg = 'transparent'; + badgeColor = 'var(--text-muted)'; + badgeBorder = 'var(--border-color)'; + suffix = ' [UNLINKED]'; + } else { + badgeBg = gw.tint; + badgeColor = gw.color; + badgeBorder = gw.color; + } + + if (gw.proto === 'DMR' && gwData['DMR_NETS'] && gwData['DMR_NETS'].length > 0) { + gwData['DMR_NETS'].forEach(netName => { + let netText = `DMR: ${esc(netName)}${esc(suffix)}`; + gwHtml += `${netText}`; + }); + } else { + let text = `${gw.label}${esc(suffix)}`; + gwHtml += `${text}`; + } + } + }); + } + cardDiv.dataset.gateways = activeGatewaysStr; + gwBar.innerHTML = gwHtml; + } else if (gwBar) { + gwBar.innerHTML = ""; + cardDiv.dataset.gateways = ""; + } + + if (healthObj && isOnline) { + healthContainer.style.display = 'flex'; + let cpu = healthObj.cpu; cpuSpan.innerText = cpu; cpuSpan.style.color = cpu < 50 ? 'var(--success)' : (cpu < 80 ? '#f59e0b' : 'var(--danger)'); + let tempVal = healthObj.temp; tempSpan.innerText = tempVal; tempSpan.style.color = tempVal < 55 ? 'var(--success)' : (tempVal < 70 ? '#f59e0b' : 'var(--danger)'); + ramSpan.innerText = healthObj.ram; let d = healthObj.disk; diskSpan.innerText = d; diskSpan.style.color = d < 85 ? 'inherit' : (d < 95 ? '#f59e0b' : 'var(--danger)'); + + let upSpan = document.getElementById(`up-${c.id}`); + if (upSpan && healthObj.uptime) { upSpan.innerText = fmtAge(healthObj.uptime); } + let agentBadge = document.getElementById(`agent-badge-${c.id}`); + if (agentBadge && healthObj.agent_version) { agentBadge.innerText = `Agent v${healthObj.agent_version}`; agentBadge.style.display = 'inline-block'; } + + const profBtnsDiv = document.getElementById(`prof-btns-${c.id}`); + const profKeys = JSON.stringify(healthObj.profiles || {}); + if (profBtnsDiv && profBtnsDiv.dataset.keys !== profKeys) { + profBtnsDiv.dataset.keys = profKeys; + if (healthObj.profiles && Object.keys(healthObj.profiles).length > 0) { + profBtnsDiv.style.display = 'flex'; + let html = ''; const colors = ["var(--accent)", "#eab308", "var(--success)", "var(--primary)"]; let idx = 0; + for (const [pKey, pLabel] of Object.entries(healthObj.profiles)) { + let col = colors[idx % colors.length]; + html += ``; + idx++; + } + profBtnsDiv.innerHTML = html; + } else { profBtnsDiv.style.display = 'none'; profBtnsDiv.innerHTML = ''; } + } + } else { + if (healthContainer) healthContainer.style.display = 'none'; + let agentBadge = document.getElementById(`agent-badge-${c.id}`); + if (agentBadge) agentBadge.style.display = 'none'; + } + + globalHealthData[c.id.toLowerCase()] = healthObj; + + let hasOfflineService = false; + if (healthObj && healthObj.processes) { + for (const [svcName, svcStatus] of Object.entries(healthObj.processes)) { if (svcStatus.toLowerCase() !== 'online') { hasOfflineService = true; break; } } + } + const warnBadge = document.getElementById(`svc-warn-${c.id}`); const btnSvc = document.getElementById(`btn-svc-${c.id}`); + + if (warnBadge) warnBadge.style.display = hasOfflineService ? 'block' : 'none'; + if (btnSvc) { + if (hasOfflineService) { btnSvc.style.background = 'var(--danger)'; btnSvc.classList.add('blink'); btnSvc.innerHTML = t('btnSvcKo'); } + else { btnSvc.style.background = '#334155'; btnSvc.classList.remove('blink'); btnSvc.innerHTML = t('btnSvc'); } + } + + let btnOta = document.getElementById(`btn-ota-${c.id}`); + let adminSummary = document.getElementById(`admin-summary-${c.id}`); + + if (btnOta) { + if (healthObj && healthObj.agent_update_available) { + btnOta.style.setProperty('background', 'var(--danger)', 'important'); + btnOta.style.setProperty('color', 'white', 'important'); + btnOta.style.setProperty('border', '1px solid var(--danger)', 'important'); + btnOta.style.animation = 'danger-glow 1.5s infinite'; + + if (adminSummary) { + adminSummary.innerHTML = "⚠️ ADMIN (UPDATE OTA!)"; + adminSummary.style.setProperty('color', 'var(--danger)', 'important'); + adminSummary.style.setProperty('border-color', 'var(--danger)', 'important'); + adminSummary.style.animation = 'danger-glow 1.5s infinite'; + } + } else { + btnOta.style.setProperty('background', '#2563eb', 'important'); + btnOta.style.setProperty('color', 'white', 'important'); + btnOta.style.setProperty('border', '1px solid transparent', 'important'); + btnOta.style.animation = 'none'; + + if (adminSummary) { + adminSummary.innerHTML = "⚙️ Admin Tools"; + adminSummary.style.setProperty('color', 'var(--text-muted)', 'important'); + adminSummary.style.setProperty('border-color', 'var(--border-color)', 'important'); + adminSummary.style.animation = 'none'; + } + } + } + + if (isOnline) { + cardDiv.classList.add('online'); statusDiv.classList.remove('status-offline'); cardDiv.style.opacity = "1"; cardDiv.style.filter = "none"; + if (isTx) cardDiv.dataset.lastTx = Date.now(); + let timeSinceTx = Date.now() - (parseInt(cardDiv.dataset.lastTx) || 0); + let showActiveColor = isTx || (!isIdle && timeSinceTx < HANG_TIME_MS); + cardDiv.style.setProperty('border-top-color', showActiveColor ? activeModeColor : "var(--border-color)", 'important'); + if(isTx) { + let shadowRGB = '59, 130, 246'; + if (activeModeColor === '#10b981') shadowRGB = '16, 185, 129'; else if (activeModeColor === '#8b5cf6') shadowRGB = '139, 92, 246'; else if (activeModeColor === '#06b6d4') shadowRGB = '6, 182, 212'; else if (activeModeColor === '#f59e0b') shadowRGB = '245, 158, 11'; + cardDiv.style.boxShadow = `0 0 20px rgba(${shadowRGB}, 0.5) !important`; + } else { cardDiv.style.boxShadow = '0 4px 12px rgba(0,0,0,0.2) !important'; } + } else { + cardDiv.classList.remove('online'); statusDiv.classList.add('status-offline'); cardDiv.style.opacity = "0.7"; cardDiv.style.filter = "grayscale(80%)"; + cardDiv.style.setProperty('border-top-color', '#64748b', 'important'); cardDiv.style.boxShadow = 'none !important'; + } + + const miniCard = document.getElementById(`mini-card-${c.id}`); + const miniStatus = document.getElementById(`mini-status-${c.id}`); + const miniName = document.getElementById(`mini-name-${c.id}`); + const miniId = document.getElementById(`mini-id-${c.id}`); + + if (miniCard && miniStatus) { + if (genObj && isOnline) { + if (miniName) miniName.innerText = genObj.callsign; + if (miniId) miniId.innerText = `ID: ${genObj.radio_id}`; + } + else { + if (miniName) miniName.innerText = c.name; + if (miniId) miniId.innerText = `ID: ${c.id.toUpperCase()}`; + } + + if (isOnline) { + miniCard.style.borderColor = (warns.length > 0) ? "#f59e0b" : "var(--success)"; + miniCard.style.opacity = "1"; + miniCard.style.filter = "none"; + miniStatus.innerText = (warns.length > 0) ? "⚠️ ALERT" : stateValue; + miniStatus.title = (warns.length > 0) ? warns.join(" | ") : stateValue; + miniStatus.style.color = (warns.length > 0) ? "#f59e0b" : "var(--success)"; + miniStatus.style.background = (warns.length > 0) ? "rgba(245, 158, 11, 0.15)" : "rgba(16, 185, 129, 0.1)"; + miniStatus.style.borderColor = (warns.length > 0) ? "rgba(245, 158, 11, 0.4)" : "rgba(16, 185, 129, 0.2)"; + } else { + miniCard.style.borderColor = "var(--border-color)"; + miniCard.style.opacity = "0.6"; + miniCard.style.filter = "grayscale(80%)"; + miniStatus.innerText = "OFFLINE"; + miniStatus.title = "OFFLINE"; + miniStatus.style.color = "var(--danger)"; + miniStatus.style.background = "rgba(239, 68, 68, 0.1)"; + miniStatus.style.borderColor = "rgba(239, 68, 68, 0.2)"; + } + } + }); + + applyFilters(); + if (document.getElementById('view-map').style.display === 'block') { + initOrUpdateMap(); + } + document.getElementById('last-update').innerText = "Sync: " + new Date().toLocaleTimeString(); + } catch (e) { console.error(e); } +} + +async function refreshLogs() { + try { + const res = await fetch('/api/logs'); const logs = await res.json(); + const tbody = document.getElementById('log-body'); let tableHTML = ""; let networkLogs = {}; + logs.forEach(row => { + const time = row[0] ? row[0].split(' ')[1] : "--:--"; + const clientId = row[1]; const protocol = row[2] || "DMR"; let source = row[3] || "---"; const target = row[4] || "---"; + const rawSlot = row[5]; const source_ext = row[8]; const rawRssi = row[9]; const sourceConn = row[10]; const ysfMode = row[11]; + + let sourceHtml = esc(source); + if (source_ext && source_ext.trim() !== "") { sourceHtml += ` /${esc(source_ext)}`; } + + let slotDisplay = rawSlot && String(rawSlot).trim() !== "" && rawSlot !== "undefined" ? (protocol === "DMR" && !String(rawSlot).toUpperCase().startsWith("TS") ? `TS${rawSlot}` : rawSlot) : "---"; + let protoColor = "#3b82f6"; if (protocol === "NXDN") protoColor = "#10b981"; else if (protocol === "YSF") protoColor = "#8b5cf6"; else if (protocol === "D-STAR") protoColor = "#06b6d4"; else if (protocol === "P25") protoColor = "#f59e0b"; + + let sourceBadge = sourceConn ? (sourceConn.toLowerCase() === 'rf' ? 'RF' : (sourceConn.toLowerCase() === 'network' ? 'NET' : `${esc(sourceConn).toUpperCase()}`)) : "---"; + let modeDisplay = ysfMode && ysfMode.trim() !== "" ? `${esc(ysfMode).toUpperCase()}` : "---"; + + let rssiDisplay = '---'; + if (rawRssi && rawRssi !== 0) { + let sLabel = "S0"; + if (rawRssi >= -93) { + let over = Math.round((rawRssi + 93) / 10) * 10; + sLabel = over > 0 ? `S9+${over}` : "S9"; + } else { + let sUnits = Math.floor((rawRssi + 141) / 6) + 1; + sLabel = `S${Math.max(1, Math.min(9, sUnits))}`; + } + let activeSegs = 1; + if (rawRssi >= -53) activeSegs = 9; else if (rawRssi >= -63) activeSegs = 8; else if (rawRssi >= -73) activeSegs = 7; else if (rawRssi >= -83) activeSegs = 6; else if (rawRssi >= -93) activeSegs = 5; else if (rawRssi >= -105) activeSegs = 4; else if (rawRssi >= -117) activeSegs = 3; else if (rawRssi >= -129) activeSegs = 2; + let barsHtml = ''; const heights = [4, 5, 6, 7, 8, 10, 12, 14, 14]; + for (let i = 0; i < 9; i++) { + let color = "rgba(255,255,255,0.1)"; + if (i < activeSegs) { if (i < 5) color = "var(--success)"; else if (i < 7) color = "#f59e0b"; else color = "var(--danger)"; } + barsHtml += `
`; + } + rssiDisplay = `
${sLabel}
${barsHtml}
${esc(rawRssi)} dBm
`; + } + + if (source.includes("🌐")) { + if (!networkLogs[clientId]) networkLogs[clientId] = ""; + networkLogs[clientId] += `
[${esc(time)}] [${esc(protocol)}] ${esc(source.replace("🌐", "").trim())}
`; + } else { + const selectedFilter = document.getElementById('stat-node-filter').value; + if (selectedFilter === 'all' || String(clientId).toLowerCase() === selectedFilter) { + tableHTML += ` + ${esc(time)} + ${esc(String(clientId).toUpperCase())} + ${esc(protocol)} + ${modeDisplay} + ${sourceBadge} + ${esc(slotDisplay)} + ${sourceHtml} + ${esc(target.trim())} + ${esc(row[6])}s + ${esc(row[7])}% + ${rssiDisplay} + `; + } + } + }); + tbody.innerHTML = tableHTML; + clients.forEach(c => { const localDiv = document.getElementById(`sys-log-${c.id}`); if (localDiv && networkLogs[c.id]) { localDiv.innerHTML = networkLogs[c.id]; } }); + } catch (e) { console.error(e); } +} + +async function refreshStats() { + try { + const node = document.getElementById('stat-node-filter').value || 'all'; + const res = await fetch(`/api/stats?node=${node}`); const data = await res.json(); + document.getElementById('stat-tgs').innerHTML = data.top_tgs.map((t, i) => `
${i+1}. ${esc(t.target)} ${t.count} tx
`).join('') || t('statNoData'); + document.getElementById('stat-calls').innerHTML = data.top_calls.map((c, i) => `
${i+1}. ${esc(c.call)} ${c.count} tx
`).join('') || t('statNoData'); + document.getElementById('stat-avg').innerText = data.avg_duration; document.getElementById('stat-today').innerText = data.today_tx; + } catch (e) { console.error("Errore statistiche:", e); } +} + +async function subscribeToPush() { + if (!('serviceWorker' in navigator) || !('PushManager' in window)) { customAlert("Error", "Push notifications are not supported by this browser.", true); return; } + if (!me.logged_in) { openLoginModal(); return; } + const permission = await Notification.requestPermission(); + if (permission !== 'granted') { customAlert("Error", "Push notifications permission denied.", true); return; } + try { + const reg = await navigator.serviceWorker.ready; const res = await fetch('/api/vapid_public_key'); const { public_key } = await res.json(); + const subscription = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlB64ToUint8Array(public_key) }); + const subRes = await fetch('/api/subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(subscription) }); + if (!subRes.ok) throw new Error('subscribe failed: HTTP ' + subRes.status); + customAlert("Success", "Push notifications enabled successfully!"); document.getElementById('push-btn').style.color = 'var(--success)'; + } catch (e) { console.error(e); customAlert("Error", "Failed to enable notifications.", true); } +} + +async function checkPushStatus() { + if (!('serviceWorker' in navigator) || !('PushManager' in window)) return; + try { const reg = await navigator.serviceWorker.ready; const subscription = await reg.pushManager.getSubscription(); const btn = document.getElementById('push-btn'); if (subscription && btn) { btn.style.color = 'var(--success)'; } } catch(e) { console.error(e); } +} + +function urlB64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i); return outputArray; } + +async function checkServerUpdate() { + if (!isAuthenticated || me.role !== 'admin') return; + try { const res = await fetch('/api/server_update/check'); const data = await res.json(); const btn = document.getElementById('server-update-btn'); if (btn) { btn.style.display = data.update_available ? 'inline-block' : 'none'; } } catch (e) { console.error(e); } +} + +function confirmServerUpdate() { + customConfirm("🔄 UPDATE SERVER", "Vuoi scaricare l'ultima versione del server da Gitea/GitHub e riavviare il servizio backend?", "var(--danger)", async () => { + try { const res = await fetch('/api/server_update/apply', { method: 'POST' }); const data = await res.json(); if (data.success) { customAlert("✅ SUCCESS", "Aggiornamento in corso. La pagina si ricaricherà a breve."); setTimeout(() => location.reload(), 5000); } else { customAlert("❌ ERRORE", esc(data.error), true); } } catch (e) { console.error(e); customAlert("❌ ERRORE", "Errore di rete.", true); } + }); +} + +function debounce(fn, ms) { let tm = null; return () => { clearTimeout(tm); tm = setTimeout(fn, ms); }; } +const refreshStatesSoon = debounce(refreshStates, 300); +const refreshLogsSoon = debounce(() => { refreshLogs(); refreshStats(); }, 500); + +if (typeof io !== 'undefined') { + const socket = io(); + socket.on('mqtt_status', function(data) { const badge = document.getElementById('mqtt-badge'); if (badge) { if (data.connected) { badge.innerText = "MQTT: ONLINE"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: OFFLINE"; badge.className = "mqtt-badge mqtt-offline"; } } }); + socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); }); + socket.on('dati_aggiornati', refreshStatesSoon); socket.on('log_aggiornato', refreshLogsSoon); +} diff --git a/static/js/modals.js b/static/js/modals.js new file mode 100644 index 0000000..64d7d84 --- /dev/null +++ b/static/js/modals.js @@ -0,0 +1,312 @@ +// --- SISTEMA TRADUZIONI (i18n) & HELPERS --- +const i18n = { + en: { + lastTransits: "Lastheard", loginTitle: "🔒 System Login", + thTime: "Time", thRep: "Repeater", thMode: "Mode", thCall: "Callsign", thDur: "Duration", + thUser: "User", thRole: "Role", thNodes: "Nodes", thActs: "Actions", + btnReqCfg: "🔄 REQ CONFIG", btnGlobal: "🚨 GLOBAL OVERRIDE", btnAdmin: "🛠️ ADMIN", btnPass: "🔑 PASS", btnLogout: "LOGOUT", + btnSvc: "⚙️ SVC", btnFile: "📂 FILE", btnBoot: "🔄 BOOT", btnAdd: "+ ADD", + waitNet: "> Waiting network...", waitData: "Waiting for node data...", forceUpdate: "🔄 FORCE UPDATE", + adminTitle: "🛠️ User & System Management", adminDBSync: "⚙️ Database Sync Config", adminTime: "Daily Update Time:", adminSave: "SAVE CONFIG", roleOp: "Operator", + modSvcTitle: "⚙️ System Daemons:", modFileTitle: "📂 Config Files", modEditTitle: "📝 INI Editor:", + warnEdit: "⚠️ WARNING: This editor directly manipulates remote node parameters.", + btnEdit: "📝 EDIT", btnStart: "▶ START", btnRestart: "🔄 RESTART", btnStop: "🛑 STOP", btnSave: "💾 SAVE & SEND", + btnHat: "🔌 RESET HAT", confHat: "Are you sure you want to physically reset the MMDVM board on node ", + confOp: "Confirm operation on ", confTgOn: "ENABLE Telegram notifications for ", confTgOff: "MUTE Telegram notifications for ", confOvr: "Are you sure you want to overwrite file on ", + warnDaemon: "⚠️ SVC KO - CHECK DAEMONS ⚠️", + promptOvr: "GLOBAL OVERRIDE", promptOvrConfirm: "Confirm sending to ENTIRE network?", + modUpdateTitle: "🔄 GLOBAL UPDATE", confUpdate: "Do you want to request updated data and configuration files from all nodes in the fleet?", alertUpdateOk: "Request sent successfully!", + btnConfReset: "⚠️ CONFIRM RESET", btnCancel: "CANCEL", promptPass: "Enter the new password:", + titleError: "❌ ERROR", titleSuccess: "✅ SUCCESS", titleAction: "⚙️ CONFIRM ACTION", titleDelete: "🗑️ DELETE USER", titleSave: "💾 SAVE", titleGlobal: "🚨 GLOBAL OVERRIDE", + btnYes: "YES, PROCEED", msgDelUser: "Confirm user deletion?", msgPassOk: "Password updated successfully!", msgPassErr: "Failed to update password.", msgLoginFail: "Login Failed", + msgConfigSaved: "Configuration saved!", msgConfigErr: "Error saving configuration", msgNetErr: "Network Error", msgOvrSel: "Select the profile to send to the ENTIRE network:", + msgOvrOk: "Command successfully sent to the network!", msgMissUser: "Missing Username", msgMissPass: "Password required for new user", btnSvcKo: "⚠️ DAEMON KO", + phNewPass: "New pass (empty to keep)", phPass: "Password", + titleSwitch: "SWITCH PROFILE", confSwitch: "Are you sure you want to switch to", titleBoot: "SYSTEM REBOOT", confBoot: "Are you sure you want to REBOOT node ", + ttReqCfg: "Request immediate data update", ttGlobal: "Force profile switch on network", ttAdmin: "User and system management", ttPass: "Change your password", ttLogout: "Log out", + ttProfA: "Switch to Profile A", ttProfB: "Switch to Profile B", ttTgOn: "Enable Telegram notifications", ttTgOff: "Disable Telegram notifications", ttSvc: "Manage system daemons", ttFile: "Edit .ini configuration files", ttHat: "Send physical reset to modem", ttBoot: "Reboot node operating system", + ttSwitchTo: "Switch to profile: ", ttSvcStart: "Start service", ttSvcRestart: "Restart service", ttSvcEdit: "Edit configuration", ttSvcStop: "Stop service", ttLang: "Change language", + statTopTG: "🎯 TOP TALKGROUPS", statTopCall: "🗣️ TOP CALLSIGNS", statLoading: "Loading...", statAvgDur: "⏱️ AVERAGE DURATION", statTodayTx: "📡 TRANSITS TODAY", statNoData: "No data", + statTitle: "DAILY STATISTICS", statAllNodes: "ALL NODES", modVersions: "Software & Firmware", + filtAll: "All Nodes", filtOnline: "Online", filtOffline: "Offline", filtAlerts: "⚠️ Alerts" + }, + it: { + lastTransits: "Ultimi ascolti", loginTitle: "🔒 Login di Sistema", + thTime: "Ora", thRep: "Ripetitore", thMode: "Modo", thCall: "Nominativo", thDur: "Durata", + thUser: "Utente", thRole: "Ruolo", thNodes: "Nodi", thActs: "Azioni", + btnReqCfg: "🔄 RICHIEDI CONFIG", btnGlobal: "🚨 OVERRIDE GLOBALE", btnAdmin: "🛠️ ADMIN", btnPass: "🔑 PASS", btnLogout: "LOGOUT", + btnSvc: "⚙️ SVC", btnFile: "📂 FILE", btnBoot: "🔄 BOOT", btnAdd: "+ AGGIUNGI", + waitNet: "> Attesa rete...", waitData: "In attesa dei dati dal nodo...", forceUpdate: "🔄 FORZA AGGIORNAMENTO", + adminTitle: "🛠️ Gestione Utenti e Sistema", adminDBSync: "⚙️ Sincronizzazione Database", adminTime: "Orario Aggiornamento:", adminSave: "SALVA CONFIG", roleOp: "Operatore", + modSvcTitle: "⚙️ Demoni Sistema:", modFileTitle: "📂 File di Configurazione", modEditTitle: "📝 Editor INI:", + warnEdit: "⚠️ ATTENZIONE: Questo editor manipola direttamente i parametri del nodo remoto.", + btnEdit: "📝 MODIFICA", btnStart: "▶ START", btnRestart: "🔄 RESTART", btnStop: "🛑 STOP", btnSave: "💾 SALVA ED INVIA", + btnHat: "🔌 RESET HAT", confHat: "Sei sicuro di voler resettare fisicamente la scheda MMDVM sul nodo ", + confOp: "Confermi l'operazione su ", confTgOn: "Vuoi ATTIVARE le notifiche Telegram per il nodo ", confTgOff: "Vuoi SILENZIARE le notifiche Telegram per il nodo ", confOvr: "Sei sicuro di voler sovrascrivere il file su ", + warnDaemon: "⚠️ SVC KO - CONTROLLA DEMONI ⚠️", + promptOvr: "OVERRIDE GLOBALE", promptOvrConfirm: "Confermi l'invio a TUTTA la rete?", + modUpdateTitle: "🔄 AGGIORNAMENTO GLOBALE", confUpdate: "Vuoi richiedere i dati e i file di configurazione aggiornati a tutti i nodi della flotta?", alertUpdateOk: "Richiesta inviata con successo!", + btnConfReset: "⚠️ CONFERMA RESET", btnCancel: "ANNULLA", promptPass: "Inserisci la nuova password:", + titleError: "❌ ERRORE", titleSuccess: "✅ OK", titleAction: "⚙️ CONFERMA AZIONE", titleDelete: "🗑️ ELIMINA UTENTE", titleSave: "💾 SALVATAGGIO", titleGlobal: "🚨 OVERRIDE GLOBALE", + btnYes: "SI, PROCEDI", msgDelUser: "Confermi l'eliminazione dell'utente?", msgPassOk: "Password aggiornata con successo!", msgPassErr: "Errore durante l'aggiornamento della password.", msgLoginFail: "Login Fallito", + msgConfigSaved: "Configurazione salvata!", msgConfigErr: "Errore durante il salvataggio", msgNetErr: "Errore di rete", msgOvrSel: "Seleziona il profilo da inviare a TUTTA la rete:", + msgOvrOk: "Comando inviato con successo a tutta la rete!", msgMissUser: "Username mancante", msgMissPass: "Password obbligatoria per il nuovo utente", btnSvcKo: "⚠️ DEMONE KO", + phNewPass: "Nuova pass (vuota per non cambiare)", phPass: "Password", + titleSwitch: "CAMBIO PROFILO", confSwitch: "Sei sicuro di voler passare al", titleBoot: "RIAVVIO SISTEMA", confBoot: "Sei sicuro di voler RIAVVIARE il nodo ", + ttReqCfg: "Richiedi aggiornamento dati", ttGlobal: "Forza cambio profilo globale", ttAdmin: "Gestione utenti e sistema", ttPass: "Cambia la tua password", ttLogout: "Disconnetti", + ttProfA: "Passa al Profilo A", ttProfB: "Passa al Profilo B", ttTgOn: "Abilita notifiche Telegram", ttTgOff: "Disabilita notifiche Telegram", ttSvc: "Gestisci demoni di sistema", ttFile: "Modifica file .ini da remoto", ttHat: "Reset fisico scheda modem", ttBoot: "Riavvia sistema operativo", + ttSwitchTo: "Passa al profilo: ", ttSvcStart: "Avvia servizio", ttSvcRestart: "Riavvia servizio", ttSvcEdit: "Modifica configurazione", ttSvcStop: "Ferma servizio", ttLang: "Cambia lingua", + statTopTG: "🎯 TOP TALKGROUPS", statTopCall: "🗣️ TOP CALLSIGNS", statLoading: "Caricamento...", statAvgDur: "⏱️ DURATA MEDIA", statTodayTx: "📡 TRANSITI OGGI", statNoData: "Nessun dato", + statTitle: "STATISTICHE GIORNALIERE", statAllNodes: "TUTTA LA RETE", modVersions: "Software & Firmware", + filtAll: "Tutti i nodi", filtOnline: "Attivi", filtOffline: "Offline", filtAlerts: "⚠️ Allarmi" + } +}; + +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 && editingUserId) newPassInput.placeholder = t('phNewPass'); + else if (newPassInput) newPassInput.placeholder = t('phPass'); +} + +function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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.borderColor = color; + document.getElementById('alert-desc').innerHTML = desc; + document.getElementById('alert-modal').style.display = 'flex'; +} + +function customConfirm(title, desc, color, callback) { + document.getElementById('confirm-title').innerHTML = title; + document.getElementById('confirm-title').style.color = color; + document.getElementById('confirm-box').style.borderColor = color; + document.getElementById('confirm-desc').innerHTML = desc; + document.getElementById('confirm-yes-btn').style.background = color; + document.getElementById('confirm-yes-btn').innerText = t('btnYes'); + document.getElementById('confirm-cancel-btn').innerText = t('btnCancel'); + confirmActionCallback = callback; + document.getElementById('confirm-modal').style.display = 'flex'; +} + +function executeConfirmAction() { + document.getElementById('confirm-modal').style.display = 'none'; + if (confirmActionCallback) { confirmActionCallback(); confirmActionCallback = null; } +} + +// --- 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'; loadUsers(); loadSettings(); cancelEdit(); } +function closeAdmin() { document.getElementById('admin-modal').style.display = 'none'; cancelEdit(); } + +async function loadUsers() { + const res = await fetch('/api/users'); if (!res.ok) return; const users = await res.json(); usersCache = {}; users.forEach(u => { usersCache[u.id] = u; }); + document.getElementById('users-table-body').innerHTML = users.map(u => ` + + ${u.id}${esc(u.username)}${esc(String(u.role).toUpperCase())}${esc(u.allowed_nodes)} + + + + + `).join(''); +} + +function startEditUser(id) { + const u = usersCache[id]; if (!u) return; + editingUserId = id; document.getElementById('new-user').value = u.username; document.getElementById('new-user').disabled = true; document.getElementById('new-pass').value = ""; document.getElementById('new-pass').placeholder = t('phNewPass'); document.getElementById('new-role').value = u.role; document.getElementById('new-nodes').value = u.allowed_nodes; + const btnSubmit = document.getElementById('btn-user-submit'); btnSubmit.innerHTML = t('titleSave'); btnSubmit.style.background = "var(--accent)"; document.getElementById('btn-user-cancel').style.display = "block"; +} + +function cancelEdit() { + editingUserId = null; document.getElementById('new-user').value = ""; document.getElementById('new-user').disabled = false; document.getElementById('new-pass').value = ""; document.getElementById('new-pass').placeholder = t('phPass'); document.getElementById('new-role').value = "operator"; document.getElementById('new-nodes').value = ""; + const btnSubmit = document.getElementById('btn-user-submit'); btnSubmit.innerHTML = t('btnAdd'); btnSubmit.style.background = "var(--success)"; document.getElementById('btn-user-cancel').style.display = "none"; +} + +async function submitUser() { + const username = document.getElementById('new-user').value; const password = document.getElementById('new-pass').value; const role = document.getElementById('new-role').value; let allowed = document.getElementById('new-nodes').value; + if (!username) return customAlert(t('titleError'), t('msgMissUser'), true); + const payload = { username, role, allowed_nodes: allowed || 'all' }; if (password) payload.password = password; + if (editingUserId) { + const res = await fetch(`/api/users/${editingUserId}`, { method: 'PUT', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) }); const data = await res.json(); + if (data.success) { cancelEdit(); loadUsers(); } else customAlert(t('titleError'), esc(data.error), true); + } else { + if (!password) return customAlert(t('titleError'), t('msgMissPass'), true); + const res = await fetch('/api/users', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) }); const data = await res.json(); + if (data.success) { cancelEdit(); loadUsers(); } else customAlert(t('titleError'), esc(data.error), true); + } +} + +function deleteUser(id) { customConfirm(t('titleDelete'), t('msgDelUser'), "var(--danger)", async () => { const r = await fetch(`/api/users/${id}`, {method: 'DELETE'}); const dd = await r.json().catch(() => ({})); if (!dd.success) customAlert(t('titleError'), esc(dd.error || 'Error'), true); loadUsers(); cancelEdit(); }); } + +// --- 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() { + let uniqueProfiles = {}; + for (const id in globalHealthData) { + if (globalHealthData[id] && globalHealthData[id].profiles) { + for (const [k, v] of Object.entries(globalHealthData[id].profiles)) { uniqueProfiles[k] = v; } + } + } + const container = document.getElementById('global-btn-container'); let html = ''; const colors = ["var(--accent)", "#eab308", "var(--success)", "var(--primary)"]; let idx = 0; + for (const [k, v] of Object.entries(uniqueProfiles)) { + let col = colors[idx % colors.length]; + html += ``; + idx++; + } + if (Object.keys(uniqueProfiles).length === 0) { html = `

No profiles configured on the network.

`; } + container.innerHTML = html; document.getElementById('override-desc').innerText = t('msgOvrSel'); document.getElementById('override-modal').style.display = 'flex'; +} + +function sendGlobalAction(action) { + document.getElementById('override-modal').style.display = 'none'; + customConfirm(t('titleGlobal'), t('promptOvrConfirm'), "var(--danger)", async () => { + try { const res = await fetch('/api/global_command', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({type: action}) }); const d = await res.json(); + if(d.success) customAlert(t('titleSuccess'), t('msgOvrOk')); else customAlert(t('titleError'), esc(d.error), true); refreshStates(); + } catch(e) { console.error(e); } + }); +} + +// --- 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 = `

${t('waitData')}

`; + else listDiv.innerHTML = listaFile.map(f => `
${esc(fileLabel(f, fileNames))}
`).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 = "

No service data available.

"; 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 += `
+
${esc(name)}${esc(String(status).toUpperCase())}
+
+ ${!isOnline ? `` : ''} + + + ${isOnline ? `` : ''} +
+
`; + } + listDiv.innerHTML = html; +} + +function controlService(clientId, service, action) { + customConfirm(t('titleAction'), `${t('confOp')}${esc(service)}?`, "var(--accent)", async () => { + try { const res = await fetch('/api/service_control', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId, service, action }) }); const data = await res.json(); + if(!data.success) customAlert(t('titleError'), "Error: " + esc(data.error), true); + } catch(e) { console.error(e); } + }); +} + +// --- MODALE EDITOR INI --- +let currentEditClient = ""; let currentEditService = ""; +async function openEditorModal(clientId, service) { + currentEditClient = clientId; currentEditService = service; document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`; + document.getElementById('config-textarea').value = "Connecting to server..."; document.getElementById('editor-status').innerText = ""; document.getElementById('editor-modal').style.display = 'flex'; + try { const res = await fetch(`/api/config_file/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`); const data = await res.json(); if (data.success) document.getElementById('config-textarea').value = data.data.raw_text || "Empty file"; else document.getElementById('config-textarea').value = "ERROR:\n" + data.error; } catch(e) { document.getElementById('config-textarea').value = "Connection error."; } +} +function closeEditorModal() { document.getElementById('editor-modal').style.display = 'none'; } + +function saveConfig() { + const textValue = document.getElementById('config-textarea').value; const statusSpan = document.getElementById('editor-status'); + customConfirm(t('titleSave'), `${t('confOvr')}${currentEditClient.toUpperCase()}?`, "var(--danger)", async () => { + statusSpan.innerText = "Sending..."; statusSpan.style.color = "var(--success)"; + try { + const res = await fetch('/api/config_file', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: currentEditClient, service: currentEditService, config_data: { "raw_text": textValue } }) }); + const data = await res.json(); + if (data.success) { customAlert(t('titleSuccess'), "File updated!"); closeEditorModal(); } else { customAlert(t('titleError'), "Server error: " + esc(data.error), true); statusSpan.innerText = "❌ Error"; } + } catch(e) { customAlert(t('titleError'), t('msgNetErr'), true); statusSpan.innerText = "❌ Network Error"; } + }); +} + +// --- 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 = "Nessun dato ancora ricevuto. Usa il tasto 🔄 RESTART sui servizi del nodo per forzare l'invio del log di avvio."; } + else { let html = ""; for (const [software, version] of Object.entries(versions)) { html += `
${esc(software)}: ${esc(version)}
`; } listDiv.innerHTML = html; } + document.getElementById('versions-modal').style.display = 'flex'; +} +function closeVersionsModal() { document.getElementById('versions-modal').style.display = 'none'; } diff --git a/sw.js b/sw.js index dc539ac..73ea7fd 100644 --- a/sw.js +++ b/sw.js @@ -1,6 +1,9 @@ -const CACHE_NAME = 'fleet-c2-v5'; +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' ]; diff --git a/templates/index.html b/templates/index.html index b525e3b..792ae90 100644 --- a/templates/index.html +++ b/templates/index.html @@ -12,148 +12,12 @@ - + + + + + + @@ -164,6 +28,7 @@
@@ -175,14 +40,20 @@
+ + + +