add Server OTA Update
This commit is contained in:
@@ -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')
|
||||
|
||||
@@ -720,6 +720,7 @@
|
||||
|
||||
if (isAuthenticated) {
|
||||
let adminBtn = role === 'admin' ? `
|
||||
<button id="server-update-btn" onclick="confirmServerUpdate()" class="auth-btn blink" style="background:var(--danger); color:white; display:none; border: 2px solid white;" title="Aggiornamento Server Disponibile">🔄 UPDATE SERVER</button>
|
||||
<button onclick="sendGlobalUpdate()" class="auth-btn" style="background:#f59e0b; color:white;" data-i18n-title="ttReqCfg" title="${t('ttReqCfg')}">${t('btnReqCfg')}</button>
|
||||
<button onclick="triggerGlobalEmergency()" class="auth-btn" style="background:#ef4444; color:white;" data-i18n-title="ttGlobal" title="${t('ttGlobal')}">${t('btnGlobal')}</button>
|
||||
<button onclick="openAdmin()" class="auth-btn" style="background:var(--accent); color:white;" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">${t('btnAdmin')}</button>` : '';
|
||||
@@ -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();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user