AP manageur V1.2 (Bêta)
This commit is contained in:
1 parent
c48d5beae0
commit
188497ae79
7 files changed
+604
-75
No files matched your search
@@ -8858,6 +8858,29 @@ def fetch_iconify_svg(clean_name, color=None):
|
||||
short_label = (name.split('-')[0] if '-' in name else name)[:6].upper()
|
||||
return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1.15em" height="1.15em" fill="none" stroke="{fallback_color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="4"/><text x="12" y="16" font-size="9" text-anchor="middle" fill="{fallback_color}" stroke="none" font-weight="bold">{short_label}</text></svg>'
|
||||
|
||||
_restore_data_lock = threading.Lock()
|
||||
_restore_data_state = {
|
||||
'running': False,
|
||||
'step': 0,
|
||||
'total_steps': 5,
|
||||
'percent': 0,
|
||||
'message': '',
|
||||
'details': '',
|
||||
'done': False,
|
||||
'error': None
|
||||
}
|
||||
|
||||
def _set_restore_progress(step, total_steps, percent, message, details='', done=False, error=None):
|
||||
with _restore_data_lock:
|
||||
_restore_data_state['running'] = not done and error is None
|
||||
_restore_data_state['step'] = step
|
||||
_restore_data_state['total_steps'] = total_steps
|
||||
_restore_data_state['percent'] = percent
|
||||
_restore_data_state['message'] = message
|
||||
_restore_data_state['details'] = details
|
||||
_restore_data_state['done'] = done
|
||||
_restore_data_state['error'] = error
|
||||
|
||||
|
||||
def export_backup_data():
|
||||
c = db()
|
||||
@@ -8998,6 +9021,9 @@ def import_backup_data(payload, options=None):
|
||||
ensure_vpn_dirs()
|
||||
c = db()
|
||||
try:
|
||||
_set_restore_progress(2, 5, 40, "Restauration des réglages & préférences...", "Application des réglages système et des catégories...")
|
||||
time.sleep(0.35)
|
||||
|
||||
# 1. Catégories d'appareils
|
||||
if restore_categories and 'custom_device_types' in backup and isinstance(backup['custom_device_types'], list):
|
||||
for dt in backup['custom_device_types']:
|
||||
@@ -9019,6 +9045,9 @@ def import_backup_data(payload, options=None):
|
||||
''', (dt_id, label, icon, desc, order))
|
||||
stats['custom_device_types'] += 1
|
||||
|
||||
_set_restore_progress(3, 5, 65, "Restauration des équipements & quotas...", "Enregistrement des appareils et quotas réseau...")
|
||||
time.sleep(0.35)
|
||||
|
||||
# 2. Noms d'appareils & types
|
||||
if restore_devices and 'client_names' in backup and isinstance(backup['client_names'], list):
|
||||
for cn in backup['client_names']:
|
||||
@@ -9081,6 +9110,9 @@ def import_backup_data(payload, options=None):
|
||||
c.execute("INSERT INTO preferences(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (str(k), str(v)))
|
||||
stats['preferences'] += 1
|
||||
|
||||
_set_restore_progress(4, 5, 85, "Restauration des profils VPN & routages...", "Configuration des tunnels et assignation du trafic...")
|
||||
time.sleep(0.35)
|
||||
|
||||
# 5. Profils VPN et routage
|
||||
if restore_vpn and 'vpn_profiles' in backup and isinstance(backup['vpn_profiles'], list):
|
||||
profile_id_map = {}
|
||||
@@ -9234,6 +9266,8 @@ def import_backup_data(payload, options=None):
|
||||
stats['api_keys'] = stats.get('api_keys', 0) + 1
|
||||
|
||||
c.commit()
|
||||
_set_restore_progress(5, 5, 95, "Reconfiguration Wi-Fi & synchronisation...", "Finalisation de la configuration réseau...")
|
||||
time.sleep(0.35)
|
||||
finally:
|
||||
c.close()
|
||||
return stats
|
||||
@@ -10646,6 +10680,7 @@ def _download_sftp(cfg, remote_filename, dest_path):
|
||||
password = str(cfg.get('password', ''))
|
||||
key_text = str(cfg.get('key', '')).strip()
|
||||
import paramiko
|
||||
import io
|
||||
ssh = paramiko.SSHClient()
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
pkey = None
|
||||
@@ -10655,13 +10690,20 @@ def _download_sftp(cfg, remote_filename, dest_path):
|
||||
pkey = pkey_class.from_private_key(io.StringIO(key_text))
|
||||
break
|
||||
except Exception: pass
|
||||
sftp = None
|
||||
try:
|
||||
connect_kwargs = {'hostname': host, 'port': port, 'username': user, 'timeout': 20}
|
||||
if pkey: connect_kwargs['pkey'] = pkey
|
||||
elif password: connect_kwargs['password'] = password
|
||||
ssh.connect(**connect_kwargs)
|
||||
sftp = ssh.open_sftp()
|
||||
_, target_file = _normalize_sftp_target(sftp, cfg.get('path', ''), remote_filename)
|
||||
sftp.get(target_file, dest_path)
|
||||
return True
|
||||
finally:
|
||||
try: sftp.close()
|
||||
except Exception: pass
|
||||
if sftp:
|
||||
try: sftp.close()
|
||||
except Exception: pass
|
||||
try: ssh.close()
|
||||
except Exception: pass
|
||||
|
||||
@@ -11287,7 +11329,21 @@ API_MSG_I18N = {
|
||||
'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'}
|
||||
'Réinitialisation en cours': {'en-us': 'Reset in progress', 'en-gb': 'Reset in progress'},
|
||||
'Analyse et vérification de la sauvegarde...': {'en-us': 'Analyzing and verifying backup...', 'en-gb': 'Analyzing and verifying backup...'},
|
||||
'Inspection du fichier et validation du format...': {'en-us': 'Inspecting file and validating format...', 'en-gb': 'Inspecting file and validating format...'},
|
||||
'Restauration des réglages & préférences...': {'en-us': 'Restoring settings & preferences...', 'en-gb': 'Restoring settings & preferences...'},
|
||||
'Application des réglages système et des catégories...': {'en-us': 'Applying system settings and categories...', 'en-gb': 'Applying system settings and categories...'},
|
||||
'Restauration des équipements & quotas...': {'en-us': 'Restoring devices & quotas...', 'en-gb': 'Restoring devices & quotas...'},
|
||||
'Enregistrement des appareils et quotas réseau...': {'en-us': 'Registering devices and network quotas...', 'en-gb': 'Registering devices and network quotas...'},
|
||||
'Restauration des profils VPN & routages...': {'en-us': 'Restoring VPN profiles & routing...', 'en-gb': 'Restoring VPN profiles & routing...'},
|
||||
'Configuration des tunnels et assignation du trafic...': {'en-us': 'Configuring tunnels and assigning traffic...', 'en-gb': 'Configuring tunnels and assigning traffic...'},
|
||||
'Reconfiguration Wi-Fi & synchronisation...': {'en-us': 'Wi-Fi reconfiguration & synchronization...', 'en-gb': 'Wi-Fi reconfiguration & synchronization...'},
|
||||
'Finalisation de la configuration réseau...': {'en-us': 'Finalizing network configuration...', 'en-gb': 'Finalizing network configuration...'},
|
||||
'Sauvegarde restaurée avec succès !': {'en-us': 'Backup restored successfully!', 'en-gb': 'Backup restored successfully!'},
|
||||
'Redirection et synchronisation finale...': {'en-us': 'Redirecting and final synchronization...', 'en-gb': 'Redirecting and final synchronization...'},
|
||||
'Restauration déjà en cours': {'en-us': 'Restoration already in progress', 'en-gb': 'Restoration already in progress'},
|
||||
'Restauration en cours': {'en-us': 'Restoration in progress', 'en-gb': 'Restoration in progress'}
|
||||
}
|
||||
|
||||
def translate_api_text(text, lang='fr'):
|
||||
@@ -11543,6 +11599,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
with _clear_data_lock:
|
||||
self.send_json(dict(_clear_data_state))
|
||||
return
|
||||
if self.path == '/api/backup/restore/progress':
|
||||
with _restore_data_lock:
|
||||
self.send_json(dict(_restore_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()
|
||||
@@ -12436,6 +12496,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
was_active = False
|
||||
try: was_active = bool(status(force_refresh=True).get('active'))
|
||||
except Exception: pass
|
||||
|
||||
_set_restore_progress(1, 5, 20, "Analyse et vérification de la sauvegarde...", "Inspection du fichier et validation du format...")
|
||||
time.sleep(0.35)
|
||||
|
||||
if 'data_base64' in data and data['data_base64']:
|
||||
raw_bytes = base64.b64decode(data['data_base64'])
|
||||
backup = inspect_backup_bytes(raw_bytes, data.get('filename', ''))
|
||||
@@ -12443,6 +12507,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
elif 'filename' in data and data['filename'] and not data.get('backup'):
|
||||
full_path, clean_name = safe_backup_filepath(data['filename'])
|
||||
if not os.path.isfile(full_path):
|
||||
_set_restore_progress(1, 5, 20, "Fichier introuvable", error="Fichier de sauvegarde introuvable", done=True)
|
||||
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
|
||||
with open(full_path, 'rb') as f_read:
|
||||
raw_bytes = f_read.read()
|
||||
@@ -12454,12 +12519,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if not was_active and stats.get('preferences', 0) > 0 and get_pref('ap_ssid', '') and get_pref('ap_password', ''):
|
||||
threading.Thread(target=restore_ap_from_db, daemon=True).start()
|
||||
log('import_configuration_complete', username(self) or 'Administrateur', request_ip(self), 'BACKUP')
|
||||
_set_restore_progress(5, 5, 100, "Sauvegarde restaurée avec succès !", "Redirection et synchronisation finale...", done=True)
|
||||
self.send_json({
|
||||
'ok': True,
|
||||
'message': f"Sauvegarde restaurée avec succès ({stats.get('vpn_profiles',0)} profils VPN, {stats.get('client_names',0)} appareils, {stats.get('preferences',0)} réglages restaurés).",
|
||||
'stats': stats
|
||||
})
|
||||
except Exception as e:
|
||||
_set_restore_progress(5, 5, 100, f"Erreur : {e}", error=str(e), done=True)
|
||||
self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400)
|
||||
return
|
||||
if self.path == '/api/backups/remote/test':
|
||||
@@ -12920,17 +12987,25 @@ class Handler(BaseHTTPRequestHandler):
|
||||
fname = str(data.get('filename', '')).strip()
|
||||
full_path, clean_name = safe_backup_filepath(fname)
|
||||
if not os.path.isfile(full_path):
|
||||
_set_restore_progress(1, 5, 20, "Fichier introuvable", error="Fichier de sauvegarde introuvable", done=True)
|
||||
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
|
||||
raw_bytes = open(full_path, 'rb').read()
|
||||
backup = inspect_backup_bytes(raw_bytes, clean_name)
|
||||
stats = import_backup_data(backup, data.get('options', {}))
|
||||
invalidate_status_cache()
|
||||
log('import_configuration_complete', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
|
||||
self.send_json({
|
||||
'ok': True,
|
||||
'message': f"Sauvegarde « {clean_name} » restaurée avec succès ({stats.get('vpn_profiles',0)} profils VPN, {stats.get('client_names',0)} appareils, {stats.get('preferences',0)} réglages).",
|
||||
'stats': stats
|
||||
}); return
|
||||
try:
|
||||
_set_restore_progress(1, 5, 20, "Analyse et vérification de la sauvegarde...", f"Chargement de {clean_name}...")
|
||||
time.sleep(0.35)
|
||||
raw_bytes = open(full_path, 'rb').read()
|
||||
backup = inspect_backup_bytes(raw_bytes, clean_name)
|
||||
stats = import_backup_data(backup, data.get('options', {}))
|
||||
invalidate_status_cache()
|
||||
log('import_configuration_complete', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
|
||||
_set_restore_progress(5, 5, 100, "Sauvegarde restaurée avec succès !", "Redirection et synchronisation finale...", done=True)
|
||||
self.send_json({
|
||||
'ok': True,
|
||||
'message': f"Sauvegarde « {clean_name} » restaurée avec succès ({stats.get('vpn_profiles',0)} profils VPN, {stats.get('client_names',0)} appareils, {stats.get('preferences',0)} réglages).",
|
||||
'stats': stats
|
||||
}); return
|
||||
except Exception as e:
|
||||
_set_restore_progress(5, 5, 100, f"Erreur : {e}", error=str(e), done=True)
|
||||
self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400); return
|
||||
if self.path == '/api/backups/remote':
|
||||
rcfg = save_backup_remote_config(data)
|
||||
log('configuration_stockage_distant', f"{username(self) or 'Administrateur'} ({rcfg.get('provider', '')})", request_ip(self), 'BACKUP')
|
||||
|
||||
Reference in new issue
Block a user