AP manageur V1.2 (Bêta)

This commit is contained in:
yoannmultigaming committed 2026-11-23 01:24:08 +01:00
1 parent e2eaea4b46
commit 165a06be22
6 files changed
+958 -54

No files matched your search

+102 -42
View File
@@ -10755,7 +10755,7 @@ def download_remote_file(remote_filename, dest_path, custom_cfg=None):
def list_remote_files_detailed(custom_cfg=None): def list_remote_files_detailed(custom_cfg=None):
cfg = custom_cfg or get_backup_remote_config() cfg = custom_cfg or get_backup_remote_config()
if not cfg.get('enabled'): if not cfg.get('enabled') and not custom_cfg:
return None, "Stockage distant désactivé" return None, "Stockage distant désactivé"
provider = str(cfg.get('provider', 'ftp')).strip().lower() provider = str(cfg.get('provider', 'ftp')).strip().lower()
p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {} p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {}
@@ -11493,7 +11493,7 @@ class Handler(BaseHTTPRequestHandler):
except Exception as e: except Exception as e:
self.send_json({'error': f'Erreur génération archive ZIP: {e}'}, 500); return self.send_json({'error': f'Erreur génération archive ZIP: {e}'}, 500); return
if self.path.startswith('/api/backups/list'): if self.path.startswith('/api/backups/list'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
parsed = urllib.parse.urlparse(self.path) parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query) qs = urllib.parse.parse_qs(parsed.query)
if qs.get('sync_remote', ['0'])[0] in ('1', 'true'): if qs.get('sync_remote', ['0'])[0] in ('1', 'true'):
@@ -11513,10 +11513,10 @@ class Handler(BaseHTTPRequestHandler):
'total_size_str': format_bytes(total_size) 'total_size_str': format_bytes(total_size)
}); return }); return
if self.path == '/api/backups/remote': if self.path == '/api/backups/remote':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
self.send_json({'ok': True, 'remote': get_backup_remote_config()}); return self.send_json({'ok': True, 'remote': get_backup_remote_config()}); return
if self.path.startswith('/api/backups/remote/files'): if self.path.startswith('/api/backups/remote/files'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
rcfg = get_backup_remote_config() rcfg = get_backup_remote_config()
if not rcfg.get('enabled'): if not rcfg.get('enabled'):
self.send_json({'ok': False, 'error': "Le stockage distant n'est pas activé. Activez-le dans les réglages de sauvegarde.", 'enabled': False}, 400); return self.send_json({'ok': False, 'error': "Le stockage distant n'est pas activé. Activez-le dans les réglages de sauvegarde.", 'enabled': False}, 400); return
@@ -12249,15 +12249,27 @@ class Handler(BaseHTTPRequestHandler):
raw_json = data.get('backup') raw_json = data.get('backup')
if raw_json and isinstance(raw_json, dict): if raw_json and isinstance(raw_json, dict):
self.send_json({'ok': True, 'filename': fname, 'backup': raw_json}); return self.send_json({'ok': True, 'filename': fname, 'backup': raw_json}); return
if not b64_content: if b64_content:
self.send_json({'error': 'Contenu du fichier manquant'}, 400); return try:
try: raw_bytes = base64.b64decode(b64_content)
raw_bytes = base64.b64decode(b64_content) backup = inspect_backup_bytes(raw_bytes, fname)
backup = inspect_backup_bytes(raw_bytes, fname) self.send_json({'ok': True, 'filename': fname, 'backup': backup})
self.send_json({'ok': True, 'filename': fname, 'backup': backup}) except Exception as e:
except Exception as e: self.send_json({'error': f'Impossible d’analyser le fichier : {e}'}, 400)
self.send_json({'error': f'Impossible d’analyser le fichier : {e}'}, 400) return
return if fname:
full_path, clean_name = safe_backup_filepath(fname)
if os.path.isfile(full_path):
try:
with open(full_path, 'rb') as f_read:
raw_bytes = f_read.read()
backup = inspect_backup_bytes(raw_bytes, clean_name)
sz = os.path.getsize(full_path)
self.send_json({'ok': True, 'filename': clean_name, 'size': sz, 'backup': backup})
return
except Exception as e:
self.send_json({'error': f'Impossible d’analyser le fichier local : {e}'}, 400); return
self.send_json({'error': 'Contenu du fichier manquant ou fichier local introuvable'}, 400); return
if self.path == '/api/backup/import': if self.path == '/api/backup/import':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
try: try:
@@ -12268,6 +12280,14 @@ class Handler(BaseHTTPRequestHandler):
raw_bytes = base64.b64decode(data['data_base64']) raw_bytes = base64.b64decode(data['data_base64'])
backup = inspect_backup_bytes(raw_bytes, data.get('filename', '')) backup = inspect_backup_bytes(raw_bytes, data.get('filename', ''))
stats = import_backup_data(backup, data.get('options', {})) stats = import_backup_data(backup, data.get('options', {}))
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):
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
with open(full_path, 'rb') as f_read:
raw_bytes = f_read.read()
backup = inspect_backup_bytes(raw_bytes, clean_name)
stats = import_backup_data(backup, data.get('options', {}))
else: else:
stats = import_backup_data(data) stats = import_backup_data(data)
invalidate_status_cache() invalidate_status_cache()
@@ -12282,6 +12302,75 @@ class Handler(BaseHTTPRequestHandler):
except Exception as e: except Exception as e:
self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400) self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400)
return return
if self.path == '/api/backups/remote/test':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
custom_cfg = data.get('config') if isinstance(data, dict) and 'config' in data else None
try:
ok, msg = test_backup_remote(custom_cfg)
self.send_json({'ok': ok, 'message': msg}); return
except Exception as e:
self.send_json({'ok': False, 'error': str(e)}, 500); return
if self.path == '/api/backups/remote/files':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
custom_cfg = data.get('config') if (isinstance(data, dict) and data.get('config')) else None
rcfg = custom_cfg or get_backup_remote_config()
if not rcfg.get('enabled') and not custom_cfg:
self.send_json({'ok': False, 'error': "Le stockage distant n'est pas activé.", 'enabled': False}, 400); return
provider = str(rcfg.get('provider', 'ftp')).strip().lower()
try:
items, err = list_remote_files_detailed(rcfg)
if items is None:
self.send_json({'ok': False, 'error': err or f"Impossible de contacter le stockage distant ({provider.upper()})", 'provider': provider}, 500); return
prov_names = {'gdrive': 'Google Drive', 'dropbox': 'Dropbox', 'sftp': 'SFTP', 'ftp': 'FTP', 'webdav': 'WebDAV', 's3': 'S3', 'webhook': 'Webhook'}
self.send_json({
'ok': True,
'enabled': True,
'provider': provider,
'provider_name': prov_names.get(provider, provider.upper()),
'files': items,
'count': len(items)
}); return
except Exception as e:
self.send_json({'ok': False, 'error': f"Erreur lors de la lecture des fichiers distants : {e}"}, 500); return
if self.path == '/api/backups/remote/file/pull':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
fname = str(data.get('filename', '')).strip()
if not fname or not fname.lower().endswith(BACKUP_ALLOWED_EXTS):
self.send_json({'error': 'Nom de fichier invalide'}, 400); return
clean_name = os.path.basename(fname)
custom_cfg = data.get('config') if isinstance(data, dict) and 'config' in data else None
ensure_backup_dir()
full_path = os.path.join(BACKUP_DIR, clean_name)
tmp_dest = full_path + '.download.tmp'
try:
download_remote_file(clean_name, tmp_dest, custom_cfg=custom_cfg)
os.replace(tmp_dest, full_path)
try:
sync_remote_backups_presence(force=True)
except Exception:
pass
log('recuperation_sauvegarde_distante', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
backup_data = None
try:
with open(full_path, 'rb') as f_read:
backup_data = inspect_backup_bytes(f_read.read(), clean_name)
except Exception as e_insp:
print(f"[ap-backup] Avertissement inspection pull : {e_insp}", flush=True)
file_size = os.path.getsize(full_path) if os.path.exists(full_path) else 0
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'message': f"Sauvegarde « {clean_name} » importée avec succès !",
'filename': clean_name,
'size': file_size,
'backup': backup_data,
'backups': items
}); return
except Exception as e:
if os.path.exists(tmp_dest):
try: os.unlink(tmp_dest)
except OSError: pass
self.send_json({'error': f"Échec récupération sauvegarde : {e}"}, 500); return
if self.path == '/api/vpn/profiles': if self.path == '/api/vpn/profiles':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
pid = create_or_update_vpn_profile(data) pid = create_or_update_vpn_profile(data)
@@ -12729,10 +12818,6 @@ class Handler(BaseHTTPRequestHandler):
rcfg = save_backup_remote_config(data) rcfg = save_backup_remote_config(data)
log('configuration_stockage_distant', f"{username(self) or 'Administrateur'} ({rcfg.get('provider', '')})", request_ip(self), 'BACKUP') log('configuration_stockage_distant', f"{username(self) or 'Administrateur'} ({rcfg.get('provider', '')})", request_ip(self), 'BACKUP')
self.send_json({'ok': True, 'message': 'Configuration du stockage distant enregistrée avec succès', 'remote': rcfg}); return self.send_json({'ok': True, 'message': 'Configuration du stockage distant enregistrée avec succès', 'remote': rcfg}); return
if self.path == '/api/backups/remote/test':
custom_cfg = data.get('config') if isinstance(data, dict) and 'config' in data else None
ok, msg = test_backup_remote(custom_cfg)
self.send_json({'ok': True, 'message': msg}); return
if self.path == '/api/backups/remote/upload': if self.path == '/api/backups/remote/upload':
fname = str(data.get('filename', '')).strip() fname = str(data.get('filename', '')).strip()
full_path, clean_name = safe_backup_filepath(fname) full_path, clean_name = safe_backup_filepath(fname)
@@ -12747,31 +12832,6 @@ class Handler(BaseHTTPRequestHandler):
log('televersement_distant_manuel', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP') log('televersement_distant_manuel', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
items, total_size = list_server_backups() items, total_size = list_server_backups()
self.send_json({'ok': True, 'message': msg, 'remote': get_backup_remote_config(), 'backups': items}); return self.send_json({'ok': True, 'message': msg, 'remote': get_backup_remote_config(), 'backups': items}); return
if self.path == '/api/backups/remote/file/pull':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
fname = str(data.get('filename', '')).strip()
if not fname or not fname.lower().endswith(BACKUP_ALLOWED_EXTS):
self.send_json({'error': 'Nom de fichier invalide'}, 400); return
clean_name = os.path.basename(fname)
ensure_backup_dir()
full_path = os.path.join(BACKUP_DIR, clean_name)
tmp_dest = full_path + '.download.tmp'
try:
download_remote_file(clean_name, tmp_dest)
os.replace(tmp_dest, full_path)
sync_remote_backups_presence(force=True)
log('recuperation_sauvegarde_distante', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'message': f"Sauvegarde « {clean_name} » importée localement avec succès !",
'backups': items
}); return
except Exception as e:
if os.path.exists(tmp_dest):
try: os.unlink(tmp_dest)
except OSError: pass
self.send_json({'error': f"Échec récupération sauvegarde : {e}"}, 500); return
if self.path == '/api/backups/remote/file/delete': if self.path == '/api/backups/remote/file/delete':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
fname = str(data.get('filename', '')).strip() fname = str(data.get('filename', '')).strip()
+21 -1
View File
@@ -1368,5 +1368,25 @@ window.I18N['en-gb'] = {
"apikey_delete_confirm": "Are you sure you want to permanently delete the API key « {name} » ?\\nAll services using it will lose access.", "apikey_delete_confirm": "Are you sure you want to permanently delete the API key « {name} » ?\\nAll services using it will lose access.",
"log_cle_api_creee": "⚡ API Key created", "log_cle_api_creee": "⚡ API Key created",
"log_cle_api_modifiee": "⚡ API Key modified", "log_cle_api_modifiee": "⚡ API Key modified",
"log_cle_api_supprimee": "🗑️ API Key deleted" "log_cle_api_supprimee": "🗑️ API Key deleted",
"setup_detected_backups_title": "Existing Backups Detected",
"setup_detected_backups_desc": "Backups were found on the server. You can restore your configuration right away.",
"btn_view_detected_backups": "View Backups",
"modal_picker_title": "Import Backup",
"modal_picker_sub": "Restore settings, VPN profiles and devices from the server, your PC or the Cloud",
"tab_server_backups": "Server Backups",
"tab_cloud_backups": "Cloud Services",
"tab_local_file": "Local File (PC)",
"server_backups_list_title": "Files found on server",
"server_backups_dir_hint": "Storage location: /app/backups/",
"server_backups_loading": "Searching for backups on the server…",
"server_backups_none": "No backups found on server.",
"cloud_setup_desc": "Connect directly to your remote storage (Google Drive, Dropbox, SFTP, FTP, WebDAV or S3) to browse and import your backups without your PC.",
"btn_test_cloud_connection": "Test Connection",
"btn_explore_cloud_backups": "Browse Cloud Backups",
"cloud_files_found_title": "Backups available on the Cloud:",
"local_file_upload_desc": "Select a backup archive (.zip) or configuration file (.json) previously exported from AP Manageur.",
"dropzone_title": "Click or drag and drop your file here",
"dropzone_hint": "Accepted formats: .zip, .json (max 100 MB)",
"btn_browse_pc": "Browse your files…"
}; };
+21 -1
View File
@@ -1368,5 +1368,25 @@ window.I18N['en-us'] = {
"apikey_delete_confirm": "Are you sure you want to permanently delete the API key « {name} » ?\\nAll services using it will lose access.", "apikey_delete_confirm": "Are you sure you want to permanently delete the API key « {name} » ?\\nAll services using it will lose access.",
"log_cle_api_creee": "⚡ API Key created", "log_cle_api_creee": "⚡ API Key created",
"log_cle_api_modifiee": "⚡ API Key modified", "log_cle_api_modifiee": "⚡ API Key modified",
"log_cle_api_supprimee": "🗑️ API Key deleted" "log_cle_api_supprimee": "🗑️ API Key deleted",
"setup_detected_backups_title": "Existing Backups Detected",
"setup_detected_backups_desc": "Backups were found on the server. You can restore your configuration right away.",
"btn_view_detected_backups": "View Backups",
"modal_picker_title": "Import Backup",
"modal_picker_sub": "Restore settings, VPN profiles and devices from the server, your PC or the Cloud",
"tab_server_backups": "Server Backups",
"tab_cloud_backups": "Cloud Services",
"tab_local_file": "Local File (PC)",
"server_backups_list_title": "Files found on server",
"server_backups_dir_hint": "Storage location: /app/backups/",
"server_backups_loading": "Searching for backups on the server…",
"server_backups_none": "No backups found on server.",
"cloud_setup_desc": "Connect directly to your remote storage (Google Drive, Dropbox, SFTP, FTP, WebDAV or S3) to browse and import your backups without your PC.",
"btn_test_cloud_connection": "Test Connection",
"btn_explore_cloud_backups": "Browse Cloud Backups",
"cloud_files_found_title": "Backups available on the Cloud:",
"local_file_upload_desc": "Select a backup archive (.zip) or configuration file (.json) previously exported from AP Manageur.",
"dropzone_title": "Click or drag and drop your file here",
"dropzone_hint": "Accepted formats: .zip, .json (max 100 MB)",
"btn_browse_pc": "Browse your files…"
}; };
+21 -1
View File
@@ -1368,5 +1368,25 @@ window.I18N['fr'] = {
"apikey_delete_confirm": "Êtes-vous sûr de vouloir supprimer définitivement la clé d’API « {name} » ?\\nTous les services l'utilisant perdront leur accès.", "apikey_delete_confirm": "Êtes-vous sûr de vouloir supprimer définitivement la clé d’API « {name} » ?\\nTous les services l'utilisant perdront leur accès.",
"log_cle_api_creee": "⚡ Clé API créée", "log_cle_api_creee": "⚡ Clé API créée",
"log_cle_api_modifiee": "⚡ Clé API modifiée", "log_cle_api_modifiee": "⚡ Clé API modifiée",
"log_cle_api_supprimee": "🗑️ Clé API supprimée" "log_cle_api_supprimee": "🗑️ Clé API supprimée",
"setup_detected_backups_title": "Sauvegardes existantes détectées",
"setup_detected_backups_desc": "Des sauvegardes ont été trouvées sur le serveur. Vous pouvez restaurer votre configuration immédiatement.",
"btn_view_detected_backups": "Voir les sauvegardes",
"modal_picker_title": "Importer une sauvegarde",
"modal_picker_sub": "Restaurez vos réglages, profils VPN et équipements depuis le serveur, votre PC ou le Cloud",
"tab_server_backups": "Sauvegardes serveur",
"tab_cloud_backups": "Services Cloud",
"tab_local_file": "Fichier local (PC)",
"server_backups_list_title": "Fichiers trouvés sur le serveur",
"server_backups_dir_hint": "Emplacement de stockage : /app/backups/",
"server_backups_loading": "Recherche des sauvegardes sur le serveur…",
"server_backups_none": "Aucune sauvegarde trouvée sur le serveur.",
"cloud_setup_desc": "Connectez-vous directement à votre stockage distant (Google Drive, Dropbox, SFTP, FTP, WebDAV ou S3) pour lister et importer vos sauvegardes sans passer par votre PC.",
"btn_test_cloud_connection": "Tester la connexion",
"btn_explore_cloud_backups": "Explorer les sauvegardes Cloud",
"cloud_files_found_title": "Sauvegardes disponibles sur le Cloud :",
"local_file_upload_desc": "Sélectionnez une archive de sauvegarde (.zip) ou un fichier de configuration (.json) exporté précédemment depuis AP Manageur.",
"dropzone_title": "Cliquez ou glissez-déposez votre fichier ici",
"dropzone_hint": "Formats acceptés : .zip, .json (max 100 Mo)",
"btn_browse_pc": "Parcourir vos fichiers…"
}; };
+791 -7
View File
@@ -478,10 +478,31 @@
} }
#modalSetupVpn > div, #modalSetupVpn > div,
#modalSetupBackup > div { #modalSetupBackup > div,
#modalSetupBackupPicker > div {
animation: modalPop .24s cubic-bezier(0.22, 1, 0.36, 1); animation: modalPop .24s cubic-bezier(0.22, 1, 0.36, 1);
} }
.setup-backup-tab.active {
border-bottom-color: var(--accent) !important;
color: var(--text) !important;
}
.setup-prov-btn {
transition: all .15s ease;
}
.setup-prov-btn:hover {
border-color: var(--accent) !important;
}
.setup-prov-btn.active {
border-color: var(--accent) !important;
background: var(--accent) !important;
color: #fff !important;
}
#setupDropZone:hover {
border-color: var(--accent) !important;
background: var(--panel3) !important;
}
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.step-panel, .step-panel,
.step-panel.slide-prev, .step-panel.slide-prev,
@@ -491,7 +512,8 @@
.field-reveal, .field-reveal,
.err-shake, .err-shake,
#modalSetupVpn > div, #modalSetupVpn > div,
#modalSetupBackup > div { #modalSetupBackup > div,
#modalSetupBackupPicker > div {
animation: none !important; animation: none !important;
} }
@@ -1214,6 +1236,22 @@
</div> </div>
</div> </div>
<!-- Bannière de détection de sauvegardes existantes -->
<div id="setupDetectedBackupsBanner"
style="display:none;margin-top:16px;padding:14px 16px;background:rgba(92,167,255,0.08);border:1px solid rgba(92,167,255,0.28);border-radius:10px;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
<div style="display:flex;align-items:center;gap:12px">
<span style="font-size:24px">💾</span>
<div>
<div style="font-weight:700;font-size:14px" id="setupDetectedBackupsTitle" data-i18n="setup_detected_backups_title">Sauvegardes existantes détectées</div>
<div class="muted" style="font-size:12px;margin-top:2px" id="setupDetectedBackupsDesc" data-i18n="setup_detected_backups_desc">Des sauvegardes ont été trouvées sur le serveur. Vous pouvez restaurer votre configuration immédiatement.</div>
</div>
</div>
<button type="button" onclick="openSetupBackupPickerModal('server')"
style="display:inline-flex;align-items:center;gap:6px;padding:7px 14px;font-size:13px;white-space:nowrap">
<span>📂</span> <span data-i18n="btn_view_detected_backups">Voir les sauvegardes</span>
</button>
</div>
<!-- Input masqué pour importer une sauvegarde --> <!-- Input masqué pour importer une sauvegarde -->
<input type="file" id="setupBackupFileInput" accept=".json,.zip,.sqlite,.sqlite3" style="display:none" <input type="file" id="setupBackupFileInput" accept=".json,.zip,.sqlite,.sqlite3" style="display:none"
onchange="handleSetupBackupFile(event)"> onchange="handleSetupBackupFile(event)">
@@ -1222,7 +1260,7 @@
<div class="muted" style="font-size:13px" id="step1CounterText" data-i18n="step1_counter">Étape 1 sur 6 <div class="muted" style="font-size:13px" id="step1CounterText" data-i18n="step1_counter">Étape 1 sur 6
</div> </div>
<div class="step-actions-right"> <div class="step-actions-right">
<button type="button" class="secondary" onclick="triggerBackupUpload()" <button type="button" class="secondary" onclick="openSetupBackupPickerModal()"
style="display:flex;align-items:center;gap:6px"> style="display:flex;align-items:center;gap:6px">
<span>📦</span> <span data-i18n="btn_import_backup">Importer une sauvegarde</span> <span>📦</span> <span data-i18n="btn_import_backup">Importer une sauvegarde</span>
</button> </button>
@@ -2388,6 +2426,227 @@
</div> </div>
</div> </div>
<!-- Modal Sélecteur de Sauvegardes (Serveur, Fichier local, Cloud) -->
<div id="modalSetupBackupPicker"
style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.72);backdrop-filter:blur(4px);z-index:9998;align-items:center;justify-content:center;padding:16px">
<div class="card"
style="max-width:760px;width:100%;max-height:92vh;display:flex;flex-direction:column;background:var(--panel);border:1px solid var(--line);box-shadow:0 12px 48px rgba(0,0,0,0.55);border-radius:14px;overflow:hidden;padding:0">
<!-- En-tête -->
<div style="padding:16px 20px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;background:var(--panel2)">
<div style="display:flex;align-items:center;gap:10px">
<span style="font-size:24px">📦</span>
<div>
<h3 style="margin:0;font-size:17px;font-weight:700" data-i18n="modal_picker_title">Importer une sauvegarde</h3>
<p class="muted" style="margin:2px 0 0;font-size:12px" data-i18n="modal_picker_sub">Restaurez vos réglages, profils VPN et équipements depuis le serveur, votre PC ou le Cloud</p>
</div>
</div>
<button type="button" class="secondary" onclick="closeSetupBackupPickerModal()"
style="padding:5px 9px;font-size:14px;line-height:1;border-radius:6px">✕</button>
</div>
<!-- Onglets (Tabs) -->
<div style="display:flex;border-bottom:1px solid var(--line);background:var(--panel2);padding:0 16px;gap:8px;overflow-x:auto">
<button type="button" class="setup-backup-tab active" id="tabBtnServer" onclick="switchSetupBackupTab('server')"
style="display:flex;align-items:center;gap:8px;padding:10px 14px;background:none;border:none;border-bottom:2px solid var(--accent);color:var(--text);font-size:13px;font-weight:600;cursor:pointer;border-radius:0">
<span>💾</span> <span data-i18n="tab_server_backups">Sauvegardes serveur</span>
<span class="pill" id="badgeServerBackupsCount" style="font-size:11px;padding:1px 6px;display:none">0</span>
</button>
<button type="button" class="setup-backup-tab" id="tabBtnCloud" onclick="switchSetupBackupTab('cloud')"
style="display:flex;align-items:center;gap:8px;padding:10px 14px;background:none;border:none;border-bottom:2px solid transparent;color:var(--muted);font-size:13px;font-weight:600;cursor:pointer;border-radius:0">
<span>☁️</span> <span data-i18n="tab_cloud_backups">Services Cloud</span>
</button>
<button type="button" class="setup-backup-tab" id="tabBtnLocal" onclick="switchSetupBackupTab('local')"
style="display:flex;align-items:center;gap:8px;padding:10px 14px;background:none;border:none;border-bottom:2px solid transparent;color:var(--muted);font-size:13px;font-weight:600;cursor:pointer;border-radius:0">
<span>💻</span> <span data-i18n="tab_local_file">Fichier local (PC)</span>
</button>
</div>
<!-- Corps défilable -->
<div style="padding:20px;overflow-y:auto;flex:1">
<!-- ================= Onglet 1 : Sauvegardes Serveur ================= -->
<div id="setupTabContent_server">
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;flex-wrap:wrap;gap:8px">
<div>
<strong style="font-size:14px" data-i18n="server_backups_list_title">Fichiers trouvés sur le serveur</strong>
<div class="muted" style="font-size:12px" data-i18n="server_backups_dir_hint">Emplacement de stockage : /app/backups/</div>
</div>
<button type="button" class="secondary" onclick="loadServerBackupsInSetup(true)" style="display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:5px 10px">
<span>🔄</span> <span data-i18n="btn_refresh">Actualiser</span>
</button>
</div>
<div id="setupServerBackupsList" style="display:flex;flex-direction:column;gap:10px">
<div class="muted" style="text-align:center;padding:24px" data-i18n="server_backups_loading">Recherche des sauvegardes sur le serveur…</div>
</div>
</div>
<!-- ================= Onglet 2 : Services Cloud ================= -->
<div id="setupTabContent_cloud" style="display:none">
<p class="muted" style="font-size:13px;margin:0 0 14px" data-i18n="cloud_setup_desc">
Connectez-vous directement à votre stockage distant (Google Drive, Dropbox, SFTP, FTP, WebDAV ou S3) pour lister et importer vos sauvegardes sans passer par votre PC.
</p>
<!-- Sélecteur de fournisseur cloud avec logos -->
<div id="setupCloudProviderSelector" style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:16px">
<button type="button" class="setup-prov-btn active" data-prov="ftp" onclick="selectSetupCloudProvider('ftp')"
style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer;border:1px solid var(--accent);background:var(--accent);color:#fff">
📡 <span>FTP / FTPS</span>
</button>
<button type="button" class="setup-prov-btn" data-prov="sftp" onclick="selectSetupCloudProvider('sftp')"
style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer;border:1px solid var(--line);background:var(--panel2);color:var(--text)">
🔐 <span>SFTP (SSH)</span>
</button>
<button type="button" class="setup-prov-btn" data-prov="gdrive" onclick="selectSetupCloudProvider('gdrive')"
style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer;border:1px solid var(--line);background:var(--panel2);color:var(--text)">
<img src="/images/gdrive.svg" width="16" height="15" alt="Google Drive" style="object-fit:contain;vertical-align:middle">
<span>Google Drive</span>
</button>
<button type="button" class="setup-prov-btn" data-prov="dropbox" onclick="selectSetupCloudProvider('dropbox')"
style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer;border:1px solid var(--line);background:var(--panel2);color:var(--text)">
<img src="/images/dropbox.svg" width="16" height="16" alt="Dropbox" style="object-fit:contain;vertical-align:middle">
<span>Dropbox</span>
</button>
<button type="button" class="setup-prov-btn" data-prov="webdav" onclick="selectSetupCloudProvider('webdav')"
style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer;border:1px solid var(--line);background:var(--panel2);color:var(--text)">
🌐 <span>WebDAV</span>
</button>
<button type="button" class="setup-prov-btn" data-prov="s3" onclick="selectSetupCloudProvider('s3')"
style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer;border:1px solid var(--line);background:var(--panel2);color:var(--text)">
🪣 <span>S3 / MinIO</span>
</button>
</div>
<input type="hidden" id="setupCloudProvider" value="ftp">
<!-- Formulaire dynamique par fournisseur -->
<div id="setupCloudFieldsBox" style="background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:14px;margin-bottom:14px">
<!-- FTP -->
<div id="setupCloudFields_ftp">
<div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:10px">
<div><label class="label" data-i18n="backup_remote_host">Hôte / IP</label><input id="setupFtpHost" type="text" placeholder="ftp.exemple.fr ou 192.168.1.10"></div>
<div><label class="label" data-i18n="backup_remote_port">Port</label><input id="setupFtpPort" type="number" value="21" min="1" max="65535"></div>
<div>
<label class="label" data-i18n="backup_remote_security">Sécurité</label>
<select id="setupFtpTls">
<option value="none">FTP Standard</option>
<option value="explicit">FTPS (TLS explicite)</option>
</select>
</div>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-top:10px">
<div><label class="label" data-i18n="backup_remote_user">Utilisateur</label><input id="setupFtpUser" type="text" placeholder="backup_user"></div>
<div>
<label class="label" data-i18n="backup_remote_pass">Mot de passe</label>
<input id="setupFtpPass" type="password" placeholder="••••••••" style="margin:0">
</div>
<div><label class="label" data-i18n="backup_remote_path">Dossier distant</label><input id="setupFtpPath" type="text" value="backups/" placeholder="backups/"></div>
</div>
</div>
<!-- SFTP -->
<div id="setupCloudFields_sftp" style="display:none">
<div style="display:grid;grid-template-columns:2fr 1fr 1.5fr;gap:10px">
<div><label class="label" data-i18n="backup_remote_host">Hôte / IP</label><input id="setupSftpHost" type="text" placeholder="nas.exemple.fr ou 192.168.1.10"></div>
<div><label class="label" data-i18n="backup_remote_port">Port</label><input id="setupSftpPort" type="number" value="22" min="1" max="65535"></div>
<div><label class="label" data-i18n="backup_remote_path">Dossier distant</label><input id="setupSftpPath" type="text" value="backups/" placeholder="backups/"></div>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px">
<div><label class="label" data-i18n="backup_remote_user">Utilisateur</label><input id="setupSftpUser" type="text" placeholder="root ou backup"></div>
<div><label class="label" data-i18n="backup_remote_pass">Mot de passe</label><input id="setupSftpPass" type="password" placeholder="••••••••" style="margin:0"></div>
</div>
<div style="margin-top:10px">
<label class="label" data-i18n="backup_remote_ssh_key">Clé privée SSH (facultative)</label>
<textarea id="setupSftpKey" rows="2" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----" style="width:100%;margin-top:4px;padding:8px 10px;background:var(--panel);border:1px solid var(--line);border-radius:8px;color:var(--text);font-family:monospace;font-size:11px;resize:vertical;box-sizing:border-box"></textarea>
</div>
</div>
<!-- Google Drive -->
<div id="setupCloudFields_gdrive" style="display:none">
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
<div><label class="label" data-i18n="backup_remote_token">Jeton d’accès OAuth2 (Access Token)</label><input id="setupGdriveToken" type="password" placeholder="ya29.a0..." style="margin:0"></div>
<div><label class="label" data-i18n="backup_remote_gdrive_folder">ID du dossier (facultatif)</label><input id="setupGdriveFolder" type="text" placeholder="1AbCdEfGh..."></div>
</div>
</div>
<!-- Dropbox -->
<div id="setupCloudFields_dropbox" style="display:none">
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
<div><label class="label" data-i18n="backup_remote_token">Jeton d’accès Dropbox</label><input id="setupDropboxToken" type="password" placeholder="sl.B..." style="margin:0"></div>
<div><label class="label" data-i18n="backup_remote_path">Dossier distant</label><input id="setupDropboxPath" type="text" value="/AP-Manageur-Backups/" placeholder="/AP-Manageur-Backups/"></div>
</div>
</div>
<!-- WebDAV -->
<div id="setupCloudFields_webdav" style="display:none">
<div><label class="label" data-i18n="backup_remote_webdav_url">URL WebDAV</label><input id="setupWebdavUrl" type="url" placeholder="https://cloud.exemple.fr/remote.php/dav/files/user/Backups/"></div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px">
<div><label class="label" data-i18n="backup_remote_user">Utilisateur</label><input id="setupWebdavUser" type="text" placeholder="utilisateur"></div>
<div><label class="label" data-i18n="backup_remote_pass">Mot de passe</label><input id="setupWebdavPass" type="password" placeholder="••••••••" style="margin:0"></div>
</div>
</div>
<!-- S3 / MinIO -->
<div id="setupCloudFields_s3" style="display:none">
<div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:10px">
<div><label class="label" data-i18n="backup_remote_s3_endpoint">Endpoint S3</label><input id="setupS3Endpoint" type="url" value="https://s3.amazonaws.com" placeholder="https://s3.amazonaws.com"></div>
<div><label class="label" data-i18n="backup_remote_s3_region">Région</label><input id="setupS3Region" type="text" value="us-east-1" placeholder="us-east-1"></div>
<div><label class="label" data-i18n="backup_remote_s3_bucket">Bucket</label><input id="setupS3Bucket" type="text" placeholder="ap-backups"></div>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px">
<div><label class="label">Access Key</label><input id="setupS3AccessKey" type="text" placeholder="AKIA..."></div>
<div><label class="label">Secret Key</label><input id="setupS3SecretKey" type="password" placeholder="••••••••" style="margin:0"></div>
</div>
</div>
</div>
<!-- Actions de test et d'exploration cloud -->
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:14px">
<button type="button" class="secondary" id="btnTestSetupCloud" onclick="testSetupCloudConnection()" style="display:inline-flex;align-items:center;gap:6px;font-size:13px">
<span>🧪</span> <span data-i18n="btn_test_cloud_connection">Tester la connexion</span>
</button>
<button type="button" id="btnExploreSetupCloud" onclick="exploreSetupCloudBackups()" style="display:inline-flex;align-items:center;gap:6px;font-size:13px">
<span>🔄</span> <span data-i18n="btn_explore_cloud_backups">Explorer les sauvegardes Cloud</span>
</button>
</div>
<div id="setupCloudMsg" style="display:none;font-size:12px;padding:8px 12px;border-radius:8px;margin-bottom:14px"></div>
<!-- Liste des fichiers Cloud trouvés -->
<div id="setupCloudFilesContainer" style="display:none">
<div style="font-weight:700;font-size:13px;margin-bottom:8px" data-i18n="cloud_files_found_title">Sauvegardes disponibles sur le Cloud :</div>
<div id="setupCloudFilesList" style="display:flex;flex-direction:column;gap:8px"></div>
</div>
</div>
<!-- ================= Onglet 3 : Fichier Local (PC) ================= -->
<div id="setupTabContent_local" style="display:none">
<p class="muted" style="font-size:13px;margin:0 0 16px" data-i18n="local_file_upload_desc">
Sélectionnez une archive de sauvegarde (.zip) ou un fichier de configuration (.json) exporté précédemment depuis AP Manageur.
</p>
<div id="setupDropZone" onclick="triggerBackupUpload()"
style="border:2px dashed var(--line);border-radius:12px;padding:36px 20px;text-align:center;cursor:pointer;background:var(--panel2);transition:all .2s ease">
<div style="font-size:38px;margin-bottom:10px">📁</div>
<div style="font-weight:700;font-size:15px;margin-bottom:4px" data-i18n="dropzone_title">Cliquez ou glissez-déposez votre fichier ici</div>
<div class="muted" style="font-size:12px" data-i18n="dropzone_hint">Formats acceptés : .zip, .json (max 100 Mo)</div>
<button type="button" class="secondary" style="margin-top:14px;pointer-events:none" data-i18n="btn_browse_pc">
Parcourir vos fichiers…
</button>
</div>
</div>
</div>
<!-- Pied de modal -->
<div style="padding:12px 20px;border-top:1px solid var(--line);background:var(--panel2);display:flex;justify-content:flex-end">
<button type="button" class="secondary" onclick="closeSetupBackupPickerModal()" data-i18n="btn_close">Fermer</button>
</div>
</div>
</div>
<!-- Modal Restauration de Sauvegarde --> <!-- Modal Restauration de Sauvegarde -->
<div id="modalSetupBackup" <div id="modalSetupBackup"
style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.72);backdrop-filter:blur(4px);z-index:9999;align-items:center;justify-content:center;padding:16px"> style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.72);backdrop-filter:blur(4px);z-index:9999;align-items:center;justify-content:center;padding:16px">
@@ -2718,7 +2977,30 @@
'modal_vpn_save_btn': 'Ajouter ce profil', 'modal_vpn_save_btn': 'Ajouter ce profil',
'btn_cancel': 'Annuler', 'btn_cancel': 'Annuler',
'toggle_pwd_show': 'Afficher', 'toggle_pwd_show': 'Afficher',
'toggle_pwd_hide': 'Masquer' 'toggle_pwd_hide': 'Masquer',
'setup_detected_backups_title': 'Sauvegardes existantes détectées',
'setup_detected_backups_desc': 'Des sauvegardes ont été trouvées sur le serveur. Vous pouvez restaurer votre configuration immédiatement.',
'btn_view_detected_backups': 'Voir les sauvegardes',
'modal_picker_title': 'Importer une sauvegarde',
'modal_picker_sub': 'Restaurez vos réglages, profils VPN et équipements depuis le serveur, votre PC ou le Cloud',
'tab_server_backups': 'Sauvegardes serveur',
'tab_cloud_backups': 'Services Cloud',
'tab_local_file': 'Fichier local (PC)',
'server_backups_list_title': 'Fichiers trouvés sur le serveur',
'server_backups_dir_hint': 'Emplacement de stockage : /app/backups/',
'server_backups_loading': 'Recherche des sauvegardes sur le serveur…',
'server_backups_none': 'Aucune sauvegarde trouvée sur le serveur.',
'cloud_setup_desc': 'Connectez-vous directement à votre stockage distant (Google Drive, Dropbox, SFTP, FTP, WebDAV ou S3) pour lister et importer vos sauvegardes sans passer par votre PC.',
'btn_test_cloud_connection': 'Tester la connexion',
'btn_explore_cloud_backups': 'Explorer les sauvegardes Cloud',
'cloud_files_found_title': 'Sauvegardes disponibles sur le Cloud :',
'local_file_upload_desc': 'Sélectionnez une archive de sauvegarde (.zip) ou un fichier de configuration (.json) exporté précédemment depuis AP Manageur.',
'dropzone_title': 'Cliquez ou glissez-déposez votre fichier ici',
'dropzone_hint': 'Formats acceptés : .zip, .json (max 100 Mo)',
'btn_browse_pc': 'Parcourir vos fichiers…',
'btn_close': 'Fermer',
'btn_refresh': 'Actualiser'
}, },
'en-us': { 'en-us': {
'page_title': 'Initial Setup - AP Manageur', 'page_title': 'Initial Setup - AP Manageur',
@@ -2855,7 +3137,30 @@
'modal_vpn_save_btn': 'Add this profile', 'modal_vpn_save_btn': 'Add this profile',
'btn_cancel': 'Cancel', 'btn_cancel': 'Cancel',
'toggle_pwd_show': 'Show', 'toggle_pwd_show': 'Show',
'toggle_pwd_hide': 'Hide' 'toggle_pwd_hide': 'Hide',
'setup_detected_backups_title': 'Existing Backups Detected',
'setup_detected_backups_desc': 'Backups were found on the server. You can restore your configuration right away.',
'btn_view_detected_backups': 'View Backups',
'modal_picker_title': 'Import Backup',
'modal_picker_sub': 'Restore settings, VPN profiles and devices from the server, your PC or the Cloud',
'tab_server_backups': 'Server Backups',
'tab_cloud_backups': 'Cloud Services',
'tab_local_file': 'Local File (PC)',
'server_backups_list_title': 'Files found on server',
'server_backups_dir_hint': 'Storage location: /app/backups/',
'server_backups_loading': 'Searching for backups on the server…',
'server_backups_none': 'No backups found on server.',
'cloud_setup_desc': 'Connect directly to your remote storage (Google Drive, Dropbox, SFTP, FTP, WebDAV or S3) to browse and import your backups without your PC.',
'btn_test_cloud_connection': 'Test Connection',
'btn_explore_cloud_backups': 'Browse Cloud Backups',
'cloud_files_found_title': 'Backups available on the Cloud:',
'local_file_upload_desc': 'Select a backup archive (.zip) or configuration file (.json) previously exported from AP Manageur.',
'dropzone_title': 'Click or drag and drop your file here',
'dropzone_hint': 'Accepted formats: .zip, .json (max 100 MB)',
'btn_browse_pc': 'Browse your files…',
'btn_close': 'Close',
'btn_refresh': 'Refresh'
}, },
'en-gb': { 'en-gb': {
'page_title': 'Initial Setup - AP Manageur', 'page_title': 'Initial Setup - AP Manageur',
@@ -2992,7 +3297,30 @@
'modal_vpn_save_btn': 'Add this profile', 'modal_vpn_save_btn': 'Add this profile',
'btn_cancel': 'Cancel', 'btn_cancel': 'Cancel',
'toggle_pwd_show': 'Show', 'toggle_pwd_show': 'Show',
'toggle_pwd_hide': 'Hide' 'toggle_pwd_hide': 'Hide',
'setup_detected_backups_title': 'Existing Backups Detected',
'setup_detected_backups_desc': 'Backups were found on the server. You can restore your configuration right away.',
'btn_view_detected_backups': 'View Backups',
'modal_picker_title': 'Import Backup',
'modal_picker_sub': 'Restore settings, VPN profiles and devices from the server, your PC or the Cloud',
'tab_server_backups': 'Server Backups',
'tab_cloud_backups': 'Cloud Services',
'tab_local_file': 'Local File (PC)',
'server_backups_list_title': 'Files found on server',
'server_backups_dir_hint': 'Storage location: /app/backups/',
'server_backups_loading': 'Searching for backups on the server…',
'server_backups_none': 'No backups found on server.',
'cloud_setup_desc': 'Connect directly to your remote storage (Google Drive, Dropbox, SFTP, FTP, WebDAV or S3) to browse and import your backups without your PC.',
'btn_test_cloud_connection': 'Test Connection',
'btn_explore_cloud_backups': 'Browse Cloud Backups',
'cloud_files_found_title': 'Backups available on the Cloud:',
'local_file_upload_desc': 'Select a backup archive (.zip) or configuration file (.json) previously exported from AP Manageur.',
'dropzone_title': 'Click or drag and drop your file here',
'dropzone_hint': 'Accepted formats: .zip, .json (max 100 MB)',
'btn_browse_pc': 'Browse your files…',
'btn_close': 'Close',
'btn_refresh': 'Refresh'
} }
}; };
@@ -3543,6 +3871,15 @@
}); });
applySetupTranslations(lang); applySetupTranslations(lang);
if (detectedServerBackups && detectedServerBackups.length > 0) {
const desc = $('setupDetectedBackupsDesc');
if (desc) {
const isEn = lang.startsWith('en');
desc.textContent = isEn
? `${detectedServerBackups.length} backup file(s) found on the server. You can restore your configuration right away.`
: `${detectedServerBackups.length} sauvegarde(s) trouvée(s) sur le serveur. Vous pouvez restaurer votre configuration en 1 clic !`;
}
}
} }
/* ============================================================ */ /* ============================================================ */
@@ -3956,8 +4293,453 @@
} }
/* ============================================================ */ /* ============================================================ */
/* GESTION IMPORT DE SAUVEGARDE (BACKUP) */ /* GESTION IMPORT DE SAUVEGARDE (SERVEUR, CLOUD, LOCAL) */
/* ============================================================ */ /* ============================================================ */
let currentSetupBackupTab = 'server';
let detectedServerBackups = [];
function openSetupBackupPickerModal(preferredTab) {
const modal = $('modalSetupBackupPicker');
if (!modal) return;
modal.style.display = 'flex';
switchSetupBackupTab(preferredTab || (detectedServerBackups.length > 0 ? 'server' : 'server'));
loadServerBackupsInSetup();
}
function closeSetupBackupPickerModal() {
const modal = $('modalSetupBackupPicker');
if (modal) modal.style.display = 'none';
}
function switchSetupBackupTab(tab) {
currentSetupBackupTab = tab;
['server', 'cloud', 'local'].forEach(t => {
const btn = $('tabBtn' + t.charAt(0).toUpperCase() + t.slice(1));
const content = $('setupTabContent_' + t);
const isActive = (t === tab);
if (btn) {
btn.classList.toggle('active', isActive);
btn.style.borderBottomColor = isActive ? 'var(--accent)' : 'transparent';
btn.style.color = isActive ? 'var(--text)' : 'var(--muted)';
}
if (content) {
content.style.display = isActive ? 'block' : 'none';
}
});
}
async function checkDetectedServerBackups() {
try {
const res = await fetch(API_URL + '/api/backups/list', { cache: 'no-store' });
if (!res.ok) return;
const d = await res.json();
detectedServerBackups = Array.isArray(d.backups) ? d.backups : [];
const banner = $('setupDetectedBackupsBanner');
const countBadge = $('badgeServerBackupsCount');
if (countBadge) {
countBadge.textContent = detectedServerBackups.length;
countBadge.style.display = detectedServerBackups.length > 0 ? 'inline-block' : 'none';
}
if (banner) {
if (detectedServerBackups.length > 0) {
banner.style.display = 'flex';
const desc = $('setupDetectedBackupsDesc');
if (desc) {
const isEn = currentLanguage.startsWith('en');
desc.textContent = isEn
? `${detectedServerBackups.length} backup file(s) found on the server. You can restore your configuration right away.`
: `${detectedServerBackups.length} sauvegarde(s) trouvée(s) sur le serveur. Vous pouvez restaurer votre configuration en 1 clic !`;
}
} else {
banner.style.display = 'none';
}
}
if (d.remote && typeof d.remote === 'object') {
populateSetupRemoteConfig(d.remote);
}
} catch (err) {
console.warn('Vérification sauvegardes serveur:', err);
}
}
async function loadServerBackupsInSetup(forceSync = false) {
const listEl = $('setupServerBackupsList');
if (!listEl) return;
const isEn = currentLanguage.startsWith('en');
listEl.innerHTML = `<div class="muted" style="text-align:center;padding:24px">${isEn ? 'Searching for backups on the server…' : 'Recherche des sauvegardes sur le serveur…'}</div>`;
try {
const url = API_URL + '/api/backups/list' + (forceSync ? '?sync_remote=1' : '');
const res = await fetch(url, { cache: 'no-store' });
const d = await res.json();
if (!res.ok) throw new Error(d.error || 'Erreur');
detectedServerBackups = Array.isArray(d.backups) ? d.backups : [];
const countBadge = $('badgeServerBackupsCount');
if (countBadge) {
countBadge.textContent = detectedServerBackups.length;
countBadge.style.display = detectedServerBackups.length > 0 ? 'inline-block' : 'none';
}
if (detectedServerBackups.length === 0) {
listEl.innerHTML = `
<div style="text-align:center;padding:32px 16px;background:var(--panel2);border:1px dashed var(--line);border-radius:10px">
<div style="font-size:32px;margin-bottom:8px">📂</div>
<div style="font-weight:700;font-size:14px;margin-bottom:6px">${isEn ? 'No backups found on the server' : 'Aucune sauvegarde trouvée sur le serveur'}</div>
<p class="muted" style="font-size:12px;margin:0 0 14px;max-width:440px;margin-left:auto;margin-right:auto">
${isEn ? 'You can import a backup file (.zip, .json) from your computer, or pull backups directly from your Cloud storage.' : 'Vous pouvez importer un fichier de sauvegarde (.zip, .json) depuis votre ordinateur, ou rapatrier vos sauvegardes directement depuis le Cloud.'}
</p>
<div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">
<button type="button" class="secondary" onclick="switchSetupBackupTab('local')" style="font-size:12px">💻 ${isEn ? 'Browse PC file' : 'Fichier local (PC)'}</button>
<button type="button" class="secondary" onclick="switchSetupBackupTab('cloud')" style="font-size:12px">☁️ ${isEn ? 'Cloud services' : 'Services Cloud'}</button>
</div>
</div>
`;
return;
}
let html = '';
detectedServerBackups.forEach(b => {
const szStr = b.size_str || `${Math.round((b.size || 0) / 1024)} Ko`;
const dtStr = b.created_at || (b.mtime ? new Date(b.mtime * 1000).toLocaleString() : '—');
const isAuto = b.trigger === 'auto';
const trigBadge = isAuto
? `<span class="pill" style="font-size:10px;color:var(--blue);border-color:var(--blue)">🤖 Auto</span>`
: `<span class="pill" style="font-size:10px">👤 Manuel</span>`;
html += `
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:12px 14px;flex-wrap:wrap">
<div style="display:flex;align-items:center;gap:10px;min-width:240px;flex:1">
<span style="font-size:22px">📦</span>
<div>
<div style="font-weight:700;font-size:13px;word-break:break-all">${b.filename}</div>
<div class="muted" style="font-size:11px;margin-top:2px;display:flex;align-items:center;gap:8px;flex-wrap:wrap">
<span>📅 ${dtStr}</span>
<span>💾 ${szStr}</span>
${trigBadge}
</div>
</div>
</div>
<button type="button" onclick="inspectServerBackup('${encodeURIComponent(b.filename)}', ${b.size || 0})"
style="display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:6px 12px;white-space:nowrap;background:var(--accent);color:#fff">
<span>🔍</span> <span>${isEn ? 'Inspect & Restore' : 'Inspecter & Restaurer'}</span>
</button>
</div>
`;
});
listEl.innerHTML = html;
if (d.remote && typeof d.remote === 'object') {
populateSetupRemoteConfig(d.remote);
}
} catch (err) {
listEl.innerHTML = `<div style="color:var(--red);padding:14px;background:rgba(255,107,107,0.1);border-radius:8px;font-size:13px">❌ ${err.message || 'Erreur'}</div>`;
}
}
async function inspectServerBackup(encodedName, fileSize) {
const fileName = decodeURIComponent(encodedName);
try {
const res = await fetch(API_URL + '/api/backup/inspect', {
method: 'POST',
headers: getSetupAuthHeaders(),
body: JSON.stringify({ filename: fileName })
});
const d = await res.json();
if (!res.ok) throw new Error(d.error || 'Erreur d\'analyse de la sauvegarde');
pendingBackupData = d.backup;
closeSetupBackupPickerModal();
showSetupBackupModal(fileName, d.size || fileSize, d.backup);
} catch (err) {
alert('Erreur lors de l\'inspection de la sauvegarde : ' + err.message);
}
}
function selectSetupCloudProvider(prov) {
if ($('setupCloudProvider')) $('setupCloudProvider').value = prov;
document.querySelectorAll('#setupCloudProviderSelector .setup-prov-btn').forEach(btn => {
const isMatch = btn.getAttribute('data-prov') === prov;
btn.classList.toggle('active', isMatch);
btn.style.borderColor = isMatch ? 'var(--accent)' : 'var(--line)';
btn.style.background = isMatch ? 'var(--accent)' : 'var(--panel2)';
btn.style.color = isMatch ? '#fff' : 'var(--text)';
});
['ftp', 'sftp', 'gdrive', 'dropbox', 'webdav', 's3'].forEach(p => {
const box = $('setupCloudFields_' + p);
if (box) box.style.display = (p === prov) ? 'block' : 'none';
});
const msg = $('setupCloudMsg');
if (msg) msg.style.display = 'none';
}
function populateSetupRemoteConfig(remote) {
if (!remote || typeof remote !== 'object') return;
if (remote.provider && $('setupCloudProvider')) {
selectSetupCloudProvider(remote.provider);
}
if (remote.ftp && typeof remote.ftp === 'object') {
if ($('setupFtpHost')) $('setupFtpHost').value = remote.ftp.host || '';
if ($('setupFtpPort')) $('setupFtpPort').value = remote.ftp.port || 21;
if ($('setupFtpTls')) $('setupFtpTls').value = remote.ftp.tls || 'none';
if ($('setupFtpUser')) $('setupFtpUser').value = remote.ftp.user || '';
if ($('setupFtpPath')) $('setupFtpPath').value = remote.ftp.path || 'backups/';
}
if (remote.sftp && typeof remote.sftp === 'object') {
if ($('setupSftpHost')) $('setupSftpHost').value = remote.sftp.host || '';
if ($('setupSftpPort')) $('setupSftpPort').value = remote.sftp.port || 22;
if ($('setupSftpUser')) $('setupSftpUser').value = remote.sftp.user || '';
if ($('setupSftpPath')) $('setupSftpPath').value = remote.sftp.path || 'backups/';
if ($('setupSftpKey')) $('setupSftpKey').value = remote.sftp.ssh_key || '';
}
if (remote.gdrive && typeof remote.gdrive === 'object') {
if ($('setupGdriveToken')) $('setupGdriveToken').value = remote.gdrive.token || '';
if ($('setupGdriveFolder')) $('setupGdriveFolder').value = remote.gdrive.folder_id || '';
}
if (remote.dropbox && typeof remote.dropbox === 'object') {
if ($('setupDropboxToken')) $('setupDropboxToken').value = remote.dropbox.token || '';
if ($('setupDropboxPath')) $('setupDropboxPath').value = remote.dropbox.path || '/AP-Manageur-Backups/';
}
if (remote.webdav && typeof remote.webdav === 'object') {
if ($('setupWebdavUrl')) $('setupWebdavUrl').value = remote.webdav.url || '';
if ($('setupWebdavUser')) $('setupWebdavUser').value = remote.webdav.user || '';
}
if (remote.s3 && typeof remote.s3 === 'object') {
if ($('setupS3Endpoint')) $('setupS3Endpoint').value = remote.s3.endpoint || 'https://s3.amazonaws.com';
if ($('setupS3Region')) $('setupS3Region').value = remote.s3.region || 'us-east-1';
if ($('setupS3Bucket')) $('setupS3Bucket').value = remote.s3.bucket || '';
if ($('setupS3AccessKey')) $('setupS3AccessKey').value = remote.s3.access_key || '';
}
}
function getSetupCloudConfig() {
const prov = $('setupCloudProvider')?.value || 'ftp';
const cfg = {
enabled: true,
provider: prov,
[prov]: {}
};
if (prov === 'ftp') {
cfg.ftp = {
host: $('setupFtpHost')?.value.trim() || '',
port: parseInt($('setupFtpPort')?.value, 10) || 21,
tls: $('setupFtpTls')?.value || 'none',
user: $('setupFtpUser')?.value.trim() || '',
password: $('setupFtpPass')?.value || '',
path: $('setupFtpPath')?.value.trim() || ''
};
} else if (prov === 'sftp') {
cfg.sftp = {
host: $('setupSftpHost')?.value.trim() || '',
port: parseInt($('setupSftpPort')?.value, 10) || 22,
user: $('setupSftpUser')?.value.trim() || '',
password: $('setupSftpPass')?.value || '',
path: $('setupSftpPath')?.value.trim() || '',
ssh_key: $('setupSftpKey')?.value.trim() || ''
};
} else if (prov === 'gdrive') {
cfg.gdrive = {
token: $('setupGdriveToken')?.value.trim() || '',
folder_id: $('setupGdriveFolder')?.value.trim() || ''
};
} else if (prov === 'dropbox') {
cfg.dropbox = {
token: $('setupDropboxToken')?.value.trim() || '',
path: $('setupDropboxPath')?.value.trim() || '/AP-Manageur-Backups/'
};
} else if (prov === 'webdav') {
cfg.webdav = {
url: $('setupWebdavUrl')?.value.trim() || '',
user: $('setupWebdavUser')?.value.trim() || '',
password: $('setupWebdavPass')?.value || ''
};
} else if (prov === 's3') {
cfg.s3 = {
endpoint: $('setupS3Endpoint')?.value.trim() || 'https://s3.amazonaws.com',
region: $('setupS3Region')?.value.trim() || 'us-east-1',
bucket: $('setupS3Bucket')?.value.trim() || '',
access_key: $('setupS3AccessKey')?.value.trim() || '',
secret_key: $('setupS3SecretKey')?.value || ''
};
}
return cfg;
}
async function testSetupCloudConnection() {
const btn = $('btnTestSetupCloud');
const msg = $('setupCloudMsg');
const isEn = currentLanguage.startsWith('en');
const cfg = getSetupCloudConfig();
if (btn) btn.disabled = true;
if (msg) {
msg.style.display = 'block';
msg.style.background = 'rgba(92,167,255,0.15)';
msg.style.color = 'var(--blue)';
msg.textContent = isEn ? 'Testing cloud connection…' : 'Test de la connexion au cloud en cours…';
}
try {
const res = await fetch(API_URL + '/api/backups/remote/test', {
method: 'POST',
headers: getSetupAuthHeaders(),
body: JSON.stringify({ config: cfg })
});
const d = await res.json();
if (!res.ok || !d.ok) throw new Error(d.error || d.message || 'Échec du test');
if (msg) {
msg.style.background = 'rgba(50,213,131,0.15)';
msg.style.color = 'var(--green)';
msg.textContent = '✅ ' + (d.message || (isEn ? 'Connection successful!' : 'Connexion réussie !'));
}
} catch (err) {
if (msg) {
msg.style.background = 'rgba(255,107,107,0.15)';
msg.style.color = 'var(--red)';
msg.textContent = '❌ ' + (err.message || 'Erreur');
}
} finally {
if (btn) btn.disabled = false;
}
}
async function exploreSetupCloudBackups() {
const btn = $('btnExploreSetupCloud');
const msg = $('setupCloudMsg');
const container = $('setupCloudFilesContainer');
const listEl = $('setupCloudFilesList');
const isEn = currentLanguage.startsWith('en');
const cfg = getSetupCloudConfig();
if (btn) btn.disabled = true;
if (msg) {
msg.style.display = 'block';
msg.style.background = 'rgba(92,167,255,0.15)';
msg.style.color = 'var(--blue)';
msg.textContent = isEn ? 'Retrieving backups from cloud…' : 'Récupération de la liste des sauvegardes sur le cloud…';
}
if (container) container.style.display = 'none';
try {
const res = await fetch(API_URL + '/api/backups/remote/files', {
method: 'POST',
headers: getSetupAuthHeaders(),
body: JSON.stringify({ config: cfg })
});
const d = await res.json();
if (!res.ok || !d.ok) throw new Error(d.error || 'Impossible de lister les fichiers distants');
const files = Array.isArray(d.files) ? d.files : [];
if (msg) {
msg.style.background = 'rgba(50,213,131,0.15)';
msg.style.color = 'var(--green)';
msg.textContent = `✅ ${files.length} ` + (isEn ? 'backup file(s) found on cloud storage' : 'fichier(s) de sauvegarde trouvé(s) sur le cloud');
}
if (container && listEl) {
container.style.display = 'block';
if (files.length === 0) {
listEl.innerHTML = `<div class="muted" style="padding:14px;background:var(--panel);border-radius:8px;font-size:12px;text-align:center">${isEn ? 'No backup files found on this cloud storage.' : 'Aucun fichier de sauvegarde trouvé sur cet espace cloud.'}</div>`;
} else {
let html = '';
files.forEach(f => {
const szStr = f.size_str || `${Math.round((f.size || 0) / 1024)} Ko`;
const dtStr = f.date || '—';
const localBadge = f.is_local
? `<span class="pill" style="font-size:10px;color:var(--green);border-color:var(--green)">💾 Déjà présent localement</span>`
: '';
html += `
<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px 12px;flex-wrap:wrap">
<div style="display:flex;align-items:center;gap:8px;min-width:220px;flex:1">
<span style="font-size:20px">☁️</span>
<div>
<div style="font-weight:700;font-size:13px;word-break:break-all">${f.name}</div>
<div class="muted" style="font-size:11px;display:flex;align-items:center;gap:6px;flex-wrap:wrap">
${dtStr ? `<span>📅 ${dtStr}</span>` : ''}
<span>💾 ${szStr}</span>
${localBadge}
</div>
</div>
</div>
<button type="button" class="btn-pull-cloud" onclick="pullAndInspectCloudBackup('${encodeURIComponent(f.name)}', this)"
style="display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:6px 12px;white-space:nowrap;background:var(--green);color:#fff">
<span>📥</span> <span>${isEn ? 'Download & Restore' : 'Rapatrier & Restaurer'}</span>
</button>
</div>
`;
});
listEl.innerHTML = html;
}
}
} catch (err) {
if (msg) {
msg.style.background = 'rgba(255,107,107,0.15)';
msg.style.color = 'var(--red)';
msg.textContent = '❌ ' + (err.message || 'Erreur');
}
} finally {
if (btn) btn.disabled = false;
}
}
async function pullAndInspectCloudBackup(encodedName, btnEl) {
const fileName = decodeURIComponent(encodedName);
const isEn = currentLanguage.startsWith('en');
const cfg = getSetupCloudConfig();
const origText = btnEl ? btnEl.innerHTML : '';
if (btnEl) {
btnEl.disabled = true;
btnEl.innerHTML = `<span>⏳</span> <span>${isEn ? 'Downloading…' : 'Téléchargement…'}</span>`;
}
try {
const res = await fetch(API_URL + '/api/backups/remote/file/pull', {
method: 'POST',
headers: getSetupAuthHeaders(),
body: JSON.stringify({ filename: fileName, config: cfg })
});
const d = await res.json();
if (!res.ok || !d.ok) throw new Error(d.error || 'Erreur lors du téléchargement');
pendingBackupData = d.backup;
closeSetupBackupPickerModal();
showSetupBackupModal(d.filename || fileName, d.size || 0, d.backup);
} catch (err) {
alert('Erreur lors du rapatriement de la sauvegarde : ' + err.message);
if (btnEl) {
btnEl.disabled = false;
btnEl.innerHTML = origText;
}
}
}
function initSetupDropZone() {
const dz = $('setupDropZone');
if (!dz) return;
['dragenter', 'dragover'].forEach(ev => {
dz.addEventListener(ev, (e) => {
e.preventDefault();
e.stopPropagation();
dz.style.borderColor = 'var(--accent)';
dz.style.background = 'var(--panel3)';
});
});
['dragleave', 'drop'].forEach(ev => {
dz.addEventListener(ev, (e) => {
e.preventDefault();
e.stopPropagation();
dz.style.borderColor = 'var(--line)';
dz.style.background = 'var(--panel2)';
});
});
dz.addEventListener('drop', (e) => {
const dt = e.dataTransfer;
const files = dt && dt.files;
if (files && files.length) {
closeSetupBackupPickerModal();
handleSetupBackupFile({ target: { files: files } });
}
});
}
function triggerBackupUpload() { function triggerBackupUpload() {
const input = $('setupBackupFileInput'); const input = $('setupBackupFileInput');
if (input) { if (input) {
@@ -4110,6 +4892,8 @@
setSetupTheme(currentTheme); setSetupTheme(currentTheme);
initStatsReportTimeSelects(); initStatsReportTimeSelects();
loadNotificationSettingsInSetup(); loadNotificationSettingsInSetup();
initSetupDropZone();
checkDetectedServerBackups();
const notifBox = $('notifChannelsBox'); const notifBox = $('notifChannelsBox');
if (notifBox) { if (notifBox) {
notifBox.addEventListener('input', updateStep4ContinueState); notifBox.addEventListener('input', updateStep4ContinueState);
+2 -2
View File
@@ -1,5 +1,5 @@
{ {
"version": "V1.2 (Bêta)", "version": "V1.2 (Bêta)",
"commit": "8d9e15eb2f7db532cc3882c24e2d2af091faffd2", "commit": "e2eaea4b46072d2b82848fa222538bbd0ad35447",
"build_date": "2026-11-22T22:57:23Z" "build_date": "2026-11-22T23:21:55Z"
} }