APmanageur Wi-Fi V1.0
This commit is contained in:
1 parent
7eef4647a5
commit
b8635b5162
5 files changed
+720
-17
No files matched your search
@@ -9011,26 +9011,408 @@ def _list_remote_s3(cfg):
|
||||
print(f"[ap-backup] Erreur listing S3 : {e}", flush=True)
|
||||
return None
|
||||
|
||||
def _download_ftp(cfg, remote_filename, dest_path):
|
||||
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)
|
||||
try:
|
||||
ftp.connect(host, port)
|
||||
ftp.login(user, password)
|
||||
if use_tls: ftp.prot_p()
|
||||
if rem_path and rem_path not in ('/', '.'):
|
||||
for part in [p for p in rem_path.split('/') if p]:
|
||||
try: ftp.cwd(part)
|
||||
except Exception: pass
|
||||
with open(dest_path, 'wb') as f:
|
||||
ftp.retrbinary(f'RETR {remote_filename}', f.write)
|
||||
return True
|
||||
finally:
|
||||
try: ftp.quit()
|
||||
except Exception:
|
||||
try: ftp.close()
|
||||
except Exception: pass
|
||||
|
||||
def _download_sftp(cfg, remote_filename, dest_path):
|
||||
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()
|
||||
password = str(cfg.get('password', ''))
|
||||
key_text = str(cfg.get('key', '')).strip()
|
||||
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
|
||||
try:
|
||||
ssh.connect(host, port=port, username=user, password=password or None, pkey=pkey, timeout=25)
|
||||
sftp = ssh.open_sftp()
|
||||
_, target_file = _normalize_sftp_target(sftp, cfg.get('path', ''), remote_filename)
|
||||
sftp.get(target_file, dest_path)
|
||||
return True
|
||||
finally:
|
||||
try: sftp.close()
|
||||
except Exception: pass
|
||||
try: ssh.close()
|
||||
except Exception: pass
|
||||
|
||||
def _download_dropbox(cfg, remote_filename, dest_path):
|
||||
token = str(cfg.get('token', '')).strip()
|
||||
if not token: raise ValueError("Jeton 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 += '/'
|
||||
dbx_path = rem_path + remote_filename
|
||||
url = "https://content.dropboxapi.com/2/files/download"
|
||||
req = urllib.request.Request(url, method='POST')
|
||||
req.add_header('Authorization', f'Bearer {token}')
|
||||
req.add_header('Dropbox-API-Arg', json.dumps({"path": dbx_path}))
|
||||
ctx = ssl.create_default_context()
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
|
||||
with open(dest_path, 'wb') as out_f:
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk: break
|
||||
out_f.write(chunk)
|
||||
return True
|
||||
|
||||
def _download_gdrive(cfg, remote_filename, dest_path):
|
||||
token = str(cfg.get('token', '')).strip()
|
||||
if not token: raise ValueError("Jeton Google Drive manquant")
|
||||
folder_id = str(cfg.get('folder_id', '')).strip()
|
||||
ctx = ssl.create_default_context()
|
||||
safe_name = remote_filename.replace("'", "\\'")
|
||||
query = f"trashed = false and name = '{safe_name}'"
|
||||
if folder_id:
|
||||
query += f" and '{folder_id}' in parents"
|
||||
search_url = f"https://www.googleapis.com/drive/v3/files?q={urllib.parse.quote(query)}&fields=files(id,name)"
|
||||
req = urllib.request.Request(search_url, method='GET')
|
||||
req.add_header('Authorization', f'Bearer {token}')
|
||||
file_id = None
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
|
||||
d = json.loads(resp.read().decode('utf-8'))
|
||||
files = d.get('files', [])
|
||||
if files: file_id = files[0]['id']
|
||||
if not file_id:
|
||||
raise FileNotFoundError(f"Fichier {remote_filename} non trouvé sur Google Drive")
|
||||
dl_url = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media"
|
||||
dl_req = urllib.request.Request(dl_url, method='GET')
|
||||
dl_req.add_header('Authorization', f'Bearer {token}')
|
||||
with urllib.request.urlopen(dl_req, context=ctx, timeout=60) as resp:
|
||||
with open(dest_path, 'wb') as out_f:
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk: break
|
||||
out_f.write(chunk)
|
||||
return True
|
||||
|
||||
def _download_webdav(cfg, remote_filename, dest_path):
|
||||
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', ''))
|
||||
req = urllib.request.Request(target_url, method='GET')
|
||||
if user or password:
|
||||
auth_str = base64.b64encode(f"{user}:{password}".encode('utf-8')).decode('ascii')
|
||||
req.add_header('Authorization', f'Basic {auth_str}')
|
||||
ctx = ssl.create_default_context()
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
|
||||
with open(dest_path, 'wb') as out_f:
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk: break
|
||||
out_f.write(chunk)
|
||||
return True
|
||||
|
||||
def _download_s3(cfg, remote_filename, dest_path):
|
||||
endpoint = str(cfg.get('endpoint', '') or 'https://s3.amazonaws.com').strip()
|
||||
bucket = str(cfg.get('bucket', '')).strip()
|
||||
if not bucket: raise ValueError("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()
|
||||
prefix = str(cfg.get('path', '') or '').strip().strip('/')
|
||||
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', f"s3remote:{bucket}/{key}", dest_path]
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError(r.stderr.strip() or f"Erreur rclone copyto ({r.returncode})")
|
||||
return True
|
||||
finally:
|
||||
if os.path.exists(rc.name):
|
||||
try: os.unlink(rc.name)
|
||||
except OSError: pass
|
||||
raise RuntimeError("Client S3 introuvable (rclone requis)")
|
||||
|
||||
def download_remote_file(remote_filename, dest_path, custom_cfg=None):
|
||||
cfg = custom_cfg or get_backup_remote_config()
|
||||
provider = str(cfg.get('provider', 'ftp')).strip().lower()
|
||||
p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {}
|
||||
if provider == 'ftp':
|
||||
return _download_ftp(p_cfg, remote_filename, dest_path)
|
||||
elif provider == 'sftp':
|
||||
return _download_sftp(p_cfg, remote_filename, dest_path)
|
||||
elif provider == 'dropbox':
|
||||
return _download_dropbox(p_cfg, remote_filename, dest_path)
|
||||
elif provider == 'gdrive':
|
||||
return _download_gdrive(p_cfg, remote_filename, dest_path)
|
||||
elif provider == 'webdav':
|
||||
return _download_webdav(p_cfg, remote_filename, dest_path)
|
||||
elif provider == 's3':
|
||||
return _download_s3(p_cfg, remote_filename, dest_path)
|
||||
else:
|
||||
raise ValueError(f"Protocole distant {provider} non pris en charge pour le téléchargement")
|
||||
|
||||
def list_remote_files_detailed(custom_cfg=None):
|
||||
cfg = custom_cfg or get_backup_remote_config()
|
||||
if not cfg.get('enabled'):
|
||||
return None, "Stockage distant désactivé"
|
||||
provider = str(cfg.get('provider', 'ftp')).strip().lower()
|
||||
p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {}
|
||||
|
||||
ensure_backup_dir()
|
||||
local_files = set()
|
||||
try:
|
||||
local_files = set(os.listdir(BACKUP_DIR))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
items = []
|
||||
if provider == 'ftp':
|
||||
import ftplib
|
||||
host = str(p_cfg.get('host', '')).strip()
|
||||
if not host: return [], ""
|
||||
try: port = int(p_cfg.get('port') or 21)
|
||||
except (ValueError, TypeError): port = 21
|
||||
user = str(p_cfg.get('user', '')).strip() or 'anonymous'
|
||||
password = str(p_cfg.get('password', ''))
|
||||
rem_path = str(p_cfg.get('path', '') or '').strip()
|
||||
use_tls = str(p_cfg.get('tls', 'none')).lower() in ('explicit', 'tls', 'ftps', '1', 'true')
|
||||
ftp = ftplib.FTP_TLS(timeout=15) if use_tls else ftplib.FTP(timeout=15)
|
||||
try:
|
||||
ftp.connect(host, port)
|
||||
ftp.login(user, password)
|
||||
if use_tls: ftp.prot_p()
|
||||
if rem_path and rem_path not in ('/', '.'):
|
||||
for part in [p for p in rem_path.split('/') if p]:
|
||||
try: ftp.cwd(part)
|
||||
except Exception: pass
|
||||
used_mlsd = False
|
||||
try:
|
||||
for line in ftp.mlsd():
|
||||
name, facts = line
|
||||
if facts.get('type') == 'file' and name.lower().endswith(BACKUP_ALLOWED_EXTS):
|
||||
size = int(facts.get('size') or 0)
|
||||
mtime_str = facts.get('modify', '')
|
||||
dt_str = ''
|
||||
if len(mtime_str) >= 14:
|
||||
dt_str = f"{mtime_str[0:4]}-{mtime_str[4:6]}-{mtime_str[6:8]} {mtime_str[8:10]}:{mtime_str[10:12]}:{mtime_str[12:14]}"
|
||||
items.append({
|
||||
'name': name,
|
||||
'size': size,
|
||||
'size_str': format_bytes(size),
|
||||
'date': dt_str,
|
||||
'is_local': (name in local_files)
|
||||
})
|
||||
used_mlsd = True
|
||||
except Exception:
|
||||
pass
|
||||
if not used_mlsd:
|
||||
try:
|
||||
for name in ftp.nlst():
|
||||
base = os.path.basename(name.strip())
|
||||
if base.lower().endswith(BACKUP_ALLOWED_EXTS):
|
||||
sz = 0
|
||||
try: sz = ftp.size(base) or 0
|
||||
except Exception: pass
|
||||
items.append({
|
||||
'name': base,
|
||||
'size': sz,
|
||||
'size_str': format_bytes(sz) if sz else '—',
|
||||
'date': '',
|
||||
'is_local': (base in local_files)
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try: ftp.quit()
|
||||
except Exception:
|
||||
try: ftp.close()
|
||||
except Exception: pass
|
||||
|
||||
elif provider == 'sftp':
|
||||
import paramiko
|
||||
host = str(p_cfg.get('host', '')).strip()
|
||||
if not host: return [], ""
|
||||
try: port = int(p_cfg.get('port') or 22)
|
||||
except (ValueError, TypeError): port = 22
|
||||
user = str(p_cfg.get('user', '')).strip()
|
||||
password = str(p_cfg.get('password', ''))
|
||||
key_text = str(p_cfg.get('key', '')).strip()
|
||||
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
|
||||
try:
|
||||
ssh.connect(host, port=port, username=user, password=password or None, pkey=pkey, timeout=15)
|
||||
sftp = ssh.open_sftp()
|
||||
target_dir, _ = _normalize_sftp_target(sftp, p_cfg.get('path', ''))
|
||||
try:
|
||||
for attr in sftp.listdir_attr(target_dir):
|
||||
base = os.path.basename(attr.filename)
|
||||
if base.lower().endswith(BACKUP_ALLOWED_EXTS):
|
||||
sz = attr.st_size or 0
|
||||
mtime = attr.st_mtime or 0
|
||||
dt_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime)) if mtime else ''
|
||||
items.append({
|
||||
'name': base,
|
||||
'size': sz,
|
||||
'size_str': format_bytes(sz),
|
||||
'date': dt_str,
|
||||
'is_local': (base in local_files)
|
||||
})
|
||||
except Exception as e_ls:
|
||||
print(f"[ap-backup] Erreur listdir_attr SFTP ({target_dir}): {e_ls}", flush=True)
|
||||
finally:
|
||||
try: sftp.close()
|
||||
except Exception: pass
|
||||
finally:
|
||||
try: ssh.close()
|
||||
except Exception: pass
|
||||
|
||||
elif provider == 'dropbox':
|
||||
token = str(p_cfg.get('token', '')).strip()
|
||||
if token:
|
||||
rem_path = str(p_cfg.get('path', '') or '/AP-Manageur-Backups/').strip()
|
||||
path_arg = "" if rem_path in ('/', '') else ('/' + rem_path.strip('/')).rstrip('/')
|
||||
url = "https://api.dropboxapi.com/2/files/list_folder"
|
||||
payload = json.dumps({"path": path_arg, "recursive": False}).encode('utf-8')
|
||||
req = urllib.request.Request(url, data=payload, method='POST')
|
||||
req.add_header('Authorization', f'Bearer {token}')
|
||||
req.add_header('Content-Type', 'application/json')
|
||||
ctx = ssl.create_default_context()
|
||||
try:
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
|
||||
data = json.loads(resp.read().decode('utf-8'))
|
||||
for entry in data.get('entries', []):
|
||||
if entry.get('.tag') == 'file':
|
||||
base = entry.get('name', '')
|
||||
if base.lower().endswith(BACKUP_ALLOWED_EXTS):
|
||||
sz = int(entry.get('size') or 0)
|
||||
mtime = entry.get('server_modified', '').replace('T', ' ').rstrip('Z')
|
||||
items.append({
|
||||
'name': base,
|
||||
'size': sz,
|
||||
'size_str': format_bytes(sz),
|
||||
'date': mtime,
|
||||
'is_local': (base in local_files)
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[ap-backup] Erreur listing détaillé Dropbox : {e}", flush=True)
|
||||
|
||||
elif provider == 'gdrive':
|
||||
token = str(p_cfg.get('token', '')).strip()
|
||||
if token:
|
||||
folder_id = str(p_cfg.get('folder_id', '')).strip()
|
||||
ctx = ssl.create_default_context()
|
||||
query = "trashed = false and mimeType != 'application/vnd.google-apps.folder'"
|
||||
if folder_id:
|
||||
query += f" and '{folder_id}' in parents"
|
||||
search_url = f"https://www.googleapis.com/drive/v3/files?q={urllib.parse.quote(query)}&pageSize=1000&fields=files(id,name,size,modifiedTime)"
|
||||
req = urllib.request.Request(search_url, method='GET')
|
||||
req.add_header('Authorization', f'Bearer {token}')
|
||||
try:
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
|
||||
data = json.loads(resp.read().decode('utf-8'))
|
||||
for f in data.get('files', []):
|
||||
base = f.get('name', '')
|
||||
if base.lower().endswith(BACKUP_ALLOWED_EXTS):
|
||||
sz = int(f.get('size') or 0)
|
||||
mtime = f.get('modifiedTime', '').replace('T', ' ').split('.')[0]
|
||||
items.append({
|
||||
'name': base,
|
||||
'size': sz,
|
||||
'size_str': format_bytes(sz),
|
||||
'date': mtime,
|
||||
'id': f.get('id', ''),
|
||||
'is_local': (base in local_files)
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[ap-backup] Erreur listing détaillé GDrive : {e}", flush=True)
|
||||
|
||||
elif provider == 'webdav':
|
||||
names = _list_remote_webdav(p_cfg)
|
||||
if names:
|
||||
for n in names:
|
||||
if n.lower().endswith(BACKUP_ALLOWED_EXTS):
|
||||
items.append({
|
||||
'name': n,
|
||||
'size': 0,
|
||||
'size_str': '—',
|
||||
'date': '',
|
||||
'is_local': (n in local_files)
|
||||
})
|
||||
|
||||
elif provider == 's3':
|
||||
names = _list_remote_s3(p_cfg)
|
||||
if names:
|
||||
for n in names:
|
||||
if n.lower().endswith(BACKUP_ALLOWED_EXTS):
|
||||
items.append({
|
||||
'name': n,
|
||||
'size': 0,
|
||||
'size_str': '—',
|
||||
'date': '',
|
||||
'is_local': (n in local_files)
|
||||
})
|
||||
|
||||
items.sort(key=lambda x: x.get('name', ''), reverse=True)
|
||||
return items, None
|
||||
|
||||
|
||||
def get_remote_storage_files(cfg=None):
|
||||
rcfg = cfg or get_backup_remote_config()
|
||||
if not rcfg.get('enabled'):
|
||||
return None
|
||||
provider = str(rcfg.get('provider', 'ftp')).strip().lower()
|
||||
p_cfg = rcfg.get(provider, {}) if isinstance(rcfg.get(provider), dict) else {}
|
||||
if provider == 'ftp':
|
||||
return _list_remote_ftp(p_cfg)
|
||||
elif provider == 'sftp':
|
||||
return _list_remote_sftp(p_cfg)
|
||||
elif provider == 'dropbox':
|
||||
return _list_remote_dropbox(p_cfg)
|
||||
elif provider == 'gdrive':
|
||||
return _list_remote_gdrive(p_cfg)
|
||||
elif provider == 'webdav':
|
||||
return _list_remote_webdav(p_cfg)
|
||||
elif provider == 's3':
|
||||
return _list_remote_s3(p_cfg)
|
||||
elif provider == 'webhook':
|
||||
if provider == 'webhook':
|
||||
return None
|
||||
try:
|
||||
items, err = list_remote_files_detailed(rcfg)
|
||||
if items is None:
|
||||
return None
|
||||
return set(x['name'] for x in items)
|
||||
except Exception as e:
|
||||
print(f"[ap-backup] Erreur get_remote_storage_files ({provider}) : {e}", flush=True)
|
||||
return None
|
||||
|
||||
def sync_remote_backups_presence(force=False):
|
||||
@@ -9526,6 +9908,59 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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/remote/files'):
|
||||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||||
rcfg = get_backup_remote_config()
|
||||
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
|
||||
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
|
||||
sync_remote_backups_presence(force=True)
|
||||
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.startswith('/api/backups/remote/file/download'):
|
||||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
qs = urllib.parse.parse_qs(parsed.query)
|
||||
fname = qs.get('file', [''])[0].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)
|
||||
with tempfile.NamedTemporaryFile('wb', delete=False, suffix='.zip') as tmp:
|
||||
tmp_path = tmp.name
|
||||
try:
|
||||
download_remote_file(clean_name, tmp_path)
|
||||
file_sz = os.path.getsize(tmp_path)
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'application/zip')
|
||||
self.send_header('Content-Disposition', f'attachment; filename="{clean_name}"')
|
||||
self.send_header('Content-Length', str(file_sz))
|
||||
self.end_headers()
|
||||
with open(tmp_path, 'rb') as f:
|
||||
while True:
|
||||
chunk = f.read(65536)
|
||||
if not chunk: break
|
||||
self.wfile.write(chunk)
|
||||
log('telechargement_sauvegarde_distante', username(self) or 'Administrateur', request_ip(self), clean_name)
|
||||
return
|
||||
except Exception as e:
|
||||
self.send_json({'error': f"Échec du téléchargement depuis le stockage distant : {e}"}, 500); return
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
try: os.unlink(tmp_path)
|
||||
except OSError: pass
|
||||
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)
|
||||
@@ -10463,6 +10898,51 @@ class Handler(BaseHTTPRequestHandler):
|
||||
log('televersement_distant_manuel', username(self) or 'Administrateur', request_ip(self), f"{clean_name} ({msg})")
|
||||
items, total_size = list_server_backups()
|
||||
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', username(self) or 'Administrateur', request_ip(self), clean_name)
|
||||
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 not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||||
fname = str(data.get('filename', '')).strip()
|
||||
if not fname:
|
||||
self.send_json({'error': 'Nom de fichier requis'}, 400); return
|
||||
clean_name = os.path.basename(fname)
|
||||
try:
|
||||
ok, msg = delete_remote_file(clean_name)
|
||||
if not ok:
|
||||
raise RuntimeError(msg)
|
||||
sync_remote_backups_presence(force=True)
|
||||
log('suppression_sauvegarde_distante', username(self) or 'Administrateur', request_ip(self), clean_name)
|
||||
items, total_size = list_server_backups()
|
||||
self.send_json({
|
||||
'ok': True,
|
||||
'message': f"Fichier « {clean_name} » supprimé du stockage distant.",
|
||||
'backups': items
|
||||
}); return
|
||||
except Exception as e:
|
||||
self.send_json({'error': f"Échec suppression sur le stockage distant : {e}"}, 500); 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':
|
||||
|
||||
+196
@@ -5166,9 +5166,14 @@
|
||||
<h3 style="margin:0;font-size:16px" data-i18n="backup_list_title">📂 Sauvegardes enregistrées</h3>
|
||||
<div id="backupsListSummary" class="muted" style="font-size:12px;margin-top:3px">—</div>
|
||||
</div>
|
||||
<div style="display:inline-flex;align-items:center;gap:8px;flex-wrap:wrap">
|
||||
<button id="btnRefreshBackups" type="button" class="secondary" onclick="refreshBackupsTab()" style="display:inline-flex;align-items:center;gap:6px" data-i18n="btn_refresh">
|
||||
🔄 Actualiser
|
||||
</button>
|
||||
<button id="btnOpenRemoteDriveModal" type="button" class="secondary" onclick="openRemoteDriveModal()" style="display:inline-flex;align-items:center;gap:6px" title="Voir, télécharger et gérer les sauvegardes présentes sur le stockage distant">
|
||||
☁️ <span data-i18n="btn_view_remote_drive">Voir les fichiers du drive</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
@@ -5898,6 +5903,49 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Fichiers du Drive / Stockage Distant -->
|
||||
<div id="modalRemoteDriveFiles" class="modal-overlay">
|
||||
<div class="modal-card" style="max-width:760px;width:95%">
|
||||
<div class="modal-header">
|
||||
<h2 style="margin:0;font-size:17px;display:flex;align-items:center;gap:8px">
|
||||
<span id="remoteDriveModalIcon">☁️</span>
|
||||
<span data-i18n="modal_remote_drive_title">Fichiers du stockage distant (Drive)</span>
|
||||
</h2>
|
||||
<button type="button" class="secondary" style="padding:4px 10px;font-size:16px" onclick="closeRemoteDriveModal()">✕</button>
|
||||
</div>
|
||||
<div class="modal-body" style="display:flex;flex-direction:column;gap:12px">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px">
|
||||
<div id="remoteDriveModalSub" class="muted" style="font-size:13px">
|
||||
Chargement des fichiers distants…
|
||||
</div>
|
||||
<button type="button" class="secondary" onclick="loadRemoteDriveFiles()" style="padding:4px 10px;font-size:12px;display:inline-flex;align-items:center;gap:4px">
|
||||
🔄 Actualiser le drive
|
||||
</button>
|
||||
</div>
|
||||
<div id="remoteDriveActionMsg" style="display:none;padding:8px 12px;border-radius:8px;font-size:13px"></div>
|
||||
<div class="table-wrap" style="max-height:400px;overflow-y:auto">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="th_file">FICHIER</th>
|
||||
<th data-i18n="th_date">DATE</th>
|
||||
<th data-i18n="th_size">TAILLE</th>
|
||||
<th data-i18n="th_status">STATUT</th>
|
||||
<th style="text-align:right" data-i18n="th_actions">ACTIONS</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="remoteDriveFilesTableBody">
|
||||
<tr><td colspan="5" class="empty">Chargement…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer" style="display:flex;justify-content:flex-end">
|
||||
<button type="button" class="secondary" onclick="closeRemoteDriveModal()" data-i18n="btn_close">Fermer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js" defer></script>
|
||||
@@ -11170,6 +11218,154 @@ ${vpnBadgeTopo}
|
||||
}
|
||||
}
|
||||
|
||||
async function openRemoteDriveModal() {
|
||||
const modal = $('modalRemoteDriveFiles');
|
||||
if (!modal) return;
|
||||
modal.classList.add('active');
|
||||
modal.style.display = 'flex';
|
||||
await loadRemoteDriveFiles();
|
||||
}
|
||||
|
||||
function closeRemoteDriveModal() {
|
||||
const modal = $('modalRemoteDriveFiles');
|
||||
if (modal) {
|
||||
modal.classList.remove('active');
|
||||
modal.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRemoteDriveFiles() {
|
||||
const tbody = $('remoteDriveFilesTableBody');
|
||||
const sub = $('remoteDriveModalSub');
|
||||
const iconEl = $('remoteDriveModalIcon');
|
||||
const msg = $('remoteDriveActionMsg');
|
||||
if (msg) msg.style.display = 'none';
|
||||
if (tbody) tbody.innerHTML = `<tr><td colspan="5" class="empty"><span class="spin">🔄</span> ${escapeHtml(t('remote_drive_loading', 'Connexion et récupération des fichiers sur le drive…'))}</td></tr>`;
|
||||
|
||||
try {
|
||||
const res = await apiFetch('/api/backups/remote/files');
|
||||
const d = await res.json();
|
||||
if (!res.ok) throw new Error(d.error || 'Erreur lors de la récupération des fichiers distants');
|
||||
|
||||
const prov = d.provider || 'ftp';
|
||||
const pName = d.provider_name || prov.toUpperCase();
|
||||
const provIconHtml = (typeof getRemoteProviderIconHtml === 'function') ? getRemoteProviderIconHtml(prov) : '☁️ ';
|
||||
if (iconEl) iconEl.innerHTML = provIconHtml;
|
||||
if (sub) {
|
||||
sub.innerHTML = `<span>${provIconHtml}<strong>${escapeHtml(pName)}</strong> • ${d.count || 0} sauvegarde(s) détectée(s)</span>`;
|
||||
}
|
||||
|
||||
if (!d.files || !d.files.length) {
|
||||
if (tbody) tbody.innerHTML = `<tr><td colspan="5" class="empty">${escapeHtml(t('remote_drive_empty', 'Aucun fichier de sauvegarde trouvé sur le stockage distant.'))}</td></tr>`;
|
||||
return;
|
||||
}
|
||||
|
||||
if (tbody) {
|
||||
tbody.innerHTML = d.files.map(f => {
|
||||
const fname = f.name || '';
|
||||
const safeArg = escapeHtml(fname).replace(/'/g, ''');
|
||||
const isLocal = !!f.is_local;
|
||||
const localBadge = isLocal
|
||||
? `<span class="pill pill-green pill-no-dot" style="font-size:10px;padding:2px 6px" title="${escapeHtml(t('backup_already_local', 'Déjà présent dans les sauvegardes locales'))}">💾 Local</span>`
|
||||
: `<span class="pill pill-no-dot" style="font-size:10px;padding:2px 6px;opacity:0.75">☁️ Drive seul</span>`;
|
||||
|
||||
const pullBtn = isLocal
|
||||
? `<button type="button" class="secondary" style="padding:4px 8px;font-size:11px" onclick="pullRemoteBackupToLocal('${safeArg}')" title="${escapeHtml(t('backup_reimport', 'Réimporter / Écraser la version locale'))}">📥 Réimporter</button>`
|
||||
: `<button type="button" class="secondary" style="padding:4px 8px;font-size:11px;border-color:var(--blue);color:var(--blue)" onclick="pullRemoteBackupToLocal('${safeArg}')" title="${escapeHtml(t('backup_import_local', 'Rapatrier dans AP Manageur'))}">📥 Rapatrier</button>`;
|
||||
|
||||
return `<tr>
|
||||
<td style="font-family:monospace;font-size:12px;word-break:break-all"><strong>${escapeHtml(fname)}</strong></td>
|
||||
<td style="white-space:nowrap;font-size:12px" class="muted">${escapeHtml(f.date || '—')}</td>
|
||||
<td style="white-space:nowrap;font-size:12px">${escapeHtml(f.size_str || '—')}</td>
|
||||
<td>${localBadge}</td>
|
||||
<td style="text-align:right;white-space:nowrap">
|
||||
<div style="display:inline-flex;gap:6px;justify-content:flex-end">
|
||||
<button type="button" class="secondary" style="padding:4px 8px;font-size:11px" onclick="downloadRemoteFileDirect('${safeArg}')" title="${escapeHtml(t('backup_btn_download_pc', 'Télécharger sur mon PC'))}">⬇️ PC</button>
|
||||
${pullBtn}
|
||||
<button type="button" class="secondary danger" style="padding:4px 8px;font-size:11px;border-color:rgba(239,68,68,0.45);color:var(--red)" onclick="deleteRemoteDriveFile('${safeArg}')" title="${escapeHtml(t('btn_delete', 'Supprimer du drive'))}">🗑️</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
} catch (e) {
|
||||
if (tbody) {
|
||||
tbody.innerHTML = `<tr><td colspan="5" class="empty" style="color:var(--red)">❌ ${escapeHtml(tErr(e.message))}</td></tr>`;
|
||||
}
|
||||
if (sub) sub.textContent = 'Erreur de connexion au stockage distant';
|
||||
}
|
||||
}
|
||||
|
||||
function downloadRemoteFileDirect(filename) {
|
||||
window.location.href = '/api/backups/remote/file/download?file=' + encodeURIComponent(filename);
|
||||
}
|
||||
|
||||
async function pullRemoteBackupToLocal(filename) {
|
||||
const msg = $('remoteDriveActionMsg');
|
||||
if (msg) {
|
||||
msg.style.display = 'block';
|
||||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||||
msg.style.color = 'var(--blue)';
|
||||
msg.innerHTML = `<span class="spin">🔄</span> Rapatriement de « ${escapeHtml(filename)} » vers le serveur local…`;
|
||||
}
|
||||
try {
|
||||
const res = await apiFetch('/api/backups/remote/file/pull', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ filename })
|
||||
});
|
||||
const d = await res.json();
|
||||
if (!res.ok) throw new Error(d.error || 'Erreur lors du rapatriement');
|
||||
if (msg) {
|
||||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||||
msg.style.color = 'var(--green)';
|
||||
msg.textContent = '✓ ' + (d.message || 'Sauvegarde rapatriée avec succès !');
|
||||
}
|
||||
if (Array.isArray(d.backups)) renderServerBackupsTable(d.backups, serverBackupsTotalSize);
|
||||
await loadRemoteDriveFiles();
|
||||
} catch (e) {
|
||||
if (msg) {
|
||||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||||
msg.style.color = 'var(--red)';
|
||||
msg.textContent = '❌ ' + tErr(e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteRemoteDriveFile(filename) {
|
||||
const confirmTxt = t('backup_confirm_remote_delete', 'Supprimer définitivement la sauvegarde « {file} » du stockage distant (Drive) ?\n\nAttention, cette action est irréversible.').replace('{file}', filename);
|
||||
if (!confirm(confirmTxt)) return;
|
||||
const msg = $('remoteDriveActionMsg');
|
||||
if (msg) {
|
||||
msg.style.display = 'block';
|
||||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||||
msg.style.color = 'var(--red)';
|
||||
msg.innerHTML = `<span class="spin">🔄</span> Suppression de « ${escapeHtml(filename)} » sur le drive…`;
|
||||
}
|
||||
try {
|
||||
const res = await apiFetch('/api/backups/remote/file/delete', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ filename })
|
||||
});
|
||||
const d = await res.json();
|
||||
if (!res.ok) throw new Error(d.error || 'Erreur suppression distante');
|
||||
if (msg) {
|
||||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||||
msg.style.color = 'var(--green)';
|
||||
msg.textContent = '✓ ' + (d.message || 'Fichier supprimé du drive.');
|
||||
}
|
||||
if (Array.isArray(d.backups)) renderServerBackupsTable(d.backups, serverBackupsTotalSize);
|
||||
await loadRemoteDriveFiles();
|
||||
} catch (e) {
|
||||
if (msg) {
|
||||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||||
msg.style.color = 'var(--red)';
|
||||
msg.textContent = '❌ ' + tErr(e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteServerBackup(filename) {
|
||||
const confirmTxt = t('backup_confirm_delete', 'Supprimer définitivement la sauvegarde « {file} » ?').replace('{file}', filename);
|
||||
if (!confirm(confirmTxt)) return;
|
||||
|
||||
+10
-1
@@ -1233,5 +1233,14 @@ window.I18N['en-gb'] = {
|
||||
"backup_btn_remote_push_title": "Upload to {prov}",
|
||||
"backup_btn_remote_push": "Upload to remote storage",
|
||||
"backup_btn_remote_short": "Remote",
|
||||
"backup_refreshing": "Checking cloud…"
|
||||
"backup_refreshing": "Checking cloud…",
|
||||
"btn_view_remote_drive": "View drive files",
|
||||
"modal_remote_drive_title": "Remote storage files (Drive)",
|
||||
"remote_drive_loading": "Connecting and retrieving files from drive…",
|
||||
"remote_drive_empty": "No backup files found on remote storage.",
|
||||
"backup_confirm_remote_delete": "Permanently delete backup \"{file}\" from remote storage (Drive)?\n\nWarning, this action cannot be undone.",
|
||||
"backup_already_local": "Already present in local backups",
|
||||
"backup_reimport": "Reimport / Overwrite local version",
|
||||
"backup_import_local": "Pull into AP Manageur",
|
||||
"backup_btn_download_pc": "Download to my PC"
|
||||
};
|
||||
+10
-1
@@ -1233,5 +1233,14 @@ window.I18N['en-us'] = {
|
||||
"backup_btn_remote_push_title": "Upload to {prov}",
|
||||
"backup_btn_remote_push": "Upload to remote storage",
|
||||
"backup_btn_remote_short": "Remote",
|
||||
"backup_refreshing": "Checking cloud…"
|
||||
"backup_refreshing": "Checking cloud…",
|
||||
"btn_view_remote_drive": "View drive files",
|
||||
"modal_remote_drive_title": "Remote storage files (Drive)",
|
||||
"remote_drive_loading": "Connecting and retrieving files from drive…",
|
||||
"remote_drive_empty": "No backup files found on remote storage.",
|
||||
"backup_confirm_remote_delete": "Permanently delete backup \"{file}\" from remote storage (Drive)?\n\nWarning, this action cannot be undone.",
|
||||
"backup_already_local": "Already present in local backups",
|
||||
"backup_reimport": "Reimport / Overwrite local version",
|
||||
"backup_import_local": "Pull into AP Manageur",
|
||||
"backup_btn_download_pc": "Download to my PC"
|
||||
};
|
||||
+10
-1
@@ -1233,5 +1233,14 @@ window.I18N['fr'] = {
|
||||
"backup_btn_remote_push_title": "Envoyer vers {prov}",
|
||||
"backup_btn_remote_push": "Envoyer vers le stockage distant",
|
||||
"backup_btn_remote_short": "Distant",
|
||||
"backup_refreshing": "Vérification cloud…"
|
||||
"backup_refreshing": "Vérification cloud…",
|
||||
"btn_view_remote_drive": "Voir les fichiers du drive",
|
||||
"modal_remote_drive_title": "Fichiers du stockage distant (Drive)",
|
||||
"remote_drive_loading": "Connexion et récupération des fichiers sur le drive…",
|
||||
"remote_drive_empty": "Aucun fichier de sauvegarde trouvé sur le stockage distant.",
|
||||
"backup_confirm_remote_delete": "Supprimer définitivement la sauvegarde « {file} » du stockage distant (Drive) ?\n\nAttention, cette action est irréversible.",
|
||||
"backup_already_local": "Déjà présent dans les sauvegardes locales",
|
||||
"backup_reimport": "Réimporter / Écraser la version locale",
|
||||
"backup_import_local": "Rapatrier dans AP Manageur",
|
||||
"backup_btn_download_pc": "Télécharger sur mon PC"
|
||||
};
|
||||
Reference in new issue
Block a user