Compare commits

..
3 Commits
3 changed files with 75 additions and 37 deletions
+11 -15
View File
@@ -360,8 +360,16 @@ def save_config_file():
# --- AGGIORNAMENTO SERVER OTA --- # --- AGGIORNAMENTO SERVER OTA ---
def background_gitea_check(): @api_bp.route('/api/server_update/check', methods=['GET'])
global GLOBAL_SERVER_UPDATE_AVAILABLE, LAST_GITEA_CHECK_TIME def get_server_update_status():
global LAST_GITEA_CHECK_TIME, GLOBAL_SERVER_UPDATE_AVAILABLE
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
# Eseguiamo il controllo sincrono (ci mette max 1-2 secondi) ogni ora
# In questo modo il frontend riceve subito il risultato VERO, non quello della cache precedente
if time.time() - LAST_GITEA_CHECK_TIME > 3600:
try: try:
subprocess.run(['git', 'fetch'], timeout=10, cwd=BASE_DIR) 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() local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip()
@@ -369,19 +377,7 @@ def background_gitea_check():
GLOBAL_SERVER_UPDATE_AVAILABLE = (local_hash != remote_hash) GLOBAL_SERVER_UPDATE_AVAILABLE = (local_hash != remote_hash)
LAST_GITEA_CHECK_TIME = time.time() LAST_GITEA_CHECK_TIME = time.time()
except Exception as e: except Exception as e:
logger.error(f"Errore controllo Gitea in background: {e}") logger.error(f"Errore controllo Gitea: {e}")
@api_bp.route('/api/server_update/check', methods=['GET'])
def get_server_update_status():
global LAST_GITEA_CHECK_TIME
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
# Se è passata più di un'ora (3600 secondi) dall'ultimo controllo, avvia il thread
if time.time() - LAST_GITEA_CHECK_TIME > 3600:
import threading
threading.Thread(target=background_gitea_check, daemon=True).start()
return jsonify({"success": True, "update_available": GLOBAL_SERVER_UPDATE_AVAILABLE}) return jsonify({"success": True, "update_available": GLOBAL_SERVER_UPDATE_AVAILABLE})
+32 -17
View File
@@ -530,13 +530,22 @@ async function initUI() {
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
if (isAuthenticated) { if (isAuthenticated) {
let adminBtn = role === 'admin' ? ` const hasAllNodes = role === 'admin' || allowedList.includes('all');
<button id="server-update-btn" onclick="confirmServerUpdate()" class="auth-btn" style="border-color:var(--danger); color:var(--danger) !important; display:none;" title="Aggiornamento Server Disponibile">[ UPD_SERVER ]</button> const canOverride = hasAllNodes;
<button onclick="sendGlobalUpdate()" class="auth-btn" style="color:var(--accent);" data-i18n-title="ttReqCfg" title="${t('ttReqCfg')}">[ ${t('btnReqCfg')} ]</button>
<button onclick="triggerGlobalEmergency()" class="auth-btn" style="color:var(--danger);" data-i18n-title="ttGlobal" title="${t('ttGlobal')}">[ ${t('btnGlobal')} ]</button>
<button onclick="openAdmin()" class="auth-btn" style="color:var(--primary);" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">[ ${t('btnAdmin')} ]</button>` : '';
authContainer.innerHTML = `${adminBtn} let actionBtns = '';
if (role === 'admin') {
actionBtns += `<button id="server-update-btn" onclick="confirmServerUpdate()" class="auth-btn" style="border-color:var(--danger); color:var(--danger) !important; display:none;" title="Aggiornamento Server Disponibile">[ UPD_SERVER ]</button>`;
actionBtns += `<button onclick="sendGlobalUpdate()" class="auth-btn" style="color:var(--accent);" data-i18n-title="ttReqCfg" title="${t('ttReqCfg')}">[ ${t('btnReqCfg')} ]</button>`;
}
if (canOverride) {
actionBtns += `<button onclick="triggerGlobalEmergency()" class="auth-btn" style="color:var(--danger);" data-i18n-title="ttGlobal" title="${t('ttGlobal')}">[ ${t('btnGlobal')} ]</button>`;
}
if (role === 'admin') {
actionBtns += `<button onclick="openAdmin()" class="auth-btn" style="color:var(--primary);" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">[ ${t('btnAdmin')} ]</button>`;
}
authContainer.innerHTML = `${actionBtns}
<span style="font-weight:300; font-size:0.85rem; margin: 0 10px; font-family:'JetBrains Mono', monospace; color:var(--primary);">USR: ${esc(String(me.user).toUpperCase())}</span> <span style="font-weight:300; font-size:0.85rem; margin: 0 10px; font-family:'JetBrains Mono', monospace; color:var(--primary);">USR: ${esc(String(me.user).toUpperCase())}</span>
<button onclick="changeMyPassword()" class="auth-btn" data-i18n-title="ttPass" title="${t('ttPass')}">[ ${t('btnPass')} ]</button> <button onclick="changeMyPassword()" class="auth-btn" data-i18n-title="ttPass" title="${t('ttPass')}">[ ${t('btnPass')} ]</button>
<button onclick="logout()" class="auth-btn" data-i18n-title="ttLogout" title="${t('ttLogout')}">[ ${t('btnLogout')} ]</button>`; <button onclick="logout()" class="auth-btn" data-i18n-title="ttLogout" title="${t('ttLogout')}">[ ${t('btnLogout')} ]</button>`;
@@ -789,7 +798,22 @@ async function refreshStates() {
cardDiv.dataset.status = isOnline ? 'online' : 'offline'; cardDiv.dataset.status = isOnline ? 'online' : 'offline';
renderSeen(c, data, isOnline); renderSeen(c, data, isOnline);
const warns = (data.warnings && data.warnings[c.id.toLowerCase()]) || []; let warns = (data.warnings && data.warnings[c.id.toLowerCase()]) ? [...data.warnings[c.id.toLowerCase()]] : [];
let hasOfflineService = false;
if (healthObj && healthObj.processes) {
for (const [svcName, svcStatus] of Object.entries(healthObj.processes)) {
let s = svcStatus.toLowerCase();
if (s !== 'online' && s !== 'standby') {
hasOfflineService = true;
warns.push(`SVC KO: ${svcName.toUpperCase()}`);
}
}
}
if (!latestStatesData.warnings) latestStatesData.warnings = {};
latestStatesData.warnings[c.id.toLowerCase()] = warns;
cardDiv.dataset.hasWarn = (warns.length > 0) ? 'true' : 'false'; cardDiv.dataset.hasWarn = (warns.length > 0) ? 'true' : 'false';
const diagDiv = document.getElementById(`diag-warn-${c.id}`); const diagDiv = document.getElementById(`diag-warn-${c.id}`);
if (diagDiv) { if (diagDiv) {
@@ -936,16 +960,7 @@ async function refreshStates() {
if (healthContainer) healthContainer.style.display = 'none'; if (healthContainer) healthContainer.style.display = 'none';
} }
// Logica tollerante per i Gateway in standby (spenti dalla UI) // Logica tollerante per i Gateway in standby (hasOfflineService calcolato in alto)
let hasOfflineService = false;
if (healthObj && healthObj.processes) {
for (const [svcName, svcStatus] of Object.entries(healthObj.processes)) {
let s = svcStatus.toLowerCase();
if (s !== 'online' && s !== 'standby') {
hasOfflineService = true; break;
}
}
}
const warnBadge = document.getElementById(`svc-warn-${c.id}`); const btnSvc = document.getElementById(`btn-svc-${c.id}`); 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 (warnBadge) warnBadge.style.display = hasOfflineService ? 'block' : 'none';
if (btnSvc) { if (hasOfflineService) { btnSvc.style.borderColor = 'var(--danger)'; btnSvc.style.color = 'var(--danger)'; } else { btnSvc.style.borderColor = 'var(--text-main)'; btnSvc.style.color = 'var(--text-main)'; } } if (btnSvc) { if (hasOfflineService) { btnSvc.style.borderColor = 'var(--danger)'; btnSvc.style.color = 'var(--danger)'; } else { btnSvc.style.borderColor = 'var(--text-main)'; btnSvc.style.color = 'var(--text-main)'; } }
+31 -4
View File
@@ -230,8 +230,13 @@ async function saveSettings() {
// --- GLOBAL OVERRIDE --- // --- GLOBAL OVERRIDE ---
function triggerGlobalEmergency() { function triggerGlobalEmergency() {
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAll = role === 'admin' || allowedList.includes('all');
let uniqueProfiles = {}; let uniqueProfiles = {};
for (const id in globalHealthData) { for (const id in globalHealthData) {
if (!hasAll && !allowedList.includes(id.toLowerCase())) continue;
if (globalHealthData[id] && globalHealthData[id].profiles) { if (globalHealthData[id] && globalHealthData[id].profiles) {
for (const [k, v] of Object.entries(globalHealthData[id].profiles)) { uniqueProfiles[k] = v; } for (const [k, v] of Object.entries(globalHealthData[id].profiles)) { uniqueProfiles[k] = v; }
} }
@@ -243,14 +248,36 @@ function triggerGlobalEmergency() {
idx++; idx++;
} }
if (Object.keys(uniqueProfiles).length === 0) { html = `<p style="color:var(--danger); font-weight:400; font-family:'JetBrains Mono',monospace;">NO_PROFS_FOUND</p>`; } if (Object.keys(uniqueProfiles).length === 0) { html = `<p style="color:var(--danger); font-weight:400; font-family:'JetBrains Mono',monospace;">NO_PROFS_FOUND</p>`; }
container.innerHTML = html; document.getElementById('override-desc').innerText = t('msgOvrSel'); document.getElementById('override-modal').style.display = 'flex'; container.innerHTML = html;
const descText = hasAll ? t('msgOvrSel') : (currentLang === 'it' ? `SELEZIONA PROFILO (NODI ASSEGNATI: ${allowedList.length}):` : `SELECT PROFILE (NODES: ${allowedList.length}):`);
document.getElementById('override-desc').innerText = descText;
document.getElementById('override-modal').style.display = 'flex';
} }
function sendGlobalAction(action) { function sendGlobalAction(action) {
document.getElementById('override-modal').style.display = 'none'; document.getElementById('override-modal').style.display = 'none';
customConfirm(t('titleGlobal'), t('promptOvrConfirm'), "var(--danger)", async () => { const role = me.role || '';
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(); const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
if(d.success) customAlert(t('titleSuccess'), t('msgOvrOk')); else customAlert(t('titleError'), esc(d.error), true); refreshStates(); const hasAll = role === 'admin' || allowedList.includes('all');
const confirmMsg = hasAll
? t('promptOvrConfirm')
: (currentLang === 'it'
? `Confermi l'invio ai tuoi nodi autorizzati (${allowedList.map(n => n.toUpperCase()).join(', ')})?`
: `Confirm sending to your authorized nodes (${allowedList.map(n => n.toUpperCase()).join(', ')})?`);
customConfirm(t('titleGlobal'), confirmMsg, "var(--danger)", async () => {
try {
const res = await fetch('/api/global_command', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({type: action})
});
const d = await res.json();
if(d.success) customAlert(t('titleSuccess'), t('msgOvrOk'));
else customAlert(t('titleError'), esc(d.error), true);
refreshStates();
} catch(e) { console.error(e); } } catch(e) { console.error(e); }
}); });
} }