AP manageur V1.1 (Bêta)
This commit is contained in:
1 parent
da07838fda
commit
0b685640f8
4 files changed
+136
-9
No files matched your search
@@ -10677,7 +10677,134 @@ def _download_gdrive(cfg, remote_filename, dest_path):
|
||||
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}')
|
||||
except Exception:
|
||||
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
|
||||
pass
|
||||
if not used_mlsd:
|
||||
try:
|
||||
|
||||
Reference in new issue
Block a user