945 lines
34 KiB
Python
945 lines
34 KiB
Python
"""Обновление Xenith Studio из GitHub или Gitea Releases.
|
||
|
||
Модуль работает только со стандартной библиотекой Python и не зависит от UI.
|
||
Он умеет:
|
||
|
||
* проверять последний релиз репозитория (включая pre-release по желанию);
|
||
* корректно сравнивать semver-версии (`v0.2.0`, `0.3.0-beta.2` и т.п.);
|
||
* скачивать zip-ассет с прогрессом и атомарной записью на диск;
|
||
* безопасно распаковывать архив и устанавливать файлы приложения поверх
|
||
текущей копии, не трогая модели, нативную сборку и пользовательские файлы.
|
||
|
||
Публичный API:
|
||
|
||
updater = AppUpdater("owner/repo", __version__)
|
||
info = updater.check()
|
||
if info.status == "update":
|
||
updater.download(info.download_url, "/tmp/xenith.zip", on_progress)
|
||
install_zip("/tmp/xenith.zip", target_dir, backup_dir)
|
||
|
||
Все сообщения об ошибках, предназначенные пользователю, — на русском языке.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import tempfile
|
||
import time
|
||
import zipfile
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Callable, Iterable, Optional
|
||
from urllib.error import HTTPError, URLError
|
||
from urllib.parse import urlparse
|
||
from urllib.request import Request, urlopen
|
||
|
||
__all__ = [
|
||
"AppUpdateInfo",
|
||
"AppUpdater",
|
||
"APP_ITEMS",
|
||
"compare_versions",
|
||
"install_release",
|
||
"install_zip",
|
||
"parse_version",
|
||
]
|
||
|
||
USER_AGENT = "Xenith-Studio-Updater"
|
||
DEFAULT_TIMEOUT = 15
|
||
CHUNK_SIZE = 64 * 1024
|
||
|
||
# Файлы и каталоги приложения, которые разрешено обновлять.
|
||
# Всё остальное (models/, xenith/, .git/, конфиги, пользовательские данные)
|
||
# остаётся нетронутым.
|
||
APP_ITEMS = (
|
||
"xenith_app.py",
|
||
"XUI",
|
||
"xenith_server.py",
|
||
"requirements.txt",
|
||
"README.md",
|
||
"LICENSE",
|
||
)
|
||
|
||
_SKIP_DIRS = {"__pycache__", ".git"}
|
||
_SKIP_SUFFIXES = (".pyc", ".pyo")
|
||
|
||
_SEMVER_RE = re.compile(
|
||
r"^[vV]?(\d+)\.(\d+)\.(\d+)"
|
||
r"(?:-([0-9A-Za-z.-]+))?"
|
||
r"(?:\+[0-9A-Za-z.-]+)?$"
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Semver
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class _SemVer:
|
||
"""Разобранная semver-версия с корректным порядком pre-release."""
|
||
|
||
__slots__ = ("major", "minor", "patch", "pre", "text")
|
||
|
||
def __init__(self, major: int, minor: int, patch: int,
|
||
pre: tuple[tuple[int, Any], ...], text: str):
|
||
self.major = major
|
||
self.minor = minor
|
||
self.patch = patch
|
||
self.pre = pre
|
||
self.text = text
|
||
|
||
def __repr__(self) -> str: # pragma: no cover - удобство отладки
|
||
return f"_SemVer({self.text!r})"
|
||
|
||
|
||
def parse_version(value: Any) -> Optional[_SemVer]:
|
||
"""Разбирает строку версии. Возвращает None, если это не semver."""
|
||
|
||
if value is None:
|
||
return None
|
||
text = str(value).strip()
|
||
match = _SEMVER_RE.match(text)
|
||
if not match:
|
||
return None
|
||
|
||
major, minor, patch, pre_text = match.groups()
|
||
pre: tuple[tuple[int, Any], ...] = ()
|
||
if pre_text:
|
||
identifiers: list[tuple[int, Any]] = []
|
||
for part in pre_text.split("."):
|
||
if not part:
|
||
return None
|
||
if part.isdigit():
|
||
identifiers.append((0, int(part)))
|
||
else:
|
||
identifiers.append((1, part))
|
||
pre = tuple(identifiers)
|
||
|
||
normalized = f"{int(major)}.{int(minor)}.{int(patch)}"
|
||
if pre_text:
|
||
normalized += f"-{pre_text}"
|
||
return _SemVer(int(major), int(minor), int(patch), pre, normalized)
|
||
|
||
|
||
def _compare_parsed(left: _SemVer, right: _SemVer) -> int:
|
||
left_core = (left.major, left.minor, left.patch)
|
||
right_core = (right.major, right.minor, right.patch)
|
||
if left_core < right_core:
|
||
return -1
|
||
if left_core > right_core:
|
||
return 1
|
||
|
||
# Версия без pre-release всегда новее версии с pre-release.
|
||
if not left.pre and not right.pre:
|
||
return 0
|
||
if not left.pre:
|
||
return 1
|
||
if not right.pre:
|
||
return -1
|
||
|
||
for left_id, right_id in zip(left.pre, right.pre):
|
||
if left_id == right_id:
|
||
continue
|
||
return -1 if left_id < right_id else 1
|
||
if len(left.pre) < len(right.pre):
|
||
return -1
|
||
if len(left.pre) > len(right.pre):
|
||
return 1
|
||
return 0
|
||
|
||
|
||
def compare_versions(left: Any, right: Any) -> int:
|
||
"""Сравнивает две semver-версии: -1, 0 или 1.
|
||
|
||
Бросает ValueError, если хотя бы одна строка не является semver.
|
||
"""
|
||
|
||
left_parsed = parse_version(left)
|
||
right_parsed = parse_version(right)
|
||
if left_parsed is None:
|
||
raise ValueError(f"Некорректная версия: {left!r}")
|
||
if right_parsed is None:
|
||
raise ValueError(f"Некорректная версия: {right!r}")
|
||
return _compare_parsed(left_parsed, right_parsed)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Результат проверки
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@dataclass
|
||
class AppUpdateInfo:
|
||
status: str = "error" # update | up_to_date | no_releases | error
|
||
current_version: str = ""
|
||
latest_version: str = ""
|
||
tag: str = ""
|
||
notes: str = ""
|
||
published_at: str = ""
|
||
prerelease: bool = False
|
||
assets: list[dict[str, Any]] = field(default_factory=list)
|
||
download_url: str = ""
|
||
asset_name: str = ""
|
||
error: str = ""
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Вспомогательные функции HTTP / файлов
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _emit(on_log: Optional[Callable[[str], None]], message: str) -> None:
|
||
if on_log is None:
|
||
return
|
||
try:
|
||
on_log(message)
|
||
except Exception:
|
||
# Ошибка в логгере не должна ломать установку.
|
||
pass
|
||
|
||
|
||
def _request(url: str, timeout: int, accept: str) -> Request:
|
||
return Request(
|
||
url,
|
||
headers={
|
||
"User-Agent": USER_AGENT,
|
||
"Accept": accept,
|
||
"X-GitHub-Api-Version": "2022-11-28",
|
||
},
|
||
)
|
||
|
||
|
||
def _read_json(url: str, timeout: int,
|
||
accept: str = "application/vnd.github+json") -> Any:
|
||
request = _request(url, timeout, accept)
|
||
with urlopen(request, timeout=timeout) as response:
|
||
raw = response.read()
|
||
return json.loads(raw.decode("utf-8"))
|
||
|
||
|
||
def _http_error_message(exc: HTTPError, url: str, label: str = "GitHub") -> str:
|
||
reason = getattr(exc, "reason", "") or ""
|
||
suffix = f" ({reason})" if reason else ""
|
||
return f"{label} вернул HTTP {exc.code}{suffix}: {url}"
|
||
|
||
|
||
def _network_error_message(exc: BaseException, url: str,
|
||
label: str = "GitHub") -> str:
|
||
if isinstance(exc, HTTPError):
|
||
return _http_error_message(exc, url, label)
|
||
if isinstance(exc, URLError):
|
||
reason = getattr(exc, "reason", exc)
|
||
return f"Не удалось связаться с {label}: {reason}"
|
||
return f"Ошибка сети при обращении к {url}: {exc}"
|
||
|
||
|
||
def _sanitize_filename(name: Any, fallback: str = "xenith-update.zip") -> str:
|
||
"""Оставляет от имени только безопасные символы и добавляет .zip."""
|
||
|
||
raw = str(name or "").replace("\\", "/")
|
||
base = os.path.basename(raw).strip()
|
||
base = re.sub(r"[^A-Za-z0-9._-]+", "_", base)
|
||
base = base.lstrip(".").strip("._-")
|
||
if not base:
|
||
base = fallback
|
||
if not base.lower().endswith(".zip"):
|
||
base += ".zip"
|
||
if len(base) > 120:
|
||
base = base[:-4][:116] + ".zip"
|
||
return base
|
||
|
||
|
||
def _download_stream(
|
||
url: str,
|
||
dest_path: str,
|
||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||
timeout: int = DEFAULT_TIMEOUT,
|
||
) -> str:
|
||
"""Скачивает url в dest_path через .part и os.replace."""
|
||
|
||
if not url:
|
||
raise ValueError("Не указан URL для скачивания")
|
||
|
||
dest_path = os.path.abspath(os.fspath(dest_path))
|
||
parent = os.path.dirname(dest_path)
|
||
if parent:
|
||
os.makedirs(parent, exist_ok=True)
|
||
|
||
part_path = dest_path + ".part"
|
||
request = _request(url, timeout, "*/*")
|
||
try:
|
||
with urlopen(request, timeout=timeout) as response:
|
||
try:
|
||
total = int(response.headers.get("Content-Length") or 0)
|
||
except (TypeError, ValueError):
|
||
total = 0
|
||
|
||
downloaded = 0
|
||
if on_progress is not None:
|
||
on_progress(0, total)
|
||
|
||
with open(part_path, "wb") as handle:
|
||
while True:
|
||
chunk = response.read(CHUNK_SIZE)
|
||
if not chunk:
|
||
break
|
||
handle.write(chunk)
|
||
downloaded += len(chunk)
|
||
if on_progress is not None:
|
||
on_progress(downloaded, total)
|
||
|
||
os.replace(part_path, dest_path)
|
||
return dest_path
|
||
except HTTPError as exc:
|
||
_remove_quietly(part_path)
|
||
raise RuntimeError(
|
||
f"Не удалось скачать обновление: HTTP {exc.code} {getattr(exc, 'reason', '')}".strip()
|
||
) from exc
|
||
except URLError as exc:
|
||
_remove_quietly(part_path)
|
||
raise RuntimeError(
|
||
f"Не удалось скачать обновление: {getattr(exc, 'reason', exc)}"
|
||
) from exc
|
||
except Exception:
|
||
_remove_quietly(part_path)
|
||
raise
|
||
|
||
|
||
def _remove_quietly(path: str) -> None:
|
||
try:
|
||
os.remove(path)
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _is_within(base: str, candidate: str) -> bool:
|
||
try:
|
||
return os.path.commonpath(
|
||
[os.path.abspath(base), os.path.abspath(candidate)]
|
||
) == os.path.abspath(base)
|
||
except ValueError:
|
||
return False
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Проверка релизов
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class AppUpdater:
|
||
"""Проверяет GitHub Releases и устанавливает обновления Xenith Studio."""
|
||
|
||
def __init__(
|
||
self,
|
||
repo: str,
|
||
current_version: str,
|
||
api_base: str = "https://api.github.com",
|
||
timeout: int = DEFAULT_TIMEOUT,
|
||
allow_prerelease: bool = False,
|
||
provider: str = "github",
|
||
):
|
||
self.repo = str(repo or "").strip().strip("/")
|
||
self.current_version = str(current_version or "").strip()
|
||
self.api_base = str(api_base or "https://api.github.com").rstrip("/")
|
||
self.timeout = max(1, int(timeout))
|
||
self.allow_prerelease = bool(allow_prerelease)
|
||
self.provider = "gitea" if str(provider).lower() == "gitea" else "github"
|
||
|
||
def _label(self) -> str:
|
||
return "Gitea" if self.provider == "gitea" else "GitHub"
|
||
|
||
def _accept(self) -> str:
|
||
return ("application/json" if self.provider == "gitea"
|
||
else "application/vnd.github+json")
|
||
|
||
# -- публичный API ------------------------------------------------------
|
||
|
||
def check(self) -> AppUpdateInfo:
|
||
info = AppUpdateInfo(current_version=self.current_version)
|
||
|
||
repo_error = self._validate_repo()
|
||
if repo_error:
|
||
info.status = "error"
|
||
info.error = repo_error
|
||
return info
|
||
|
||
current = parse_version(self.current_version)
|
||
if current is None:
|
||
info.status = "error"
|
||
info.error = (
|
||
f"Текущая версия приложения некорректна: {self.current_version!r}"
|
||
)
|
||
return info
|
||
|
||
try:
|
||
release = self._fetch_release()
|
||
except _NoReleases as exc:
|
||
info.status = "no_releases"
|
||
info.error = str(exc)
|
||
return info
|
||
except Exception as exc:
|
||
info.status = "error"
|
||
info.error = str(exc) or "Не удалось проверить обновления"
|
||
return info
|
||
|
||
if not isinstance(release, dict):
|
||
info.status = "error"
|
||
info.error = f"{self._label()} вернул неожиданный ответ вместо данных релиза"
|
||
return info
|
||
|
||
tag = str(release.get("tag_name") or "").strip()
|
||
latest = parse_version(tag)
|
||
if latest is None:
|
||
info.status = "no_releases"
|
||
info.error = (
|
||
"У репозитория пока нет релизов с корректной semver-версией"
|
||
)
|
||
return info
|
||
|
||
info.tag = tag
|
||
info.latest_version = latest.text
|
||
info.notes = str(release.get("body") or "")
|
||
info.published_at = str(release.get("published_at")
|
||
or release.get("created_at") or "")
|
||
info.prerelease = bool(release.get("prerelease"))
|
||
info.assets = self._normalize_assets(release.get("assets"))
|
||
info.download_url, info.asset_name = self._select_asset(
|
||
info.assets, release.get("zipball_url"), tag
|
||
)
|
||
|
||
comparison = _compare_parsed(latest, current)
|
||
if comparison <= 0:
|
||
info.status = "up_to_date"
|
||
return info
|
||
|
||
# Без явного разрешения pre-release не устанавливаем, даже если
|
||
# GitHub неожиданно вернул его в /releases/latest.
|
||
if (latest.pre or info.prerelease) and not self.allow_prerelease:
|
||
info.status = "up_to_date"
|
||
return info
|
||
|
||
info.status = "update"
|
||
return info
|
||
|
||
def download(
|
||
self,
|
||
url: str,
|
||
dest_path: str,
|
||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||
) -> str:
|
||
"""Скачивает ассет обновления. Возвращает путь к готовому файлу."""
|
||
|
||
return _download_stream(
|
||
url, dest_path, on_progress=on_progress, timeout=self.timeout
|
||
)
|
||
|
||
# -- внутреннее ---------------------------------------------------------
|
||
|
||
def _validate_repo(self) -> str:
|
||
parts = self.repo.split("/")
|
||
if len(parts) != 2 or not parts[0].strip() or not parts[1].strip():
|
||
return (
|
||
f"Некорректный репозиторий {self._label()}: ожидается формат "
|
||
'"владелец/имя"'
|
||
)
|
||
return ""
|
||
|
||
def _fetch_release(self) -> Any:
|
||
if self.provider == "gitea":
|
||
return self._fetch_gitea_release()
|
||
if not self.allow_prerelease:
|
||
url = f"{self.api_base}/repos/{self.repo}/releases/latest"
|
||
try:
|
||
return _read_json(url, self.timeout)
|
||
except HTTPError as exc:
|
||
if exc.code == 404:
|
||
raise _NoReleases(
|
||
"У репозитория пока нет релизов"
|
||
) from exc
|
||
raise RuntimeError(_http_error_message(exc, url, self._label())) from exc
|
||
except URLError as exc:
|
||
raise RuntimeError(_network_error_message(exc, url, self._label())) from exc
|
||
except json.JSONDecodeError as exc:
|
||
raise RuntimeError(
|
||
f"{self._label()} вернул некорректный JSON: {exc}"
|
||
) from exc
|
||
|
||
url = f"{self.api_base}/repos/{self.repo}/releases?per_page=10"
|
||
try:
|
||
payload = _read_json(url, self.timeout)
|
||
except HTTPError as exc:
|
||
if exc.code == 404:
|
||
raise _NoReleases("У репозитория пока нет релизов") from exc
|
||
raise RuntimeError(_http_error_message(exc, url, self._label())) from exc
|
||
except URLError as exc:
|
||
raise RuntimeError(_network_error_message(exc, url, self._label())) from exc
|
||
except json.JSONDecodeError as exc:
|
||
raise RuntimeError(
|
||
f"{self._label()} вернул некорректный JSON: {exc}"
|
||
) from exc
|
||
|
||
if isinstance(payload, dict):
|
||
# Иногда API может вернуть объект ошибки вместо списка.
|
||
message = payload.get("message")
|
||
if message:
|
||
raise RuntimeError(f"{self._label()} API: {message}")
|
||
raise RuntimeError(f"{self._label()} вернул неожиданный ответ вместо списка релизов")
|
||
|
||
if not isinstance(payload, list):
|
||
raise RuntimeError(f"{self._label()} вернул неожиданный ответ вместо списка релизов")
|
||
|
||
for release in payload:
|
||
if not isinstance(release, dict) or release.get("draft"):
|
||
continue
|
||
if parse_version(release.get("tag_name")) is None:
|
||
continue
|
||
return release
|
||
|
||
raise _NoReleases("У репозитория пока нет релизов с корректной версией")
|
||
|
||
def _fetch_gitea_release(self) -> Any:
|
||
url = f"{self.api_base}/repos/{self.repo}/releases?per_page=30"
|
||
try:
|
||
payload = _read_json(url, self.timeout, self._accept())
|
||
except HTTPError as exc:
|
||
if exc.code == 404:
|
||
raise _NoReleases("У репозитория пока нет релизов") from exc
|
||
raise RuntimeError(_http_error_message(exc, url, self._label())) from exc
|
||
except URLError as exc:
|
||
raise RuntimeError(_network_error_message(exc, url, self._label())) from exc
|
||
except json.JSONDecodeError as exc:
|
||
raise RuntimeError(
|
||
f"{self._label()} вернул некорректный JSON: {exc}"
|
||
) from exc
|
||
|
||
if isinstance(payload, dict):
|
||
message = payload.get("message")
|
||
if message:
|
||
raise RuntimeError(f"{self._label()} API: {message}")
|
||
raise RuntimeError(
|
||
f"{self._label()} вернул неожиданный ответ вместо списка релизов"
|
||
)
|
||
if not isinstance(payload, list):
|
||
raise RuntimeError(
|
||
f"{self._label()} вернул неожиданный ответ вместо списка релизов"
|
||
)
|
||
|
||
best: Optional[tuple[_SemVer, dict]] = None
|
||
for release in payload:
|
||
if not isinstance(release, dict) or release.get("draft"):
|
||
continue
|
||
version = parse_version(release.get("tag_name"))
|
||
if version is None:
|
||
continue
|
||
if release.get("prerelease") and not self.allow_prerelease:
|
||
continue
|
||
if best is None or _compare_parsed(version, best[0]) > 0:
|
||
best = (version, release)
|
||
if best is None:
|
||
raise _NoReleases("У репозитория пока нет релизов с корректной версией")
|
||
return best[1]
|
||
|
||
@staticmethod
|
||
def _normalize_assets(raw_assets: Any) -> list[dict[str, Any]]:
|
||
assets: list[dict[str, Any]] = []
|
||
if not isinstance(raw_assets, list):
|
||
return assets
|
||
for asset in raw_assets:
|
||
if not isinstance(asset, dict):
|
||
continue
|
||
try:
|
||
size = int(asset.get("size") or 0)
|
||
except (TypeError, ValueError):
|
||
size = 0
|
||
assets.append(
|
||
{
|
||
"name": str(asset.get("name") or ""),
|
||
"size": size,
|
||
"browser_download_url": str(
|
||
asset.get("browser_download_url") or ""
|
||
),
|
||
}
|
||
)
|
||
return assets
|
||
|
||
@staticmethod
|
||
def _select_asset(
|
||
assets: Iterable[dict[str, Any]],
|
||
zipball_url: Any,
|
||
tag: str,
|
||
) -> tuple[str, str]:
|
||
zips = [
|
||
asset
|
||
for asset in assets
|
||
if str(asset.get("name") or "").lower().endswith(".zip")
|
||
and str(asset.get("browser_download_url") or "").strip()
|
||
]
|
||
linux_zips = [
|
||
asset for asset in zips if "linux" in str(asset.get("name") or "").lower()
|
||
]
|
||
chosen = (linux_zips or zips or [None])[0]
|
||
|
||
if chosen is not None:
|
||
return (
|
||
str(chosen.get("browser_download_url") or ""),
|
||
str(chosen.get("name") or ""),
|
||
)
|
||
|
||
if zipball_url:
|
||
url = str(zipball_url)
|
||
basename = os.path.basename(urlparse(url).path) or f"{tag or 'release'}.zip"
|
||
return url, _sanitize_filename(basename, fallback="xenith-update.zip")
|
||
return "", ""
|
||
|
||
|
||
def install_release(
|
||
self,
|
||
info: AppUpdateInfo,
|
||
target_dir: str,
|
||
cache_dir: str,
|
||
backup_dir: str,
|
||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||
on_log: Optional[Callable[[str], None]] = None,
|
||
dry_run: bool = False,
|
||
) -> tuple[str, bool]:
|
||
return install_release(
|
||
info, target_dir, cache_dir, backup_dir,
|
||
on_progress=on_progress, on_log=on_log, dry_run=dry_run,
|
||
timeout=self.timeout,
|
||
)
|
||
|
||
|
||
class _NoReleases(Exception):
|
||
"""Внутренний сигнал: у репозитория нет подходящих релизов."""
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Установка
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _validate_zip_member(name: str) -> list[str]:
|
||
"""Проверяет путь внутри архива и возвращает его части."""
|
||
|
||
normalized = str(name).replace("\\", "/")
|
||
if "\x00" in normalized:
|
||
raise ValueError(f"Недопустимое имя файла в архиве: {name!r}")
|
||
|
||
if normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
|
||
raise ValueError(f"Абсолютный путь в архиве запрещён: {name!r}")
|
||
|
||
parts = [part for part in normalized.split("/") if part not in ("", ".")]
|
||
if any(part == ".." for part in parts):
|
||
raise ValueError(
|
||
f"Небезопасный путь в архиве (выход за пределы каталога): {name!r}"
|
||
)
|
||
return parts
|
||
|
||
|
||
def _extract_zip_safe(zip_path: str, staging: str) -> None:
|
||
"""Распаковывает архив в staging, проверяя все пути заранее."""
|
||
|
||
try:
|
||
with zipfile.ZipFile(zip_path) as archive:
|
||
members = archive.infolist()
|
||
if not members:
|
||
raise ValueError("Архив обновления пуст")
|
||
|
||
# Сначала проверяем все записи, чтобы ничего не распаковать
|
||
# до обнаружения zip-slip.
|
||
for member in members:
|
||
_validate_zip_member(member.filename)
|
||
|
||
staging_abs = os.path.abspath(staging)
|
||
for member in members:
|
||
parts = _validate_zip_member(member.filename)
|
||
if not parts:
|
||
continue
|
||
|
||
target = os.path.abspath(os.path.join(staging_abs, *parts))
|
||
if not _is_within(staging_abs, target):
|
||
raise ValueError(
|
||
f"Небезопасный путь в архиве: {member.filename!r}"
|
||
)
|
||
|
||
if member.is_dir():
|
||
os.makedirs(target, exist_ok=True)
|
||
continue
|
||
|
||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||
with archive.open(member) as source:
|
||
with open(target, "wb") as destination:
|
||
shutil.copyfileobj(source, destination)
|
||
|
||
mode = (member.external_attr >> 16) & 0o777
|
||
if mode:
|
||
try:
|
||
os.chmod(target, mode)
|
||
except OSError:
|
||
pass
|
||
except zipfile.BadZipFile as exc:
|
||
raise ValueError(f"Повреждённый zip-архив: {exc}") from exc
|
||
|
||
|
||
def _find_app_root(staging: str) -> Optional[str]:
|
||
"""Ищет каталог с xenith_app.py (самый верхний из найденных)."""
|
||
|
||
found: list[str] = []
|
||
for root, dirs, files in os.walk(staging):
|
||
dirs[:] = [
|
||
name
|
||
for name in dirs
|
||
if name not in _SKIP_DIRS
|
||
and not os.path.islink(os.path.join(root, name))
|
||
]
|
||
if "xenith_app.py" in files:
|
||
found.append(root)
|
||
|
||
if not found:
|
||
return None
|
||
|
||
found.sort(key=lambda path: (path.count(os.sep), len(path)))
|
||
return found[0]
|
||
|
||
|
||
def _iter_app_files(app_root: str) -> Iterable[tuple[str, str]]:
|
||
"""Возвращает (абсолютный путь, относительный путь) для файлов приложения."""
|
||
|
||
for item in APP_ITEMS:
|
||
source = os.path.join(app_root, item)
|
||
if os.path.isfile(source):
|
||
yield source, item
|
||
continue
|
||
if not os.path.isdir(source):
|
||
continue
|
||
|
||
for root, dirs, files in os.walk(source):
|
||
dirs[:] = [
|
||
name
|
||
for name in dirs
|
||
if name not in _SKIP_DIRS
|
||
and not os.path.islink(os.path.join(root, name))
|
||
]
|
||
for filename in sorted(files):
|
||
if filename.endswith(_SKIP_SUFFIXES):
|
||
continue
|
||
path = os.path.join(root, filename)
|
||
if os.path.islink(path) or not os.path.isfile(path):
|
||
continue
|
||
relative = os.path.relpath(path, app_root)
|
||
yield path, relative
|
||
|
||
|
||
def _unique_backup_dir(backup_dir: str) -> str:
|
||
base = time.strftime("%Y%m%d-%H%M%S")
|
||
candidate = os.path.join(backup_dir, base)
|
||
counter = 1
|
||
while os.path.exists(candidate):
|
||
candidate = os.path.join(backup_dir, f"{base}-{counter}")
|
||
counter += 1
|
||
return candidate
|
||
|
||
|
||
def _backup_existing(
|
||
target_dir: str,
|
||
backup_root: str,
|
||
relative: str,
|
||
on_log: Optional[Callable[[str], None]],
|
||
) -> None:
|
||
source = os.path.join(target_dir, relative)
|
||
if not os.path.exists(source):
|
||
return
|
||
|
||
destination = os.path.join(backup_root, relative)
|
||
os.makedirs(os.path.dirname(destination), exist_ok=True)
|
||
|
||
if os.path.isdir(source) and not os.path.islink(source):
|
||
shutil.copytree(
|
||
source,
|
||
destination,
|
||
dirs_exist_ok=True,
|
||
ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo", ".git"),
|
||
)
|
||
else:
|
||
shutil.copy2(source, destination, follow_symlinks=False)
|
||
|
||
_emit(on_log, f"Бэкап: {relative} -> {destination}")
|
||
|
||
|
||
def _atomic_copy(source: str, destination: str) -> None:
|
||
"""Копирует файл через временный файл в том же каталоге и os.replace."""
|
||
|
||
parent = os.path.dirname(destination)
|
||
if parent:
|
||
os.makedirs(parent, exist_ok=True)
|
||
|
||
prefix = f".{os.path.basename(destination)}."
|
||
fd, temp_path = tempfile.mkstemp(prefix=prefix, suffix=".tmp", dir=parent or None)
|
||
os.close(fd)
|
||
try:
|
||
shutil.copyfile(source, temp_path)
|
||
shutil.copymode(source, temp_path)
|
||
os.replace(temp_path, destination)
|
||
except Exception:
|
||
_remove_quietly(temp_path)
|
||
raise
|
||
|
||
|
||
def install_zip(
|
||
zip_path: str,
|
||
target_dir: str,
|
||
backup_dir: str,
|
||
dry_run: bool = False,
|
||
on_log: Optional[Callable[[str], None]] = None,
|
||
) -> bool:
|
||
"""Устанавливает zip-обновление поверх target_dir.
|
||
|
||
Ничего не удаляет: заменяются только файлы приложения, а их предыдущие
|
||
версии сохраняются в backup_dir/<timestamp>/ с теми же относительными
|
||
путями. Возвращает True при успехе.
|
||
"""
|
||
|
||
target_abs = os.path.abspath(os.fspath(target_dir))
|
||
backup_abs = os.path.abspath(os.fspath(backup_dir))
|
||
staging = tempfile.mkdtemp(prefix="xenith-update-")
|
||
|
||
try:
|
||
_emit(on_log, f"Распаковка обновления: {zip_path}")
|
||
try:
|
||
_extract_zip_safe(os.fspath(zip_path), staging)
|
||
except (OSError, ValueError, zipfile.BadZipFile) as exc:
|
||
_emit(on_log, f"Ошибка архива: {exc}")
|
||
return False
|
||
|
||
app_root = _find_app_root(staging)
|
||
if app_root is None:
|
||
_emit(
|
||
on_log,
|
||
"В архиве не найден xenith_app.py — это не обновление Xenith Studio",
|
||
)
|
||
return False
|
||
|
||
planned: list[tuple[str, str]] = []
|
||
for source, relative in _iter_app_files(app_root):
|
||
destination = os.path.join(target_abs, relative)
|
||
if not _is_within(target_abs, destination):
|
||
_emit(on_log, f"Небезопасный путь назначения: {relative}")
|
||
return False
|
||
planned.append((source, relative))
|
||
|
||
if not planned:
|
||
_emit(on_log, "В архиве нет файлов приложения для установки")
|
||
return False
|
||
|
||
_emit(on_log, f"Файлов к установке: {len(planned)}")
|
||
|
||
# Бэкап существующих путей — до любых изменений.
|
||
backup_root = ""
|
||
if not dry_run:
|
||
existing_items = [
|
||
item
|
||
for item in APP_ITEMS
|
||
if os.path.exists(os.path.join(app_root, item))
|
||
and os.path.exists(os.path.join(target_abs, item))
|
||
]
|
||
if existing_items:
|
||
backup_root = _unique_backup_dir(backup_abs)
|
||
os.makedirs(backup_root, exist_ok=True)
|
||
_emit(on_log, f"Каталог бэкапа: {backup_root}")
|
||
for item in existing_items:
|
||
try:
|
||
_backup_existing(
|
||
target_abs, backup_root, item, on_log
|
||
)
|
||
except OSError as exc:
|
||
_emit(on_log, f"Не удалось создать бэкап {item}: {exc}")
|
||
return False
|
||
else:
|
||
existing_items = [
|
||
item
|
||
for item in APP_ITEMS
|
||
if os.path.exists(os.path.join(app_root, item))
|
||
and os.path.exists(os.path.join(target_abs, item))
|
||
]
|
||
for item in existing_items:
|
||
_emit(on_log, f"[dry-run] Будет сохранён бэкап: {item}")
|
||
|
||
if dry_run:
|
||
for _source, relative in planned:
|
||
_emit(on_log, f"[dry-run] Будет скопировано: {relative}")
|
||
_emit(on_log, "[dry-run] Изменения не применялись")
|
||
return True
|
||
|
||
os.makedirs(target_abs, exist_ok=True)
|
||
copied = 0
|
||
for source, relative in planned:
|
||
destination = os.path.join(target_abs, relative)
|
||
try:
|
||
_atomic_copy(source, destination)
|
||
except OSError as exc:
|
||
_emit(on_log, f"Ошибка копирования {relative}: {exc}")
|
||
return False
|
||
copied += 1
|
||
_emit(on_log, f"Установлен: {relative}")
|
||
|
||
_emit(on_log, f"Обновление установлено. Файлов: {copied}")
|
||
return True
|
||
except Exception as exc:
|
||
_emit(on_log, f"Ошибка установки: {exc}")
|
||
return False
|
||
finally:
|
||
shutil.rmtree(staging, ignore_errors=True)
|
||
|
||
|
||
def install_release(
|
||
info: AppUpdateInfo,
|
||
target_dir: str,
|
||
cache_dir: str,
|
||
backup_dir: str,
|
||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||
on_log: Optional[Callable[[str], None]] = None,
|
||
dry_run: bool = False,
|
||
timeout: int = DEFAULT_TIMEOUT,
|
||
) -> tuple[str, bool]:
|
||
"""Скачивает релиз в cache_dir и устанавливает его.
|
||
|
||
Возвращает пару (путь_к_архиву, успех). При ошибке скачивания путь пустой.
|
||
Имя файла в кэше всегда очищается от потенциально опасных символов.
|
||
"""
|
||
|
||
if info is None or not info.download_url:
|
||
_emit(on_log, "Нет URL для скачивания обновления")
|
||
return "", False
|
||
|
||
filename = _sanitize_filename(
|
||
info.asset_name or os.path.basename(urlparse(info.download_url).path),
|
||
fallback="xenith-update.zip",
|
||
)
|
||
|
||
cache_abs = os.path.abspath(os.fspath(cache_dir))
|
||
os.makedirs(cache_abs, exist_ok=True)
|
||
zip_path = os.path.join(cache_abs, filename)
|
||
|
||
_emit(on_log, f"Скачивание обновления: {info.download_url}")
|
||
try:
|
||
_download_stream(
|
||
info.download_url,
|
||
zip_path,
|
||
on_progress=on_progress,
|
||
timeout=timeout,
|
||
)
|
||
except Exception as exc:
|
||
_emit(on_log, f"Ошибка скачивания: {exc}")
|
||
return "", False
|
||
|
||
_emit(on_log, f"Архив сохранён: {zip_path}")
|
||
ok = install_zip(
|
||
zip_path,
|
||
target_dir,
|
||
backup_dir,
|
||
dry_run=dry_run,
|
||
on_log=on_log,
|
||
)
|
||
return zip_path, ok
|