APmanageur Wi-Fi V1.0

This commit is contained in:
yoannmultigaming committed 2026-11-22 19:00:04 +01:00
1 parent 204b9b1abb
commit 4a36ad70e5
3 files changed
+179 -23

No files matched your search

+157 -15
View File
@@ -516,6 +516,65 @@ def init_db():
c.execute("DELETE FROM client_limits WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
c.execute("DELETE FROM client_vpn_routes WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
c.execute("DELETE FROM blocked_clients WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
# Harmonisation des journaux : 127.0.0.1 -> SYSTEM
c.execute("UPDATE connection_logs SET ip='SYSTEM' WHERE ip IN ('127.0.0.1', '::1', 'localhost')")
# Rétro-alimentation de client_names à partir des connexions antérieures ayant un nom et une IP
c.execute('''
INSERT INTO client_names (mac, name, last_ip, last_seen)
SELECT UPPER(mac), name, ip, event_time
FROM connection_logs
WHERE event LIKE '%connexion%'
AND mac LIKE '__:__:__:__:__:__'
AND name NOT IN ('Nom non communiqué', '')
AND ip NOT IN ('Non attribuée', '', '—')
ORDER BY id ASC
ON CONFLICT(mac) DO UPDATE SET
name = CASE
WHEN excluded.name NOT LIKE 'Client %' AND excluded.name != 'Nom non communiqué' THEN excluded.name
WHEN client_names.name IS NULL OR client_names.name = '' OR client_names.name = 'Nom non communiqué' THEN excluded.name
ELSE client_names.name
END,
last_ip = CASE WHEN excluded.last_ip NOT IN ('Non attribuée', '', '—') THEN excluded.last_ip ELSE client_names.last_ip END,
last_seen = excluded.last_seen
''')
# Mise à jour rétroactive des logs ayant un nom manquant
c.execute('''
UPDATE connection_logs
SET name = (
SELECT name FROM client_names
WHERE UPPER(client_names.mac) = UPPER(connection_logs.mac)
AND client_names.name NOT IN ('Nom non communiqué', '')
LIMIT 1
)
WHERE (name = 'Nom non communiqué' OR name IS NULL OR name = '')
AND mac LIKE '__:__:__:__:__:__'
AND EXISTS (
SELECT 1 FROM client_names
WHERE UPPER(client_names.mac) = UPPER(connection_logs.mac)
AND client_names.name NOT IN ('Nom non communiqué', '')
)
''')
# Mise à jour rétroactive des logs ayant une IP manquante
c.execute('''
UPDATE connection_logs
SET ip = (
SELECT last_ip FROM client_names
WHERE UPPER(client_names.mac) = UPPER(connection_logs.mac)
AND client_names.last_ip NOT IN ('Non attribuée', '', '—')
LIMIT 1
)
WHERE (ip = 'Non attribuée' OR ip IS NULL OR ip = '' OR ip = '—')
AND mac LIKE '__:__:__:__:__:__'
AND EXISTS (
SELECT 1 FROM client_names
WHERE UPPER(client_names.mac) = UPPER(connection_logs.mac)
AND client_names.last_ip NOT IN ('Non attribuée', '', '—')
)
''')
except Exception as e_clean:
print(f"[ap-db] Avertissement nettoyage MAC : {e_clean}", flush=True)
c.commit()
@@ -1152,6 +1211,39 @@ def request_ip(h):
return raw_direct
def log(event, name='Nom non communiqué', ip='Non attribuée', mac='—'):
# Remplacer 127.0.0.1 ou localhost par SYSTEM
if ip in ('127.0.0.1', '::1', 'localhost'):
ip = 'SYSTEM'
mac_clean = str(mac or '—').strip().upper()
if is_valid_mac(mac_clean):
# Si le nom ou l'IP est non communiqué, vérifier dans la table des abonnés (client_names) et journaux récents
if name in ('Nom non communiqué', '', None, 'Inconnu') or ip in ('Non attribuée', '', None, '—'):
try:
c = db()
row = c.execute('SELECT name, last_ip FROM client_names WHERE UPPER(mac)=?', (mac_clean,)).fetchone()
if row:
if (name in ('Nom non communiqué', '', None, 'Inconnu')) and row[0] and row[0] != 'Nom non communiqué':
name = row[0]
saved_ip = row[1] or ''
if is_bridge_mode() and saved_ip.startswith('10.42.'):
saved_ip = ''
if (ip in ('Non attribuée', '', None, '—')) and saved_ip and saved_ip != 'Non attribuée':
ip = saved_ip
if name in ('Nom non communiqué', '', None, 'Inconnu') or ip in ('Non attribuée', '', None, '—'):
row_prev = c.execute("SELECT name, ip FROM connection_logs WHERE UPPER(mac)=? AND ip NOT IN ('Non attribuée', '', '—') ORDER BY id DESC LIMIT 1", (mac_clean,)).fetchone()
if row_prev:
if (name in ('Nom non communiqué', '', None, 'Inconnu')) and row_prev[0] and row_prev[0] != 'Nom non communiqué':
clean_n = re.sub(r'\s*\[🛡️[^\]]*\]', '', row_prev[0]).strip()
if clean_n: name = clean_n
if (ip in ('Non attribuée', '', None, '—')) and row_prev[1] and row_prev[1] != 'Non attribuée':
ip = row_prev[1]
c.close()
except Exception: pass
if name in ('Nom non communiqué', '', None, 'Inconnu'):
name = device_name(ip if ip != 'Non attribuée' else '', mac_clean)
mac = mac_clean
ts = time.strftime('%Y-%m-%d %H:%M:%S')
print(f"[ap-event] [{ts}] {event} | client='{name}' ({mac}) | ip={ip}", flush=True)
try:
@@ -1164,10 +1256,28 @@ def logs():
rows = c.execute('SELECT event_time,event,name,ip,mac FROM connection_logs ORDER BY id DESC LIMIT 200').fetchall()
vpn_routes = dict(c.execute('SELECT mac, profile_id FROM client_vpn_routes WHERE profile_id > 0').fetchall())
vpn_profiles = {r[0]: {'name': r[1], 'status': r[2], 'iface': r[3]} for r in c.execute('SELECT id, name, status, iface FROM vpn_profiles').fetchall()}
known_clients = {r[0].upper(): {'name': r[1], 'last_ip': r[2]} for r in c.execute('SELECT mac, name, last_ip FROM client_names').fetchall() if r[0]}
c.close()
result = []
for r in rows:
mac = (r[4] or '').upper()
ev_name = r[2]
ev_ip = r[3]
if ev_ip in ('127.0.0.1', '::1', 'localhost'):
ev_ip = 'SYSTEM'
# Résolution dynamique si le nom ou l'IP est manquant pour un équipement Wi-Fi
if mac in known_clients:
if not ev_name or ev_name == 'Nom non communiqué':
kname = known_clients[mac].get('name')
if kname and kname != 'Nom non communiqué':
ev_name = kname
if not ev_ip or ev_ip == 'Non attribuée':
kip = known_clients[mac].get('last_ip')
if kip and kip != 'Non attribuée':
ev_ip = kip
if (not ev_name or ev_name == 'Nom non communiqué') and is_valid_mac(mac):
ev_name = device_name(ev_ip if ev_ip != 'Non attribuée' else '', mac)
pid = vpn_routes.get(mac, 0)
prof = vpn_profiles.get(pid) if pid > 0 else None
vname = prof['name'] if prof else ''
@@ -1175,8 +1285,8 @@ def logs():
result.append({
'time': r[0],
'event': r[1],
'name': r[2],
'ip': r[3],
'name': ev_name,
'ip': ev_ip,
'mac': r[4],
'vpn_profile_name': vname,
'vpn_routed': vrouted
@@ -4264,14 +4374,27 @@ def clients():
ip = 'Non attribuée'
blocked = mac in blocked_macs; name = device_name(ip if ip != 'Non attribuée' else '', mac)
if not name.startswith('Client ') and name != 'Nom non communiqué':
try:
c = db(); c.execute('INSERT INTO client_names(mac,name,last_ip,last_seen) VALUES(?,?,?,?) ON CONFLICT(mac) DO UPDATE SET name=excluded.name,last_ip=CASE WHEN excluded.last_ip != \'Non attribuée\' THEN excluded.last_ip ELSE client_names.last_ip END,last_seen=excluded.last_seen', (mac,name,ip,time.strftime('%Y-%m-%d %H:%M:%S'))); c.commit(); c.close()
except sqlite3.Error: pass
elif ip != 'Non attribuée':
try:
c = db(); c.execute('UPDATE client_names SET last_ip=?,last_seen=? WHERE mac=?', (ip,time.strftime('%Y-%m-%d %H:%M:%S'),mac)); c.commit(); c.close()
except sqlite3.Error: pass
now_ts = time.strftime('%Y-%m-%d %H:%M:%S')
try:
c = db()
c.execute('''
INSERT INTO client_names(mac, name, last_ip, last_seen)
VALUES(?, ?, ?, ?)
ON CONFLICT(mac) DO UPDATE SET
name = CASE
WHEN excluded.name NOT LIKE 'Client %' AND excluded.name != 'Nom non communiqué' AND excluded.name != '' THEN excluded.name
WHEN client_names.name IS NULL OR client_names.name = '' OR client_names.name = 'Nom non communiqué' THEN excluded.name
ELSE client_names.name
END,
last_ip = CASE
WHEN excluded.last_ip NOT IN ('Non attribuée', '', '—') THEN excluded.last_ip
ELSE client_names.last_ip
END,
last_seen = excluded.last_seen
''', (mac.upper(), name, ip, now_ts))
c.commit()
c.close()
except sqlite3.Error: pass
vroute = vpn_routes.get(mac)
vpid = vroute['profile_id'] if vroute else 0
@@ -5452,16 +5575,35 @@ def update_logs(items):
for mac in [m for m in pending if m not in current]: pending.pop(mac, None)
for mac in last_macs - set(current):
name, ip = 'Nom non communiqué', 'Non attribuée'
mac_u = str(mac or '').strip().upper()
try:
c = db(); row = c.execute('SELECT name,last_ip FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
c = db()
# 1. Vérification dans la table des appareils / abonnés (client_names)
row = c.execute('SELECT name, last_ip FROM client_names WHERE UPPER(mac)=?', (mac_u,)).fetchone()
if row:
name = row[0] or name
if row[0] and row[0] != 'Nom non communiqué':
name = row[0]
saved_ip = row[1] or ''
if is_bridge_mode() and saved_ip.startswith('10.42.'):
saved_ip = ''
ip = saved_ip or ip
if saved_ip and saved_ip != 'Non attribuée':
ip = saved_ip
# 2. Si le nom ou l'IP manque encore, chercher dans les logs de connexion récents
if name == 'Nom non communiqué' or ip == 'Non attribuée':
row_log = c.execute("SELECT name, ip FROM connection_logs WHERE UPPER(mac)=? AND ip NOT IN ('Non attribuée', '', '—') ORDER BY id DESC LIMIT 1", (mac_u,)).fetchone()
if row_log:
if (name == 'Nom non communiqué' or not name) and row_log[0] and row_log[0] != 'Nom non communiqué':
clean_n = re.sub(r'\s*\[🛡️[^\]]*\]', '', row_log[0]).strip()
if clean_n: name = clean_n
if (ip == 'Non attribuée' or not ip) and row_log[1] and row_log[1] != 'Non attribuée':
ip = row_log[1]
c.close()
except sqlite3.Error: pass
log('déconnexion', name, ip, mac)
if (ip == 'Non attribuée' or not ip) and mac_u in station_live_ips:
ip = station_live_ips[mac_u]
if name == 'Nom non communiqué' or not name:
name = device_name(ip if ip != 'Non attribuée' else '', mac_u)
log('déconnexion', name, ip, mac_u)
dispatch_notification('device_disconnected', "📴 Appareil déconnecté", f"L'appareil « {name} » s'est déconnecté du réseau Wi-Fi.", details={"Nom": name, "IP": ip, "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=2, level="info")
try:
c_v = db()
@@ -10159,7 +10301,7 @@ def backup_scheduler_loop():
print(f"[ap-backup] Déclenchement sauvegarde automatique Cron ({cron_expr}) à {cur_key}...", flush=True)
try:
info = create_server_backup(trigger='auto')
log('sauvegarde_automatique', f"Cron ({info['filename']})", '127.0.0.1', 'BACKUP')
log('sauvegarde_automatique', f"Cron ({info['filename']})", 'SYSTEM', 'BACKUP')
print(f"[ap-backup] Sauvegarde automatique créée : {info['filename']} ({info['size_str']})", flush=True)
except Exception as e_bk:
print(f"[ap-backup] Erreur sauvegarde automatique : {e_bk}", flush=True)
+20 -6
View File
@@ -2431,7 +2431,7 @@
</div>
<div style="text-align:center;margin-top:14px">
<button id="btnSkipLoader" type="button" class="secondary"
style="display:inline-block;padding:8px 18px;font-size:13px;font-weight:600;border-radius:20px;border:1px solid var(--line);color:var(--text);background:var(--panel2);cursor:pointer;transition:all .2s ease"
style="display:none;padding:8px 18px;font-size:13px;font-weight:600;border-radius:20px;border:1px solid var(--line);color:var(--text);background:var(--panel2);cursor:pointer;transition:all .2s ease"
onclick="skipLoaderToDashboard()" data-i18n="loader_skip">Passer au tableau de bord →</button>
</div>
</div>
@@ -9532,7 +9532,18 @@ ${vpnBadgeTopo}
const macText = macCategoryMap[log.mac] || (log.mac || '—');
const vpnBadgeLog = log.vpn_profile_name ?
(log.vpn_routed ? `<span class="pill pill-green pill-no-dot" style="font-size:10px;margin-left:6px;padding:2px 6px;vertical-align:middle" title="Routé via VPN">🛡️ ${escapeHtml(log.vpn_profile_name)}</span>` : `<span class="pill pill-no-dot" style="font-size:10px;margin-left:6px;padding:2px 6px;background:rgba(255,107,107,.15);color:var(--red);vertical-align:middle" title="Profil VPN coupé">⚠️ ${escapeHtml(log.vpn_profile_name)}</span>`) : '';
return `<tr><td>${log.time}</td><td>${eventHtml}</td><td>${escapeHtml(log.name || 'Nom non communiqué')}${vpnBadgeLog}</td><td>${log.ip || '—'}</td><td>${macText}</td></tr>`;
const ipDisp = (log.ip === '127.0.0.1' || log.ip === '::1' || log.ip === 'localhost') ? 'SYSTEM' : (log.ip || '—');
let devName = log.name;
let devIp = ipDisp;
if ((!devName || devName === 'Nom non communiqué' || devIp === 'Non attribuée') && log.mac && log.mac.includes(':')) {
const mUpper = log.mac.toUpperCase();
const known = (typeof allDevicesCache !== 'undefined' && Array.isArray(allDevicesCache)) ? allDevicesCache.find(d => d.mac && d.mac.toUpperCase() === mUpper) : null;
if (known) {
if (!devName || devName === 'Nom non communiqué') devName = known.name;
if (devIp === 'Non attribuée' && known.ip && known.ip !== 'Non attribuée') devIp = known.ip;
}
}
return `<tr><td>${log.time}</td><td>${eventHtml}</td><td>${escapeHtml(devName || 'Nom non communiqué')}${vpnBadgeLog}</td><td>${devIp}</td><td>${macText}</td></tr>`;
}).join('');
renderPagination('logsPagination', logsPage, logsDataCache.length, 'changeLogsPage', 10);
}
@@ -14242,6 +14253,8 @@ ${vpnBadgeTopo}
}
function hideLoaderScreen() {
const skipBtn = $('btnSkipLoader');
if (skipBtn) skipBtn.style.display = 'none';
const l = $('loader');
if (l) {
l.style.opacity = '0';
@@ -14283,9 +14296,9 @@ ${vpnBadgeTopo}
}
}
// Bouton passer au tableau de bord actif dès le chargement
// Bouton passer au tableau de bord masqué initialement (s'affiche uniquement à l'étape des Tests VPN)
const bInit = $('btnSkipLoader');
if (bInit) bInit.style.display = 'inline-block';
if (bInit) bInit.style.display = 'none';
function updateLoaderProgress(percent, title, detail, step) {
const p = Math.max(0, Math.min(100, Math.round(percent)));
@@ -14321,7 +14334,7 @@ ${vpnBadgeTopo}
async function initializeAndShowDashboard(isStarting = true) {
loaderSkipped = false;
const skipBtn = $('btnSkipLoader');
if (skipBtn) skipBtn.style.display = 'inline-block';
if (skipBtn) skipBtn.style.display = 'none';
showLoaderScreen();
const mainTitle = isStarting ? t('loader_starting', "Démarrage en cours…") : t('loader_refreshing', "Actualisation en cours…");
if ($('loaderBadgeText')) $('loaderBadgeText').textContent = isStarting ? t('loader_starting_badge', "Démarrage en cours") : t('loader_refreshing_badge', "Actualisation en cours");
@@ -14358,7 +14371,6 @@ ${vpnBadgeTopo}
while (Date.now() - wifiStart < maxWifiWaitMs) {
if (loaderSkipped) break;
const elapsed = Date.now() - wifiStart;
if (skipBtn) skipBtn.style.display = 'inline-block';
const progressBonus = Math.min(18, Math.round((elapsed / maxWifiWaitMs) * 18));
const remSec = Math.max(1, Math.round((maxWifiWaitMs - elapsed) / 1000));
updateLoaderProgress(35 + progressBonus, mainTitle, t('loader_step2_activating', "Activation du réseau Wi-Fi ({s}s)…").replace('{s}', remSec), 2);
@@ -14384,6 +14396,7 @@ ${vpnBadgeTopo}
if (!authToken || loaderSkipped) return;
// 3. Connexions et Tests de connectivité VPN
if (skipBtn) skipBtn.style.display = 'inline-block';
updateLoaderProgress(60, mainTitle, t('loader_step3_detecting', "Détection et vérification des profils VPN…"), 3);
let vpnProfiles = [];
try {
@@ -14496,6 +14509,7 @@ ${vpnBadgeTopo}
if (!authToken || loaderSkipped) return;
// 4. Chargement final et synchronisation du tableau de bord
if (skipBtn) skipBtn.style.display = 'none';
updateLoaderProgress(90, mainTitle, t('loader_step4_sync', "Synchronisation des équipements, tunnels et métriques…"), 4);
try {
await load();
+2 -2
View File
@@ -1,5 +1,5 @@
{
"version": "V5.5",
"commit": "43ec72a72d44155b28f93dcb60f392bc6e713a59",
"build_date": "2026-11-22T01:17:36Z"
"commit": "204b9b1abb26eb3dd675f5f3ba89782a7d6d944b",
"build_date": "2026-11-22T16:57:07Z"
}