AP manageur V1.2 (Bêta)

This commit is contained in:
yoannmultigaming committed 2026-11-23 02:52:03 +01:00
1 parent 44c2048d3b
commit 9b86c11a24
6 files changed
+404 -209

No files matched your search

+148 -61
View File
@@ -4328,8 +4328,10 @@ def teardown_bridge(bridge_name='br0', bridge_eth=None):
conns = command('nmcli', '-t', '-g', 'NAME', 'connection', 'show').splitlines()
for c in conns:
if c.startswith(('ap-bridge-eth-', f"ap-bridge-{bridge_name}")):
subprocess.run(['nmcli', 'connection', 'down', c], capture_output=True)
subprocess.run(['nmcli', 'connection', 'delete', c], capture_output=True)
try: subprocess.run(['nmcli', '--wait', '2', 'connection', 'down', c], capture_output=True, timeout=3)
except Exception: pass
try: subprocess.run(['nmcli', '--wait', '2', 'connection', 'delete', c], capture_output=True, timeout=3)
except Exception: pass
# Détecter si une interface Ethernet physique de l'hôte est asservie à ce pont
slaved_eth = None
@@ -10654,8 +10656,6 @@ def _download_sftp(cfg, remote_filename, dest_path):
break
except Exception: pass
try:
ssh.connect(host, port=port, username=user, password=password or None, pkey=pkey, timeout=25)
sftp = ssh.open_sftp()
_, target_file = _normalize_sftp_target(sftp, cfg.get('path', ''), remote_filename)
sftp.get(target_file, dest_path)
return True
@@ -11277,7 +11277,17 @@ API_MSG_I18N = {
'SSID ou mot de passe Wi-Fi invalide': {'en-us': 'Invalid Wi-Fi SSID or password', 'en-gb': 'Invalid Wi-Fi SSID or password'},
'Sécurité Wi-Fi invalide': {'en-us': 'Invalid Wi-Fi security setting', 'en-gb': 'Invalid Wi-Fi security setting'},
'Délai d’attente dépassé': {'en-us': 'Request timed out', 'en-gb': 'Request timed out'},
"Délai d'attente dépassé": {'en-us': 'Request timed out', 'en-gb': 'Request timed out'}
"Délai d'attente dépassé": {'en-us': 'Request timed out', 'en-gb': 'Request timed out'},
'Arrêt des tunnels VPN actifs...': {'en-us': 'Stopping active VPN tunnels...', 'en-gb': 'Stopping active VPN tunnels...'},
'Arrêt du point d’accès Wi-Fi...': {'en-us': 'Stopping Wi-Fi access point...', 'en-gb': 'Stopping Wi-Fi access point...'},
"Arrêt du point d'accès Wi-Fi...": {'en-us': 'Stopping Wi-Fi access point...', 'en-gb': 'Stopping Wi-Fi access point...'},
'Suppression des profils réseau NetworkManager...': {'en-us': 'Deleting NetworkManager connection profiles...', 'en-gb': 'Deleting NetworkManager connection profiles...'},
'Nettoyage du pont réseau et des règles pare-feu...': {'en-us': 'Cleaning network bridge and firewall rules...', 'en-gb': 'Cleaning network bridge and firewall rules...'},
'Suppression de la base de données et des sessions...': {'en-us': 'Deleting database and active sessions...', 'en-gb': 'Deleting database and active sessions...'},
'Toutes les données ont été réinitialisées avec succès.': {'en-us': 'All data has been reset successfully.', 'en-gb': 'All data has been reset successfully.'},
'Démarrage de la réinitialisation...': {'en-us': 'Starting reset process...', 'en-gb': 'Starting reset process...'},
'Réinitialisation déjà en cours': {'en-us': 'Reset already in progress', 'en-gb': 'Reset already in progress'},
'Réinitialisation en cours': {'en-us': 'Reset in progress', 'en-gb': 'Reset in progress'}
}
def translate_api_text(text, lang='fr'):
@@ -11292,6 +11302,122 @@ def translate_api_text(text, lang='fr'):
text = text.replace(k, trans)
return text
_clear_data_lock = threading.Lock()
_clear_data_state = {
'running': False,
'step': 0,
'total_steps': 5,
'percent': 0,
'message': '',
'done': False,
'error': None
}
def _set_clear_progress(step, total_steps, percent, message, done=False, error=None):
with _clear_data_lock:
_clear_data_state['running'] = not done and error is None
_clear_data_state['step'] = step
_clear_data_state['total_steps'] = total_steps
_clear_data_state['percent'] = percent
_clear_data_state['message'] = message
_clear_data_state['done'] = done
_clear_data_state['error'] = error
def run_clear_all_data(caller_ip=''):
try:
# Étape 1 : Arrêt des tunnels VPN actifs
_set_clear_progress(1, 5, 20, "Arrêt des tunnels VPN actifs...")
try:
c_v = db()
v_rows = c_v.execute('SELECT id FROM vpn_profiles').fetchall()
c_v.close()
for (vpid,) in v_rows:
try: disconnect_vpn_profile(vpid, caller_ip=caller_ip)
except Exception: pass
except Exception: pass
time.sleep(0.35)
# Étape 2 : Arrêt du point d'accès Wi-Fi (hostapd)
_set_clear_progress(2, 5, 40, "Arrêt du point d'accès Wi-Fi...")
try:
stop_hostapd(INTERFACE)
except Exception: pass
time.sleep(0.35)
# Étape 3 : Suppression des profils réseau NetworkManager
_set_clear_progress(3, 5, 60, "Suppression des profils réseau NetworkManager...")
try:
name = connection_name()
names_to_delete = set()
if name: names_to_delete.add(name)
r_nm = subprocess.run(['nmcli', '-t', '-g', 'NAME', 'connection', 'show'], capture_output=True, text=True, timeout=3)
if r_nm.returncode == 0:
for line in r_nm.stdout.splitlines():
line = line.strip()
if line.startswith('AP-') or line.startswith('ap-bridge') or line == name:
names_to_delete.add(line)
for n in names_to_delete:
if n:
try: subprocess.run(['nmcli', '--wait', '2', 'connection', 'down', n], capture_output=True, text=True, timeout=3)
except Exception: pass
try: subprocess.run(['nmcli', '--wait', '2', 'connection', 'delete', n], capture_output=True, text=True, timeout=3)
except Exception: pass
except Exception: pass
time.sleep(0.35)
# Étape 4 : Nettoyage du pont réseau et des règles pare-feu
_set_clear_progress(4, 5, 80, "Nettoyage du pont réseau et des règles pare-feu...")
try: teardown_bridge()
except Exception: pass
try: teardown_ap_nat()
except Exception: pass
try:
if os.path.exists(CONNECTION_FILE): os.remove(CONNECTION_FILE)
except OSError: pass
try:
if os.path.exists(UPTIME_FILE): os.remove(UPTIME_FILE)
except OSError: pass
try:
conf = '/etc/NetworkManager/dnsmasq-shared.d/20-max-clients.conf'
if os.path.exists(conf): os.remove(conf)
except OSError: pass
time.sleep(0.35)
# Étape 5 : Purge de la base de données et des sessions
_set_clear_progress(5, 5, 95, "Suppression de la base de données et des sessions...")
c = db()
c.execute('DELETE FROM connection_logs')
c.execute('DELETE FROM blocked_clients')
c.execute('DELETE FROM client_names')
c.execute('DELETE FROM client_traffic')
c.execute('DELETE FROM client_traffic_daily')
c.execute('DELETE FROM client_limits')
c.execute('DELETE FROM vpn_profiles')
c.execute('DELETE FROM client_vpn_routes')
c.execute('DELETE FROM auth_users')
c.execute('DELETE FROM auth_passkeys')
c.execute('DROP TABLE IF EXISTS recovery_codes')
c.execute('DELETE FROM preferences')
c.execute('DELETE FROM auth_sessions')
c.execute('DELETE FROM api_keys')
c.commit()
c.close()
sessions.clear()
with _api_keys_cache_lock: _api_keys_cache.clear()
invalidate_status_cache()
try: sync_vpn_client_rules()
except Exception: pass
with traffic_lock: station_traffic.clear()
log('reinitialisation_donnees', 'Système', caller_ip, 'SYSTEM')
time.sleep(0.35)
_set_clear_progress(5, 5, 100, "Toutes les données ont été réinitialisées avec succès.", done=True)
except Exception as e:
print(f"[ap-data-clear] Erreur pendant la réinitialisation : {e}", flush=True)
_set_clear_progress(5, 5, 100, f"Erreur : {e}", done=True, error=str(e))
class Handler(BaseHTTPRequestHandler):
def get_req_lang(self):
@@ -11413,6 +11539,10 @@ class Handler(BaseHTTPRequestHandler):
self.send_error(404, 'Image introuvable')
return
if self.path == '/api/auth/status': self.send_json(auth_state()); return
if self.path == '/api/data/clear/progress':
with _clear_data_lock:
self.send_json(dict(_clear_data_state))
return
if self.path == '/api/device-types':
c = db()
rows = c.execute('SELECT id, label, icon, desc, sort_order FROM custom_device_types ORDER BY sort_order ASC, id ASC').fetchall()
@@ -12723,62 +12853,19 @@ class Handler(BaseHTTPRequestHandler):
update_background_metrics()
self.send_json({'ok':True,'message':'Journaux supprimés'}); return
if self.path == '/api/data/clear':
# Arrêter les tunnels VPN actifs avant suppression
try:
c_v = db()
v_rows = c_v.execute('SELECT id FROM vpn_profiles').fetchall()
c_v.close()
for (vpid,) in v_rows:
try: disconnect_vpn_profile(vpid)
except Exception: pass
except Exception: pass
name = connection_name()
names_to_delete = set()
if name: names_to_delete.add(name)
out = subprocess.run(['nmcli', '-t', '-g', 'NAME', 'connection', 'show'], capture_output=True, text=True).stdout
for line in out.splitlines():
line = line.strip()
if line.startswith('AP-') or line.startswith('ap-bridge') or line == name:
names_to_delete.add(line)
for n in names_to_delete:
if n:
subprocess.run(['nmcli', 'connection', 'down', n], capture_output=True, text=True)
subprocess.run(['nmcli', 'connection', 'delete', n], capture_output=True, text=True)
stop_hostapd(INTERFACE)
teardown_bridge()
teardown_ap_nat()
try: os.remove(CONNECTION_FILE)
except OSError: pass
try: os.remove(UPTIME_FILE)
except OSError: pass
try:
conf = '/etc/NetworkManager/dnsmasq-shared.d/20-max-clients.conf'
if os.path.exists(conf): os.remove(conf)
except OSError: pass
c=db()
c.execute('DELETE FROM connection_logs')
c.execute('DELETE FROM blocked_clients')
c.execute('DELETE FROM client_names')
c.execute('DELETE FROM client_traffic')
c.execute('DELETE FROM client_traffic_daily')
c.execute('DELETE FROM client_limits')
c.execute('DELETE FROM vpn_profiles')
c.execute('DELETE FROM client_vpn_routes')
c.execute('DELETE FROM auth_users')
c.execute('DELETE FROM auth_passkeys')
c.execute('DROP TABLE IF EXISTS recovery_codes')
c.execute('DELETE FROM preferences')
c.execute('DELETE FROM auth_sessions')
c.execute('DELETE FROM api_keys')
c.commit(); c.close()
sessions.clear()
with _api_keys_cache_lock: _api_keys_cache.clear()
invalidate_status_cache()
try: sync_vpn_client_rules()
except Exception: pass
with traffic_lock: station_traffic.clear()
log('reinitialisation_donnees', 'Système', request_ip(self), 'SYSTEM')
self.send_json({'ok':True,'message':'Toutes les données et le point d’accès ont été réinitialisés et supprimés','redirect':'/setup'}); return
with _clear_data_lock:
if _clear_data_state.get('running'):
self.send_json({'ok': True, 'started': True, 'message': 'Réinitialisation déjà en cours', 'redirect': '/setup'}); return
_clear_data_state['running'] = True
_clear_data_state['step'] = 1
_clear_data_state['total_steps'] = 5
_clear_data_state['percent'] = 10
_clear_data_state['message'] = "Démarrage de la réinitialisation..."
_clear_data_state['done'] = False
_clear_data_state['error'] = None
t = threading.Thread(target=run_clear_all_data, args=(request_ip(self),), daemon=True)
t.start()
self.send_json({'ok': True, 'started': True, 'message': 'Réinitialisation en cours', 'redirect': '/setup'}); return
if self.path == '/api/backups/schedule':
sched = save_backup_schedule(data)
log('planification_sauvegarde_modifiee', f"{username(self) or 'Administrateur'} ({sched.get('cron_expr', '')})", request_ip(self), 'BACKUP')
+218 -146
View File
@@ -7220,6 +7220,81 @@
</div>
</div>
</div>
<!-- 11. Modal Progression Réinitialisation des données -->
<div id="modalClearAllProgress" class="modal-overlay" style="z-index:999999;backdrop-filter:blur(6px);background:rgba(0,0,0,0.85)">
<div class="modal-card" style="max-width:480px;width:92%;padding:28px 24px;border:1px solid rgba(239,68,68,0.4);box-shadow:0 16px 40px rgba(0,0,0,0.6), 0 0 30px rgba(239,68,68,0.2);border-radius:18px;display:flex;flex-direction:column;align-items:center;gap:18px">
<!-- Icône animée -->
<div style="position:relative;width:68px;height:68px;display:flex;align-items:center;justify-content:center">
<div style="position:absolute;inset:0;border-radius:50%;border:2px solid rgba(239,68,68,0.35);animation:radarPulse 2s ease-out infinite"></div>
<div id="clearProgressIcon" style="font-size:34px;z-index:1;animation:iconFloat 2s ease-in-out infinite">🗑️</div>
</div>
<!-- Titre et sous-titre -->
<div style="text-align:center">
<h2 style="margin:0;font-size:18px;letter-spacing:-0.3px;color:var(--text)" data-i18n="reset_progress_title">Réinitialisation des données</h2>
<div style="margin-top:6px;display:inline-flex;align-items:center;gap:6px;background:rgba(239,68,68,0.12);border:1px solid rgba(239,68,68,0.3);color:var(--red);padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600">
<span id="clearProgressBadgeIcon" style="display:inline-flex;align-items:center;justify-content:center;animation:spin 1.5s linear infinite">⚙️</span>
<span id="clearProgressBadgeText" data-i18n="reset_progress_badge">Suppression en cours…</span>
</div>
</div>
<!-- Barre de progression -->
<div class="loader-progress-box" style="width:100%;margin-top:4px">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;font-size:12px">
<span id="clearProgressStepLabel" style="font-weight:600;color:var(--text)" data-i18n="reset_step_label">Étape 1 / 5</span>
<span id="clearProgressPercent" style="font-weight:700;color:var(--red);font-family:monospace">0%</span>
</div>
<div class="loader-bar-bg" style="height:10px;border-radius:8px;background:var(--panel2);border:1px solid var(--line);overflow:hidden">
<div id="clearProgressBar" class="loader-bar-fill" style="width:0%;height:100%;background:linear-gradient(90deg, #ef4444, #f97316);box-shadow:0 0 12px rgba(239,68,68,0.5);border-radius:8px;transition:width .35s ease"></div>
</div>
</div>
<!-- Libellés d'état dynamique -->
<div style="text-align:center;min-height:44px;width:100%">
<div id="clearProgressStatusText" style="font-weight:700;font-size:14px;color:var(--text)" data-i18n="reset_starting">Démarrage de la suppression…</div>
<div id="clearProgressDetails" class="muted" style="font-size:12px;margin-top:3px" data-i18n="reset_preparing">Préparation des services réseau et de la base de données…</div>
</div>
<!-- Checklist visuelle des étapes -->
<div class="loader-checklist" style="display:grid;grid-template-columns:1fr;gap:7px;width:100%;margin-top:4px;border-top:1px solid var(--line);padding-top:12px">
<div id="clearStepVpn" class="loader-step active" style="display:flex;align-items:center;gap:8px;padding:7px 12px;background:var(--panel2);border-radius:8px;border:1px solid rgba(239,68,68,0.4);font-size:12.5px">
<span class="step-icon">🛡️</span>
<span class="step-name" style="flex:1" data-i18n="reset_step1_vpn">Arrêt des tunnels VPN</span>
<span class="step-state" id="clearStepVpnState" style="font-weight:700;color:var(--red)">↻</span>
</div>
<div id="clearStepWifi" class="loader-step" style="display:flex;align-items:center;gap:8px;padding:7px 12px;background:var(--panel2);border-radius:8px;border:1px solid transparent;font-size:12.5px">
<span class="step-icon">📶</span>
<span class="step-name" style="flex:1" data-i18n="reset_step2_wifi">Arrêt du Wi-Fi (hostapd)</span>
<span class="step-state" id="clearStepWifiState">⏳</span>
</div>
<div id="clearStepNetwork" class="loader-step" style="display:flex;align-items:center;gap:8px;padding:7px 12px;background:var(--panel2);border-radius:8px;border:1px solid transparent;font-size:12.5px">
<span class="step-icon">⚙️</span>
<span class="step-name" style="flex:1" data-i18n="reset_step3_net">Suppression des connexions réseau</span>
<span class="step-state" id="clearStepNetworkState">⏳</span>
</div>
<div id="clearStepBridge" class="loader-step" style="display:flex;align-items:center;gap:8px;padding:7px 12px;background:var(--panel2);border-radius:8px;border:1px solid transparent;font-size:12.5px">
<span class="step-icon">🌐</span>
<span class="step-name" style="flex:1" data-i18n="reset_step4_bridge">Nettoyage pare-feu &amp; routage</span>
<span class="step-state" id="clearStepBridgeState">⏳</span>
</div>
<div id="clearStepDb" class="loader-step" style="display:flex;align-items:center;gap:8px;padding:7px 12px;background:var(--panel2);border-radius:8px;border:1px solid transparent;font-size:12.5px">
<span class="step-icon">🗄️</span>
<span class="step-name" style="flex:1" data-i18n="reset_step5_db">Purge de la base et des sessions</span>
<span class="step-state" id="clearStepDbState">⏳</span>
</div>
</div>
<div id="clearProgressErrorBox" style="display:none;width:100%;margin-top:8px;padding:10px;background:rgba(239,68,68,0.15);border:1px solid var(--red);border-radius:8px;color:var(--red);font-size:12px;text-align:center">
<span id="clearProgressErrorText"></span>
<div style="margin-top:8px">
<button type="button" class="secondary" style="padding:4px 10px;font-size:12px" onclick="closeClearProgressModal()">Fermer</button>
</div>
</div>
</div>
</div>
</main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js" defer></script>
@@ -9309,133 +9384,6 @@ ${vpnBadgeTopo}
? (rate ? ` <small style="opacity:.78;font-weight:500">(${Math.round(rate)} Mbps)</small>` : ` <small style="opacity:.78;font-weight:500">(~)</small>`)
: ` <small style="opacity:.78;font-weight:500">(${val} dBm)</small>`;
const tip = isEst
? (rate ? `Estimé via lien Wi-Fi ${rate} MBit/s (pilote Raspberry Pi brcmfmac)` : `Qualité estimée via les statistiques de paquets (pilote Raspberry Pi brcmfmac)`)
: `${val} dBm`;
if (val >= -50) return `<span class="signal signal-excellent" title="${tip}">${t('signal_excellent', 'Excellent')}${suffix}</span>`;
if (val >= -60) return `<span class="signal signal-bon" title="${tip}">${t('signal_good', 'Bon')}${suffix}</span>`;
if (val >= -70) return `<span class="signal signal-moyen" title="${tip}">${t('signal_fair', 'Moyen')}${suffix}</span>`;
return `<span class="signal signal-faible" title="${tip}">${t('signal_weak', 'Faible')}${suffix}</span>`;
}
function cleanQrBox(box) {
if (!box) return;
const canvas = box.querySelector('canvas');
const img = box.querySelector('img');
if (!canvas && !img) return;
if (img && img.src && img.src.startsWith('data:image')) {
img.style.display = 'block'; img.style.width = '100%'; img.style.height = '100%';
if (canvas) canvas.remove();
return;
}
if (canvas) {
try {
const dataUrl = canvas.toDataURL('image/png');
if (dataUrl && dataUrl.length > 50) {
if (img) {
img.src = dataUrl; img.style.display = 'block'; img.style.width = '100%'; img.style.height = '100%';
canvas.remove(); return;
}
}
} catch (_) { }
canvas.style.display = 'block'; canvas.style.width = '100%'; canvas.style.height = '100%';
if (img) img.remove();
return;
}
if (img) { img.style.display = 'block'; img.style.width = '100%'; img.style.height = '100%' }
}
let currentSettingsTab = 'wifi';
let currentNotifSubTab = sessionStorage.getItem('apNotifSubTab') || 'services';
function selectNotifSubTab(subTab) {
currentNotifSubTab = subTab;
sessionStorage.setItem('apNotifSubTab', subTab);
const isServices = subTab === 'services';
const isAlerts = subTab === 'alerts';
const ts = $('tabNotifServices'), ta = $('tabNotifAlerts');
if (ts) { ts.classList.toggle('active', isServices); ts.setAttribute('aria-selected', isServices); }
if (ta) { ta.classList.toggle('active', isAlerts); ta.setAttribute('aria-selected', isAlerts); }
const ps = $('panelNotifServices'), pa = $('panelNotifAlerts');
if (ps) ps.style.display = isServices ? 'block' : 'none';
if (pa) pa.style.display = isAlerts ? 'block' : 'none';
}
function selectSettingsTab(tabKey) {
if (tabKey === '2fa') tabKey = 'admin';
currentSettingsTab = tabKey;
const tabs = ['wifi', 'admin', 'vpn', 'proxy', 'notif', 'custom', 'backup', 'danger'];
tabs.forEach(k => {
const btnId = 'tabSettings' + k.charAt(0).toUpperCase() + k.slice(1);
const panelId = 'panelSettings' + k.charAt(0).toUpperCase() + k.slice(1);
const btn = $(btnId); const panel = $(panelId);
if (btn) {
btn.classList.toggle('active', k === tabKey);
btn.setAttribute('aria-selected', k === tabKey ? 'true' : 'false');
}
if (panel) {
panel.style.display = (k === tabKey) ? 'block' : 'none';
panel.classList.toggle('active', k === tabKey);
}
});
if (tabKey === 'admin') { if (typeof loadAdminUser === 'function') loadAdminUser(); if (typeof loadSessions === 'function') loadSessions(); if (typeof loadPasskeysList === 'function') loadPasskeysList(); if (typeof loadApiKeys === 'function') loadApiKeys(); }
if (tabKey === 'vpn') {
if (typeof loadVpnProfiles === 'function') loadVpnProfiles();
if (typeof loadVpnClients === 'function') loadVpnClients();
startVpnTabRefresh();
}
if (tabKey === 'proxy') {
if (typeof loadReverseProxySettings === 'function') loadReverseProxySettings();
}
if (tabKey === 'notif') {
if (typeof selectNotifSubTab === 'function') selectNotifSubTab(currentNotifSubTab || 'services');
if (typeof loadNotificationSettings === 'function') loadNotificationSettings();
}
if (tabKey === 'custom') {
if (typeof loadDeviceTypes === 'function') loadDeviceTypes();
if (typeof loadUpdateSettings === 'function') loadUpdateSettings();
}
if (tabKey === 'backup') {
if (typeof loadBackupsTab === 'function') loadBackupsTab();
}
}
let vpnTabRefreshTimer = null;
function startVpnTabRefresh() {
if (vpnTabRefreshTimer) clearInterval(vpnTabRefreshTimer);
vpnTabRefreshTimer = setInterval(() => {
if (authToken && currentTab === 'settings' && currentSettingsTab === 'vpn') {
if (typeof loadVpnProfiles === 'function') loadVpnProfiles();
if (typeof loadVpnClients === 'function') loadVpnClients();
} else {
clearInterval(vpnTabRefreshTimer);
vpnTabRefreshTimer = null;
}
}, 3000);
}
function qr() {
if (!status.ssid || !status.password) return;
let box = $('qrcode'); let signature = status.ssid + '\u0000' + status.password;
if (signature === qrSignature) return;
$('qrPassword').value = status.password; box.replaceChildren();
new QRCode(box, { text: `WIFI:T:WPA;S:${esc(status.ssid)};P:${esc(status.password)};;`, width: 190, height: 190 });
cleanQrBox(box);
setTimeout(() => cleanQrBox(box), 50);
setTimeout(() => cleanQrBox(box), 200);
qrSignature = signature;
}
async function controlAp(action) {
return runAction(async () => {
try {
const response = await apiFetch('/api/ap/control', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) });
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Action refusée');
await new Promise(resolve => setTimeout(resolve, 1000)); await load();
} catch (e) { alert(tErr(e.message)) }
});
}
function updateApButtons() {
const active = !!status.active, configured = !!status.configured;
if ($('dashboardView')) $('dashboardView').classList.toggle('active', currentTab === 'dashboard');
if ($('statsView')) $('statsView').classList.toggle('active', configured && currentTab === 'stats');
if ($('devicesView')) $('devicesView').classList.toggle('active', configured && currentTab === 'devices');
@@ -13251,28 +13199,152 @@ ${vpnBadgeTopo}
$('apControl').onclick = () => controlAp(status.active ? 'stop' : 'start');
$('apRestart').onclick = () => { if (status && status.active) controlAp('restart'); };
window.closeClearProgressModal = function() {
const modal = $('modalClearAllProgress');
if (modal) modal.classList.remove('active');
};
$('clearAllData').onclick = () => runAction(async () => {
if (!confirm(t('confirm_delete_all_data', '⚠️ ATTENTION : Voulez-vous vraiment supprimer toutes les données de l’application ?'))) return;
const message = $('clearDataMessage'); message.textContent = t('loading', 'Suppression…');
try {
const response = await apiFetch('/api/data/clear', { method: 'POST' }); const data = await response.json();
if (!response.ok) throw Error(data.error || 'Suppression refusée');
message.textContent = tMsg(data.message);
authToken = '';
const modal = $('modalClearAllProgress');
if (modal) modal.classList.add('active');
// Réinitialisation de l'affichage de la modale
$('clearProgressBar').style.width = '8%';
$('clearProgressPercent').textContent = '8%';
$('clearProgressStepLabel').textContent = (t('reset_step_label', 'Étape {step} / {total}') || 'Étape {step} / {total}').replace('{step}', '1').replace('{total}', '5');
$('clearProgressBadgeText').textContent = t('reset_progress_badge', 'Suppression en cours…');
$('clearProgressBadgeIcon').textContent = '⚙️';
$('clearProgressBadgeIcon').style.animation = 'spin 1.5s linear infinite';
$('clearProgressIcon').textContent = '🗑️';
$('clearProgressStatusText').textContent = t('reset_starting', 'Démarrage de la suppression…');
$('clearProgressDetails').textContent = t('reset_preparing', 'Déconnexion des interfaces réseau et réinitialisation…');
if ($('clearProgressErrorBox')) $('clearProgressErrorBox').style.display = 'none';
const stepPills = [
{ id: 'clearStepVpn', stateId: 'clearStepVpnState' },
{ id: 'clearStepWifi', stateId: 'clearStepWifiState' },
{ id: 'clearStepNetwork', stateId: 'clearStepNetworkState' },
{ id: 'clearStepBridge', stateId: 'clearStepBridgeState' },
{ id: 'clearStepDb', stateId: 'clearStepDbState' }
];
stepPills.forEach((s, idx) => {
const el = $(s.id);
const st = $(s.stateId);
if (el) {
el.className = idx === 0 ? 'loader-step active' : 'loader-step';
el.style.borderColor = idx === 0 ? 'rgba(239,68,68,0.4)' : 'transparent';
}
if (st) {
st.textContent = idx === 0 ? '↻' : '⏳';
st.style.color = idx === 0 ? 'var(--red)' : 'inherit';
}
});
let clearPollInterval = null;
let isRedirecting = false;
const doPoll = async () => {
try {
sessionStorage.removeItem('apAuthToken');
localStorage.removeItem('apAuthToken');
sessionStorage.removeItem('apAppStarted');
localStorage.removeItem('apAppStarted');
sessionStorage.removeItem('apVisited');
localStorage.removeItem('apTheme');
sessionStorage.removeItem('setupExplicitTheme');
sessionStorage.removeItem('setupExplicitLang');
clearAuthCookie();
} catch (_) { }
await new Promise(resolve => setTimeout(resolve, 600));
window.location.replace('/setup');
} catch (e) { message.textContent = tErr(e.message); }
const res = await fetch(API_URL + '/api/data/clear/progress', { cache: 'no-store' });
if (!res.ok) return;
const p = await res.json();
if (!p) return;
const pct = Math.min(100, Math.max(0, p.percent || 0));
$('clearProgressBar').style.width = pct + '%';
$('clearProgressPercent').textContent = pct + '%';
if (p.step) {
$('clearProgressStepLabel').textContent = (t('reset_step_label', 'Étape {step} / {total}') || 'Étape {step} / {total}')
.replace('{step}', p.step).replace('{total}', p.total_steps || 5);
}
if (p.message) {
$('clearProgressStatusText').textContent = tMsg(p.message);
}
const curStep = p.step || 1;
stepPills.forEach((s, idx) => {
const stepNum = idx + 1;
const el = $(s.id);
const st = $(s.stateId);
if (!el || !st) return;
if (curStep > stepNum || (p.done && curStep >= stepNum && !p.error)) {
el.className = 'loader-step done';
el.style.borderColor = 'rgba(34,197,94,0.3)';
st.textContent = '✓';
st.style.color = 'var(--green)';
} else if (curStep === stepNum && !p.done) {
el.className = 'loader-step active';
el.style.borderColor = 'rgba(239,68,68,0.4)';
st.textContent = '↻';
st.style.color = 'var(--red)';
} else {
el.className = 'loader-step';
el.style.borderColor = 'transparent';
st.textContent = '⏳';
st.style.color = 'inherit';
}
});
if (p.error) {
if (clearPollInterval) clearInterval(clearPollInterval);
if ($('clearProgressErrorBox')) {
$('clearProgressErrorBox').style.display = 'block';
$('clearProgressErrorText').textContent = tErr(p.error);
}
$('clearProgressBadgeText').textContent = t('error', 'Erreur');
$('clearProgressBadgeIcon').textContent = '⚠️';
$('clearProgressBadgeIcon').style.animation = 'none';
return;
}
if (p.done && !isRedirecting) {
isRedirecting = true;
if (clearPollInterval) clearInterval(clearPollInterval);
$('clearProgressBar').style.width = '100%';
$('clearProgressPercent').textContent = '100%';
$('clearProgressBadgeText').textContent = t('done', 'Terminé !');
$('clearProgressBadgeIcon').textContent = '✅';
$('clearProgressBadgeIcon').style.animation = 'none';
$('clearProgressIcon').textContent = '✅';
$('clearProgressStatusText').textContent = t('reset_complete_title', 'Réinitialisation terminée avec succès !');
$('clearProgressDetails').textContent = t('reset_redirecting', 'Redirection vers l’assistant d’installation (Setup)…');
authToken = '';
try {
sessionStorage.clear();
localStorage.clear();
clearAuthCookie();
} catch (_) {}
setTimeout(() => {
window.location.replace('/setup');
}, 800);
}
} catch (_) {}
};
clearPollInterval = setInterval(doPoll, 250);
try {
const response = await apiFetch('/api/data/clear', { method: 'POST', timeout: 60000 });
const data = await response.json();
if (!response.ok) {
throw Error(data.error || 'Suppression refusée');
}
} catch (e) {
if (!isRedirecting) {
if (clearPollInterval) clearInterval(clearPollInterval);
if ($('clearProgressErrorBox')) {
$('clearProgressErrorBox').style.display = 'block';
$('clearProgressErrorText').textContent = tErr(e.message);
}
$('clearProgressBadgeText').textContent = t('error', 'Erreur');
$('clearProgressBadgeIcon').textContent = '⚠️';
$('clearProgressBadgeIcon').style.animation = 'none';
}
}
});
document.querySelectorAll('input[name="settingsMode"]').forEach(r => r.addEventListener('change', () => { if ($('settingsBridgeBlock')) $('settingsBridgeBlock').style.display = r.value === 'bridge' ? 'block' : 'none' }));
+12
View File
@@ -158,6 +158,18 @@ window.I18N['en-gb'] = {
"danger_import_btn": "📤 Import Backup…",
"danger_subtitle": "Critical system maintenance actions.",
"danger_title": "Danger Zone",
"reset_progress_title": "Resetting Data",
"reset_progress_badge": "Reset in progress…",
"reset_step_label": "Step {step} / {total}",
"reset_starting": "Starting reset process…",
"reset_preparing": "Disconnecting network interfaces and resetting…",
"reset_step1_vpn": "Stopping VPN tunnels",
"reset_step2_wifi": "Stopping Wi-Fi (hostapd)",
"reset_step3_net": "Deleting network connections",
"reset_step4_bridge": "Cleaning firewall & routing",
"reset_step5_db": "Purging database and sessions",
"reset_complete_title": "Reset completed successfully!",
"reset_redirecting": "Redirecting to initial setup…",
"dash_card_clients": "Connected Clients",
"dash_card_ssid": "SSID",
"dash_card_status": "AP Status",
+12
View File
@@ -158,6 +158,18 @@ window.I18N['en-us'] = {
"danger_import_btn": "📤 Import Backup…",
"danger_subtitle": "Critical system maintenance actions.",
"danger_title": "Danger Zone",
"reset_progress_title": "Resetting Data",
"reset_progress_badge": "Reset in progress…",
"reset_step_label": "Step {step} / {total}",
"reset_starting": "Starting reset process…",
"reset_preparing": "Disconnecting network interfaces and resetting…",
"reset_step1_vpn": "Stopping VPN tunnels",
"reset_step2_wifi": "Stopping Wi-Fi (hostapd)",
"reset_step3_net": "Deleting network connections",
"reset_step4_bridge": "Cleaning firewall & routing",
"reset_step5_db": "Purging database and sessions",
"reset_complete_title": "Reset completed successfully!",
"reset_redirecting": "Redirecting to initial setup…",
"dash_card_clients": "Connected Clients",
"dash_card_ssid": "SSID",
"dash_card_status": "AP Status",
+12
View File
@@ -158,6 +158,18 @@ window.I18N['fr'] = {
"danger_import_btn": "📤 Importer une sauvegarde…",
"danger_subtitle": "Actions critiques de maintenance du système.",
"danger_title": "Zone dangereuse",
"reset_progress_title": "Réinitialisation des données",
"reset_progress_badge": "Suppression en cours…",
"reset_step_label": "Étape {step} / {total}",
"reset_starting": "Démarrage de la suppression…",
"reset_preparing": "Déconnexion des interfaces réseau et réinitialisation…",
"reset_step1_vpn": "Arrêt des tunnels VPN",
"reset_step2_wifi": "Arrêt du Wi-Fi (hostapd)",
"reset_step3_net": "Suppression des connexions réseau",
"reset_step4_bridge": "Nettoyage pare-feu & routage",
"reset_step5_db": "Purge de la base et des sessions",
"reset_complete_title": "Réinitialisation terminée avec succès !",
"reset_redirecting": "Redirection vers l’assistant d’installation (Setup)…",
"dash_card_clients": "Clients connectés",
"dash_card_ssid": "SSID",
"dash_card_status": "État de l’AP",
+2 -2
View File
@@ -1,5 +1,5 @@
{
"version": "V1.2 (Bêta)",
"commit": "165a06be2256a6fbcf35e8ff6e1f04f085586459",
"build_date": "2026-11-23T00:24:08Z"
"commit": "44c2048d3b501f41a2d9a36f56250b897d13258e",
"build_date": "2026-11-23T01:26:27Z"
}