APmanageur Wi-Fi V1.0

This commit is contained in:
yoannmultigaming committed 2026-11-18 18:38:33 +01:00
1 parent c46d60d262
commit ed08f9c8d4
8 files changed
+913 -24

No files matched your search

+2 -1
View File
@@ -42,9 +42,10 @@ RUN chmod +x /entrypoint.sh && rm -f /var/www/html/index.html.orig \
ENV AP_DB_FILE=/data/ap-dashboard.sqlite3 \ ENV AP_DB_FILE=/data/ap-dashboard.sqlite3 \
AP_CONNECTION_FILE=/data/connection \ AP_CONNECTION_FILE=/data/connection \
AP_UPTIME_FILE=/data/uptime \ AP_UPTIME_FILE=/data/uptime \
AP_BACKUP_DIR=/backups \
AP_DNS="1.1.1.1,9.9.9.9" AP_DNS="1.1.1.1,9.9.9.9"
VOLUME ["/data", "/etc/NetworkManager/system-connections", "/var/lib/NetworkManager"] VOLUME ["/data", "/backups", "/etc/NetworkManager/system-connections", "/var/lib/NetworkManager"]
ENV AP_WEB_PORT=1001 ENV AP_WEB_PORT=1001
EXPOSE 1001 EXPOSE 1001
+338
View File
@@ -7853,6 +7853,252 @@ def inspect_backup_bytes(raw_bytes, filename=''):
raise ValueError(f"Fichier de sauvegarde non reconnu (ni ZIP, ni SQLite, ni JSON) : {e}") raise ValueError(f"Fichier de sauvegarde non reconnu (ni ZIP, ni SQLite, ni JSON) : {e}")
BACKUP_DIR = os.environ.get('AP_BACKUP_DIR', '/backups').strip() or '/backups'
BACKUP_ALLOWED_EXTS = ('.zip', '.json', '.sqlite', '.sqlite3', '.db')
backup_lock = threading.Lock()
_last_backup_cron_minute = None
def ensure_backup_dir():
try:
os.makedirs(BACKUP_DIR, exist_ok=True)
return True
except OSError as e:
print(f"[ap-backup] Impossible de créer le dossier {BACKUP_DIR} : {e}", flush=True)
return False
def safe_backup_filepath(filename):
fname = str(filename or '').strip()
if not fname or fname in ('.', '..') or os.path.basename(fname) != fname or '/' in fname or '\\' in fname:
raise ValueError('Nom de fichier de sauvegarde invalide')
if not fname.lower().endswith(BACKUP_ALLOWED_EXTS):
raise ValueError('Extension de sauvegarde non autorisée')
ensure_backup_dir()
base_real = os.path.realpath(BACKUP_DIR)
full_path = os.path.realpath(os.path.join(base_real, fname))
if not full_path.startswith(base_real + os.sep):
raise ValueError('Chemin de sauvegarde hors du dossier autorisé')
return full_path, fname
def build_backup_zip_bytes():
backup = export_backup_data()
json_bytes = json.dumps(backup, ensure_ascii=False, indent=2).encode('utf-8')
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
zf.writestr('configuration.json', json_bytes)
if os.path.exists(DB_FILE):
try:
with open(DB_FILE, 'rb') as f_db:
zf.writestr('ap-dashboard.sqlite3', f_db.read())
except Exception as e_db:
print(f"[backup] Inclusion sqlite impossible : {e_db}", flush=True)
readme_text = (
f"Sauvegarde AP Manageur ({APP_VERSION})\n"
f"Date d'export : {datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n"
"Contenu de cette archive :\n"
"- configuration.json : Configuration complète (réglages Wi-Fi, profils VPN WireGuard & OpenVPN, routage appareils, noms et logos des équipements, catégories, blocage et réglages système).\n"
"- ap-dashboard.sqlite3 : Base de données SQLite brute complète.\n\n"
"Restauration :\n"
"Vous pouvez importer ou restaurer directement cette archive .zip (ou configuration.json) "
"dans AP Manageur (Réglages > Sauvegardes ou Assistant Setup).\n"
)
zf.writestr('README.txt', readme_text.encode('utf-8'))
return buf.getvalue()
def default_backup_schedule():
return {
'enabled': False,
'cron_expr': '0 3 * * *',
'day': '*',
'hour': 3,
'minute': 0,
'retention': 7,
'last_run': '',
'last_file': '',
'last_status': ''
}
def get_backup_schedule():
cfg = default_backup_schedule()
raw = get_pref('backup_schedule', '')
if raw:
try:
loaded = json.loads(raw)
if isinstance(loaded, dict):
cfg.update(loaded)
except Exception:
pass
cfg['enabled'] = bool(cfg.get('enabled', False))
try: cfg['retention'] = max(0, min(365, int(cfg.get('retention', 7))))
except (ValueError, TypeError): cfg['retention'] = 7
if not str(cfg.get('cron_expr', '')).strip() or len(str(cfg.get('cron_expr', '')).strip().split()) != 5:
cfg['cron_expr'] = f"{cfg.get('minute', 0)} {cfg.get('hour', 3)} * * {cfg.get('day', '*')}"
return cfg
def save_backup_schedule(data):
cur = get_backup_schedule()
if 'enabled' in data:
cur['enabled'] = bool(data['enabled'])
if 'day' in data:
cur['day'] = str(data['day']).strip() or '*'
if 'hour' in data:
h_raw = str(data['hour']).strip()
if h_raw == '*':
cur['hour'] = '*'
else:
try: cur['hour'] = max(0, min(23, int(h_raw)))
except (ValueError, TypeError): cur['hour'] = 3
if 'minute' in data:
try: cur['minute'] = max(0, min(59, int(data['minute'])))
except (ValueError, TypeError): cur['minute'] = 0
if 'retention' in data:
try: cur['retention'] = max(0, min(365, int(data['retention'])))
except (ValueError, TypeError): cur['retention'] = 7
cron_raw = str(data.get('cron_expr', '')).strip()
if cron_raw:
parts = cron_raw.split()
if len(parts) != 5:
raise ValueError('Expression Cron invalide : 5 champs attendus (minute heure jour mois jour_semaine)')
cur['cron_expr'] = ' '.join(parts)
else:
cur['cron_expr'] = f"{cur['minute']} {cur['hour']} * * {cur['day']}"
set_pref('backup_schedule', json.dumps(cur, ensure_ascii=False))
return cur
def apply_backup_retention(retention):
try:
keep = int(retention or 0)
except (ValueError, TypeError):
return 0
if keep <= 0 or not os.path.isdir(BACKUP_DIR):
return 0
auto_files = []
for entry in os.listdir(BACKUP_DIR):
if entry.startswith('ap-manageur-backup-auto-') and entry.lower().endswith('.zip'):
full = os.path.join(BACKUP_DIR, entry)
if os.path.isfile(full):
try:
auto_files.append((os.path.getmtime(full), full, entry))
except OSError:
pass
auto_files.sort(key=lambda x: x[0], reverse=True)
removed = 0
for _, full, entry in auto_files[keep:]:
try:
os.remove(full)
removed += 1
except OSError:
pass
if removed:
print(f"[ap-backup] Rétention appliquée : {removed} ancienne(s) sauvegarde(s) automatique(s) supprimée(s) (max={keep}).", flush=True)
return removed
def create_server_backup(trigger='manual'):
with backup_lock:
if not ensure_backup_dir():
raise RuntimeError(f"Dossier de sauvegarde inaccessible : {BACKUP_DIR}")
tag = 'auto' if trigger == 'auto' else 'manual'
now_str = time.strftime('%Y%m%d-%H%M%S')
fname = f"ap-manageur-backup-{tag}-{now_str}.zip"
full_path = os.path.join(BACKUP_DIR, fname)
# Éviter collision si deux sauvegardes dans la même seconde
idx = 1
while os.path.exists(full_path):
fname = f"ap-manageur-backup-{tag}-{now_str}-{idx}.zip"
full_path = os.path.join(BACKUP_DIR, fname)
idx += 1
zip_bytes = build_backup_zip_bytes()
tmp_path = full_path + '.tmp'
with open(tmp_path, 'wb') as f:
f.write(zip_bytes)
os.replace(tmp_path, full_path)
sched = get_backup_schedule()
sched['last_run'] = time.strftime('%Y-%m-%d %H:%M:%S')
sched['last_file'] = fname
sched['last_status'] = 'ok'
set_pref('backup_schedule', json.dumps(sched, ensure_ascii=False))
if tag == 'auto':
apply_backup_retention(sched.get('retention', 7))
st = os.stat(full_path)
return {
'filename': fname,
'size': st.st_size,
'size_str': format_bytes(st.st_size),
'mtime': st.st_mtime,
'created_at': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_mtime)),
'trigger': tag
}
def list_server_backups():
ensure_backup_dir()
items = []
total_size = 0
try:
for entry in os.listdir(BACKUP_DIR):
if not entry.lower().endswith(BACKUP_ALLOWED_EXTS):
continue
full = os.path.join(BACKUP_DIR, entry)
if not os.path.isfile(full):
continue
try:
st = os.stat(full)
total_size += st.st_size
low = entry.lower()
if '-auto-' in low:
trig = 'auto'
elif '-manual-' in low or low.startswith('ap-manageur-'):
trig = 'manual'
else:
trig = 'external'
items.append({
'filename': entry,
'size': st.st_size,
'size_str': format_bytes(st.st_size),
'mtime': st.st_mtime,
'created_at': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_mtime)),
'trigger': trig
})
except OSError:
continue
except OSError:
pass
items.sort(key=lambda x: x['mtime'], reverse=True)
return items, total_size
def backup_scheduler_loop():
"""Boucle d'arrière-plan vérifiant l'expression Cron et créant automatiquement les sauvegardes dans BACKUP_DIR."""
global _last_backup_cron_minute
while True:
try:
now = datetime.datetime.now()
cur_key = f"{now.year}-{now.month:02d}-{now.day:02d} {now.hour:02d}:{now.minute:02d}"
if cur_key != _last_backup_cron_minute:
sched = get_backup_schedule()
if sched.get('enabled'):
cron_expr = str(sched.get('cron_expr', '')).strip()
if cron_expr and match_cron(cron_expr, now):
_last_backup_cron_minute = cur_key
print(f"[ap-backup] Déclenchement sauvegarde automatique Cron ({cron_expr}) à {cur_key}...", flush=True)
try:
info = create_server_backup(trigger='auto')
log('sauvegarde_automatique', 'Cron', '127.0.0.1', info['filename'])
print(f"[ap-backup] Sauvegarde automatique créée : {info['filename']} ({info['size_str']})", flush=True)
except Exception as e_bk:
print(f"[ap-backup] Erreur sauvegarde automatique : {e_bk}", flush=True)
try:
sc = get_backup_schedule()
sc['last_run'] = time.strftime('%Y-%m-%d %H:%M:%S')
sc['last_status'] = f'error: {e_bk}'
set_pref('backup_schedule', json.dumps(sc, ensure_ascii=False))
except Exception:
pass
except Exception as e:
print(f"[ap-backup] Erreur boucle scheduler backup : {e}", flush=True)
time.sleep(20)
API_MSG_I18N = { API_MSG_I18N = {
'Authentification réussie': {'en-us': 'Authentication successful', 'en-gb': 'Authentication successful'}, 'Authentification réussie': {'en-us': 'Authentication successful', 'en-gb': 'Authentication successful'},
'Authentification réussie avec': {'en-us': 'Authentication successful with', 'en-gb': 'Authentication successful with'}, 'Authentification réussie avec': {'en-us': 'Authentication successful with', 'en-gb': 'Authentication successful with'},
@@ -8169,6 +8415,40 @@ class Handler(BaseHTTPRequestHandler):
return return
except Exception as e: except Exception as e:
self.send_json({'error': f'Erreur génération archive ZIP: {e}'}, 500); return self.send_json({'error': f'Erreur génération archive ZIP: {e}'}, 500); return
if self.path == '/api/backups/list':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'backup_dir': BACKUP_DIR,
'schedule': get_backup_schedule(),
'backups': items,
'total_count': len(items),
'total_size': total_size,
'total_size_str': format_bytes(total_size)
}); 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)
qs = urllib.parse.parse_qs(parsed.query)
fname = (qs.get('file', [''])[0]).strip()
try:
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
content = open(full_path, 'rb').read()
ext = os.path.splitext(clean_name)[1].lower()
ctype = 'application/zip' if ext == '.zip' else ('application/json; charset=utf-8' if ext == '.json' else 'application/x-sqlite3')
self.send_response(200)
self.send_header('Content-Type', ctype)
self.send_header('Content-Disposition', f'attachment; filename="{clean_name}"')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content)
log('export_sauvegarde_complete', username(self) or 'Administrateur', request_ip(self), clean_name)
return
except Exception as e:
self.send_json({'error': str(e)}, 400); return
if self.path in ('/api/auth/admin', '/api/auth/user'): if self.path in ('/api/auth/admin', '/api/auth/user'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
c = db() c = db()
@@ -8997,6 +9277,63 @@ class Handler(BaseHTTPRequestHandler):
with traffic_lock: station_traffic.clear() with traffic_lock: station_traffic.clear()
log('reinitialisation_donnees', 'Système', request_ip(self), 'SYSTEM') log('reinitialisation_donnees', 'Système', request_ip(self), 'SYSTEM')
self.send_json({'ok':True,'message':'Toutes les données et le point d’accès ont été réinitialisés et supprimés','redirect':'/setup'}); return self.send_json({'ok':True,'message':'Toutes les données et le point d’accès ont été réinitialisés et supprimés','redirect':'/setup'}); return
if self.path == '/api/backups/schedule':
sched = save_backup_schedule(data)
log('planification_sauvegarde_modifiee', username(self) or 'Administrateur', request_ip(self), sched.get('cron_expr', ''))
self.send_json({'ok': True, 'message': 'Planification des sauvegardes enregistrée', 'schedule': sched}); return
if self.path == '/api/backups/create':
info = create_server_backup(trigger='manual')
log('creation_sauvegarde_serveur', username(self) or 'Administrateur', request_ip(self), info['filename'])
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'message': f"Sauvegarde créée : {info['filename']} ({info['size_str']})",
'backup': info,
'backups': items,
'total_count': len(items),
'total_size': total_size,
'total_size_str': format_bytes(total_size),
'schedule': get_backup_schedule()
}); return
if self.path == '/api/backups/delete':
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
os.remove(full_path)
log('suppression_sauvegarde', username(self) or 'Administrateur', request_ip(self), clean_name)
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'message': f'Sauvegarde supprimée : {clean_name}',
'backups': items,
'total_count': len(items),
'total_size': total_size,
'total_size_str': format_bytes(total_size)
}); return
if self.path == '/api/backups/inspect':
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
raw_bytes = open(full_path, 'rb').read()
backup = inspect_backup_bytes(raw_bytes, clean_name)
self.send_json({'ok': True, 'filename': clean_name, 'backup': backup}); return
if self.path == '/api/backups/restore':
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
raw_bytes = open(full_path, 'rb').read()
backup = inspect_backup_bytes(raw_bytes, clean_name)
stats = import_backup_data(backup, data.get('options', {}))
invalidate_status_cache()
log('import_configuration_complete', username(self) or 'Administrateur', request_ip(self), clean_name)
self.send_json({
'ok': True,
'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/auth/2fa/status': if self.path == '/api/auth/2fa/status':
self.send_json({'enabled':auth_state()['two_factor'],'recovery_remaining':recovery_remaining()}); return self.send_json({'enabled':auth_state()['two_factor'],'recovery_remaining':recovery_remaining()}); return
if self.path == '/api/auth/2fa/enable': if self.path == '/api/auth/2fa/enable':
@@ -9179,6 +9516,7 @@ if __name__ == '__main__':
threading.Thread(target=vpn_healthcheck_loop, daemon=True).start() threading.Thread(target=vpn_healthcheck_loop, daemon=True).start()
threading.Thread(target=update_background_metrics, daemon=True).start() threading.Thread(target=update_background_metrics, daemon=True).start()
threading.Thread(target=stats_report_scheduler_loop, daemon=True).start() threading.Thread(target=stats_report_scheduler_loop, daemon=True).start()
threading.Thread(target=backup_scheduler_loop, daemon=True).start()
try: os.remove(SOCKET_PATH) try: os.remove(SOCKET_PATH)
except OSError: pass except OSError: pass
server = UnixServer(SOCKET_PATH, Handler) server = UnixServer(SOCKET_PATH, Handler)
+3
View File
@@ -24,6 +24,8 @@ services:
AP_BRIDGE_NAME: "br0" AP_BRIDGE_NAME: "br0"
# Limite du nombre de connexions Wi-Fi simultanées (laisser vide ou 0 = illimité, ex. "10") # Limite du nombre de connexions Wi-Fi simultanées (laisser vide ou 0 = illimité, ex. "10")
AP_MAX_CLIENTS: "0" AP_MAX_CLIENTS: "0"
# Dossier interne des sauvegardes automatiques et manuelles (monté ci-dessous dans volumes)
AP_BACKUP_DIR: "/backups"
# Serveurs DNS fournis aux clients Wi-Fi : # Serveurs DNS fournis aux clients Wi-Fi :
# - En mode "ap" (NAT) : distribués directement aux clients via DHCP (Option 6) # - En mode "ap" (NAT) : distribués directement aux clients via DHCP (Option 6)
# - En mode "bridge" (Pont) : redirige automatiquement et de manière transparente toutes les requêtes DNS des clients Wi-Fi vers ces serveurs # - En mode "bridge" (Pont) : redirige automatiquement et de manière transparente toutes les requêtes DNS des clients Wi-Fi vers ces serveurs
@@ -31,6 +33,7 @@ services:
AP_DNS: "1.1.1.1,9.9.9.9" AP_DNS: "1.1.1.1,9.9.9.9"
volumes: volumes:
- /path/to/APmanageur/data:/data - /path/to/APmanageur/data:/data
- /path/to/APmanageur/backups:/backups # Dossier des sauvegardes automatiques (Cron) et manuelles
- /path/to/APmanageur/nm-connections:/etc/NetworkManager/system-connections - /path/to/APmanageur/nm-connections:/etc/NetworkManager/system-connections
- /path/to/APmanageur/nm-state:/var/lib/NetworkManager - /path/to/APmanageur/nm-state:/var/lib/NetworkManager
- /etc/localtime:/etc/localtime:ro # Synchronise l'horloge avec l'hôte - /etc/localtime:/etc/localtime:ro # Synchronise l'horloge avec l'hôte
+1 -1
View File
@@ -61,7 +61,7 @@ log "Interface Wi-Fi sélectionnée : $IFACE"
log "Configuration pont (si mode pont activé dans l'interface) : pont=$AP_BRIDGE_NAME, eth=${AP_BRIDGE_ETH:-auto}" log "Configuration pont (si mode pont activé dans l'interface) : pont=$AP_BRIDGE_NAME, eth=${AP_BRIDGE_ETH:-auto}"
# 2. NetworkManager : gère UNIQUEMENT l'interface Wi-Fi (l'interface Ethernet hôte ne doit JAMAIS être gérée par NM dans le conteneur) # 2. NetworkManager : gère UNIQUEMENT l'interface Wi-Fi (l'interface Ethernet hôte ne doit JAMAIS être gérée par NM dans le conteneur)
mkdir -p /etc/NetworkManager/conf.d /run/dbus /run/NetworkManager /var/run/apache2 /var/lock/apache2 /var/log/apache2 /data /etc/wireguard /etc/openvpn /run/ap-vpn /dev/net mkdir -p /etc/NetworkManager/conf.d /run/dbus /run/NetworkManager /var/run/apache2 /var/lock/apache2 /var/log/apache2 /data "${AP_BACKUP_DIR:-/backups}" /etc/wireguard /etc/openvpn /run/ap-vpn /dev/net
chown -R www-data:www-data /var/run/apache2 /var/lock/apache2 /var/log/apache2 2>/dev/null || true chown -R www-data:www-data /var/run/apache2 /var/lock/apache2 /var/log/apache2 2>/dev/null || true
if [[ ! -c /dev/net/tun ]]; then if [[ ! -c /dev/net/tun ]]; then
mknod /dev/net/tun c 10 200 2>/dev/null || true mknod /dev/net/tun c 10 200 2>/dev/null || true
+455 -22
View File
@@ -2888,6 +2888,10 @@
onclick="selectSettingsTab('custom')"> onclick="selectSettingsTab('custom')">
<span>🎨</span> <span data-i18n="settings_tab_custom">Personnalisation</span> <span>🎨</span> <span data-i18n="settings_tab_custom">Personnalisation</span>
</button> </button>
<button id="tabSettingsBackup" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
onclick="selectSettingsTab('backup')">
<span>📦</span> <span data-i18n="settings_tab_backup">Sauvegardes</span>
</button>
<button id="tabSettingsDanger" class="settings-nav-btn" type="button" role="tab" aria-selected="false" <button id="tabSettingsDanger" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
onclick="selectSettingsTab('danger')"> onclick="selectSettingsTab('danger')">
<span>⚠️</span> <span data-i18n="settings_tab_danger">Zone dangereuse</span> <span>⚠️</span> <span data-i18n="settings_tab_danger">Zone dangereuse</span>
@@ -4752,30 +4756,24 @@
</div> </div>
<!-- 5. Zone dangereuse --> <!-- 5. Zone dangereuse -->
<div id="panelSettingsDanger" class="settings-panel card" style="display:none"> <!-- 7. Sauvegardes & Automatisation Cron -->
<h2 data-i18n="danger_title">Zone dangereuse &amp; Maintenance</h2> <div id="panelSettingsBackup" class="settings-panel card" style="display:none;max-width:960px">
<p class="muted" data-i18n="danger_subtitle">Gestion des sauvegardes, restauration de la configuration et <div style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:10px">
actions critiques de maintenance du système.</p>
<!-- Module de Sauvegarde & Restauration (Export / Import) -->
<div
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:18px;margin-top:16px">
<div
style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:12px">
<div> <div>
<strong style="font-size:15px;display:flex;align-items:center;gap:8px" data-i18n="danger_backup_title"> <h2 style="margin:0 0 4px" data-i18n="backup_tab_title">Sauvegardes &amp; Restauration</h2>
📦 Sauvegarde &amp; Restauration globale <p class="muted" style="margin:0" data-i18n="backup_tab_subtitle">Créez, planifiez (Cron), exportez, restaurez ou supprimez vos sauvegardes stockées dans le volume Docker.</p>
</strong>
<p class="muted" style="margin:6px 0 0;font-size:13px;line-height:1.5" data-i18n="danger_backup_desc">
Exportez l'intégralité de la configuration système (réglages Wi-Fi, profils VPN WireGuard &amp; OpenVPN,
routages des équipements, noms et logos des appareils, liste noire de blocage et base de données SQLite)
dans un fichier sécurisé, ou restaurez une configuration précédente en un clic.
</p>
</div> </div>
<span id="backupDirBadge" class="pill pill-blue pill-no-dot" style="font-size:12px;font-family:monospace">📁 /backups</span>
</div> </div>
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:14px"> <!-- Actions rapides : Créer / Exporter / Importer -->
<button id="btnExportBackup" type="button" onclick="exportBackup()" <div style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-top:16px">
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
<button id="btnCreateServerBackup" type="button" onclick="createServerBackupNow()"
style="display:inline-flex;align-items:center;gap:8px" data-i18n="backup_create_now_btn">
💾 Créer une sauvegarde maintenant
</button>
<button id="btnExportBackup" type="button" class="secondary" onclick="exportBackup()"
style="display:inline-flex;align-items:center;gap:8px" data-i18n="danger_export_btn"> style="display:inline-flex;align-items:center;gap:8px" data-i18n="danger_export_btn">
📥 Exporter la configuration &amp; base de données 📥 Exporter la configuration &amp; base de données
</button> </button>
@@ -4791,7 +4789,111 @@
style="margin-top:12px;font-size:12px;display:none;padding:8px 12px;border-radius:6px"></div> style="margin-top:12px;font-size:12px;display:none;padding:8px 12px;border-radius:6px"></div>
</div> </div>
<div class="notice" style="margin-top:20px;border-color:rgba(239,68,68,0.3)"> <!-- Automatisation Cron -->
<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_cron_title">
⏱️ Automatisation des sauvegardes (Cron)
</strong>
<p class="muted" style="margin:4px 0 0;font-size:13px" data-i18n="backup_cron_desc">
Planifiez des sauvegardes automatiques enregistrées dans le dossier configuré via Docker Compose.
</p>
</div>
<label style="display:inline-flex;align-items:center;gap:8px;cursor:pointer;font-weight:600;user-select:none">
<input type="checkbox" id="backupCronEnabled" style="width:auto;margin:0" onchange="onBackupCronToggle()">
<span data-i18n="backup_cron_enable">Activer la planification</span>
</label>
</div>
<div id="backupCronFields" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin-top:12px">
<div>
<label class="label" for="backupCronDay" data-i18n="backup_cron_day_label">Fréquence / Jour</label>
<select id="backupCronDay" onchange="syncBackupCronFromSelects()">
<option value="*" data-i18n="stats_cron_day_all_short">Tous les jours</option>
<option value="1-5" data-i18n="stats_cron_day_workdays_short">Jours ouvrés (Lun-Ven)</option>
<option value="6,7" data-i18n="stats_cron_day_weekend_short">Week-end (Sam-Dim)</option>
<option value="1" data-i18n="stats_cron_day_mon">Chaque Lundi</option>
<option value="2" data-i18n="stats_cron_day_tue">Chaque Mardi</option>
<option value="3" data-i18n="stats_cron_day_wed">Chaque Mercredi</option>
<option value="4" data-i18n="stats_cron_day_thu">Chaque Jeudi</option>
<option value="5" data-i18n="stats_cron_day_fri">Chaque Vendredi</option>
<option value="6" data-i18n="stats_cron_day_sat">Chaque Samedi</option>
<option value="0" data-i18n="stats_cron_day_sun">Chaque Dimanche</option>
</select>
</div>
<div>
<label class="label" for="backupCronHour" data-i18n="backup_cron_hour_label">Heure</label>
<select id="backupCronHour" onchange="syncBackupCronFromSelects()"></select>
</div>
<div>
<label class="label" for="backupCronMinute" data-i18n="backup_cron_min_label">Minute</label>
<select id="backupCronMinute" onchange="syncBackupCronFromSelects()"></select>
</div>
<div>
<label class="label" for="backupCronRetention" data-i18n="backup_cron_retention_label">Rétention (0 = illimité)</label>
<input id="backupCronRetention" type="number" min="0" max="365" value="7">
</div>
</div>
<div style="display:grid;grid-template-columns:1fr auto;gap:10px;align-items:end;margin-top:12px">
<div>
<label class="label" for="backupCronExpr" data-i18n="backup_cron_expr_label">Expression Cron (minute heure jour mois jour_semaine)</label>
<input id="backupCronExpr" type="text" value="0 3 * * *" placeholder="0 3 * * *" style="font-family:monospace;margin-bottom:0" oninput="updateBackupCronSummary()">
</div>
<button id="btnSaveBackupSchedule" type="button" onclick="saveBackupSchedule()" data-i18n="backup_cron_save_btn">
💾 Enregistrer
</button>
</div>
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-top:10px">
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
<span id="backupCronHuman" class="pill pill-blue pill-no-dot" style="font-size:12px">📅 Tous les jours à 03:00</span>
<button type="button" class="secondary" style="padding:3px 9px;font-size:11px" onclick="applyBackupCronPreset('0 3 * * *','*',3,0)" data-i18n="backup_preset_daily">Chaque nuit 03:00</button>
<button type="button" class="secondary" style="padding:3px 9px;font-size:11px" onclick="applyBackupCronPreset('0 4 * * 0','0',4,0)" data-i18n="backup_preset_weekly">Dimanche 04:00</button>
<button type="button" class="secondary" style="padding:3px 9px;font-size:11px" onclick="applyBackupCronPreset('0 */6 * * *','*','*',0)" data-i18n="backup_preset_6h">Toutes les 6h</button>
</div>
<span id="backupCronLastRun" class="muted" style="font-size:12px"></span>
</div>
<div id="backupScheduleMsg" style="margin-top:10px;font-size:12px;display:none;padding:8px 12px;border-radius:6px"></div>
</div>
<!-- Liste des sauvegardes enregistrées -->
<div style="margin-top:20px">
<div class="topline" style="flex-wrap:wrap;gap:10px;margin-bottom:12px">
<div>
<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>
<button type="button" class="secondary" onclick="loadBackupsTab()" style="display:inline-flex;align-items:center;gap:6px" data-i18n="btn_refresh">
🔄 Actualiser
</button>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th data-i18n="backup_th_file">FICHIER</th>
<th data-i18n="backup_th_type">TYPE</th>
<th data-i18n="backup_th_date">DATE</th>
<th data-i18n="backup_th_size">TAILLE</th>
<th data-i18n="backup_th_actions" style="text-align:right">ACTIONS</th>
</tr>
</thead>
<tbody id="backupsTableBody">
<tr><td colspan="5" class="empty" data-i18n="loading">Chargement…</td></tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- 8. Zone dangereuse -->
<div id="panelSettingsDanger" class="settings-panel card" style="display:none">
<h2 data-i18n="danger_title">Zone dangereuse &amp; Maintenance</h2>
<p class="muted" data-i18n="danger_subtitle">Actions critiques de maintenance et réinitialisation complète du système.</p>
<div class="notice" style="margin-top:16px;border-color:rgba(239,68,68,0.3)">
<strong style="color:var(--red);display:flex;align-items:center;gap:6px" data-i18n="danger_delete_title">⚠️ <strong style="color:var(--red);display:flex;align-items:center;gap:6px" data-i18n="danger_delete_title">⚠️
Suppression irréversible</strong> Suppression irréversible</strong>
<p style="margin:8px 0 14px" data-i18n="danger_delete_desc">Supprime l’historique des logs, les appareils <p style="margin:8px 0 14px" data-i18n="danger_delete_desc">Supprime l’historique des logs, les appareils
@@ -7620,7 +7722,7 @@ ${vpnBadgeTopo}
function selectSettingsTab(tabKey) { function selectSettingsTab(tabKey) {
if (tabKey === '2fa') tabKey = 'admin'; if (tabKey === '2fa') tabKey = 'admin';
currentSettingsTab = tabKey; currentSettingsTab = tabKey;
const tabs = ['wifi', 'admin', 'vpn', 'proxy', 'notif', 'custom', 'danger']; const tabs = ['wifi', 'admin', 'vpn', 'proxy', 'notif', 'custom', 'backup', 'danger'];
tabs.forEach(k => { tabs.forEach(k => {
const btnId = 'tabSettings' + k.charAt(0).toUpperCase() + k.slice(1); const btnId = 'tabSettings' + k.charAt(0).toUpperCase() + k.slice(1);
const panelId = 'panelSettings' + k.charAt(0).toUpperCase() + k.slice(1); const panelId = 'panelSettings' + k.charAt(0).toUpperCase() + k.slice(1);
@@ -7650,6 +7752,9 @@ ${vpnBadgeTopo}
if (tabKey === 'custom') { if (tabKey === 'custom') {
if (typeof loadDeviceTypes === 'function') loadDeviceTypes(); if (typeof loadDeviceTypes === 'function') loadDeviceTypes();
} }
if (tabKey === 'backup') {
if (typeof loadBackupsTab === 'function') loadBackupsTab();
}
} }
let vpnTabRefreshTimer = null; let vpnTabRefreshTimer = null;
@@ -10405,6 +10510,334 @@ ${vpnBadgeTopo}
} }
} }
/* ============================================================
Onglet Sauvegardes : Planification Cron & Gestion des fichiers
============================================================ */
let serverBackupsCache = [];
function initBackupCronSelects() {
const hSel = $('backupCronHour');
const mSel = $('backupCronMinute');
if (hSel && hSel.options.length <= 1) {
let hHtml = '<option value="*">' + t('stats_cron_day_all', 'Toutes les heures (*)') + '</option>';
for (let i = 0; i < 24; i++) {
const v = String(i).padStart(2, '0');
hHtml += `<option value="${i}"${i === 3 ? ' selected' : ''}>${v}h (${v}:00)</option>`;
}
hSel.innerHTML = hHtml;
}
if (mSel && mSel.options.length <= 1) {
let mHtml = '';
for (let i = 0; i < 60; i++) {
const v = String(i).padStart(2, '0');
mHtml += `<option value="${i}"${i === 0 ? ' selected' : ''}>${v} min (:${v})</option>`;
}
mSel.innerHTML = mHtml;
}
}
function onBackupCronToggle() {
const en = !!($('backupCronEnabled') && $('backupCronEnabled').checked);
const box = $('backupCronFields');
if (box) box.style.opacity = en ? '1' : '0.65';
updateBackupCronSummary();
}
function syncBackupCronFromSelects() {
const d = $('backupCronDay')?.value || '*';
const h = $('backupCronHour')?.value ?? '3';
const m = $('backupCronMinute')?.value ?? '0';
const expr = `${m} ${h} * * ${d}`;
if ($('backupCronExpr')) $('backupCronExpr').value = expr;
updateBackupCronSummary();
}
function applyBackupCronPreset(expr, day, hour, minute) {
initBackupCronSelects();
if ($('backupCronEnabled')) $('backupCronEnabled').checked = true;
if ($('backupCronDay')) $('backupCronDay').value = String(day);
if ($('backupCronHour')) $('backupCronHour').value = String(hour);
if ($('backupCronMinute')) $('backupCronMinute').value = String(minute);
if ($('backupCronExpr')) $('backupCronExpr').value = expr;
onBackupCronToggle();
}
function updateBackupCronSummary() {
const badge = $('backupCronHuman');
if (!badge) return;
const expr = ($('backupCronExpr')?.value || '').trim();
const parts = expr.split(/\s+/);
if (parts.length !== 5) {
badge.textContent = '⚠️ ' + t('backup_cron_invalid', 'Expression Cron invalide (5 champs requis)');
return;
}
const [minPart, hourPart, domPart, monthPart, dowPart] = parts;
if (domPart !== '*' || monthPart !== '*' || hourPart.includes('/') || minPart.includes('/')) {
badge.textContent = '⚙️ Cron : ' + expr;
return;
}
const daysMap = {
'*': t('stats_cron_day_all_short', 'Tous les jours'),
'1-5': t('stats_cron_day_workdays_short', 'Jours ouvrés (Lun-Ven)'),
'6,7': t('stats_cron_day_weekend_short', 'Week-end (Sam-Dim)'),
'1': t('stats_cron_day_mon', 'Chaque Lundi'),
'2': t('stats_cron_day_tue', 'Chaque Mardi'),
'3': t('stats_cron_day_wed', 'Chaque Mercredi'),
'4': t('stats_cron_day_thu', 'Chaque Jeudi'),
'5': t('stats_cron_day_fri', 'Chaque Vendredi'),
'6': t('stats_cron_day_sat', 'Chaque Samedi'),
'0': t('stats_cron_day_sun', 'Chaque Dimanche'),
'7': t('stats_cron_day_sun', 'Chaque Dimanche')
};
const dStr = daysMap[dowPart] || (t('stats_cron_day_prefix', 'Jour ') + dowPart);
let timeStr = '';
if (hourPart === '*') {
timeStr = t('stats_cron_hourly_at', 'toutes les heures à :{min}').replace('{min}', String(minPart).padStart(2, '0'));
} else {
timeStr = t('stats_cron_at_time', 'à {time}').replace('{time}', `${String(hourPart).padStart(2, '0')}:${String(minPart).padStart(2, '0')}`);
}
badge.textContent = `📅 ${dStr} ${timeStr}`;
}
function renderServerBackupsTable(backups, totalSizeStr) {
serverBackupsCache = Array.isArray(backups) ? backups : [];
const tbody = $('backupsTableBody');
const summary = $('backupsListSummary');
if (summary) {
summary.textContent = t('backup_list_summary', '{count} sauvegarde(s) • Espace utilisé : {size}')
.replace('{count}', String(serverBackupsCache.length))
.replace('{size}', totalSizeStr || '0 o');
}
if (!tbody) return;
if (!serverBackupsCache.length) {
tbody.innerHTML = `<tr><td colspan="5" class="empty">${escapeHtml(t('backup_list_empty', 'Aucune sauvegarde dans le dossier pour le moment.'))}</td></tr>`;
return;
}
tbody.innerHTML = serverBackupsCache.map(bk => {
const fname = bk.filename || '';
const safeArg = escapeHtml(fname).replace(/'/g, '&#39;');
const typePill = bk.trigger === 'auto'
? `<span class="pill pill-green pill-no-dot" style="font-size:11px;padding:2px 8px">🤖 ${escapeHtml(t('backup_type_auto', 'Auto (Cron)'))}</span>`
: (bk.trigger === 'manual'
? `<span class="pill pill-blue pill-no-dot" style="font-size:11px;padding:2px 8px">👤 ${escapeHtml(t('backup_type_manual', 'Manuel'))}</span>`
: `<span class="pill pill-no-dot" style="font-size:11px;padding:2px 8px">📄 ${escapeHtml(t('backup_type_external', 'Externe'))}</span>`);
return `<tr>
<td style="font-family:monospace;font-size:12px;word-break:break-all"><strong>${escapeHtml(fname)}</strong></td>
<td>${typePill}</td>
<td style="white-space:nowrap;font-size:12px" class="muted">${escapeHtml(bk.created_at || '—')}</td>
<td style="white-space:nowrap;font-size:12px">${escapeHtml(bk.size_str || '—')}</td>
<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(--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>
</td>
</tr>`;
}).join('');
}
function applyBackupScheduleToUI(sched) {
if (!sched) return;
initBackupCronSelects();
if ($('backupCronEnabled')) $('backupCronEnabled').checked = !!sched.enabled;
if ($('backupCronDay') && sched.day !== undefined) $('backupCronDay').value = String(sched.day);
if ($('backupCronHour') && sched.hour !== undefined) $('backupCronHour').value = String(sched.hour);
if ($('backupCronMinute') && sched.minute !== undefined) $('backupCronMinute').value = String(sched.minute);
if ($('backupCronRetention') && sched.retention !== undefined) $('backupCronRetention').value = String(sched.retention);
if ($('backupCronExpr') && sched.cron_expr) $('backupCronExpr').value = sched.cron_expr;
if ($('backupCronLastRun')) {
$('backupCronLastRun').textContent = sched.last_run
? `${t('backup_last_run', 'Dernière exécution :')} ${sched.last_run}${sched.last_file ? ' (' + sched.last_file + ')' : ''}`
: t('backup_never_run', 'Aucune exécution enregistrée');
}
onBackupCronToggle();
}
async function loadBackupsTab() {
initBackupCronSelects();
try {
const res = await apiFetch('/api/backups/list', { cache: 'no-store' });
const d = await res.json();
if (!res.ok) throw new Error(d.error || 'Erreur chargement sauvegardes');
if ($('backupDirBadge') && d.backup_dir) $('backupDirBadge').textContent = '📁 ' + d.backup_dir;
applyBackupScheduleToUI(d.schedule);
renderServerBackupsTable(d.backups || [], d.total_size_str || '0 o');
} catch (e) {
const tbody = $('backupsTableBody');
if (tbody) tbody.innerHTML = `<tr><td colspan="5" class="empty">${escapeHtml(tErr(e.message))}</td></tr>`;
}
}
async function saveBackupSchedule() {
const msg = $('backupScheduleMsg');
const btn = $('btnSaveBackupSchedule');
const expr = ($('backupCronExpr')?.value || '').trim();
if (expr.split(/\s+/).length !== 5) {
if (msg) {
msg.style.display = 'block';
msg.style.background = 'rgba(239,68,68,0.12)';
msg.style.color = 'var(--red)';
msg.textContent = t('backup_cron_invalid', 'Expression Cron invalide (5 champs requis)');
}
return;
}
if (btn) btn.disabled = true;
try {
const payload = {
enabled: !!($('backupCronEnabled') && $('backupCronEnabled').checked),
day: $('backupCronDay')?.value || '*',
hour: $('backupCronHour')?.value ?? '3',
minute: parseInt($('backupCronMinute')?.value || '0', 10) || 0,
retention: parseInt($('backupCronRetention')?.value || '7', 10) || 0,
cron_expr: expr
};
const res = await apiFetch('/api/backups/schedule', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const d = await res.json();
if (!res.ok) throw new Error(d.error || 'Erreur enregistrement');
applyBackupScheduleToUI(d.schedule);
if (msg) {
msg.style.display = 'block';
msg.style.background = 'rgba(50,213,131,0.12)';
msg.style.color = 'var(--green)';
msg.textContent = '✓ ' + t('backup_schedule_saved', 'Planification Cron enregistrée avec succès !');
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 createServerBackupNow() {
const msg = $('backupActionMsg');
const btn = $('btnCreateServerBackup');
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_creating_server', 'Création de la sauvegarde sur le serveur en cours…');
}
try {
const res = await apiFetch('/api/backups/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
const d = await res.json();
if (!res.ok) throw new Error(d.error || 'Erreur création sauvegarde');
if (d.schedule) applyBackupScheduleToUI(d.schedule);
renderServerBackupsTable(d.backups || [], d.total_size_str || '0 o');
if (msg) {
msg.style.background = 'rgba(50,213,131,0.12)';
msg.style.color = 'var(--green)';
msg.textContent = '✓ ' + (d.message || t('backup_created_success', 'Sauvegarde créée avec succès !'));
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 6000);
}
} 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 downloadServerBackup(filename) {
const msg = $('backupActionMsg');
try {
const res = await apiFetch('/api/backups/download?file=' + encodeURIComponent(filename));
if (!res.ok) {
let errText = 'Erreur téléchargement';
try { const d = await res.json(); if (d.error) errText = d.error; } catch (_) { }
throw new Error(errText);
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 2000);
} 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);
}
}
}
async function restoreServerBackup(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_analyzing', 'Analyse de la sauvegarde en cours…');
}
try {
const res = await apiFetch('/api/backups/inspect', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filename })
});
const d = await res.json();
if (!res.ok) throw new Error(d.error || 'Fichier invalide');
if (msg) msg.style.display = 'none';
pendingBackupData = d.backup;
showImportBackupModal(filename, d.backup);
} 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;
const msg = $('backupActionMsg');
try {
const res = await apiFetch('/api/backups/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');
renderServerBackupsTable(d.backups || [], d.total_size_str || '0 o');
if (msg) {
msg.style.display = 'block';
msg.style.background = 'rgba(50,213,131,0.12)';
msg.style.color = 'var(--green)';
msg.textContent = '✓ ' + (d.message || t('backup_deleted_success', 'Sauvegarde supprimé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);
}
}
}
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_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 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 = []; const REGISTERED_PASSWORD_TOGGLES = [];
+38
View File
@@ -1160,4 +1160,42 @@ window.I18N['en-gb'] = {
"tip_switch_to_ap": "Switch instantly to AP Mode (Router/NAT)", "tip_switch_to_ap": "Switch instantly to AP Mode (Router/NAT)",
"tip_switch_to_bridge": "Switch instantly to Bridge Mode (Router DHCP)", "tip_switch_to_bridge": "Switch instantly to Bridge Mode (Router DHCP)",
"mode_switching": "Switching…", "mode_switching": "Switching…",
"settings_tab_backup": "Backups",
"backup_tab_title": "Backups & Restore",
"backup_tab_subtitle": "Create, schedule (Cron), export, restore, or delete backups stored in the Docker volume.",
"backup_create_now_btn": "💾 Create Backup Now",
"backup_cron_title": "⏱️ Automated Backups (Cron)",
"backup_cron_desc": "Schedule automatic backups saved into the directory configured via Docker Compose.",
"backup_cron_enable": "Enable Schedule",
"backup_cron_day_label": "Frequency / Day",
"backup_cron_hour_label": "Hour",
"backup_cron_min_label": "Minute",
"backup_cron_retention_label": "Retention (0 = unlimited)",
"backup_cron_expr_label": "Cron Expression (minute hour day month weekday)",
"backup_cron_save_btn": "💾 Save",
"backup_cron_invalid": "Invalid Cron expression (5 fields required)",
"backup_preset_daily": "Every night 03:00",
"backup_preset_weekly": "Sunday 04:00",
"backup_preset_6h": "Every 6h",
"backup_list_title": "📂 Saved Backups",
"backup_list_summary": "{count} backup(s) • Disk usage: {size}",
"backup_list_empty": "No backups in the directory yet.",
"backup_th_file": "FILE",
"backup_th_type": "TYPE",
"backup_th_date": "DATE",
"backup_th_size": "SIZE",
"backup_th_actions": "ACTIONS",
"backup_type_auto": "Auto (Cron)",
"backup_type_manual": "Manual",
"backup_type_external": "External",
"backup_btn_export": "Export",
"backup_btn_restore": "Restore",
"backup_last_run": "Last run:",
"backup_never_run": "No run recorded yet",
"backup_schedule_saved": "Cron schedule saved successfully!",
"backup_creating_server": "Creating backup on server…",
"backup_created_success": "Backup created successfully!",
"backup_analyzing": "Inspecting backup file…",
"backup_confirm_delete": "Permanently delete backup \"{file}\"?",
"backup_deleted_success": "Backup deleted."
}; };
+38
View File
@@ -1160,4 +1160,42 @@ window.I18N['en-us'] = {
"tip_switch_to_ap": "Switch instantly to AP Mode (Router/NAT)", "tip_switch_to_ap": "Switch instantly to AP Mode (Router/NAT)",
"tip_switch_to_bridge": "Switch instantly to Bridge Mode (Router DHCP)", "tip_switch_to_bridge": "Switch instantly to Bridge Mode (Router DHCP)",
"mode_switching": "Switching…", "mode_switching": "Switching…",
"settings_tab_backup": "Backups",
"backup_tab_title": "Backups & Restore",
"backup_tab_subtitle": "Create, schedule (Cron), export, restore, or delete backups stored in the Docker volume.",
"backup_create_now_btn": "💾 Create Backup Now",
"backup_cron_title": "⏱️ Automated Backups (Cron)",
"backup_cron_desc": "Schedule automatic backups saved into the directory configured via Docker Compose.",
"backup_cron_enable": "Enable Schedule",
"backup_cron_day_label": "Frequency / Day",
"backup_cron_hour_label": "Hour",
"backup_cron_min_label": "Minute",
"backup_cron_retention_label": "Retention (0 = unlimited)",
"backup_cron_expr_label": "Cron Expression (minute hour day month weekday)",
"backup_cron_save_btn": "💾 Save",
"backup_cron_invalid": "Invalid Cron expression (5 fields required)",
"backup_preset_daily": "Every night 03:00",
"backup_preset_weekly": "Sunday 04:00",
"backup_preset_6h": "Every 6h",
"backup_list_title": "📂 Saved Backups",
"backup_list_summary": "{count} backup(s) • Disk usage: {size}",
"backup_list_empty": "No backups in the directory yet.",
"backup_th_file": "FILE",
"backup_th_type": "TYPE",
"backup_th_date": "DATE",
"backup_th_size": "SIZE",
"backup_th_actions": "ACTIONS",
"backup_type_auto": "Auto (Cron)",
"backup_type_manual": "Manual",
"backup_type_external": "External",
"backup_btn_export": "Export",
"backup_btn_restore": "Restore",
"backup_last_run": "Last run:",
"backup_never_run": "No run recorded yet",
"backup_schedule_saved": "Cron schedule saved successfully!",
"backup_creating_server": "Creating backup on server…",
"backup_created_success": "Backup created successfully!",
"backup_analyzing": "Inspecting backup file…",
"backup_confirm_delete": "Permanently delete backup \"{file}\"?",
"backup_deleted_success": "Backup deleted."
}; };
+38
View File
@@ -1160,4 +1160,42 @@ window.I18N['fr'] = {
"tip_switch_to_ap": "Basculer instantanément en Mode AP (Routeur/NAT)", "tip_switch_to_ap": "Basculer instantanément en Mode AP (Routeur/NAT)",
"tip_switch_to_bridge": "Basculer instantanément en Mode Pont (DHCP Box)", "tip_switch_to_bridge": "Basculer instantanément en Mode Pont (DHCP Box)",
"mode_switching": "Bascule…", "mode_switching": "Bascule…",
"settings_tab_backup": "Sauvegardes",
"backup_tab_title": "Sauvegardes & Restauration",
"backup_tab_subtitle": "Créez, planifiez (Cron), exportez, restaurez ou supprimez vos sauvegardes stockées dans le volume Docker.",
"backup_create_now_btn": "💾 Créer une sauvegarde maintenant",
"backup_cron_title": "⏱️ Automatisation des sauvegardes (Cron)",
"backup_cron_desc": "Planifiez des sauvegardes automatiques enregistrées dans le dossier configuré via Docker Compose.",
"backup_cron_enable": "Activer la planification",
"backup_cron_day_label": "Fréquence / Jour",
"backup_cron_hour_label": "Heure",
"backup_cron_min_label": "Minute",
"backup_cron_retention_label": "Rétention (0 = illimité)",
"backup_cron_expr_label": "Expression Cron (minute heure jour mois jour_semaine)",
"backup_cron_save_btn": "💾 Enregistrer",
"backup_cron_invalid": "Expression Cron invalide (5 champs requis)",
"backup_preset_daily": "Chaque nuit 03:00",
"backup_preset_weekly": "Dimanche 04:00",
"backup_preset_6h": "Toutes les 6h",
"backup_list_title": "📂 Sauvegardes enregistrées",
"backup_list_summary": "{count} sauvegarde(s) • Espace utilisé : {size}",
"backup_list_empty": "Aucune sauvegarde dans le dossier pour le moment.",
"backup_th_file": "FICHIER",
"backup_th_type": "TYPE",
"backup_th_date": "DATE",
"backup_th_size": "TAILLE",
"backup_th_actions": "ACTIONS",
"backup_type_auto": "Auto (Cron)",
"backup_type_manual": "Manuel",
"backup_type_external": "Externe",
"backup_btn_export": "Exporter",
"backup_btn_restore": "Restaurer",
"backup_last_run": "Dernière exécution :",
"backup_never_run": "Aucune exécution enregistrée",
"backup_schedule_saved": "Planification Cron enregistrée avec succès !",
"backup_creating_server": "Création de la sauvegarde sur le serveur en cours…",
"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."
}; };