Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Successful in 48s
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Successful in 3m39s
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Failing after 10m57s
496 lines
17 KiB
Python
496 lines
17 KiB
Python
"""Controllo versioni e auto-aggiornamento cross-platform via Gitea Releases (o JSON custom)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import shlex
|
|
import shutil
|
|
import ssl
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import urllib.error
|
|
import urllib.request
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Callable, Optional
|
|
|
|
from version import APP_NAME, APP_VERSION, RELEASES_PAGE_URL, UPDATE_RELEASES_API
|
|
|
|
|
|
def get_ssl_context() -> ssl.SSLContext:
|
|
"""Restituisce un SSLContext con certificati CA validi anche in bundle PyInstaller/macOS."""
|
|
# 1. Prova prima certifi se presente (standard de-facto con bundle CA Mozilla aggiornato)
|
|
try:
|
|
import certifi
|
|
return ssl.create_default_context(cafile=certifi.where())
|
|
except Exception:
|
|
pass
|
|
|
|
# 2. Crea il contesto SSL standard
|
|
try:
|
|
ctx = ssl.create_default_context()
|
|
if ctx.get_ca_certs():
|
|
return ctx
|
|
except Exception:
|
|
ctx = ssl.create_default_context()
|
|
|
|
# 3. Su macOS e Linux, se l'ambiente PyInstaller non ha trovato i certificati,
|
|
# carica i certificati di root di sistema noti
|
|
known_ca_bundles = (
|
|
"/etc/ssl/cert.pem", # macOS default e BSD
|
|
"/etc/ssl/certs/ca-certificates.crt", # Debian / Ubuntu
|
|
"/etc/pki/tls/certs/ca-bundle.crt", # Fedora / RHEL / CentOS
|
|
"/etc/ssl/ca-bundle.pem", # OpenSUSE
|
|
"/opt/homebrew/etc/openssl@3/cert.pem", # Homebrew macOS Apple Silicon
|
|
"/usr/local/etc/openssl@3/cert.pem", # Homebrew macOS Intel
|
|
)
|
|
for ca_path in known_ca_bundles:
|
|
if os.path.isfile(ca_path):
|
|
try:
|
|
ctx.load_verify_locations(cafile=ca_path)
|
|
if ctx.get_ca_certs():
|
|
return ctx
|
|
except Exception:
|
|
continue
|
|
|
|
return ctx
|
|
|
|
|
|
@dataclass
|
|
class ReleaseAsset:
|
|
"""Singolo file eseguibile o installer allegato a una release."""
|
|
|
|
name: str
|
|
download_url: str
|
|
size: int = 0
|
|
|
|
|
|
@dataclass
|
|
class ReleaseInfo:
|
|
"""Metadati di una release disponibile."""
|
|
|
|
version: str
|
|
tag_name: str
|
|
title: str
|
|
notes: str = ""
|
|
html_url: str = RELEASES_PAGE_URL
|
|
assets: list[ReleaseAsset] = field(default_factory=list)
|
|
|
|
|
|
@dataclass
|
|
class UpdateCheckResult:
|
|
"""Esito della verifica aggiornamenti."""
|
|
|
|
status: str # "up_to_date", "update_available", "unavailable", "error"
|
|
current_version: str
|
|
message: str = ""
|
|
release: Optional[ReleaseInfo] = None
|
|
selected_asset: Optional[ReleaseAsset] = None
|
|
|
|
|
|
def normalize_version_string(version: str) -> str:
|
|
"""Rimuove prefisso 'v' ed eventuali spazi dalla stringa versione."""
|
|
return (version or "").strip().lstrip("vV")
|
|
|
|
|
|
def parse_version_tuple(version: str) -> tuple[int, ...]:
|
|
"""Converte una stringa semver (es. 'v1.2.3-rc1') in tupla numerica confrontabile."""
|
|
cleaned = normalize_version_string(version)
|
|
if not cleaned:
|
|
return (0,)
|
|
core = re.split(r"[-+]", cleaned, maxsplit=1)[0]
|
|
parts: list[int] = []
|
|
for segment in core.split("."):
|
|
match = re.match(r"(\d+)", segment.strip())
|
|
parts.append(int(match.group(1)) if match else 0)
|
|
return tuple(parts) or (0,)
|
|
|
|
|
|
def is_newer_version(remote_version: str, current_version: str) -> bool:
|
|
"""Restituisce True se remote_version è strettamente maggiore di current_version."""
|
|
remote = list(parse_version_tuple(remote_version))
|
|
current = list(parse_version_tuple(current_version))
|
|
max_len = max(len(remote), len(current))
|
|
remote.extend([0] * (max_len - len(remote)))
|
|
current.extend([0] * (max_len - len(current)))
|
|
return tuple(remote) > tuple(current)
|
|
|
|
|
|
def _extract_assets_from_payload(data: dict) -> list[ReleaseAsset]:
|
|
"""Estrae la lista degli asset sia da schema Gitea/GitHub sia da JSON custom."""
|
|
assets: list[ReleaseAsset] = []
|
|
raw_assets = data.get("assets")
|
|
if isinstance(raw_assets, list):
|
|
for item in raw_assets:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
url = item.get("browser_download_url") or item.get("download_url") or item.get("url") or ""
|
|
name = item.get("name") or (url.rsplit("/", 1)[-1] if url else "")
|
|
size = int(item.get("size") or 0)
|
|
if name and url:
|
|
assets.append(ReleaseAsset(name=str(name), download_url=str(url), size=size))
|
|
return assets
|
|
|
|
# Supporto opzionale a campi flat (es. endpoint DB stile Flux app_config)
|
|
for key, fallback_name in (
|
|
("windows_url", "BarcodeServerSetup.exe"),
|
|
("linux_url", "BarcodeServer-x86_64.AppImage"),
|
|
("macos_url", "BarcodeServer-macOS.zip"),
|
|
("mac_url", "BarcodeServer-macOS.zip"),
|
|
("download_url", "update-package"),
|
|
):
|
|
url = data.get(key)
|
|
if isinstance(url, str) and url.strip():
|
|
inferred_name = url.rstrip("/").rsplit("/", 1)[-1] or fallback_name
|
|
assets.append(ReleaseAsset(name=inferred_name, download_url=url.strip()))
|
|
|
|
return assets
|
|
|
|
|
|
def parse_release_payload(payload: object) -> Optional[ReleaseInfo]:
|
|
"""Interpreta il JSON restituito dall'endpoint aggiornamenti."""
|
|
if isinstance(payload, list):
|
|
payload = payload[0] if payload else None
|
|
if not isinstance(payload, dict):
|
|
return None
|
|
|
|
tag_or_version = (
|
|
payload.get("tag_name")
|
|
or payload.get("version")
|
|
or payload.get("latest_version")
|
|
or ""
|
|
)
|
|
version = normalize_version_string(str(tag_or_version))
|
|
if not version:
|
|
return None
|
|
|
|
title = str(payload.get("name") or payload.get("title") or f"{APP_NAME} v{version}")
|
|
notes = str(payload.get("body") or payload.get("release_notes") or payload.get("notes") or "")
|
|
html_url = str(payload.get("html_url") or payload.get("release_url") or RELEASES_PAGE_URL)
|
|
assets = _extract_assets_from_payload(payload)
|
|
return ReleaseInfo(
|
|
version=version,
|
|
tag_name=str(tag_or_version),
|
|
title=title,
|
|
notes=notes,
|
|
html_url=html_url,
|
|
assets=assets,
|
|
)
|
|
|
|
|
|
def select_asset_for_platform(
|
|
assets: list[ReleaseAsset], platform_name: Optional[str] = None
|
|
) -> Optional[ReleaseAsset]:
|
|
"""Seleziona l'installer o pacchetto più adatto per il sistema operativo corrente."""
|
|
if not assets:
|
|
return None
|
|
|
|
plat = platform_name or sys.platform
|
|
lower_pairs = [(asset.name.lower(), asset) for asset in assets]
|
|
|
|
if plat == "win32":
|
|
for priority in (
|
|
lambda n: n.endswith(".exe") and "setup" in n,
|
|
lambda n: n.endswith(".exe"),
|
|
lambda n: n.endswith(".msi"),
|
|
lambda n: n.endswith(".zip") and "win" in n,
|
|
):
|
|
for name, asset in lower_pairs:
|
|
if priority(name):
|
|
return asset
|
|
elif plat.startswith("linux"):
|
|
for priority in (
|
|
lambda n: n.endswith(".appimage"),
|
|
lambda n: "linux" in n and (n.endswith(".tar.gz") or n.endswith(".zip")),
|
|
):
|
|
for name, asset in lower_pairs:
|
|
if priority(name):
|
|
return asset
|
|
elif plat == "darwin":
|
|
for priority in (
|
|
lambda n: n.endswith(".zip") and ("mac" in n or "darwin" in n or ".app" in n),
|
|
lambda n: n.endswith(".dmg"),
|
|
lambda n: n.endswith(".zip"),
|
|
):
|
|
for name, asset in lower_pairs:
|
|
if priority(name):
|
|
return asset
|
|
|
|
return None
|
|
|
|
|
|
def can_self_update() -> tuple[bool, str]:
|
|
"""Indica se l'app può auto-aggiornarsi direttamente sul sistema corrente."""
|
|
if not getattr(sys, "frozen", False):
|
|
return False, "Avviata da sorgente Python: aggiornamento automatico disponibile solo nei pacchetti rilasciati."
|
|
|
|
if sys.platform == "win32":
|
|
return True, ""
|
|
|
|
if sys.platform.startswith("linux"):
|
|
appimage_path = os.environ.get("APPIMAGE")
|
|
if not appimage_path:
|
|
return False, "Eseguibile Linux non avviato tramite AppImage: scarica manualmente la nuova release."
|
|
target = Path(appimage_path)
|
|
if target.exists() and not os.access(target, os.W_OK):
|
|
return False, f"Permessi insufficienti per sostituire {target}."
|
|
if not target.exists() and not os.access(target.parent, os.W_OK):
|
|
return False, f"Cartella {target.parent} non scrivibile."
|
|
return True, ""
|
|
|
|
if sys.platform == "darwin":
|
|
bundle = _find_macos_app_bundle()
|
|
if not bundle:
|
|
return False, "Bundle .app non rilevato: scarica il pacchetto .dmg dalla pagina release."
|
|
if not os.access(bundle.parent, os.W_OK):
|
|
return False, f"Cartella {bundle.parent} non scrivibile: sostituisci manualmente l'app."
|
|
return True, ""
|
|
|
|
return False, "Piattaforma non supportata per l'auto-aggiornamento."
|
|
|
|
|
|
def _find_macos_app_bundle() -> Optional[Path]:
|
|
"""Risale dal percorso sys.executable al bundle '.app' su macOS."""
|
|
exe_path = Path(sys.executable).resolve()
|
|
for parent in exe_path.parents:
|
|
if parent.suffix == ".app":
|
|
return parent
|
|
return None
|
|
|
|
|
|
def check_for_updates(
|
|
current_version: str = APP_VERSION,
|
|
update_url: str = "",
|
|
timeout: float = 8.0,
|
|
) -> UpdateCheckResult:
|
|
"""Interroga l'API delle release e confronta la versione remota con quella locale."""
|
|
target_url = (update_url or "").strip() or UPDATE_RELEASES_API
|
|
req = urllib.request.Request(
|
|
target_url,
|
|
headers={
|
|
"Accept": "application/json",
|
|
"User-Agent": f"BarcodeReaderServer/{current_version}",
|
|
},
|
|
)
|
|
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout, context=get_ssl_context()) as resp:
|
|
raw = resp.read().decode("utf-8", errors="replace")
|
|
payload = json.loads(raw)
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code == 404:
|
|
return UpdateCheckResult(
|
|
status="unavailable",
|
|
current_version=current_version,
|
|
message="Nessuna release pubblica trovata sul server (HTTP 404).",
|
|
)
|
|
return UpdateCheckResult(
|
|
status="error",
|
|
current_version=current_version,
|
|
message=f"Errore HTTP {exc.code} durante il controllo aggiornamenti.",
|
|
)
|
|
except Exception as exc:
|
|
return UpdateCheckResult(
|
|
status="error",
|
|
current_version=current_version,
|
|
message=f"Impossibile contattare il server aggiornamenti: {exc}",
|
|
)
|
|
|
|
release = parse_release_payload(payload)
|
|
if not release:
|
|
return UpdateCheckResult(
|
|
status="unavailable",
|
|
current_version=current_version,
|
|
message="Risposta release non valida o nessuna versione pubblicata.",
|
|
)
|
|
|
|
if not is_newer_version(release.version, current_version):
|
|
return UpdateCheckResult(
|
|
status="up_to_date",
|
|
current_version=current_version,
|
|
message=f"L'applicazione è già aggiornata (v{current_version}).",
|
|
release=release,
|
|
)
|
|
|
|
asset = select_asset_for_platform(release.assets)
|
|
return UpdateCheckResult(
|
|
status="update_available",
|
|
current_version=current_version,
|
|
message=f"Disponibile la nuova versione v{release.version} (attuale v{current_version}).",
|
|
release=release,
|
|
selected_asset=asset,
|
|
)
|
|
|
|
|
|
def download_asset(
|
|
asset: ReleaseAsset,
|
|
progress_callback: Optional[Callable[[int, int], None]] = None,
|
|
timeout: float = 30.0,
|
|
) -> Path:
|
|
"""Scarica l'asset della release in una directory temporanea e ne restituisce il Path."""
|
|
download_dir = Path(tempfile.mkdtemp(prefix="barcode_server_update_"))
|
|
safe_name = Path(asset.name).name or "update_package"
|
|
dest_path = download_dir / safe_name
|
|
|
|
req = urllib.request.Request(
|
|
asset.download_url,
|
|
headers={"User-Agent": f"BarcodeReaderServer/{APP_VERSION}"},
|
|
)
|
|
with urllib.request.urlopen(req, timeout=timeout, context=get_ssl_context()) as resp:
|
|
total = int(resp.headers.get("Content-Length") or asset.size or 0)
|
|
downloaded = 0
|
|
with open(dest_path, "wb") as out:
|
|
while True:
|
|
chunk = resp.read(65536)
|
|
if not chunk:
|
|
break
|
|
out.write(chunk)
|
|
downloaded += len(chunk)
|
|
if progress_callback:
|
|
progress_callback(downloaded, total)
|
|
|
|
return dest_path
|
|
|
|
|
|
def apply_downloaded_update(downloaded_path: Path) -> None:
|
|
"""Avvia il processo di sostituzione e riavvio dell'applicazione."""
|
|
if sys.platform == "win32":
|
|
_apply_windows_update(downloaded_path)
|
|
elif sys.platform.startswith("linux"):
|
|
_apply_linux_appimage_update(downloaded_path)
|
|
elif sys.platform == "darwin":
|
|
_apply_macos_update(downloaded_path)
|
|
else:
|
|
raise RuntimeError(f"Auto-aggiornamento non supportato su {sys.platform}")
|
|
|
|
|
|
def _apply_windows_update(installer_path: Path) -> None:
|
|
"""Avvia un batch nascosto che attende l'uscita, installa silently e riavvia l'app."""
|
|
pid = os.getpid()
|
|
current_exe = str(Path(sys.executable).resolve())
|
|
helper_bat = installer_path.parent / "apply_update.bat"
|
|
|
|
if installer_path.suffix.lower() == ".exe":
|
|
install_cmd = f'"{installer_path}" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /CLOSEAPPLICATIONS'
|
|
elif installer_path.suffix.lower() == ".msi":
|
|
install_cmd = f'msiexec /i "{installer_path}" /passive /norestart'
|
|
else:
|
|
os.startfile(str(installer_path)) # type: ignore[attr-defined]
|
|
return
|
|
|
|
script_content = (
|
|
"@echo off\r\n"
|
|
":wait_pid\r\n"
|
|
f'tasklist /FI "PID eq {pid}" 2>nul | find "{pid}" >nul\r\n'
|
|
"if not errorlevel 1 (\r\n"
|
|
" ping 127.0.0.1 -n 2 >nul\r\n"
|
|
" goto wait_pid\r\n"
|
|
")\r\n"
|
|
f"{install_cmd}\r\n"
|
|
"if %ERRORLEVEL% EQU 0 (\r\n"
|
|
f' start "" "{current_exe}"\r\n'
|
|
")\r\n"
|
|
)
|
|
helper_bat.write_text(script_content, encoding="utf-8")
|
|
|
|
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(
|
|
subprocess, "DETACHED_PROCESS", 0
|
|
)
|
|
subprocess.Popen(
|
|
["cmd.exe", "/c", str(helper_bat)],
|
|
close_fds=True,
|
|
creationflags=creationflags,
|
|
)
|
|
|
|
|
|
def _apply_linux_appimage_update(new_appimage: Path) -> None:
|
|
"""Sostituisce l'AppImage corrente dopo la chiusura e riavvia il processo."""
|
|
appimage_env = os.environ.get("APPIMAGE")
|
|
if not appimage_env:
|
|
raise RuntimeError("Variabile APPIMAGE non presente.")
|
|
|
|
target_appimage = Path(appimage_env).resolve()
|
|
new_appimage.chmod(0o755)
|
|
|
|
staged = target_appimage.with_suffix(".AppImage.new")
|
|
shutil.copy2(new_appimage, staged)
|
|
staged.chmod(0o755)
|
|
|
|
pid = os.getpid()
|
|
helper_sh = new_appimage.parent / "apply_update.sh"
|
|
target_q = shlex.quote(str(target_appimage))
|
|
staged_q = shlex.quote(str(staged))
|
|
|
|
script_content = (
|
|
"#!/bin/sh\n"
|
|
f"while kill -0 {pid} 2>/dev/null; do sleep 0.2; done\n"
|
|
f"mv -f {staged_q} {target_q}\n"
|
|
f"chmod +x {target_q}\n"
|
|
f"exec {target_q} >/dev/null 2>&1 &\n"
|
|
)
|
|
helper_sh.write_text(script_content, encoding="utf-8")
|
|
helper_sh.chmod(0o755)
|
|
|
|
clean_env = os.environ.copy()
|
|
for var in ("LD_LIBRARY_PATH", "QT_PLUGIN_PATH", "QML2_IMPORT_PATH", "APPIMAGE", "APPDIR", "OWD"):
|
|
clean_env.pop(var, None)
|
|
|
|
subprocess.Popen(
|
|
["/bin/sh", str(helper_sh)],
|
|
start_new_session=True,
|
|
close_fds=True,
|
|
env=clean_env,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
|
|
|
|
def _apply_macos_update(package_path: Path) -> None:
|
|
"""Aggiorna il bundle .app da archivio .zip (o apre il .dmg se necessario)."""
|
|
bundle = _find_macos_app_bundle()
|
|
if not bundle:
|
|
subprocess.Popen(["open", str(package_path)], start_new_session=True)
|
|
return
|
|
|
|
suffix = package_path.suffix.lower()
|
|
if suffix == ".dmg":
|
|
subprocess.Popen(["open", str(package_path)], start_new_session=True)
|
|
return
|
|
|
|
if suffix != ".zip":
|
|
subprocess.Popen(["open", str(package_path)], start_new_session=True)
|
|
return
|
|
|
|
pid = os.getpid()
|
|
extract_dir = package_path.parent / "extracted"
|
|
extract_dir.mkdir(exist_ok=True)
|
|
helper_sh = package_path.parent / "apply_update.sh"
|
|
|
|
script_content = (
|
|
"#!/bin/sh\n"
|
|
f"while kill -0 {pid} 2>/dev/null; do sleep 0.2; done\n"
|
|
f"ditto -xk {shlex.quote(str(package_path))} {shlex.quote(str(extract_dir))}\n"
|
|
f'NEW_APP=$(find {shlex.quote(str(extract_dir))} -maxdepth 3 -name "*.app" | head -n 1)\n'
|
|
'if [ -n "$NEW_APP" ]; then\n'
|
|
f" rm -rf {shlex.quote(str(bundle))}\n"
|
|
f' mv "$NEW_APP" {shlex.quote(str(bundle))}\n'
|
|
f" open -n {shlex.quote(str(bundle))}\n"
|
|
"fi\n"
|
|
)
|
|
helper_sh.write_text(script_content, encoding="utf-8")
|
|
helper_sh.chmod(0o755)
|
|
|
|
subprocess.Popen(
|
|
["/bin/sh", str(helper_sh)],
|
|
start_new_session=True,
|
|
close_fds=True,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
|