APmanageur Wi-Fi V1.0
This commit is contained in:
1 parent
ff54694291
commit
6f353a5ff5
3 files changed
+115
-34
No files matched your search
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user