APmanageur Wi-Fi V1.0

This commit is contained in:
yoannmultigaming committed 2026-11-22 20:55:05 +01:00
1 parent ff54694291
commit 6f353a5ff5
3 files changed
+115 -34

No files matched your search

+97 -30
View File
@@ -508,17 +508,26 @@ def record_live_device_name(mac, name, ip=None):
if not name or name.startswith('Client ') or name == 'Nom non communiqué':
return
station_live_names[mac] = name
now = time.time()
_device_name_cache[mac] = (name, now + 300)
try:
c = db()
ts = time.strftime('%Y-%m-%d %H:%M:%S')
# Ne mettre à jour la base SQLite que si cet appareil est un vrai client Wi-Fi déjà enregistré
# (c'est-à-dire qui a déjà été connecté au point d'accès ou qui a des logs de connexion)
row = c.execute("SELECT name FROM client_names WHERE UPPER(mac)=?", (mac,)).fetchone()
cn_cols = {col[1] for col in c.execute('PRAGMA table_info(client_names)').fetchall()}
has_cust = 'is_custom' in cn_cols
q = "SELECT name, COALESCE(is_custom, 0) FROM client_names WHERE UPPER(mac)=?" if has_cust else "SELECT name, 0 FROM client_names WHERE UPPER(mac)=?"
row = c.execute(q, (mac,)).fetchone()
if row:
if row[1]: # is_custom == 1 : nom personnalisé par l'utilisateur !
# Conserver impérativement le nom personnalisé de l'utilisateur
station_live_names[mac] = row[0]
_device_name_cache[mac] = (row[0], time.time() + 86400)
if ip and ip not in ('Non attribuée', '', '—'):
c.execute("UPDATE client_names SET last_ip=?, last_seen=? WHERE UPPER(mac)=?", (ip, ts, mac))
c.commit()
c.close()
return
station_live_names[mac] = name
_device_name_cache[mac] = (name, time.time() + 300)
if row[0] in ('Nom non communiqué', '', None) or row[0].startswith('Client '):
if ip and ip not in ('Non attribuée', '', '—'):
c.execute("UPDATE client_names SET name=?, last_ip=?, last_seen=? WHERE UPPER(mac)=?",
@@ -625,10 +634,21 @@ def device_name(ip, mac):
# 1. Base de données client_names (nom personnalisé ou précédemment appris)
if mac:
try:
c = db(); row = c.execute('SELECT name FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
if row and row[0] and not row[0].startswith('Client ') and row[0] != 'Nom non communiqué':
_device_name_cache[mac] = (row[0], now + 300)
return row[0]
c = db()
cn_cols = {col[1] for col in c.execute('PRAGMA table_info(client_names)').fetchall()}
has_cust = 'is_custom' in cn_cols
q = 'SELECT name, COALESCE(is_custom, 0) FROM client_names WHERE UPPER(mac)=?' if has_cust else 'SELECT name, 0 FROM client_names WHERE UPPER(mac)=?'
row = c.execute(q, (mac,)).fetchone()
c.close()
if row and row[0]:
is_cust = bool(row[1])
if is_cust:
_device_name_cache[mac] = (row[0], now + 86400)
station_live_names[mac] = row[0]
return row[0]
elif not row[0].startswith('Client ') and row[0] != 'Nom non communiqué':
_device_name_cache[mac] = (row[0], now + 300)
return row[0]
except sqlite3.Error: pass
# 2. Nom capturé en direct (DHCP sniffer, mDNS, LLMNR, NetBIOS)
@@ -712,13 +732,18 @@ def init_db():
recovery_table(c)
c.execute('CREATE TABLE IF NOT EXISTS connection_logs(id INTEGER PRIMARY KEY,event_time TEXT,event TEXT,name TEXT,ip TEXT,mac TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS blocked_clients(mac TEXT PRIMARY KEY,blocked_at TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS client_names(mac TEXT PRIMARY KEY,name TEXT NOT NULL,last_ip TEXT,last_seen TEXT,device_type TEXT DEFAULT "")')
c.execute('CREATE TABLE IF NOT EXISTS client_names(mac TEXT PRIMARY KEY,name TEXT NOT NULL,last_ip TEXT,last_seen TEXT,device_type TEXT DEFAULT "",is_custom INTEGER DEFAULT 0)')
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
if 'device_type' not in cn_cols:
try:
c.execute('ALTER TABLE client_names ADD COLUMN device_type TEXT DEFAULT ""')
c.commit()
except Exception: pass
if 'is_custom' not in cn_cols:
try:
c.execute('ALTER TABLE client_names ADD COLUMN is_custom INTEGER DEFAULT 0')
c.commit()
except Exception: pass
c.execute('CREATE TABLE IF NOT EXISTS client_traffic(mac TEXT PRIMARY KEY, rx_bytes INTEGER DEFAULT 0, tx_bytes INTEGER DEFAULT 0, last_updated TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS client_traffic_daily(mac TEXT, traffic_date TEXT, rx_bytes INTEGER DEFAULT 0, tx_bytes INTEGER DEFAULT 0, PRIMARY KEY(mac, traffic_date))')
c.execute('CREATE INDEX IF NOT EXISTS idx_client_traffic_daily_date ON client_traffic_daily(traffic_date)')
@@ -4735,27 +4760,39 @@ def clients():
if not ip and not is_bridge:
ip = lease_ip(mac)
# 2. Historique base de données (si non obsolète)
if not ip:
try:
c = db(); row = c.execute('SELECT last_ip FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
if row and row[0] and row[0] != 'Non attribuée':
# 2. Historique base de données (si non obsolète) et nom personnalisé
custom_name = None
try:
c = db()
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
has_cust = 'is_custom' in cn_cols
q = 'SELECT last_ip, name, COALESCE(is_custom, 0) FROM client_names WHERE UPPER(mac)=?' if has_cust else 'SELECT last_ip, name, 0 FROM client_names WHERE UPPER(mac)=?'
row = c.execute(q, (mac,)).fetchone()
c.close()
if row:
if row[2] and row[1]: # is_custom == 1 : nom personnalisé défini par l'utilisateur
custom_name = row[1]
if not ip and row[0] and row[0] != 'Non attribuée':
saved_ip = row[0]
if is_bridge and not saved_ip.startswith('10.42.'):
ip = saved_ip
elif not is_bridge and saved_ip.startswith('10.42.'):
ip = saved_ip
except sqlite3.Error: pass
except sqlite3.Error: pass
if not ip or (is_bridge and ip.startswith('10.42.')):
ip = 'Non attribuée'
blocked = mac in blocked_macs
if mac in station_live_names:
if custom_name:
name = custom_name
station_live_names[mac] = custom_name
_device_name_cache[mac] = (custom_name, time.time() + 86400)
elif mac in station_live_names:
name = station_live_names[mac]
else:
name = device_name(ip if ip != 'Non attribuée' else '', mac)
if (name.startswith('Client ') or name == 'Nom non communiqué') and ip != 'Non attribuée':
if not custom_name and (name.startswith('Client ') or name == 'Nom non communiqué') and ip != 'Non attribuée':
res_n = resolve_client_hostname_now(ip, mac)
if res_n:
name = res_n
@@ -4763,10 +4800,11 @@ def clients():
try:
c = db()
c.execute('''
INSERT INTO client_names(mac, name, last_ip, last_seen)
VALUES(?, ?, ?, ?)
INSERT INTO client_names(mac, name, last_ip, last_seen, is_custom)
VALUES(?, ?, ?, ?, 0)
ON CONFLICT(mac) DO UPDATE SET
name = CASE
WHEN client_names.is_custom = 1 THEN client_names.name
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
@@ -5251,7 +5289,14 @@ def all_devices(lang='fr'):
names_dict = {}
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
has_dev_type = 'device_type' in cn_cols
query = 'SELECT mac, name, last_ip, last_seen, COALESCE(device_type, "") FROM client_names' if has_dev_type else 'SELECT mac, name, last_ip, last_seen, "" FROM client_names'
has_cust = 'is_custom' in cn_cols
if has_dev_type and has_cust:
query = 'SELECT mac, name, last_ip, last_seen, COALESCE(device_type, ""), COALESCE(is_custom, 0) FROM client_names'
elif has_dev_type:
query = 'SELECT mac, name, last_ip, last_seen, COALESCE(device_type, ""), 0 FROM client_names'
else:
query = 'SELECT mac, name, last_ip, last_seen, "", 0 FROM client_names'
for r in c.execute(query).fetchall():
m = (r[0] or '').upper()
if m and is_valid_mac(m):
@@ -5259,7 +5304,8 @@ def all_devices(lang='fr'):
'name': r[1] or '',
'last_ip': r[2] or '',
'last_seen': r[3] or '',
'device_type': r[4] or ''
'device_type': r[4] or '',
'is_custom': bool(r[5]) if len(r) > 5 else False
}
logs_dict = {}
@@ -5358,11 +5404,13 @@ def all_devices(lang='fr'):
vd = vpn_routes.get(mac)
name = ''
if live and live.get('name') and live['name'] not in ('Nom non communiqué', 'Inconnu'):
name = live['name']
if not name and nd.get('name') and nd['name'] not in ('Nom non communiqué', 'Inconnu'):
if nd.get('is_custom') and nd.get('name'):
name = nd['name']
if not name and ld.get('name'):
elif live and live.get('name') and live['name'] not in ('Nom non communiqué', 'Inconnu'):
name = live['name']
elif not name and nd.get('name') and nd['name'] not in ('Nom non communiqué', 'Inconnu'):
name = nd['name']
elif not name and ld.get('name'):
name = ld['name']
if not name or name.startswith('Client '):
if mac in station_live_names:
@@ -11782,9 +11830,28 @@ class Handler(BaseHTTPRequestHandler):
if not is_valid_mac(mac): raise ValueError('Adresse MAC invalide')
if not new_name: raise ValueError('Nom manquant')
c = db()
c.execute('INSERT INTO client_names(mac, name, last_ip, last_seen) VALUES(?, ?, "Non attribuée", ?) ON CONFLICT(mac) DO UPDATE SET name=excluded.name', (mac, new_name, time.strftime('%Y-%m-%d %H:%M:%S')))
cn_cols = {col[1] for col in c.execute('PRAGMA table_info(client_names)').fetchall()}
if 'is_custom' not in cn_cols:
try:
c.execute('ALTER TABLE client_names ADD COLUMN is_custom INTEGER DEFAULT 0')
c.commit()
except Exception: pass
c.execute('''
INSERT INTO client_names(mac, name, last_ip, last_seen, is_custom)
VALUES(?, ?, "Non attribuée", ?, 1)
ON CONFLICT(mac) DO UPDATE SET name=excluded.name, is_custom=1
''', (mac, new_name, time.strftime('%Y-%m-%d %H:%M:%S')))
# Mettre à jour rétroactivement les logs de cet appareil
c.execute('''
UPDATE connection_logs
SET name = ?
WHERE UPPER(mac) = ?
''', (new_name, mac))
c.commit(); c.close()
self.send_json({'ok': True, 'message': 'Appareil renommé avec succès'}); return
station_live_names[mac] = new_name
_device_name_cache[mac] = (new_name, time.time() + 86400)
log('appareil_renomme', f"{username(self) or 'admin'} -> {new_name}", request_ip(self), mac)
self.send_json({'ok': True, 'message': 'Appareil renommé avec succès', 'name': new_name}); return
if self.path == '/api/devices/set_type':
mac = str(data.get('mac', '')).strip().upper()
dev_type = str(data.get('device_type', '')).strip().lower()
+17 -3
View File
@@ -9409,7 +9409,7 @@ ${vpnBadgeTopo}
const nameLabel = String(c.name || t('name_unknown', 'Nom non communiqué')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
const blockBtnLabel = c.blocked ? t('btn_unblock', 'Débloquer') : t('btn_block', 'Bloquer');
const quotaBtnLabel = '⚖️ ' + t('btn_quota', 'Quota');
return `<tr><td><div class="client"><div class="avatar">${String(c.name || '?')[0].toUpperCase()}</div><strong>${nameLabel}</strong></div></td><td>${ipLabel}</td><td>${c.mac || '—'}</td><td>${vpnHtml}</td><td>${signalQuality(c.signal_dbm, c)}</td><td>${speedHtml}</td><td><div style="display:inline-flex;gap:4px;align-items:center"><button class="secondary" type="button" style="padding:4px 8px;font-size:11px" onclick="openDeviceLimitsModal('${c.mac}')" title="${t('modal_limits_title', 'Gérer le quota et la limitation de débit')}">${quotaBtnLabel}</button><button class="secondary" type="button" onclick="toggleBlock('${c.mac}',${!c.blocked})">${blockBtnLabel}</button></div></td></tr>`;
return `<tr><td><div class="client"><div class="avatar">${String(c.name || '?')[0].toUpperCase()}</div><div style="display:flex;align-items:center;gap:6px"><strong>${nameLabel}</strong><button class="secondary" type="button" style="padding:2px 5px;font-size:11px;line-height:1;border-radius:4px" onclick="renameDevice('${c.mac}')" title="${t('rename_device_attr', 'Renommer cet appareil')}">✏️</button></div></div></td><td>${ipLabel}</td><td>${c.mac || '—'}</td><td>${vpnHtml}</td><td>${signalQuality(c.signal_dbm, c)}</td><td>${speedHtml}</td><td><div style="display:inline-flex;gap:4px;align-items:center"><button class="secondary" type="button" style="padding:4px 8px;font-size:11px" onclick="openDeviceLimitsModal('${c.mac}')" title="${t('modal_limits_title', 'Gérer le quota et la limitation de débit')}">${quotaBtnLabel}</button><button class="secondary" type="button" onclick="toggleBlock('${c.mac}',${!c.blocked})">${blockBtnLabel}</button></div></td></tr>`;
}).join('') : `<tr><td colspan="7" class="empty">${t('no_clients', 'Aucun client connecté')}</td></tr>`;
renderPagination('clientsPagination', clientsPage, clients.length, 'changeClientsPage', 10);
@@ -9775,7 +9775,10 @@ ${vpnBadgeTopo}
};
async function renameDevice(mac) {
const dev = devicesDataCache.find(d => d.mac.toUpperCase() === mac.toUpperCase());
if (!mac) return;
const mUpper = mac.toUpperCase();
const dev = ((typeof devicesDataCache !== 'undefined' && Array.isArray(devicesDataCache)) ? devicesDataCache.find(d => d.mac && d.mac.toUpperCase() === mUpper) : null) ||
((typeof clients !== 'undefined' && Array.isArray(clients)) ? clients.find(c => c.mac && c.mac.toUpperCase() === mUpper) : null);
const currentName = dev ? dev.name : '';
const newName = prompt(t('prompt_device_name', "Entrez un nom personnalisé pour cet appareil :"), currentName || "");
if (newName === null) return;
@@ -9785,10 +9788,21 @@ ${vpnBadgeTopo}
const res = await apiFetch('/api/devices/rename', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mac, name: trimmed })
body: JSON.stringify({ mac: mUpper, name: trimmed })
});
const d = await res.json();
if (!res.ok) throw new Error(d.error || 'Erreur lors du renommage');
// Mise à jour immédiate des caches pour un retour visuel instantané
if (typeof devicesDataCache !== 'undefined' && Array.isArray(devicesDataCache)) {
const dItem = devicesDataCache.find(x => x.mac && x.mac.toUpperCase() === mUpper);
if (dItem) dItem.name = trimmed;
}
if (typeof clients !== 'undefined' && Array.isArray(clients)) {
const cItem = clients.find(x => x.mac && x.mac.toUpperCase() === mUpper);
if (cItem) cItem.name = trimmed;
}
renderDevicesTable();
render();
await loadDevices();
await load();
} catch (e) {
+1 -1
View File
@@ -1,5 +1,5 @@
{
"version": "V5.5",
"commit": "2fb1b7fb3c17f7355cf58c18d6890597797c2191",
"build_date": "2026-11-22T20:30:00Z"
"build_date": "2026-11-22T20:45:00Z"
}