APmanageur Wi-Fi V1.1 (Bêta)

This commit is contained in:
yoannmultigaming committed 2026-11-22 23:22:19 +01:00
1 parent 4ab701ee58
commit da07838fda
4 files changed
+169 -139

No files matched your search

+149 -131
View File
@@ -1,4 +1,11 @@
#!/usr/bin/env python3
# ==============================================================================
# VERSION DU LOGICIEL AP MANAGEUR
# Modifiez cette variable pour changer la version dans toute l'application :
# ==============================================================================
APP_VERSION = 'V1.1 (Bêta)'
# ==============================================================================
import base64, copy, hashlib, hmac, json, os, re, secrets, socket, sqlite3, subprocess, threading, time, urllib.parse, urllib.request, urllib.error, socketserver, shutil, datetime, atexit, signal, struct, smtplib, ssl, ipaddress, queue, http.client, io, zipfile, tempfile
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
@@ -290,7 +297,6 @@ if not is_auto_channel():
else:
AP_CHANNEL = get_effective_ap_channel(AP_BAND)
APP_VERSION = 'V1.1 (Béta)'
SERVER_BOOT_TIME = time.time()
app_startup_done = False
SESSION_TTL = 30 * 86400 # 30 jours (1 mois)
@@ -1010,6 +1016,7 @@ def auth_state():
admin_ok = bool(row)
wifi_ok = bool(conn or rows.get('ap_ssid'))
return {
'version': APP_VERSION,
'configured': admin_ok,
'admin_configured': admin_ok,
'wifi_configured': wifi_ok,
@@ -4409,10 +4416,16 @@ def get_current_commit():
try:
with open(v_path, 'r', encoding='utf-8') as f:
vdata = json.load(f)
need_save = False
if vdata.get('commit') != git_sha:
vdata['commit'] = git_sha
need_save = True
if vdata.get('version') != APP_VERSION:
vdata['version'] = APP_VERSION
need_save = True
if need_save:
with open(v_path, 'w', encoding='utf-8') as f:
json.dump(vdata, f, indent=2)
json.dump(vdata, f, indent=2, ensure_ascii=False)
except Exception:
pass
return git_sha
@@ -4439,6 +4452,135 @@ def get_current_commit():
pass
return ''
def sync_version_files():
"""Synchronise la version du logiciel (APP_VERSION) vers tous les fichiers :
- version.json (/app, /var/www/html, /data, BASE_DIR, etc.)
- setup.html (badges de version)
- index.html (variable JS APP_VERSION, badges et balises de version)
"""
try:
cur_version = str(APP_VERSION).strip()
cur_commit = get_current_commit()
now_iso = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
# 1. Mise à jour de tous les emplacements de version.json
v_paths = [
os.path.join(BASE_DIR, 'version.json'),
os.path.join(os.getcwd(), 'version.json'),
'version.json',
'/app/version.json',
'/var/www/html/version.json',
'/data/version.json'
]
done_vpaths = set()
for vp in v_paths:
try:
norm_p = os.path.abspath(vp)
if norm_p in done_vpaths:
continue
done_vpaths.add(norm_p)
folder = os.path.dirname(norm_p)
if not os.path.isfile(norm_p) and not os.path.isdir(folder):
continue
vdata = {}
if os.path.isfile(norm_p):
try:
with open(norm_p, 'r', encoding='utf-8') as f:
vdata = json.load(f)
except Exception:
vdata = {}
if not isinstance(vdata, dict):
vdata = {}
vdata['version'] = cur_version
if cur_commit and not vdata.get('commit'):
vdata['commit'] = cur_commit
if not vdata.get('build_date'):
vdata['build_date'] = now_iso
with open(norm_p, 'w', encoding='utf-8') as f:
json.dump(vdata, f, indent=2, ensure_ascii=False)
except Exception:
pass
# 2. Synchronisation de setup.html
setup_paths = [
os.path.join(BASE_DIR, 'setup.html'),
os.path.join(os.getcwd(), 'setup.html'),
'setup.html',
'/app/setup.html',
'/var/www/html/setup.html'
]
done_spaths = set()
for sp in setup_paths:
try:
norm_sp = os.path.abspath(sp)
if norm_sp in done_spaths or not os.path.isfile(norm_sp):
continue
done_spaths.add(norm_sp)
with open(norm_sp, 'r', encoding='utf-8') as f:
content = f.read()
new_content = re.sub(
r'(<span[^>]*class="[^"]*app-version[^"]*"[^>]*>)[^<]*(</span>)',
rf'\g<1>{cur_version}\g<2>',
content
)
if new_content == content:
new_content = re.sub(
r'<span class="pill" style="margin-left:6px;font-size:11px">[^<]*</span>',
f'<span class="pill app-version" style="margin-left:6px;font-size:11px">{cur_version}</span>',
content
)
if new_content != content:
with open(norm_sp, 'w', encoding='utf-8') as f:
f.write(new_content)
except Exception:
pass
# 3. Synchronisation de index.html
index_paths = [
os.path.join(BASE_DIR, 'index.html'),
os.path.join(os.getcwd(), 'index.html'),
'index.html',
'/app/index.html',
'/var/www/html/index.html'
]
done_ipaths = set()
for ip in index_paths:
try:
norm_ip = os.path.abspath(ip)
if norm_ip in done_ipaths or not os.path.isfile(norm_ip):
continue
done_ipaths.add(norm_ip)
with open(norm_ip, 'r', encoding='utf-8') as f:
content = f.read()
# Remplacer la constante JS
new_content = re.sub(
r'(const|let|var)\s+APP_VERSION\s*=\s*["\'][^"\']+["\'];',
f'let APP_VERSION = "{cur_version}";',
content
)
# Remplacer les badges HTML portant la classe app-version
new_content = re.sub(
r'(<span[^>]*class="[^"]*app-version[^"]*"[^>]*>)[^<]*(</span>)',
rf'\g<1>{cur_version}\g<2>',
new_content
)
# Remplacer advUpdateVersionTag
new_content = re.sub(
r'(id="advUpdateVersionTag"[^>]*>)[^<]*(</div>)',
rf'\g<1>AP Manageur {cur_version}\g<2>',
new_content
)
if new_content != content:
with open(norm_ip, 'w', encoding='utf-8') as f:
f.write(new_content)
except Exception:
pass
except Exception as e_sync:
print(f"[ap-version] Erreur synchronisation version : {e_sync}", flush=True)
# Synchronisation initiale à l'import
sync_version_files()
def check_gitea_update(force_refresh=False):
"""Vérifie si une nouvelle version est disponible sur le dépôt Gitea (cache selon intervalle, non bloquant)."""
enabled = get_pref('update_checker_enabled', '1') == '1'
@@ -4652,7 +4794,7 @@ def status(force_refresh=False):
b_name = master or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
eff_chan = get_effective_ap_channel(AP_BAND)
res = {'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name or db_ssid),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME,'channel':eff_chan,'channel_auto':is_auto_channel(),'band':AP_BAND,'update':check_gitea_update(force_refresh=False)}
res = {'version':APP_VERSION,'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name or db_ssid),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME,'channel':eff_chan,'channel_auto':is_auto_channel(),'band':AP_BAND,'update':check_gitea_update(force_refresh=False)}
with _status_cache_lock:
_status_cache['time'] = now
_status_cache['data'] = res
@@ -10535,134 +10677,6 @@ 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}')
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:
@@ -11144,6 +11158,9 @@ class Handler(BaseHTTPRequestHandler):
body=json.dumps(data,ensure_ascii=False).encode(); self.send_response(status); self.send_header('Content-Type','application/json; charset=utf-8'); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token, X-Language, Accept-Language'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
def do_OPTIONS(self): self.send_response(204); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.end_headers()
def do_GET(self):
if self.path == '/api/version':
self.send_json({'ok': True, 'version': APP_VERSION, 'commit': get_current_commit()})
return
if self.path in ('/','/index.html','/ap_dashboard.html'):
try: body=open(os.path.join(os.path.dirname(__file__),'index.html'),'rb').read(); self.send_response(200); self.send_header('Content-Type','text/html; charset=utf-8'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
except OSError: self.send_error(404,'index.html introuvable')
@@ -12831,6 +12848,7 @@ def update_checker_loop():
if __name__ == '__main__':
print(f"[ap-api] Initialisation de la base de données et surveillance sur {INTERFACE}...", flush=True)
sync_version_files()
db()
ensure_dnsmasq_dns()
try: