Files

469 lines
17 KiB
Python

"""Обновление встроенного движка 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