From 2f0abdc9bf72f1c30d0a5c200919337c9186787b Mon Sep 17 00:00:00 2001 From: Roby Date: Thu, 22 Oct 2026 13:11:46 +0200 Subject: [PATCH] add Server OTA Update --- app.py | 47 ++++++++++++++++++++++++++++++++++++++++++++ templates/index.html | 35 ++++++++++++++++++++++++++++++++- 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/app.py b/app.py index 6a016d6..21af8a5 100644 --- a/app.py +++ b/app.py @@ -1282,6 +1282,53 @@ def save_config_file(): audit(auth['username'], cid, f"EDIT_CONFIG_{service.upper()}") return jsonify({"success": True}) +@app.route('/api/server_update/check', methods=['GET']) +def check_server_update(): + auth = get_auth() + if not auth or auth['role'] != 'admin': + return err("Unauthorized", 403) + + try: + # Aggiorna le informazioni dal remote senza unire i file + subprocess.run(['git', 'fetch'], timeout=10, cwd=BASE_DIR) + + # Confronta il commit locale con quello remoto + local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip() + remote_hash = subprocess.check_output(['git', 'rev-parse', '@{u}'], cwd=BASE_DIR).decode('utf-8').strip() + + update_available = local_hash != remote_hash + return jsonify({"success": True, "update_available": update_available}) + except Exception as e: + logger.error(f"Errore controllo aggiornamenti server: {e}") + return jsonify({"success": False, "error": "Impossibile verificare aggiornamenti"}) + +@app.route('/api/server_update/apply', methods=['POST']) +def apply_server_update(): + auth = get_auth() + if not auth or auth['role'] != 'admin': + return err("Unauthorized", 403) + + try: + audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE') + logger.warning(f"🔄 Aggiornamento OTA del server avviato da {auth['username']}") + + # Esegue il pull + subprocess.run(['git', 'pull', '--ff-only'], timeout=30, cwd=BASE_DIR, check=True) + + # Programma il riavvio (esce dal processo, systemd lo farà ripartire) + def restart_server(): + time.sleep(2) + os._exit(1) + + threading.Thread(target=restart_server, daemon=True).start() + return jsonify({"success": True}) + except subprocess.CalledProcessError as e: + logger.error(f"Errore durante git pull: {e}") + return err("Conflitto o errore durante il git pull.") + except Exception as e: + logger.error(f"Errore aggiornamento server: {e}") + return err(str(e)) + @app.route('/manifest.json') def serve_manifest(): return send_from_directory(BASE_DIR, 'manifest.json') diff --git a/templates/index.html b/templates/index.html index a84758b..4bbf54b 100644 --- a/templates/index.html +++ b/templates/index.html @@ -718,8 +718,9 @@ const role = me.role || ''; const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); - if (isAuthenticated) { + if (isAuthenticated) { let adminBtn = role === 'admin' ? ` + ` : ''; @@ -1342,6 +1343,38 @@ } function urlB64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i); return outputArray; } + async function checkServerUpdate() { + if (!isAuthenticated || me.role !== 'admin') return; + try { + const res = await fetch('/api/server_update/check'); + const data = await res.json(); + const btn = document.getElementById('server-update-btn'); + if (btn) { + btn.style.display = data.update_available ? 'inline-block' : 'none'; + } + } catch (e) { console.error("Errore check update server:", e); } + } + + function confirmServerUpdate() { + customConfirm("🔄 UPDATE SERVER", "Vuoi scaricare l'ultima versione del server da Gitea/GitHub e riavviare il servizio backend?", "var(--danger)", async () => { + try { + const res = await fetch('/api/server_update/apply', { method: 'POST' }); + const data = await res.json(); + if (data.success) { + customAlert("✅ SUCCESS", "Aggiornamento in corso. La pagina si ricaricherà a breve."); + setTimeout(() => location.reload(), 5000); // Ricarica dopo 5 secondi + } else { + customAlert("❌ ERRORE", esc(data.error), true); + } + } catch (e) { console.error(e); customAlert("❌ ERRORE", "Errore di rete.", true); } + }); + } + + // Controlla gli aggiornamenti ogni ora + setInterval(checkServerUpdate, 3600000); + // Effettua un controllo 5 secondi dopo l'avvio della UI + setTimeout(checkServerUpdate, 5000); + initUI(); checkPushStatus();