APmanageur Wi-Fi V1.0
This commit is contained in:
1 parent
ed08f9c8d4
commit
6f048ad433
6 files changed
+937
-6
No files matched your search
+2
-2
@@ -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 \
|
||||
|
||||
@@ -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':
|
||||
|
||||
+369
@@ -4858,6 +4858,150 @@
|
||||
<div id="backupScheduleMsg" style="margin-top:10px;font-size:12px;display:none;padding:8px 12px;border-radius:6px"></div>
|
||||
</div>
|
||||
|
||||
<!-- Stockage distant (FTP, SFTP, Google Drive, Dropbox, WebDAV, S3, Webhook) -->
|
||||
<div style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:18px;margin-top:16px">
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||||
<div>
|
||||
<strong style="font-size:15px;display:flex;align-items:center;gap:8px" data-i18n="backup_remote_title">
|
||||
☁️ Stockage distant (FTP, SFTP, Cloud)
|
||||
</strong>
|
||||
<p class="muted" style="margin:4px 0 0;font-size:13px" data-i18n="backup_remote_desc">
|
||||
Exportez automatiquement ou manuellement vos sauvegardes vers un serveur FTP/SFTP, Google Drive, Dropbox, WebDAV (Nextcloud/NAS), S3/MinIO ou Webhook.
|
||||
</p>
|
||||
</div>
|
||||
<label style="display:inline-flex;align-items:center;gap:8px;cursor:pointer;font-weight:600;user-select:none">
|
||||
<input type="checkbox" id="backupRemoteEnabled" style="width:auto;margin:0" onchange="onBackupRemoteProviderChange()">
|
||||
<span data-i18n="backup_remote_enable">Activer le stockage distant</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div id="backupRemoteBody">
|
||||
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px;align-items:end;margin-bottom:14px">
|
||||
<div>
|
||||
<label class="label" for="backupRemoteProvider" data-i18n="backup_remote_provider_label">Destination distante</label>
|
||||
<select id="backupRemoteProvider" onchange="onBackupRemoteProviderChange()" style="margin-bottom:0">
|
||||
<option value="ftp">📡 Serveur FTP / FTPS</option>
|
||||
<option value="sftp">🔐 Serveur SFTP (SSH)</option>
|
||||
<option value="gdrive">☁️ Google Drive (API v3)</option>
|
||||
<option value="dropbox">📦 Dropbox (API v2)</option>
|
||||
<option value="webdav">🌐 WebDAV (Nextcloud / ownCloud / NAS)</option>
|
||||
<option value="s3">🪣 S3 / MinIO / Compatible S3</option>
|
||||
<option value="webhook">🔗 Webhook HTTP (POST / PUT)</option>
|
||||
</select>
|
||||
</div>
|
||||
<label style="display:inline-flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;padding:8px 0;user-select:none">
|
||||
<input type="checkbox" id="backupRemoteAutoUpload" checked style="width:auto;margin:0">
|
||||
<span data-i18n="backup_remote_autoupload">Transférer automatiquement à chaque sauvegarde (Cron & manuelle)</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- FTP / FTPS -->
|
||||
<div id="remoteFields_ftp" class="remote-provider-fields" style="background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||||
<div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:10px">
|
||||
<div><label class="label" for="remoteFtpHost" data-i18n="backup_remote_host">Hôte / IP</label><input id="remoteFtpHost" type="text" placeholder="ftp.exemple.fr ou 192.168.1.10"></div>
|
||||
<div><label class="label" for="remoteFtpPort" data-i18n="backup_remote_port">Port</label><input id="remoteFtpPort" type="number" value="21" min="1" max="65535"></div>
|
||||
<div>
|
||||
<label class="label" for="remoteFtpTls" data-i18n="backup_remote_security">Sécurité</label>
|
||||
<select id="remoteFtpTls">
|
||||
<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">
|
||||
<div><label class="label" for="remoteFtpUser" data-i18n="backup_remote_user">Utilisateur</label><input id="remoteFtpUser" type="text" placeholder="backup_user"></div>
|
||||
<div><label class="label" for="remoteFtpPass" data-i18n="backup_remote_pass">Mot de passe</label><input id="remoteFtpPass" type="password" placeholder="••••••••"></div>
|
||||
<div><label class="label" for="remoteFtpPath" data-i18n="backup_remote_path">Dossier distant</label><input id="remoteFtpPath" type="text" value="/backups/" placeholder="/backups/ap-manageur/"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- SFTP (SSH) -->
|
||||
<div id="remoteFields_sftp" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||||
<div style="display:grid;grid-template-columns:2fr 1fr 1.5fr;gap:10px">
|
||||
<div><label class="label" for="remoteSftpHost" data-i18n="backup_remote_host">Hôte / IP</label><input id="remoteSftpHost" type="text" placeholder="nas.exemple.fr ou 192.168.1.10"></div>
|
||||
<div><label class="label" for="remoteSftpPort" data-i18n="backup_remote_port">Port</label><input id="remoteSftpPort" type="number" value="22" min="1" max="65535"></div>
|
||||
<div><label class="label" for="remoteSftpPath" data-i18n="backup_remote_path">Dossier distant</label><input id="remoteSftpPath" type="text" value="/backups/" placeholder="/home/user/backups/"></div>
|
||||
</div>
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
|
||||
<div><label class="label" for="remoteSftpUser" data-i18n="backup_remote_user">Utilisateur</label><input id="remoteSftpUser" type="text" placeholder="root ou backup"></div>
|
||||
<div><label class="label" for="remoteSftpPass" data-i18n="backup_remote_pass">Mot de passe (si pas de clé SSH)</label><input id="remoteSftpPass" type="password" placeholder="••••••••"></div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label" for="remoteSftpKey" data-i18n="backup_remote_ssh_key">Clé privée SSH (facultative — format PEM / OpenSSH)</label>
|
||||
<textarea id="remoteSftpKey" rows="3" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----" style="font-family:monospace;font-size:11px"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Google Drive -->
|
||||
<div id="remoteFields_gdrive" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||||
<div><label class="label" for="remoteGdriveToken" data-i18n="backup_remote_token">Jeton d’accès OAuth2 (Access Token)</label><input id="remoteGdriveToken" type="password" placeholder="ya29.a0..."></div>
|
||||
<div><label class="label" for="remoteGdriveFolder" data-i18n="backup_remote_gdrive_folder">ID du dossier Drive (facultatif)</label><input id="remoteGdriveFolder" type="text" placeholder="1AbCdEfGhIjKlMnOp..."></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dropbox -->
|
||||
<div id="remoteFields_dropbox" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||||
<div><label class="label" for="remoteDropboxToken" data-i18n="backup_remote_token">Jeton d’accès (Access Token Dropbox)</label><input id="remoteDropboxToken" type="password" placeholder="sl.B..."></div>
|
||||
<div><label class="label" for="remoteDropboxPath" data-i18n="backup_remote_path">Dossier distant</label><input id="remoteDropboxPath" type="text" value="/AP-Manageur-Backups/" placeholder="/AP-Manageur-Backups/"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- WebDAV -->
|
||||
<div id="remoteFields_webdav" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||||
<div><label class="label" for="remoteWebdavUrl" data-i18n="backup_remote_webdav_url">URL WebDAV (Nextcloud / ownCloud / Synology / kDrive)</label><input id="remoteWebdavUrl" 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">
|
||||
<div><label class="label" for="remoteWebdavUser" data-i18n="backup_remote_user">Utilisateur</label><input id="remoteWebdavUser" type="text" placeholder="utilisateur"></div>
|
||||
<div><label class="label" for="remoteWebdavPass" data-i18n="backup_remote_pass">Mot de passe / Mot de passe d’application</label><input id="remoteWebdavPass" type="password" placeholder="••••••••"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- S3 / MinIO -->
|
||||
<div id="remoteFields_s3" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||||
<div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:10px">
|
||||
<div><label class="label" for="remoteS3Endpoint" data-i18n="backup_remote_s3_endpoint">Endpoint S3 / MinIO</label><input id="remoteS3Endpoint" type="url" value="https://s3.amazonaws.com" placeholder="https://s3.fr-par.scw.cloud"></div>
|
||||
<div><label class="label" for="remoteS3Region" data-i18n="backup_remote_s3_region">Région</label><input id="remoteS3Region" type="text" value="us-east-1" placeholder="fr-par"></div>
|
||||
<div><label class="label" for="remoteS3Bucket" data-i18n="backup_remote_s3_bucket">Bucket</label><input id="remoteS3Bucket" type="text" placeholder="ap-backups"></div>
|
||||
</div>
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px">
|
||||
<div><label class="label" for="remoteS3AccessKey">Access Key</label><input id="remoteS3AccessKey" type="text" placeholder="AKIA..."></div>
|
||||
<div><label class="label" for="remoteS3SecretKey">Secret Key</label><input id="remoteS3SecretKey" type="password" placeholder="••••••••"></div>
|
||||
<div><label class="label" for="remoteS3Path" data-i18n="backup_remote_path">Préfixe / Dossier</label><input id="remoteS3Path" type="text" value="backups/" placeholder="backups/"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Webhook HTTP -->
|
||||
<div id="remoteFields_webhook" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||||
<div style="display:grid;grid-template-columns:2.5fr 1fr 1fr;gap:10px">
|
||||
<div><label class="label" for="remoteWebhookUrl">URL Webhook</label><input id="remoteWebhookUrl" type="url" placeholder="https://serveur.exemple.fr/upload"></div>
|
||||
<div>
|
||||
<label class="label" for="remoteWebhookMethod">Méthode</label>
|
||||
<select id="remoteWebhookMethod"><option value="POST">POST (multipart)</option><option value="PUT">PUT (binaire)</option></select>
|
||||
</div>
|
||||
<div><label class="label" for="remoteWebhookField">Champ fichier</label><input id="remoteWebhookField" type="text" value="backup" placeholder="backup"></div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label" for="remoteWebhookHeaders" data-i18n="backup_remote_headers">En-têtes HTTP personnalisés (1 par ligne : Clé: Valeur)</label>
|
||||
<textarea id="remoteWebhookHeaders" rows="2" placeholder="Authorization: Bearer mon_token" style="font-family:monospace;font-size:12px"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-top:12px">
|
||||
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
|
||||
<button id="btnTestBackupRemote" type="button" class="secondary" onclick="testBackupRemote()" data-i18n="backup_remote_test_btn">
|
||||
🧪 Tester la connexion
|
||||
</button>
|
||||
<button id="btnSaveBackupRemote" type="button" onclick="saveBackupRemoteConfig()" data-i18n="backup_remote_save_btn">
|
||||
💾 Enregistrer le stockage distant
|
||||
</button>
|
||||
</div>
|
||||
<span id="backupRemoteLastStatus" class="muted" style="font-size:12px"></span>
|
||||
</div>
|
||||
<div id="backupRemoteMsg" style="margin-top:10px;font-size:12px;display:none;padding:8px 12px;border-radius:6px"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Liste des sauvegardes enregistrées -->
|
||||
<div style="margin-top:20px">
|
||||
<div class="topline" style="flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||||
@@ -10629,6 +10773,7 @@ ${vpnBadgeTopo}
|
||||
<td style="text-align:right;white-space:nowrap">
|
||||
<div style="display:inline-flex;gap:6px;flex-wrap:wrap;justify-content:flex-end">
|
||||
<button type="button" class="secondary" style="padding:5px 10px;font-size:12px" onclick="downloadServerBackup('${safeArg}')" title="${escapeHtml(t('backup_btn_export', 'Exporter'))}">⬇️ ${escapeHtml(t('backup_btn_export', 'Exporter'))}</button>
|
||||
<button type="button" class="secondary" style="padding:5px 10px;font-size:12px;border-color:var(--green);color:var(--green)" onclick="uploadServerBackupToRemote('${safeArg}')" title="${escapeHtml(t('backup_btn_remote_push', 'Envoyer vers le stockage distant'))}">☁️ ${escapeHtml(t('backup_btn_remote_short', 'Distant'))}</button>
|
||||
<button type="button" class="secondary" style="padding:5px 10px;font-size:12px;border-color:var(--blue);color:var(--blue)" onclick="restoreServerBackup('${safeArg}')" title="${escapeHtml(t('backup_btn_restore', 'Restaurer'))}">♻️ ${escapeHtml(t('backup_btn_restore', 'Restaurer'))}</button>
|
||||
<button type="button" class="secondary danger" style="padding:5px 10px;font-size:12px;border-color:rgba(239,68,68,0.45);color:var(--red)" onclick="deleteServerBackup('${safeArg}')" title="${escapeHtml(t('btn_delete', 'Supprimer'))}">🗑️</button>
|
||||
</div>
|
||||
@@ -10662,6 +10807,7 @@ ${vpnBadgeTopo}
|
||||
if (!res.ok) throw new Error(d.error || 'Erreur chargement sauvegardes');
|
||||
if ($('backupDirBadge') && d.backup_dir) $('backupDirBadge').textContent = '📁 ' + d.backup_dir;
|
||||
applyBackupScheduleToUI(d.schedule);
|
||||
if (d.remote) applyBackupRemoteToUI(d.remote);
|
||||
renderServerBackupsTable(d.backups || [], d.total_size_str || '0 o');
|
||||
} catch (e) {
|
||||
const tbody = $('backupsTableBody');
|
||||
@@ -10838,6 +10984,229 @@ ${vpnBadgeTopo}
|
||||
}
|
||||
}
|
||||
|
||||
function onBackupRemoteProviderChange() {
|
||||
const prov = $('backupRemoteProvider')?.value || 'ftp';
|
||||
const en = !!($('backupRemoteEnabled') && $('backupRemoteEnabled').checked);
|
||||
const body = $('backupRemoteBody');
|
||||
if (body) body.style.opacity = en ? '1' : '0.72';
|
||||
['ftp', 'sftp', 'gdrive', 'dropbox', 'webdav', 's3', 'webhook'].forEach(k => {
|
||||
const el = $('remoteFields_' + k);
|
||||
if (el) el.style.display = (k === prov) ? 'block' : 'none';
|
||||
});
|
||||
}
|
||||
|
||||
function getBackupRemotePayload() {
|
||||
return {
|
||||
enabled: !!($('backupRemoteEnabled') && $('backupRemoteEnabled').checked),
|
||||
auto_upload: !!($('backupRemoteAutoUpload') && $('backupRemoteAutoUpload').checked),
|
||||
provider: $('backupRemoteProvider')?.value || 'ftp',
|
||||
ftp: {
|
||||
host: $('remoteFtpHost')?.value?.trim() || '',
|
||||
port: parseInt($('remoteFtpPort')?.value || '21', 10) || 21,
|
||||
tls: $('remoteFtpTls')?.value || 'none',
|
||||
user: $('remoteFtpUser')?.value?.trim() || '',
|
||||
password: $('remoteFtpPass')?.value || '',
|
||||
path: $('remoteFtpPath')?.value?.trim() || '/backups/'
|
||||
},
|
||||
sftp: {
|
||||
host: $('remoteSftpHost')?.value?.trim() || '',
|
||||
port: parseInt($('remoteSftpPort')?.value || '22', 10) || 22,
|
||||
user: $('remoteSftpUser')?.value?.trim() || '',
|
||||
password: $('remoteSftpPass')?.value || '',
|
||||
key: $('remoteSftpKey')?.value?.trim() || '',
|
||||
path: $('remoteSftpPath')?.value?.trim() || '/backups/'
|
||||
},
|
||||
gdrive: {
|
||||
token: $('remoteGdriveToken')?.value?.trim() || '',
|
||||
folder_id: $('remoteGdriveFolder')?.value?.trim() || ''
|
||||
},
|
||||
dropbox: {
|
||||
token: $('remoteDropboxToken')?.value?.trim() || '',
|
||||
path: $('remoteDropboxPath')?.value?.trim() || '/AP-Manageur-Backups/'
|
||||
},
|
||||
webdav: {
|
||||
url: $('remoteWebdavUrl')?.value?.trim() || '',
|
||||
user: $('remoteWebdavUser')?.value?.trim() || '',
|
||||
password: $('remoteWebdavPass')?.value || ''
|
||||
},
|
||||
s3: {
|
||||
endpoint: $('remoteS3Endpoint')?.value?.trim() || 'https://s3.amazonaws.com',
|
||||
region: $('remoteS3Region')?.value?.trim() || 'us-east-1',
|
||||
bucket: $('remoteS3Bucket')?.value?.trim() || '',
|
||||
access_key: $('remoteS3AccessKey')?.value?.trim() || '',
|
||||
secret_key: $('remoteS3SecretKey')?.value || '',
|
||||
path: $('remoteS3Path')?.value?.trim() || 'backups/'
|
||||
},
|
||||
webhook: {
|
||||
url: $('remoteWebhookUrl')?.value?.trim() || '',
|
||||
method: $('remoteWebhookMethod')?.value || 'POST',
|
||||
field_name: $('remoteWebhookField')?.value?.trim() || 'backup',
|
||||
headers: $('remoteWebhookHeaders')?.value || ''
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function applyBackupRemoteToUI(rcfg) {
|
||||
if (!rcfg) return;
|
||||
if ($('backupRemoteEnabled')) $('backupRemoteEnabled').checked = !!rcfg.enabled;
|
||||
if ($('backupRemoteAutoUpload')) $('backupRemoteAutoUpload').checked = rcfg.auto_upload !== false;
|
||||
if ($('backupRemoteProvider') && rcfg.provider) $('backupRemoteProvider').value = rcfg.provider;
|
||||
|
||||
const f = rcfg.ftp || {};
|
||||
if ($('remoteFtpHost')) $('remoteFtpHost').value = f.host || '';
|
||||
if ($('remoteFtpPort')) $('remoteFtpPort').value = f.port || 21;
|
||||
if ($('remoteFtpTls')) $('remoteFtpTls').value = f.tls || 'none';
|
||||
if ($('remoteFtpUser')) $('remoteFtpUser').value = f.user || '';
|
||||
if ($('remoteFtpPass')) $('remoteFtpPass').value = f.password || '';
|
||||
if ($('remoteFtpPath')) $('remoteFtpPath').value = f.path || '/backups/';
|
||||
|
||||
const s = rcfg.sftp || {};
|
||||
if ($('remoteSftpHost')) $('remoteSftpHost').value = s.host || '';
|
||||
if ($('remoteSftpPort')) $('remoteSftpPort').value = s.port || 22;
|
||||
if ($('remoteSftpUser')) $('remoteSftpUser').value = s.user || '';
|
||||
if ($('remoteSftpPass')) $('remoteSftpPass').value = s.password || '';
|
||||
if ($('remoteSftpKey')) $('remoteSftpKey').value = s.key || '';
|
||||
if ($('remoteSftpPath')) $('remoteSftpPath').value = s.path || '/backups/';
|
||||
|
||||
const g = rcfg.gdrive || {};
|
||||
if ($('remoteGdriveToken')) $('remoteGdriveToken').value = g.token || '';
|
||||
if ($('remoteGdriveFolder')) $('remoteGdriveFolder').value = g.folder_id || '';
|
||||
|
||||
const dbx = rcfg.dropbox || {};
|
||||
if ($('remoteDropboxToken')) $('remoteDropboxToken').value = dbx.token || '';
|
||||
if ($('remoteDropboxPath')) $('remoteDropboxPath').value = dbx.path || '/AP-Manageur-Backups/';
|
||||
|
||||
const wd = rcfg.webdav || {};
|
||||
if ($('remoteWebdavUrl')) $('remoteWebdavUrl').value = wd.url || '';
|
||||
if ($('remoteWebdavUser')) $('remoteWebdavUser').value = wd.user || '';
|
||||
if ($('remoteWebdavPass')) $('remoteWebdavPass').value = wd.password || '';
|
||||
|
||||
const s3 = rcfg.s3 || {};
|
||||
if ($('remoteS3Endpoint')) $('remoteS3Endpoint').value = s3.endpoint || 'https://s3.amazonaws.com';
|
||||
if ($('remoteS3Region')) $('remoteS3Region').value = s3.region || 'us-east-1';
|
||||
if ($('remoteS3Bucket')) $('remoteS3Bucket').value = s3.bucket || '';
|
||||
if ($('remoteS3AccessKey')) $('remoteS3AccessKey').value = s3.access_key || '';
|
||||
if ($('remoteS3SecretKey')) $('remoteS3SecretKey').value = s3.secret_key || '';
|
||||
if ($('remoteS3Path')) $('remoteS3Path').value = s3.path || 'backups/';
|
||||
|
||||
const wh = rcfg.webhook || {};
|
||||
if ($('remoteWebhookUrl')) $('remoteWebhookUrl').value = wh.url || '';
|
||||
if ($('remoteWebhookMethod')) $('remoteWebhookMethod').value = wh.method || 'POST';
|
||||
if ($('remoteWebhookField')) $('remoteWebhookField').value = wh.field_name || 'backup';
|
||||
if ($('remoteWebhookHeaders')) $('remoteWebhookHeaders').value = wh.headers || '';
|
||||
|
||||
const stEl = $('backupRemoteLastStatus');
|
||||
if (stEl) {
|
||||
if (rcfg.last_upload_time) {
|
||||
const icon = rcfg.last_upload_status === 'ok' ? '✅' : '❌';
|
||||
stEl.textContent = `${icon} ${t('backup_remote_last_upload', 'Dernier envoi :')} ${rcfg.last_upload_time} (${rcfg.last_upload_file || ''})${rcfg.last_upload_error ? ' — ' + rcfg.last_upload_error : ''}`;
|
||||
} else {
|
||||
stEl.textContent = '';
|
||||
}
|
||||
}
|
||||
onBackupRemoteProviderChange();
|
||||
}
|
||||
|
||||
async function saveBackupRemoteConfig() {
|
||||
const msg = $('backupRemoteMsg');
|
||||
const btn = $('btnSaveBackupRemote');
|
||||
if (btn) btn.disabled = true;
|
||||
try {
|
||||
const res = await apiFetch('/api/backups/remote', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(getBackupRemotePayload())
|
||||
});
|
||||
const d = await res.json();
|
||||
if (!res.ok) throw new Error(d.error || 'Erreur enregistrement');
|
||||
if (d.remote) applyBackupRemoteToUI(d.remote);
|
||||
if (msg) {
|
||||
msg.style.display = 'block';
|
||||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||||
msg.style.color = 'var(--green)';
|
||||
msg.textContent = '✓ ' + t('backup_remote_saved', 'Configuration du stockage distant enregistrée !');
|
||||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 5000);
|
||||
}
|
||||
} catch (e) {
|
||||
if (msg) {
|
||||
msg.style.display = 'block';
|
||||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||||
msg.style.color = 'var(--red)';
|
||||
msg.textContent = '❌ ' + tErr(e.message);
|
||||
}
|
||||
} finally {
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function testBackupRemote() {
|
||||
const msg = $('backupRemoteMsg');
|
||||
const btn = $('btnTestBackupRemote');
|
||||
if (btn) btn.disabled = true;
|
||||
if (msg) {
|
||||
msg.style.display = 'block';
|
||||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||||
msg.style.color = 'var(--blue)';
|
||||
msg.textContent = t('backup_remote_testing', 'Test de connexion et de transfert en cours…');
|
||||
}
|
||||
try {
|
||||
const res = await apiFetch('/api/backups/remote/test', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ config: getBackupRemotePayload() }),
|
||||
timeout: 45000
|
||||
});
|
||||
const d = await res.json();
|
||||
if (!res.ok) throw new Error(d.error || 'Échec du test');
|
||||
if (msg) {
|
||||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||||
msg.style.color = 'var(--green)';
|
||||
msg.textContent = '✓ ' + (d.message || t('backup_remote_test_ok', 'Connexion et transfert réussis !'));
|
||||
}
|
||||
} catch (e) {
|
||||
if (msg) {
|
||||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||||
msg.style.color = 'var(--red)';
|
||||
msg.textContent = '❌ ' + tErr(e.message);
|
||||
}
|
||||
} finally {
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadServerBackupToRemote(filename) {
|
||||
const msg = $('backupActionMsg');
|
||||
if (msg) {
|
||||
msg.style.display = 'block';
|
||||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||||
msg.style.color = 'var(--blue)';
|
||||
msg.textContent = t('backup_remote_uploading', 'Envoi de « {file} » vers le stockage distant…').replace('{file}', filename);
|
||||
}
|
||||
try {
|
||||
const res = await apiFetch('/api/backups/remote/upload', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ filename }),
|
||||
timeout: 120000
|
||||
});
|
||||
const d = await res.json();
|
||||
if (!res.ok) throw new Error(d.error || 'Échec du transfert distant');
|
||||
if (d.remote) applyBackupRemoteToUI(d.remote);
|
||||
if (msg) {
|
||||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||||
msg.style.color = 'var(--green)';
|
||||
msg.textContent = '✓ ' + (d.message || t('backup_remote_upload_ok', 'Sauvegarde transférée vers le stockage distant !'));
|
||||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 7000);
|
||||
}
|
||||
} catch (e) {
|
||||
if (msg) {
|
||||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||||
msg.style.color = 'var(--red)';
|
||||
msg.textContent = '❌ ' + tErr(e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const EYE_OPEN = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>';
|
||||
const EYE_OFF = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 4.2A10.7 10.7 0 0 1 12 4c5 0 8.5 4 10 8a16.7 16.7 0 0 1-3.1 4.8M6.6 6.6C4.7 7.8 3.5 9.7 2 12c1.5 4 5 8 10 8 1 0 2-.2 2.9-.5"/></svg>';
|
||||
const REGISTERED_PASSWORD_TOGGLES = [];
|
||||
|
||||
+30
-1
@@ -1197,5 +1197,34 @@ window.I18N['en-gb'] = {
|
||||
"backup_created_success": "Backup created successfully!",
|
||||
"backup_analyzing": "Inspecting backup file…",
|
||||
"backup_confirm_delete": "Permanently delete backup \"{file}\"?",
|
||||
"backup_deleted_success": "Backup deleted."
|
||||
"backup_deleted_success": "Backup deleted.",
|
||||
"backup_remote_title": "☁️ Remote Storage (FTP, SFTP, Cloud)",
|
||||
"backup_remote_desc": "Automatically or manually upload backups to FTP/SFTP, Google Drive, Dropbox, WebDAV (Nextcloud/NAS), S3/MinIO, or an HTTP Webhook.",
|
||||
"backup_remote_enable": "Enable Remote Storage",
|
||||
"backup_remote_provider_label": "Remote Destination",
|
||||
"backup_remote_autoupload": "Automatically upload every new backup (Cron & manual)",
|
||||
"backup_remote_host": "Host / IP",
|
||||
"backup_remote_port": "Port",
|
||||
"backup_remote_security": "Security",
|
||||
"backup_remote_user": "Username",
|
||||
"backup_remote_pass": "Password",
|
||||
"backup_remote_path": "Remote Directory",
|
||||
"backup_remote_ssh_key": "SSH Private Key (optional — PEM / OpenSSH format)",
|
||||
"backup_remote_token": "Access Token",
|
||||
"backup_remote_gdrive_folder": "Drive Folder ID (optional)",
|
||||
"backup_remote_webdav_url": "WebDAV URL (Nextcloud / ownCloud / Synology / kDrive)",
|
||||
"backup_remote_s3_endpoint": "S3 / MinIO Endpoint",
|
||||
"backup_remote_s3_region": "Region",
|
||||
"backup_remote_s3_bucket": "Bucket",
|
||||
"backup_remote_headers": "Custom HTTP Headers (1 per line: Key: Value)",
|
||||
"backup_remote_test_btn": "🧪 Test Connection",
|
||||
"backup_remote_save_btn": "💾 Save Remote Storage",
|
||||
"backup_remote_last_upload": "Last upload:",
|
||||
"backup_remote_saved": "Remote storage configuration saved!",
|
||||
"backup_remote_testing": "Testing connection and upload…",
|
||||
"backup_remote_test_ok": "Connection and upload succeeded!",
|
||||
"backup_remote_uploading": "Uploading \"{file}\" to remote storage…",
|
||||
"backup_remote_upload_ok": "Backup uploaded to remote storage!",
|
||||
"backup_btn_remote_push": "Upload to remote storage",
|
||||
"backup_btn_remote_short": "Remote"
|
||||
};
|
||||
+30
-1
@@ -1197,5 +1197,34 @@ window.I18N['en-us'] = {
|
||||
"backup_created_success": "Backup created successfully!",
|
||||
"backup_analyzing": "Inspecting backup file…",
|
||||
"backup_confirm_delete": "Permanently delete backup \"{file}\"?",
|
||||
"backup_deleted_success": "Backup deleted."
|
||||
"backup_deleted_success": "Backup deleted.",
|
||||
"backup_remote_title": "☁️ Remote Storage (FTP, SFTP, Cloud)",
|
||||
"backup_remote_desc": "Automatically or manually upload backups to FTP/SFTP, Google Drive, Dropbox, WebDAV (Nextcloud/NAS), S3/MinIO, or an HTTP Webhook.",
|
||||
"backup_remote_enable": "Enable Remote Storage",
|
||||
"backup_remote_provider_label": "Remote Destination",
|
||||
"backup_remote_autoupload": "Automatically upload every new backup (Cron & manual)",
|
||||
"backup_remote_host": "Host / IP",
|
||||
"backup_remote_port": "Port",
|
||||
"backup_remote_security": "Security",
|
||||
"backup_remote_user": "Username",
|
||||
"backup_remote_pass": "Password",
|
||||
"backup_remote_path": "Remote Directory",
|
||||
"backup_remote_ssh_key": "SSH Private Key (optional — PEM / OpenSSH format)",
|
||||
"backup_remote_token": "Access Token",
|
||||
"backup_remote_gdrive_folder": "Drive Folder ID (optional)",
|
||||
"backup_remote_webdav_url": "WebDAV URL (Nextcloud / ownCloud / Synology / kDrive)",
|
||||
"backup_remote_s3_endpoint": "S3 / MinIO Endpoint",
|
||||
"backup_remote_s3_region": "Region",
|
||||
"backup_remote_s3_bucket": "Bucket",
|
||||
"backup_remote_headers": "Custom HTTP Headers (1 per line: Key: Value)",
|
||||
"backup_remote_test_btn": "🧪 Test Connection",
|
||||
"backup_remote_save_btn": "💾 Save Remote Storage",
|
||||
"backup_remote_last_upload": "Last upload:",
|
||||
"backup_remote_saved": "Remote storage configuration saved!",
|
||||
"backup_remote_testing": "Testing connection and upload…",
|
||||
"backup_remote_test_ok": "Connection and upload succeeded!",
|
||||
"backup_remote_uploading": "Uploading \"{file}\" to remote storage…",
|
||||
"backup_remote_upload_ok": "Backup uploaded to remote storage!",
|
||||
"backup_btn_remote_push": "Upload to remote storage",
|
||||
"backup_btn_remote_short": "Remote"
|
||||
};
|
||||
+30
-1
@@ -1197,5 +1197,34 @@ window.I18N['fr'] = {
|
||||
"backup_created_success": "Sauvegarde créée avec succès !",
|
||||
"backup_analyzing": "Analyse de la sauvegarde en cours…",
|
||||
"backup_confirm_delete": "Supprimer définitivement la sauvegarde « {file} » ?",
|
||||
"backup_deleted_success": "Sauvegarde supprimée."
|
||||
"backup_deleted_success": "Sauvegarde supprimée.",
|
||||
"backup_remote_title": "☁️ Stockage distant (FTP, SFTP, Cloud)",
|
||||
"backup_remote_desc": "Exportez automatiquement ou manuellement vos sauvegardes vers un serveur FTP/SFTP, Google Drive, Dropbox, WebDAV (Nextcloud/NAS), S3/MinIO ou Webhook.",
|
||||
"backup_remote_enable": "Activer le stockage distant",
|
||||
"backup_remote_provider_label": "Destination distante",
|
||||
"backup_remote_autoupload": "Transférer automatiquement à chaque sauvegarde (Cron & manuelle)",
|
||||
"backup_remote_host": "Hôte / IP",
|
||||
"backup_remote_port": "Port",
|
||||
"backup_remote_security": "Sécurité",
|
||||
"backup_remote_user": "Utilisateur",
|
||||
"backup_remote_pass": "Mot de passe",
|
||||
"backup_remote_path": "Dossier distant",
|
||||
"backup_remote_ssh_key": "Clé privée SSH (facultative — format PEM / OpenSSH)",
|
||||
"backup_remote_token": "Jeton d’accès (Access Token)",
|
||||
"backup_remote_gdrive_folder": "ID du dossier Drive (facultatif)",
|
||||
"backup_remote_webdav_url": "URL WebDAV (Nextcloud / ownCloud / Synology / kDrive)",
|
||||
"backup_remote_s3_endpoint": "Endpoint S3 / MinIO",
|
||||
"backup_remote_s3_region": "Région",
|
||||
"backup_remote_s3_bucket": "Bucket",
|
||||
"backup_remote_headers": "En-têtes HTTP personnalisés (1 par ligne : Clé: Valeur)",
|
||||
"backup_remote_test_btn": "🧪 Tester la connexion",
|
||||
"backup_remote_save_btn": "💾 Enregistrer le stockage distant",
|
||||
"backup_remote_last_upload": "Dernier envoi :",
|
||||
"backup_remote_saved": "Configuration du stockage distant enregistrée !",
|
||||
"backup_remote_testing": "Test de connexion et de transfert en cours…",
|
||||
"backup_remote_test_ok": "Connexion et transfert réussis !",
|
||||
"backup_remote_uploading": "Envoi de « {file} » vers le stockage distant…",
|
||||
"backup_remote_upload_ok": "Sauvegarde transférée vers le stockage distant !",
|
||||
"backup_btn_remote_push": "Envoyer vers le stockage distant",
|
||||
"backup_btn_remote_short": "Distant"
|
||||
};
|
||||
Reference in new issue
Block a user