diff --git a/README.md b/README.md index 56494d4..4aee8d8 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,33 @@ # Xenith-Studio -графическая оболочка на python для Xenith \ No newline at end of file +графическая оболочка на python для Xenith + +## Запуск + +```bash +python3 xenith_app.py +``` + +## Обновления + +Приложение проверяет обновления через GitHub Releases в разделе +«Настройки → Обновления». Репозиторий задаётся там же (`owner/name`). +Релиз должен содержать zip-ассет с `xenith_app.py` и каталогом `XUI/` +(или GitHub-архив исходников). Перед установкой создаётся резервная копия, +после установки приложение нужно перезапустить. + +Обновление движка Xenith идёт по официальному контракту движка: +`updates/manifest.json` + sha256 файлов. Проверка версии работает и без +манифеста, но установка возможна только когда манифест опубликован. +Файлы движка резервируются в `tmp/backup/`. + +## Сервер для телефона + +В приложении: вкладка «Сервер» → «Запустить». Сервер отдаёт +OpenAI-совместимый `/v1` и Ollama-совместимый `/api` API с Bearer-токеном. + +Автономный вариант: + +```bash +python3 xenith_server.py --model models/ui_chat_model.xnh --host 0.0.0.0 --port 1234 +``` diff --git a/XUI/components/settings_window.py b/XUI/components/settings_window.py index 4247c04..2ed4b4f 100644 --- a/XUI/components/settings_window.py +++ b/XUI/components/settings_window.py @@ -3,6 +3,7 @@ import os import threading import time +import webbrowser from tkinter import filedialog, messagebox import customtkinter as ctk @@ -10,6 +11,8 @@ import customtkinter as ctk from .. import theme from ..theme import c, mono_font, ui_font from .controls import IconButton +from ..core.engine_updater import EngineUpdater +from ..version import __version__ as APP_VERSION ENGINE_TYPES = { "ollama": "Ollama", @@ -68,6 +71,7 @@ class SettingsWindow(ctk.CTkToplevel): ("appearance", "Внешний вид"), ("engines", "Движки"), ("mcp", "MCP"), + ("updates", "Обновления"), ("about", "О программе"), ] for key, label in categories: @@ -90,6 +94,7 @@ class SettingsWindow(ctk.CTkToplevel): "appearance": self._build_appearance(), "engines": self._build_engines(), "mcp": self._build_mcp(), + "updates": self._build_updates(), "about": self._build_about(), } for f in self.frames.values(): @@ -153,6 +158,8 @@ class SettingsWindow(ctk.CTkToplevel): self.refresh_engines() if key == "mcp": self._refresh_mcp() + if key == "updates": + self._refresh_updates() # ================================================================== # Внешний вид @@ -605,6 +612,300 @@ class SettingsWindow(ctk.CTkToplevel): except Exception as e: self.engine_status.configure(text=f"Ошибка MCP: {e}", text_color=c("danger")) + # ================================================================== + # Обновления + # ================================================================== + def _build_updates(self): + frame = ctk.CTkFrame(self.content, fg_color="transparent") + body = ctk.CTkScrollableFrame(frame, fg_color="transparent") + body.pack(fill="both", expand=True, padx=8, pady=8) + + # --- приложение --- + app_card = ctk.CTkFrame(body, fg_color=c("panel"), corner_radius=12, + border_width=1, border_color=c("border")) + app_card.pack(fill="x", padx=8, pady=(4, 10)) + ctk.CTkLabel(app_card, text="Приложение", font=ui_font(13), text_color=c("text")).pack( + anchor="w", padx=14, pady=(12, 2)) + ctk.CTkLabel(app_card, text=f"Версия {APP_VERSION} · обновление из GitHub Releases", + font=ui_font(11), text_color=c("text_faint")).pack(anchor="w", padx=14) + + repo_row = ctk.CTkFrame(app_card, fg_color="transparent") + repo_row.pack(fill="x", padx=14, pady=(10, 4)) + ctk.CTkLabel(repo_row, text="Репозиторий", font=ui_font(11), + text_color=c("text_dim")).pack(side="left") + self.app_repo_entry = ctk.CTkEntry(repo_row, height=32, font=ui_font(12)) + self.app_repo_entry.pack(side="left", fill="x", expand=True, padx=8) + try: + repo = ((self.app.engine.config.get("app_update") or {}).get("github_repo") + or "BIPfR/Xenith-Studio") + except Exception: + repo = "BIPfR/Xenith-Studio" + self.app_repo_entry.insert(0, repo) + + app_actions = ctk.CTkFrame(app_card, fg_color="transparent") + app_actions.pack(fill="x", padx=14, pady=(2, 4)) + self.app_check_btn = ctk.CTkButton(app_actions, text="Проверить", width=110, height=32, + command=self.check_app_update) + self.app_check_btn.pack(side="left") + self.app_install_btn = ctk.CTkButton(app_actions, text="Скачать и установить", width=180, + height=32, state="disabled", + fg_color=c("control"), hover_color=c("control"), + text_color=c("text_faint"), font=ui_font(12), + command=self.install_app_update) + self.app_install_btn.pack(side="left", padx=8) + ctk.CTkButton(app_card, text="Открыть GitHub", width=120, height=28, + fg_color="transparent", hover_color=c("card_hover"), + text_color=c("text_dim"), font=ui_font(11), + command=lambda: webbrowser.open( + "https://github.com/" + (self.app_repo_entry.get().strip() or "BIPfR/Xenith-Studio")) + ).pack(anchor="w", padx=14, pady=(0, 2)) + self.app_status = ctk.CTkLabel(app_card, text="", font=ui_font(11), + text_color=c("text_faint"), anchor="w", justify="left", + wraplength=560) + self.app_status.pack(fill="x", padx=14, pady=(2, 10)) + + # --- движок --- + eng_card = ctk.CTkFrame(body, fg_color=c("panel"), corner_radius=12, + border_width=1, border_color=c("border")) + eng_card.pack(fill="x", padx=8, pady=(0, 10)) + ctk.CTkLabel(eng_card, text="Движок Xenith", font=ui_font(13), text_color=c("text")).pack( + anchor="w", padx=14, pady=(12, 2)) + try: + eng_ver = self.app.engine.get_engine("xenith").version() if self.app.engine.get_engine("xenith") else "—" + except Exception: + eng_ver = "—" + self.eng_version_label = ctk.CTkLabel( + eng_card, text=f"Версия {eng_ver} · обновление по манифесту движка", + font=ui_font(11), text_color=c("text_faint")) + self.eng_version_label.pack(anchor="w", padx=14) + + eng_actions = ctk.CTkFrame(eng_card, fg_color="transparent") + eng_actions.pack(fill="x", padx=14, pady=(10, 4)) + self.eng_check_btn = ctk.CTkButton(eng_actions, text="Проверить", width=110, height=32, + command=self.check_engine_update) + self.eng_check_btn.pack(side="left") + self.eng_install_btn = ctk.CTkButton(eng_actions, text="Обновить движок", width=150, + height=32, state="disabled", + fg_color=c("control"), hover_color=c("control"), + text_color=c("text_faint"), font=ui_font(12), + command=self.install_engine_update) + self.eng_install_btn.pack(side="left", padx=8) + ctk.CTkButton(eng_card, text="Репозиторий движка", width=150, height=28, + fg_color="transparent", hover_color=c("card_hover"), + text_color=c("text_dim"), font=ui_font(11), + command=lambda: webbrowser.open("https://git.bipfr.ru/BIPfR/Xenith") + ).pack(anchor="w", padx=14, pady=(0, 2)) + self.eng_status = ctk.CTkLabel(eng_card, text="", font=ui_font(11), + text_color=c("text_faint"), anchor="w", justify="left", + wraplength=560) + self.eng_status.pack(fill="x", padx=14, pady=(2, 10)) + + ctk.CTkLabel(body, text="Лог обновления", font=ui_font(11), + text_color=c("text_dim")).pack(anchor="w", padx=8, pady=(4, 2)) + self.update_log = ctk.CTkTextbox(body, height=120, wrap="word", font=mono_font(10)) + self.update_log.pack(fill="x", padx=8, pady=(0, 8)) + + self._app_updater = None + self._app_info = None + self._engine_updater = None + self._engine_info = None + return frame + + def _set_primary_enabled(self, btn, enabled): + try: + if enabled: + btn.configure(state="normal", fg_color=c("action_bg"), + hover_color=c("action_hover"), text_color=c("action_fg")) + else: + btn.configure(state="disabled", fg_color=c("control"), + hover_color=c("control"), text_color=c("text_faint")) + except Exception: + pass + + def _update_log(self, line): + try: + self.update_log.insert("end", str(line) + "\n") + self.update_log.see("end") + except Exception: + pass + + def _app_project_dir(self): + # XUI/components/settings_window.py -> корень проекта + return os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) + + def _save_app_repo(self): + repo = self.app_repo_entry.get().strip() + if repo: + self.app.engine.config.setdefault("app_update", {})["github_repo"] = repo + self.app.engine.save_config() + + def check_app_update(self): + repo = self.app_repo_entry.get().strip() + if "/" not in repo: + self.app_status.configure(text="Укажите репозиторий в виде owner/name", text_color=c("danger")) + return + self._save_app_repo() + self.app_status.configure(text="Проверка GitHub…", text_color=c("text_faint")) + self._set_primary_enabled(self.app_install_btn, False) + + def task(): + try: + from ..core.app_updater import AppUpdater + up = AppUpdater(repo, APP_VERSION) + info = up.check() + self.app.post_ui(lambda: self._on_app_update(info, up)) + except Exception as e: + self.app.post_ui(lambda msg=str(e): self.app_status.configure( + text=f"Ошибка обновления приложения: {msg}", text_color=c("danger"))) + + threading.Thread(target=task, daemon=True).start() + + def _on_app_update(self, info, updater): + self._app_info = info + self._app_updater = updater + status = getattr(info, "status", "error") + if status == "update": + self.app_status.configure( + text=f"Доступна версия {info.latest_version} (сейчас {info.current_version})", + text_color=c("text")) + self._set_primary_enabled(self.app_install_btn, True) + self._update_log(f"github: доступна {info.latest_version} ({info.tag})") + elif status == "up_to_date": + self.app_status.configure(text=f"Актуальная версия {info.current_version}", + text_color=c("text_faint")) + self._update_log("github: обновлений нет") + elif status == "no_releases": + self.app_status.configure(text="У репозитория пока нет релизов", + text_color=c("text_faint")) + self._update_log("github: релизов нет") + else: + self.app_status.configure(text=f"Проверка не удалась: {getattr(info,'error','')}", + text_color=c("danger")) + self._update_log(f"github: {getattr(info,'error','')}") + + def install_app_update(self): + if self._app_info is None or self._app_updater is None: + return + if not messagebox.askyesno( + "Обновление приложения", + "Скачать последний релиз и заменить файлы приложения?\n" + "Будет создана резервная копия; приложение нужно перезапустить.", + parent=self): + return + self._set_primary_enabled(self.app_install_btn, False) + self.app_status.configure(text="Скачивание и установка…", text_color=c("text_faint")) + + def log(line): + self.app.post_ui(lambda l=line: self._update_log(l)) + + def task(): + try: + cache = os.path.join(os.path.expanduser("~"), ".cache", "xenith-studio", "updates") + backup = os.path.join(os.path.expanduser("~"), ".local", "share", + "xenith-studio", "backup") + result = self._app_updater.install_release( + self._app_info, self._app_project_dir(), cache, backup, on_log=log) + if isinstance(result, tuple): + ok = bool(result[1]) if len(result) > 1 else bool(result[0]) + else: + ok = bool(result) + self.app.post_ui(lambda: self._on_app_installed(ok)) + except Exception as e: + self.app.post_ui(lambda msg=str(e): self._on_app_installed(False, msg)) + + threading.Thread(target=task, daemon=True).start() + + def _on_app_installed(self, ok, error=""): + if ok: + self.app_status.configure(text="Обновление установлено. Перезапустите приложение", + text_color=c("success")) + self._update_log("github: установлено, нужен перезапуск") + else: + self.app_status.configure(text=f"Установка не удалась: {error}", + text_color=c("danger")) + self._set_primary_enabled(self.app_install_btn, False) + + def check_engine_update(self): + self.eng_status.configure(text="Проверка движка…", text_color=c("text_faint")) + self._set_primary_enabled(self.eng_install_btn, False) + + def task(): + try: + try: + import xenith_engine as xe + cur = str(xe.version()) + except Exception: + cur = None + up = EngineUpdater(current_version=cur, app_dir=self._app_project_dir()) + info = up.check() + self.app.post_ui(lambda: self._on_engine_update(info, up)) + except Exception as e: + self.app.post_ui(lambda msg=str(e): self.eng_status.configure( + text=f"Ошибка проверки движка: {msg}", text_color=c("danger"))) + + threading.Thread(target=task, daemon=True).start() + + def _on_engine_update(self, info, updater): + self._engine_info = info + self._engine_updater = updater + if info.status == "update": + text = f"Доступна {info.remote} (сейчас {info.current})" + if info.changed_files: + text += f" · файлов: {info.changed_files}" + self.eng_status.configure(text=text, text_color=c("text")) + self._set_primary_enabled(self.eng_install_btn, bool(info.can_install)) + self._update_log(f"engine: {info.message}") + elif info.status == "up_to_date": + self.eng_status.configure(text=f"Актуальная версия {info.current}", + text_color=c("text_faint")) + self._update_log("engine: обновлений нет") + elif info.status == "no_manifest": + self.eng_status.configure(text=info.message, text_color=c("warn")) + self._update_log("engine: " + info.message) + elif info.status == "local_newer": + self.eng_status.configure(text=info.message, text_color=c("text_faint")) + self._update_log("engine: " + info.message) + else: + self.eng_status.configure(text=f"Проверка не удалась: {info.error}", + text_color=c("danger")) + self._update_log("engine: " + (info.error or "ошибка")) + + def install_engine_update(self): + if self._engine_info is None or self._engine_updater is None: + return + if not messagebox.askyesno( + "Обновление движка", + "Установить обновление движка? Текущие файлы будут сохранены в backup. " + "После установки нужен перезапуск приложения.", + parent=self): + return + self._set_primary_enabled(self.eng_install_btn, False) + self.eng_status.configure(text="Установка обновления движка…", text_color=c("text_faint")) + + def log(line): + self.app.post_ui(lambda l=line: self._update_log(l)) + + def task(): + try: + ok = self._engine_updater.install(self._engine_info, on_log=log) + self.app.post_ui(lambda: self._on_engine_installed(ok)) + except Exception as e: + self.app.post_ui(lambda msg=str(e): self._on_engine_installed(False, msg)) + + threading.Thread(target=task, daemon=True).start() + + def _on_engine_installed(self, ok, error=""): + if ok: + self.eng_status.configure(text="Движок обновлён. Перезапустите приложение", + text_color=c("success")) + else: + self.eng_status.configure(text=f"Обновление движка не установлено: {error}", + text_color=c("danger")) + self._set_primary_enabled(self.eng_install_btn, False) + + def _refresh_updates(self): + pass + # ================================================================== # О программе # ================================================================== @@ -616,7 +917,7 @@ class SettingsWindow(ctk.CTkToplevel): "", f"Движок: {self.app.engine.describe()}", f"Активный движок: {self.app.engine.active_name()}", - f"Версия приложения: 0.2", + f"Версия приложения: {APP_VERSION}", f"Конфиг: {os.path.join(os.path.expanduser('~'), '.config', 'xenith-studio', 'config.json')}", ] for line in lines: diff --git a/XUI/core/app_updater.py b/XUI/core/app_updater.py new file mode 100644 index 0000000..9e57d5f --- /dev/null +++ b/XUI/core/app_updater.py @@ -0,0 +1,870 @@ +"""Обновление Xenith Studio из GitHub 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", + "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) -> Any: + request = _request(url, timeout, "application/vnd.github+json") + 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) -> str: + reason = getattr(exc, "reason", "") or "" + suffix = f" ({reason})" if reason else "" + return f"GitHub вернул HTTP {exc.code}{suffix}: {url}" + + +def _network_error_message(exc: BaseException, url: str) -> str: + if isinstance(exc, HTTPError): + return _http_error_message(exc, url) + if isinstance(exc, URLError): + reason = getattr(exc, "reason", exc) + return f"Не удалось связаться с GitHub: {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, + ): + 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) + + # -- публичный 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 = "GitHub вернул неожиданный ответ вместо данных релиза" + 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 "") + 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 ( + "Некорректный репозиторий GitHub: ожидается формат " + '"владелец/имя"' + ) + return "" + + def _fetch_release(self) -> Any: + 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)) from exc + except URLError as exc: + raise RuntimeError(_network_error_message(exc, url)) from exc + except json.JSONDecodeError as exc: + raise RuntimeError( + f"GitHub вернул некорректный 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)) from exc + except URLError as exc: + raise RuntimeError(_network_error_message(exc, url)) from exc + except json.JSONDecodeError as exc: + raise RuntimeError( + f"GitHub вернул некорректный JSON: {exc}" + ) from exc + + if isinstance(payload, dict): + # Иногда API может вернуть объект ошибки вместо списка. + message = payload.get("message") + if message: + raise RuntimeError(f"GitHub API: {message}") + raise RuntimeError("GitHub вернул неожиданный ответ вместо списка релизов") + + if not isinstance(payload, list): + raise RuntimeError("GitHub вернул неожиданный ответ вместо списка релизов") + + 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("У репозитория пока нет релизов с корректной версией") + + @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 "", "" + + +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// с теми же относительными + путями. Возвращает 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 diff --git a/XUI/core/config.py b/XUI/core/config.py index 203ced9..edcecb6 100644 --- a/XUI/core/config.py +++ b/XUI/core/config.py @@ -41,6 +41,10 @@ DEFAULT_CONFIG = { "roots": [], "servers": {}, }, + "app_update": { + "github_repo": "BIPfR/Xenith-Studio", + "include_prerelease": False, + }, } diff --git a/XUI/core/engine_updater.py b/XUI/core/engine_updater.py new file mode 100644 index 0000000..7302e86 --- /dev/null +++ b/XUI/core/engine_updater.py @@ -0,0 +1,468 @@ +"""Обновление встроенного движка Xenith по официальному манифесту. + +Повторяет правила нативного апдейтера: +- обновляемся только если версия в репозитории СТРОГО больше локальной; +- качаем только файлы, чей sha256 отличается; +- проверяем sha256, делаем backup, атомарно заменяем; +- ничего не удаляем, models/config не трогаем; +- установка требует updates/manifest.json (без манифеста только проверка). +""" + +import hashlib +import json +import os +import platform +import re +import shutil +import ssl +import tempfile +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from typing import Callable, List, Optional + + +def _strip_git(repo: str) -> str: + repo = (repo or "").strip().rstrip("/") + if repo.endswith(".git"): + repo = repo[:-4] + return repo + + +def parse_semver(value: str): + s = (value or "").strip() + while s and s[0] in ("v", "V"): + s = s[1:] + s = s.strip() + if not s: + return None + pre = "" + if "-" in s: + s, pre = s.split("-", 1) + parts = s.split(".") + try: + nums = [int(p) for p in parts[:3]] + except Exception: + return None + while len(nums) < 3: + nums.append(0) + return tuple(nums), pre + + +def semver_cmp(a: str, b: str) -> int: + va, vb = parse_semver(a), parse_semver(b) + if va is None or vb is None: + return 0 + na, pa = va + nb, pb = vb + for x, y in zip(na, nb): + if x != y: + return 1 if x > y else -1 + if pa == pb: + return 0 + if not pa: + return 1 + if not pb: + return -1 + aa, bb = pa.split("."), pb.split(".") + for i in range(max(len(aa), len(bb))): + if i >= len(aa): + return -1 + if i >= len(bb): + return 1 + x, y = aa[i], bb[i] + xn, yn = x.isdigit(), y.isdigit() + if xn and yn: + if int(x) != int(y): + return 1 if int(x) > int(y) else -1 + elif xn != yn: + return -1 if xn else 1 + elif x != y: + return 1 if x > y else -1 + return 0 + + +def sha256_file(path: str) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1024 * 256), b""): + h.update(chunk) + return h.hexdigest() + + +def _ssl_context(verify: bool): + if verify: + return ssl.create_default_context() + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + return ctx + + +def _http_get(url: str, timeout: int = 15, verify: bool = True, + on_progress: Optional[Callable[[int, int], None]] = None, + dest: Optional[str] = None): + req = urllib.request.Request(url, headers={"User-Agent": "Xenith-Studio-Updater/1.0"}) + ctx = _ssl_context(verify) + with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp: + total = int(resp.headers.get("Content-Length") or 0) + if dest is None: + return resp.read() + done = 0 + tmp = dest + ".part" + with open(tmp, "wb") as f: + while True: + chunk = resp.read(1024 * 128) + if not chunk: + break + f.write(chunk) + done += len(chunk) + if on_progress: + try: + on_progress(done, total) + except Exception: + pass + os.replace(tmp, dest) + return dest + + +@dataclass +class EngineUpdateInfo: + status: str = "error" # update | up_to_date | local_newer | error | no_manifest + current: str = "" + remote: str = "" + tag: str = "" + notes: str = "" + manifest_url: str = "" + install_dir: str = "" + files: List[dict] = field(default_factory=list) + changed_files: int = 0 + changed_bytes: int = 0 + can_install: bool = False + error: str = "" + message: str = "" + + +def _read_update_conf(path: str) -> dict: + defaults = { + "enabled": True, + "repo": "https://git.bipfr.ru/BIPfR/Xenith", + "branch": "master", + "manifest_url": "", + "files_base": "", + "install_dir": "", + "backup_dir": "tmp/backup", + "timeout_sec": 15, + "verify_tls": True, + } + try: + with open(path, "r", encoding="utf-8") as f: + text = f.read() + except Exception: + return defaults + in_update = False + out = dict(defaults) + for raw in text.splitlines(): + line = raw.rstrip() + if not line.strip() or line.strip().startswith("#"): + continue + if not line.startswith(" ") and line.strip() == "update:": + in_update = True + continue + if in_update and not line.startswith(" "): + break + if not in_update: + continue + m = re.match(r"\s{2}([A-Za-z0-9_]+):\s*(.*)$", line) + if not m: + continue + key, val = m.group(1), m.group(2).strip() + if val in ("true", "false"): + out[key] = val == "true" + elif val.startswith('"') and val.endswith('"'): + out[key] = val[1:-1] + elif val.startswith("'") and val.endswith("'"): + out[key] = val[1:-1] + elif val.isdigit(): + out[key] = int(val) + else: + out[key] = val + return out + + +def _platform() -> str: + system = platform.system().lower() + machine = platform.machine().lower() + if system == "linux": + osname = "linux" + elif system == "windows": + osname = "windows" + elif system == "darwin": + osname = "macos" + else: + osname = system or "linux" + if machine in ("aarch64", "arm64"): + arch = "arm64" + elif machine.startswith("arm"): + arch = "arm" + else: + arch = "x64" + return f"{osname}-{arch}" + + +class EngineUpdater: + def __init__(self, settings: dict = None, current_version: str = None, + install_dir: str = None, app_dir: str = None): + self.app_dir = app_dir or os.getcwd() + self.conf = _read_update_conf(os.path.join(self.app_dir, "xenith", "config.yaml")) + if settings: + self.conf.update(settings) + if current_version is None: + try: + import xenith_engine as xe + current_version = str(xe.version()) + except Exception: + current_version = "0.0.0" + self.current = str(current_version) + if install_dir: + self.install_dir = os.path.abspath(install_dir) + elif self.conf.get("install_dir"): + p = str(self.conf["install_dir"]) + self.install_dir = p if os.path.isabs(p) else os.path.abspath(os.path.join(self.app_dir, p)) + else: + try: + import xenith_engine as xe + self.install_dir = os.path.dirname(os.path.abspath(xe.__file__)) + except Exception: + self.install_dir = os.path.abspath(self.app_dir) + + # ---------- URLs ---------- + def manifest_url(self) -> str: + explicit = str(self.conf.get("manifest_url") or "").strip() + if explicit: + return explicit + repo = _strip_git(str(self.conf.get("repo") or "")) + branch = str(self.conf.get("branch") or "master") + return f"{repo}/raw/branch/{branch}/updates/manifest.json" + + def files_base(self) -> str: + explicit = str(self.conf.get("files_base") or "").strip() + if explicit: + return explicit.rstrip("/") + repo = _strip_git(str(self.conf.get("repo") or "")) + branch = str(self.conf.get("branch") or "master") + return f"{repo}/raw/branch/{branch}" + + def version_url(self) -> str: + repo = _strip_git(str(self.conf.get("repo") or "")) + branch = str(self.conf.get("branch") or "master") + return f"{repo}/raw/branch/{branch}/version.txt" + + # ---------- check ---------- + def _get_manifest(self): + timeout = int(self.conf.get("timeout_sec") or 15) + verify = bool(self.conf.get("verify_tls", True)) + try: + body = _http_get(self.manifest_url(), timeout=timeout, verify=verify) + data = json.loads(body.decode("utf-8", "replace")) + if not isinstance(data, dict) or not data.get("files"): + return None, "в манифесте нет files" + for item in data.get("files") or []: + if not isinstance(item, dict): + return None, "некорректный манифест: элемент files не объект" + rel = str(item.get("path") or "") + if not self._safe_rel(rel): + return None, f"некорректный манифест: небезопасный путь {rel!r}" + sha = str(item.get("sha256") or "") + if len(sha) != 64 or any(ch not in "0123456789abcdefABCDEF" for ch in sha): + return None, f"некорректный манифест: плохой sha256 для {rel!r}" + return data, "" + except urllib.error.HTTPError as e: + return None, f"HTTP {e.code} ({self.manifest_url()})" + except Exception as e: + return None, str(e) + + def _remote_version(self): + timeout = int(self.conf.get("timeout_sec") or 15) + verify = bool(self.conf.get("verify_tls", True)) + try: + body = _http_get(self.version_url(), timeout=timeout, verify=verify) + text = body.decode("utf-8", "replace").strip().splitlines() + return (text[0].strip() if text else ""), "" + except Exception as e: + return "", str(e) + + def _count_changes(self, manifest) -> tuple: + changed = 0 + size = 0 + plat = _platform() + for item in manifest.get("files") or []: + if not isinstance(item, dict): + continue + want = str(item.get("platform") or "") + if want and want not in ("any", "*", plat): + continue + rel = str(item.get("path") or "") + if not self._safe_rel(rel): + continue + dst = os.path.join(self.install_dir, rel) + sha = str(item.get("sha256") or "").lower() + try: + if os.path.isfile(dst) and sha256_file(dst) == sha: + continue + except Exception: + pass + if not os.path.exists(dst) and item.get("optional"): + continue + changed += 1 + try: + size += int(item.get("size") or 0) + except Exception: + pass + return changed, size + + def check(self) -> EngineUpdateInfo: + info = EngineUpdateInfo(current=self.current, install_dir=self.install_dir, + manifest_url=self.manifest_url()) + manifest, merr = self._get_manifest() + if merr.startswith("некорректный манифест"): + info.status = "error" + info.error = merr + return info + if manifest: + remote = str(manifest.get("version") or "") + info.remote = remote + info.tag = str(manifest.get("tag") or "") + info.notes = str(manifest.get("notes") or "") + if not parse_semver(remote): + info.status = "error" + info.error = f"не удалось разобрать версию манифеста: {remote}" + return info + cmp = semver_cmp(remote, self.current) + if cmp > 0: + info.status = "update" + info.can_install = True + info.files = list(manifest.get("files") or []) + info.changed_files, info.changed_bytes = self._count_changes(manifest) + info.message = f"доступна версия {remote} (сейчас {self.current})" + elif cmp == 0: + info.status = "up_to_date" + info.message = f"установлена актуальная версия {self.current}" + else: + info.status = "local_newer" + info.message = f"локальная версия {self.current} новее {remote}" + return info + + # Манифеста нет — можно только сообщить версию из version.txt. + remote, verr = self._remote_version() + info.remote = remote + info.error = merr or verr + if remote and parse_semver(remote): + info.tag = remote + if semver_cmp(remote, self.current) > 0: + info.status = "no_manifest" + info.message = (f"в репозитории версия {remote}, но updates/manifest.json " + f"не опубликован — установка недоступна") + elif semver_cmp(remote, self.current) == 0: + info.status = "up_to_date" + info.message = f"установлена актуальная версия {self.current}" + else: + info.status = "local_newer" + info.message = f"локальная версия {self.current} новее {remote}" + else: + info.status = "error" + info.error = merr or verr or "не удалось проверить обновления" + return info + + # ---------- install ---------- + def _safe_rel(self, rel: str) -> bool: + if not rel or rel.startswith(("/", "\\")) or len(rel) > 4096: + return False + parts = rel.replace("\\", "/").split("/") + return all(p not in ("", ".", "..") for p in parts) + + def install(self, info: EngineUpdateInfo = None, dry_run: bool = False, + on_log: Optional[Callable[[str], None]] = None) -> bool: + log = on_log or (lambda _s: None) + info = info or self.check() + if info.status != "update" or not info.can_install: + log(info.message or info.error or "обновление не требуется") + return False + manifest, merr = self._get_manifest() + if not manifest: + log(f"нет манифеста: {merr}") + return False + timeout = int(self.conf.get("timeout_sec") or 60) + verify = bool(self.conf.get("verify_tls", True)) + base = str(manifest.get("files_base") or "").rstrip("/") or self.files_base() + plat = _platform() + backup_root = os.path.join( + self.install_dir, + str(self.conf.get("backup_dir") or "tmp/backup"), + time.strftime("%Y%m%d-%H%M%S"), + ) + changed = 0 + ok = True + for item in manifest.get("files") or []: + if not isinstance(item, dict): + continue + rel = str(item.get("path") or "") + if not self._safe_rel(rel): + log(f"пропущен небезопасный путь: {rel}") + ok = False + continue + want_platform = str(item.get("platform") or "") + if want_platform and want_platform not in ("any", "*", plat): + continue + dst = os.path.join(self.install_dir, rel) + want_sha = str(item.get("sha256") or "").lower() + try: + if os.path.isfile(dst) and sha256_file(dst) == want_sha: + continue + except Exception: + pass + if not os.path.exists(dst) and item.get("optional"): + continue + changed += 1 + if dry_run: + log(f"[dry-run] {rel}") + continue + url = str(item.get("url") or "") + if not url: + url = base + "/" + urllib.parse.quote(rel) + elif not url.startswith(("http://", "https://")): + url = base + "/" + url.lstrip("/") + log(f"скачивание {rel}") + tmp_dir = tempfile.mkdtemp(prefix="xenith-engine-", dir=self.install_dir) + tmp_file = os.path.join(tmp_dir, "download") + try: + _http_get(url, timeout=timeout, verify=verify, dest=tmp_file) + got = sha256_file(tmp_file) + if want_sha and got != want_sha: + raise RuntimeError(f"sha256 не совпал для {rel}: {got}") + if os.path.exists(dst): + backup = os.path.join(backup_root, rel) + os.makedirs(os.path.dirname(backup), exist_ok=True) + shutil.copy2(dst, backup) + os.makedirs(os.path.dirname(dst) or self.install_dir, exist_ok=True) + staged = dst + ".xenith-new" + shutil.copy2(tmp_file, staged) + mode = str(item.get("mode") or "") + if mode in ("755", "0755", "777", "0777"): + os.chmod(staged, 0o755) + elif mode in ("644", "0644"): + os.chmod(staged, 0o644) + os.replace(staged, dst) + log(f"обновлён {rel}") + except Exception as e: + ok = False + log(f"ошибка {rel}: {e}") + finally: + shutil.rmtree(tmp_dir, ignore_errors=True) + if changed == 0: + log("нет изменённых файлов") + if ok: + log("обновление движка установлено — перезапустите приложение") + return ok and changed > 0 diff --git a/XUI/version.py b/XUI/version.py new file mode 100644 index 0000000..d3ec452 --- /dev/null +++ b/XUI/version.py @@ -0,0 +1 @@ +__version__ = "0.2.0"