Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7bbd080b0 | ||
|
|
019e518534 | ||
|
|
e199fb8f29 | ||
|
|
43e0e77790 | ||
|
|
1bb1c2cc99 |
+22
-17
@@ -226,6 +226,9 @@ def service_control():
|
||||
|
||||
d = json_body()
|
||||
cid = str(d.get('clientId', '')).strip().lower()
|
||||
|
||||
if not check_node_allowed(auth['allowed_nodes'], cid):
|
||||
return err("Permesso negato per questo nodo", 403)
|
||||
action = str(d.get('action', '')).strip().lower()
|
||||
service = str(d.get('service', '')).strip()
|
||||
if not CID_RE.match(cid):
|
||||
@@ -323,6 +326,8 @@ def get_config_file(cid, service):
|
||||
if not auth or auth['role'] != 'admin':
|
||||
return err("Non autorizzato", 403)
|
||||
cid = cid.lower()
|
||||
if not check_node_allowed(auth['allowed_nodes'], cid):
|
||||
return err("Permesso negato per questo nodo", 403)
|
||||
service = service.lower()
|
||||
if not CID_RE.match(cid) or not SERVICE_RE.match(service):
|
||||
return err("Parametri non validi")
|
||||
@@ -339,6 +344,9 @@ def save_config_file():
|
||||
|
||||
d = json_body()
|
||||
cid = str(d.get('clientId', '')).strip().lower()
|
||||
|
||||
if not check_node_allowed(auth['allowed_nodes'], cid):
|
||||
return err("Permesso negato per questo nodo", 403)
|
||||
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):
|
||||
@@ -360,29 +368,26 @@ def save_config_file():
|
||||
|
||||
# --- AGGIORNAMENTO SERVER OTA ---
|
||||
|
||||
def background_gitea_check():
|
||||
global GLOBAL_SERVER_UPDATE_AVAILABLE, LAST_GITEA_CHECK_TIME
|
||||
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()
|
||||
GLOBAL_SERVER_UPDATE_AVAILABLE = (local_hash != remote_hash)
|
||||
LAST_GITEA_CHECK_TIME = time.time()
|
||||
except Exception as e:
|
||||
logger.error(f"Errore controllo Gitea in background: {e}")
|
||||
|
||||
@api_bp.route('/api/server_update/check', methods=['GET'])
|
||||
def get_server_update_status():
|
||||
global LAST_GITEA_CHECK_TIME
|
||||
global LAST_GITEA_CHECK_TIME, GLOBAL_SERVER_UPDATE_AVAILABLE
|
||||
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()
|
||||
|
||||
force_check = request.args.get('force') == '1'
|
||||
|
||||
# Eseguiamo il controllo sincrono se è passata 1 ora OPPURE se forzato dal client
|
||||
if force_check or (time.time() - LAST_GITEA_CHECK_TIME > 3600):
|
||||
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()
|
||||
GLOBAL_SERVER_UPDATE_AVAILABLE = (local_hash != remote_hash)
|
||||
LAST_GITEA_CHECK_TIME = time.time()
|
||||
except Exception as e:
|
||||
logger.error(f"Errore controllo Gitea: {e}")
|
||||
|
||||
return jsonify({"success": True, "update_available": GLOBAL_SERVER_UPDATE_AVAILABLE})
|
||||
|
||||
@api_bp.route('/api/server_update/apply', methods=['POST'])
|
||||
|
||||
+50
-26
@@ -112,7 +112,7 @@ function openNodeFocus(clientId) {
|
||||
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
|
||||
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
|
||||
|
||||
const modesCard = document.getElementById('focus-modes-card');
|
||||
if (modesCard) {
|
||||
@@ -290,7 +290,7 @@ function sendTgCommand(clientId, comando) {
|
||||
async function fetchNodeConfigForModes(clientId) {
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
|
||||
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
|
||||
const modesCard = document.getElementById('focus-modes-card');
|
||||
if (!canControl) {
|
||||
if (modesCard) modesCard.style.display = 'none';
|
||||
@@ -349,7 +349,7 @@ async function fetchNodeConfigForModes(clientId) {
|
||||
function renderModeToggles(clientId, statusMsg = "") {
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
|
||||
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
|
||||
|
||||
const modesCard = document.getElementById('focus-modes-card');
|
||||
if (modesCard) {
|
||||
@@ -530,13 +530,22 @@ async function initUI() {
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
|
||||
if (isAuthenticated) {
|
||||
let adminBtn = role === 'admin' ? `
|
||||
<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>
|
||||
<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>` : '';
|
||||
const hasAllNodes = allowedList.includes('all');
|
||||
const canOverride = hasAllNodes;
|
||||
|
||||
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 = `${adminBtn}
|
||||
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>
|
||||
<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>`;
|
||||
@@ -545,8 +554,8 @@ async function initUI() {
|
||||
}
|
||||
|
||||
grid.innerHTML = clients.map(c => {
|
||||
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
|
||||
let showReboot = (role === 'admin');
|
||||
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
|
||||
let showReboot = (role === 'admin' && canControl);
|
||||
|
||||
return `
|
||||
<div class="card" id="card-${c.id}" data-status="offline" data-gateways="" data-loc="" data-has-warn="false">
|
||||
@@ -756,8 +765,8 @@ async function refreshStates() {
|
||||
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
|
||||
let showReboot = (role === 'admin');
|
||||
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
|
||||
let showReboot = (role === 'admin' && canControl);
|
||||
|
||||
let isTx = false;
|
||||
let activeModeColor = "var(--primary)";
|
||||
@@ -789,7 +798,22 @@ async function refreshStates() {
|
||||
cardDiv.dataset.status = isOnline ? 'online' : 'offline';
|
||||
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';
|
||||
const diagDiv = document.getElementById(`diag-warn-${c.id}`);
|
||||
if (diagDiv) {
|
||||
@@ -936,16 +960,7 @@ async function refreshStates() {
|
||||
if (healthContainer) healthContainer.style.display = 'none';
|
||||
}
|
||||
|
||||
// Logica tollerante per i Gateway in standby (spenti dalla UI)
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Logica tollerante per i Gateway in standby (hasOfflineService calcolato in alto)
|
||||
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.borderColor = 'var(--danger)'; btnSvc.style.color = 'var(--danger)'; } else { btnSvc.style.borderColor = 'var(--text-main)'; btnSvc.style.color = 'var(--text-main)'; } }
|
||||
@@ -1370,9 +1385,18 @@ async function checkPushStatus() {
|
||||
|
||||
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() {
|
||||
async function checkServerUpdate(force = false) {
|
||||
if (!isAuthenticated || me.role !== 'admin') return;
|
||||
try { const res = await fetch('/api/server_update/check'); if (!res.ok) return; 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); }
|
||||
try {
|
||||
const url = force ? '/api/server_update/check?force=1' : '/api/server_update/check';
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) return;
|
||||
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() {
|
||||
|
||||
+31
-4
@@ -230,8 +230,13 @@ async function saveSettings() {
|
||||
|
||||
// --- GLOBAL OVERRIDE ---
|
||||
function triggerGlobalEmergency() {
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
const hasAll = allowedList.includes('all');
|
||||
|
||||
let uniqueProfiles = {};
|
||||
for (const id in globalHealthData) {
|
||||
if (!hasAll && !allowedList.includes(id.toLowerCase())) continue;
|
||||
if (globalHealthData[id] && globalHealthData[id].profiles) {
|
||||
for (const [k, v] of Object.entries(globalHealthData[id].profiles)) { uniqueProfiles[k] = v; }
|
||||
}
|
||||
@@ -243,14 +248,36 @@ function triggerGlobalEmergency() {
|
||||
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>`; }
|
||||
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) {
|
||||
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();
|
||||
const role = me.role || '';
|
||||
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||
const hasAll = 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); }
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user