diff --git a/Dockerfile b/Dockerfile index 34ff6e5..7fa05e0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,11 +6,11 @@ ENV DEBIAN_FRONTEND=noninteractive \ # Apache2 + NetworkManager embarqué + outils Wi-Fi + Python RUN apt-get update \ && apt full-upgrade -y && apt-get install -y --no-install-recommends \ - ca-certificates apache2 nano python3 python3-cryptography python3-dbus tzdata \ + ca-certificates apache2 nano python3 python3-cryptography python3-dbus python3-paramiko tzdata \ network-manager wpasupplicant hostapd dbus \ iw iproute2 rfkill wireless-regdb \ dnsmasq-base iptables nftables procps kmod tcpdump \ - wireguard-tools openvpn ebtables curl conntrack \ + wireguard-tools openvpn ebtables curl conntrack rclone \ && a2enmod proxy proxy_http headers setenvif remoteip rewrite \ && a2disconf other-vhosts-access-log 2>/dev/null || true \ && ln -sf /dev/stdout /var/log/apache2/access.log \ diff --git a/ap.py b/ap.py index 8217962..09b688c 100644 --- a/ap.py +++ b/ap.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -import base64, hashlib, hmac, json, os, re, secrets, socket, sqlite3, subprocess, threading, time, urllib.parse, urllib.request, urllib.error, socketserver, shutil, datetime, atexit, signal, struct, smtplib, ssl, ipaddress, queue, http.client, io, zipfile, tempfile +import base64, copy, hashlib, hmac, json, os, re, secrets, socket, sqlite3, subprocess, threading, time, urllib.parse, urllib.request, urllib.error, socketserver, shutil, datetime, atexit, signal, struct, smtplib, ssl, ipaddress, queue, http.client, io, zipfile, tempfile from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -8021,6 +8021,14 @@ def create_server_backup(trigger='manual'): if tag == 'auto': apply_backup_retention(sched.get('retention', 7)) + # Si téléversement distant automatique activé, lancer en arrière-plan + try: + rcfg = get_backup_remote_config() + if rcfg.get('enabled') and rcfg.get('auto_upload', True): + threading.Thread(target=_bg_upload_backup_to_remote, args=(full_path, fname), daemon=True).start() + except Exception as e_th: + print(f"[ap-backup] Erreur démarrage téléversement distant : {e_th}", flush=True) + st = os.stat(full_path) return { 'filename': fname, @@ -8031,6 +8039,453 @@ def create_server_backup(trigger='manual'): 'trigger': tag } +def _bg_upload_backup_to_remote(full_path, fname): + try: + upload_backup_to_remote(full_path, remote_filename=fname) + except Exception as e: + print(f"[ap-backup] Échec téléversement distant en arrière-plan ({fname}) : {e}", flush=True) + +def default_backup_remote_config(): + return { + 'enabled': False, + 'auto_upload': True, + 'provider': 'ftp', + 'ftp': {'host': '', 'port': 21, 'user': '', 'password': '', 'path': '/backups/', 'tls': 'none'}, + 'sftp': {'host': '', 'port': 22, 'user': '', 'password': '', 'key': '', 'path': '/backups/'}, + 'dropbox': {'token': '', 'path': '/AP-Manageur-Backups/'}, + 'gdrive': {'token': '', 'folder_id': ''}, + 'webdav': {'url': '', 'user': '', 'password': '', 'path': ''}, + 's3': {'endpoint': 'https://s3.amazonaws.com', 'region': 'us-east-1', 'bucket': '', 'access_key': '', 'secret_key': '', 'path': 'backups/'}, + 'webhook': {'url': '', 'method': 'POST', 'headers': '', 'field_name': 'backup'}, + 'last_upload_time': '', + 'last_upload_file': '', + 'last_upload_status': '', + 'last_upload_error': '' + } + +def get_backup_remote_config(): + cfg = default_backup_remote_config() + raw = get_pref('backup_remote_config', '') + if raw: + try: + loaded = json.loads(raw) + if isinstance(loaded, dict): + for k, v in loaded.items(): + if k in ('ftp', 'sftp', 'dropbox', 'gdrive', 'webdav', 's3', 'webhook') and isinstance(v, dict): + cfg[k].update(v) + else: + cfg[k] = v + except Exception: + pass + cfg['enabled'] = bool(cfg.get('enabled', False)) + cfg['auto_upload'] = bool(cfg.get('auto_upload', True)) + if cfg.get('provider') not in ('ftp', 'sftp', 'dropbox', 'gdrive', 'webdav', 's3', 'webhook'): + cfg['provider'] = 'ftp' + return cfg + +def save_backup_remote_config(data): + cur = get_backup_remote_config() + if not isinstance(data, dict): + raise ValueError('Données de configuration distante invalides') + if 'enabled' in data: + cur['enabled'] = bool(data['enabled']) + if 'auto_upload' in data: + cur['auto_upload'] = bool(data['auto_upload']) + if 'provider' in data: + prov = str(data['provider']).strip().lower() + if prov in ('ftp', 'sftp', 'dropbox', 'gdrive', 'webdav', 's3', 'webhook'): + cur['provider'] = prov + for p in ('ftp', 'sftp', 'dropbox', 'gdrive', 'webdav', 's3', 'webhook'): + if p in data and isinstance(data[p], dict): + cur[p].update(data[p]) + set_pref('backup_remote_config', json.dumps(cur, ensure_ascii=False)) + return cur + +def _upload_ftp(cfg, local_path, remote_filename): + import ftplib + host = str(cfg.get('host', '')).strip() + if not host: raise ValueError("Hôte FTP manquant") + try: port = int(cfg.get('port') or 21) + except (ValueError, TypeError): port = 21 + user = str(cfg.get('user', '')).strip() or 'anonymous' + password = str(cfg.get('password', '')) + rem_path = str(cfg.get('path', '') or '/').strip() + use_tls = str(cfg.get('tls', 'none')).lower() in ('explicit', 'tls', 'ftps', '1', 'true') + + ftp = ftplib.FTP_TLS(timeout=25) if use_tls else ftplib.FTP(timeout=25) + ftp.connect(host, port) + ftp.login(user, password) + if use_tls: + ftp.prot_p() + if rem_path and rem_path != '/': + for part in [p for p in rem_path.split('/') if p]: + try: + ftp.cwd(part) + except ftplib.error_perm: + try: + ftp.mkd(part) + ftp.cwd(part) + except Exception: + pass + with open(local_path, 'rb') as f: + ftp.storbinary(f"STOR {remote_filename}", f) + try: ftp.quit() + except Exception: pass + return True, f"Téléversé sur FTP ({host}:{port})" + +def _upload_sftp(cfg, local_path, remote_filename): + host = str(cfg.get('host', '')).strip() + if not host: raise ValueError("Hôte SFTP manquant") + try: port = int(cfg.get('port') or 22) + except (ValueError, TypeError): port = 22 + user = str(cfg.get('user', '')).strip() + if not user: raise ValueError("Nom d'utilisateur SFTP manquant") + password = str(cfg.get('password', '')) + key_text = str(cfg.get('key', '')).strip() + rem_path = str(cfg.get('path', '') or '/').strip() + if not rem_path.endswith('/'): rem_path += '/' + target_remote_file = rem_path + remote_filename + + try: + import paramiko + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + pkey = None + if key_text: + for pkey_class in (paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey): + try: + pkey = pkey_class.from_private_key(io.StringIO(key_text)) + break + except Exception: pass + if not pkey: + raise ValueError("Clé privée SSH non reconnue (format PEM / OpenSSH attendu)") + ssh.connect(host, port=port, username=user, password=password or None, pkey=pkey, timeout=25) + sftp = ssh.open_sftp() + parts = [p for p in rem_path.split('/') if p] + curr = '/' if rem_path.startswith('/') else '' + for p in parts: + curr = os.path.join(curr, p) + try: sftp.stat(curr) + except IOError: + try: sftp.mkdir(curr) + except IOError: pass + sftp.put(local_path, target_remote_file) + sftp.close() + ssh.close() + return True, f"Téléversé via SFTP sur {host}:{port}" + except ImportError: + pass + except Exception as e_param: + # Si paramiko échoue (ex: auth), remonter directement si erreur SSH explicite, sinon fallback curl + if 'Authentication' in str(e_param) or 'Clé privée' in str(e_param): + raise + + curl_bin = find_bin('curl') + if not curl_bin: + raise RuntimeError("Client SFTP introuvable (installez python3-paramiko ou curl)") + url_path = target_remote_file if target_remote_file.startswith('/') else '/' + target_remote_file + sftp_url = f"sftp://{host}:{port}{url_path}" + curl_cmd = [curl_bin, '-sS', '-k', '--ftp-create-dirs', '--max-time', '120'] + key_tmp_name = None + try: + if key_text: + kt = tempfile.NamedTemporaryFile('w', delete=False) + kt.write(key_text + '\n') + kt.flush(); kt.close() + os.chmod(kt.name, 0o600) + key_tmp_name = kt.name + curl_cmd += ['-u', f"{user}:", '--key', key_tmp_name] + else: + curl_cmd += ['-u', f"{user}:{password}"] + curl_cmd += ['-T', local_path, sftp_url] + r = subprocess.run(curl_cmd, capture_output=True, text=True) + if r.returncode != 0: + raise RuntimeError(r.stderr.strip() or f"Erreur SFTP (code {r.returncode})") + return True, f"Téléversé via SFTP (curl) sur {host}:{port}" + finally: + if key_tmp_name and os.path.exists(key_tmp_name): + try: os.unlink(key_tmp_name) + except OSError: pass + +def _upload_dropbox(cfg, local_path, remote_filename): + token = str(cfg.get('token', '')).strip() + if not token: raise ValueError("Jeton d'accès (Access Token) Dropbox manquant") + rem_path = str(cfg.get('path', '') or '/AP-Manageur-Backups/').strip() + if not rem_path.startswith('/'): rem_path = '/' + rem_path + if not rem_path.endswith('/'): rem_path += '/' + dropbox_path = rem_path + remote_filename + + url = "https://content.dropboxapi.com/2/files/upload" + dbx_arg = json.dumps({ + "path": dropbox_path, + "mode": "overwrite", + "autorename": False, + "mute": False, + "strict_conflict": False + }) + with open(local_path, 'rb') as f: + file_bytes = f.read() + + req = urllib.request.Request(url, data=file_bytes, method='POST') + req.add_header('Authorization', f'Bearer {token}') + req.add_header('Dropbox-API-Arg', dbx_arg) + req.add_header('Content-Type', 'application/octet-stream') + ctx = ssl.create_default_context() + try: + with urllib.request.urlopen(req, context=ctx, timeout=60) as resp: + res_data = json.loads(resp.read().decode('utf-8')) + return True, f"Téléversé sur Dropbox ({res_data.get('path_display', dropbox_path)})" + except urllib.error.HTTPError as e: + body = '' + try: body = e.read().decode('utf-8', errors='replace')[:300] + except Exception: pass + raise RuntimeError(f"HTTP {e.code} Dropbox : {body or e.reason}") + +def _upload_gdrive(cfg, local_path, remote_filename): + token = str(cfg.get('token', '')).strip() + if not token: raise ValueError("Jeton d'accès (Access Token OAuth2) Google Drive manquant") + folder_id = str(cfg.get('folder_id', '')).strip() + + url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart" + metadata = {"name": remote_filename} + if folder_id: + metadata["parents"] = [folder_id] + + boundary = "========GDRIVE_APMANAGEUR_BOUNDARY========" + meta_json = json.dumps(metadata) + with open(local_path, 'rb') as f: + file_bytes = f.read() + + ctype = 'text/plain' if remote_filename.lower().endswith('.txt') else 'application/zip' + body = ( + f"--{boundary}\r\n" + f"Content-Type: application/json; charset=UTF-8\r\n\r\n" + f"{meta_json}\r\n" + f"--{boundary}\r\n" + f"Content-Type: {ctype}\r\n\r\n" + ).encode('utf-8') + file_bytes + f"\r\n--{boundary}--\r\n".encode('utf-8') + + req = urllib.request.Request(url, data=body, method='POST') + req.add_header('Authorization', f'Bearer {token}') + req.add_header('Content-Type', f'multipart/related; boundary={boundary}') + ctx = ssl.create_default_context() + try: + with urllib.request.urlopen(req, context=ctx, timeout=60) as resp: + res_data = json.loads(resp.read().decode('utf-8')) + return True, f"Téléversé sur Google Drive (ID: {res_data.get('id', '?')})" + except urllib.error.HTTPError as e: + body = '' + try: body = e.read().decode('utf-8', errors='replace')[:300] + except Exception: pass + raise RuntimeError(f"HTTP {e.code} Google Drive : {body or e.reason}") + +def _upload_webdav(cfg, local_path, remote_filename): + server_url = str(cfg.get('url', '')).strip() + if not server_url: raise ValueError("URL WebDAV manquante") + if not server_url.endswith('/'): server_url += '/' + extra_path = str(cfg.get('path', '')).strip().strip('/') + if extra_path: + server_url += '/'.join(urllib.parse.quote(p) for p in extra_path.split('/')) + '/' + target_url = server_url + urllib.parse.quote(remote_filename) + user = str(cfg.get('user', '')).strip() + password = str(cfg.get('password', '')) + + with open(local_path, 'rb') as f: + file_bytes = f.read() + + req = urllib.request.Request(target_url, data=file_bytes, method='PUT') + if user or password: + auth_str = base64.b64encode(f"{user}:{password}".encode('utf-8')).decode('ascii') + req.add_header('Authorization', f'Basic {auth_str}') + req.add_header('Content-Type', 'application/octet-stream') + ctx = ssl.create_default_context() + try: + with urllib.request.urlopen(req, context=ctx, timeout=60) as resp: + return True, f"Téléversé sur WebDAV (HTTP {resp.status})" + except urllib.error.HTTPError as e: + raise RuntimeError(f"HTTP {e.code} WebDAV : {e.reason}") + +def _upload_s3(cfg, local_path, remote_filename): + endpoint = str(cfg.get('endpoint', '') or 'https://s3.amazonaws.com').strip() + bucket = str(cfg.get('bucket', '')).strip() + if not bucket: raise ValueError("Nom du bucket S3 manquant") + region = str(cfg.get('region', '') or 'us-east-1').strip() + access_key = str(cfg.get('access_key', '')).strip() + secret_key = str(cfg.get('secret_key', '')).strip() + if not access_key or not secret_key: + raise ValueError("Clés S3 (Access Key et Secret Key) obligatoires") + prefix = str(cfg.get('path', '') or '').strip().strip('/') + s3_key = f"{prefix}/{remote_filename}" if prefix else remote_filename + + rclone_bin = find_bin('rclone') + if rclone_bin: + rc = tempfile.NamedTemporaryFile('w', delete=False) + try: + rc.write(f"[s3remote]\ntype = s3\nprovider = Other\nendpoint = {endpoint}\nregion = {region}\naccess_key_id = {access_key}\nsecret_access_key = {secret_key}\n") + rc.flush(); rc.close() + cmd = [rclone_bin, '--config', rc.name, 'copyto', local_path, f"s3remote:{bucket}/{s3_key}"] + r = subprocess.run(cmd, capture_output=True, text=True, timeout=120) + if r.returncode != 0: + raise RuntimeError(r.stderr.strip() or r.stdout.strip() or f"Code rclone {r.returncode}") + return True, f"Téléversé sur S3 ({bucket}/{s3_key})" + finally: + if os.path.exists(rc.name): + try: os.unlink(rc.name) + except OSError: pass + + with open(local_path, 'rb') as f: + payload = f.read() + payload_hash = hashlib.sha256(payload).hexdigest() + now_dt = datetime.datetime.now(datetime.timezone.utc) + amz_date = now_dt.strftime('%Y%m%dT%H%M%SZ') + datestamp = now_dt.strftime('%Y%m%d') + if not endpoint.startswith('http://') and not endpoint.startswith('https://'): + endpoint = 'https://' + endpoint + parsed = urllib.parse.urlparse(endpoint) + host = parsed.netloc + canonical_uri = f"/{bucket}/{urllib.parse.quote(s3_key, safe='/')}" + canonical_headers = f"host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n" + signed_headers = "host;x-amz-content-sha256;x-amz-date" + canonical_req = f"PUT\n{canonical_uri}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}" + algorithm = "AWS4-HMAC-SHA256" + credential_scope = f"{datestamp}/{region}/s3/aws4_request" + string_to_sign = f"{algorithm}\n{amz_date}\n{credential_scope}\n{hashlib.sha256(canonical_req.encode('utf-8')).hexdigest()}" + def _sign(k, m): return hmac.new(k, m.encode('utf-8'), hashlib.sha256).digest() + k_sign = _sign(_sign(_sign(_sign(('AWS4' + secret_key).encode('utf-8'), datestamp), region), 's3'), 'aws4_request') + signature = hmac.new(k_sign, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() + auth_hdr = f"{algorithm} Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}" + + full_url = f"{endpoint.rstrip('/')}{canonical_uri}" + req = urllib.request.Request(full_url, data=payload, method='PUT') + req.add_header('Host', host) + req.add_header('x-amz-date', amz_date) + req.add_header('x-amz-content-sha256', payload_hash) + req.add_header('Authorization', auth_hdr) + req.add_header('Content-Type', 'application/octet-stream') + ctx = ssl.create_default_context() + try: + with urllib.request.urlopen(req, context=ctx, timeout=60) as resp: + return True, f"Téléversé sur S3 ({bucket}/{s3_key} - HTTP {resp.status})" + except urllib.error.HTTPError as e: + body = '' + try: body = e.read().decode('utf-8', errors='replace')[:300] + except Exception: pass + raise RuntimeError(f"HTTP {e.code} S3 : {body or e.reason}") + +def _upload_webhook(cfg, local_path, remote_filename): + url = str(cfg.get('url', '')).strip() + if not url: raise ValueError("URL du Webhook manquante") + method = str(cfg.get('method', 'POST') or 'POST').strip().upper() + if method not in ('POST', 'PUT'): method = 'POST' + headers_raw = str(cfg.get('headers', '')) + field_name = str(cfg.get('field_name', 'backup') or 'backup').strip() + + with open(local_path, 'rb') as f: + file_bytes = f.read() + + if method == 'PUT': + body = file_bytes + content_type = 'application/octet-stream' + else: + boundary = "========WEBHOOK_APMANAGEUR_BOUNDARY========" + body = ( + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="{field_name}"; filename="{remote_filename}"\r\n' + f"Content-Type: application/octet-stream\r\n\r\n" + ).encode('utf-8') + file_bytes + f"\r\n--{boundary}--\r\n".encode('utf-8') + content_type = f'multipart/form-data; boundary={boundary}' + + req = urllib.request.Request(url, data=body, method=method) + req.add_header('Content-Type', content_type) + if headers_raw: + for line in headers_raw.splitlines(): + if ':' in line: + k, v = line.split(':', 1) + if k.strip(): + req.add_header(k.strip(), v.strip()) + ctx = ssl.create_default_context() + try: + with urllib.request.urlopen(req, context=ctx, timeout=60) as resp: + return True, f"Sauvegarde transmise au Webhook (HTTP {resp.status})" + except urllib.error.HTTPError as e: + raise RuntimeError(f"HTTP {e.code} Webhook : {e.reason}") + +def upload_backup_to_remote(local_filepath_or_name, custom_cfg=None, remote_filename=None, persist_status=True): + cfg = copy.deepcopy(custom_cfg) if custom_cfg else get_backup_remote_config() + provider = str(cfg.get('provider', 'ftp')).strip().lower() + + if os.path.isabs(local_filepath_or_name) and os.path.isfile(local_filepath_or_name): + local_path = local_filepath_or_name + fname = remote_filename or os.path.basename(local_filepath_or_name) + else: + full_p, clean_n = safe_backup_filepath(local_filepath_or_name) + local_path = full_p + fname = remote_filename or clean_n + + if not os.path.isfile(local_path): + raise FileNotFoundError(f"Fichier de sauvegarde introuvable : {fname}") + + p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {} + now_ts = time.strftime('%Y-%m-%d %H:%M:%S') + + try: + if provider == 'ftp': + ok, msg = _upload_ftp(p_cfg, local_path, fname) + elif provider == 'sftp': + ok, msg = _upload_sftp(p_cfg, local_path, fname) + elif provider == 'dropbox': + ok, msg = _upload_dropbox(p_cfg, local_path, fname) + elif provider == 'gdrive': + ok, msg = _upload_gdrive(p_cfg, local_path, fname) + elif provider == 'webdav': + ok, msg = _upload_webdav(p_cfg, local_path, fname) + elif provider == 's3': + ok, msg = _upload_s3(p_cfg, local_path, fname) + elif provider == 'webhook': + ok, msg = _upload_webhook(p_cfg, local_path, fname) + else: + raise ValueError(f"Protocole de stockage distant inconnu : {provider}") + + if persist_status: + saved = get_backup_remote_config() + saved['last_upload_time'] = now_ts + saved['last_upload_file'] = fname + saved['last_upload_status'] = 'ok' + saved['last_upload_error'] = '' + set_pref('backup_remote_config', json.dumps(saved, ensure_ascii=False)) + print(f"[ap-backup] Sauvegarde {fname} transmise vers {provider.upper()} : {msg}", flush=True) + return True, msg + except Exception as e: + err_msg = str(e) + if persist_status: + try: + saved = get_backup_remote_config() + saved['last_upload_time'] = now_ts + saved['last_upload_file'] = fname + saved['last_upload_status'] = 'error' + saved['last_upload_error'] = err_msg[:300] + set_pref('backup_remote_config', json.dumps(saved, ensure_ascii=False)) + except Exception: pass + print(f"[ap-backup] Échec téléversement {fname} vers {provider.upper()} : {err_msg}", flush=True) + raise RuntimeError(f"Échec téléversement distant ({provider.upper()}) : {err_msg}") + +def test_backup_remote(custom_cfg=None): + cfg = custom_cfg or get_backup_remote_config() + provider = str(cfg.get('provider', 'ftp')).strip().lower() + now_str = time.strftime('%Y%m%d-%H%M%S') + test_fname = f"ap-manageur-test-{now_str}.txt" + tmp_name = None + try: + with tempfile.NamedTemporaryFile('w', delete=False, suffix='.txt') as tmp: + tmp.write(f"Test de connectivité stockage distant AP Manageur ({provider.upper()}) - {now_str}\n") + tmp_name = tmp.name + ok, msg = upload_backup_to_remote(tmp_name, custom_cfg=cfg, remote_filename=test_fname, persist_status=False) + return True, f"Connexion et test de transfert réussis ({provider.upper()}) : {msg}" + finally: + if tmp_name and os.path.exists(tmp_name): + try: os.unlink(tmp_name) + except OSError: pass + def list_server_backups(): ensure_backup_dir() items = [] @@ -8422,11 +8877,15 @@ class Handler(BaseHTTPRequestHandler): 'ok': True, 'backup_dir': BACKUP_DIR, 'schedule': get_backup_schedule(), + 'remote': get_backup_remote_config(), 'backups': items, 'total_count': len(items), 'total_size': total_size, 'total_size_str': format_bytes(total_size) }); return + if self.path == '/api/backups/remote': + if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return + self.send_json({'ok': True, 'remote': get_backup_remote_config()}); return if self.path.startswith('/api/backups/download'): if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return parsed = urllib.parse.urlparse(self.path) @@ -9334,6 +9793,22 @@ class Handler(BaseHTTPRequestHandler): '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 + if self.path == '/api/backups/remote': + rcfg = save_backup_remote_config(data) + log('configuration_stockage_distant', username(self) or 'Administrateur', request_ip(self), rcfg.get('provider', '')) + 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': + fname = str(data.get('filename', '')).strip() + full_path, clean_name = safe_backup_filepath(fname) + if not os.path.isfile(full_path): + self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return + ok, msg = upload_backup_to_remote(full_path, remote_filename=clean_name) + log('televersement_distant_manuel', username(self) or 'Administrateur', request_ip(self), f"{clean_name} ({msg})") + self.send_json({'ok': True, 'message': msg, 'remote': get_backup_remote_config()}); return if self.path == '/api/auth/2fa/status': self.send_json({'enabled':auth_state()['two_factor'],'recovery_remaining':recovery_remaining()}); return if self.path == '/api/auth/2fa/enable': diff --git a/index.html b/index.html index 2fcb2ca..7fabefb 100644 --- a/index.html +++ b/index.html @@ -4858,6 +4858,150 @@
+ ++ Exportez automatiquement ou manuellement vos sauvegardes vers un serveur FTP/SFTP, Google Drive, Dropbox, WebDAV (Nextcloud/NAS), S3/MinIO ou Webhook. +
+