<?phpnamespace App\Core;use JumPHP\Http\Http;use JumPHP\Http\HttpResponse;use JumPHP\Tauri\Updater;/** * The installed WinZik keeps itself up to date, like the JumPHP IDE (games/ide/src/SelfUpdate.php): 8 s after it * starts and every 6 hours it reads update.json (project.yaml `update_url`: apps/winzik/installer/update.json on the * main branch of the repository, written by tools/release.sh), checks its signature (config/update.pub, ECDSA P-256, * tools/app-release.php of JumPHP), and when the version is newer downloads this computer's executable, checks its * SHA-256 and puts it in place of the running one (JumPHP\Tauri\Updater::replace). The next start runs it, or * "Redémarrer" now. Only the one-file executable can do it (JUMPHP_EXECUTABLE); elsewhere it stays off. * * States: off | idle | checking | latest | installing | installed | error * * The phone app (AutoUpdate::phone(), Platform::isPhoneApp()): the same signed update.json, its "android" entry (the * APK of the release: url, sha256, size, versionCode). A newer one is 'available' (the UI shows it: androidUpdate()). * With "Mettre WinZik à jour tout seul" (options autoUpdate, tick($dt, true)) it goes on by itself, as on a computer: * - the APK is downloaded on Wi-Fi only (AndroidApp::network() 'unmetered'; mobile data: it waits, the banner offers it), * its size and SHA-256 checked against the signed update.json: 'ready'; * - installed at a good moment ($goodMoment, WinZik::goodMomentToUpdate(): nothing plays, or a song just started with * the screen off), after $beforeInstall (WinZik saves the song and its position), through a PackageInstaller session * (AndroidApp::installSilently: no install screen; Android asks "install unknown apps" once): 'installing', 'confirm' * while Android asks; * - Android stops the app, installs, and reopens it (the screen off: by itself; on: a tap on its notification); it * plays the song on (WinZik::load()). * installAndroidUpdate() (the button "Mettre à jour") does the same at once, whatever the network or the moment. A refusal * or a failure is 'error' and the automatic install of that version stops (the button stays). * enabled() stays false on a phone (it is the desktop self-replacement the splash, the song of the last time and the menu * wait for); isPhone(). * Phone states: off | idle | checking | latest | available | downloading | ready | installing | confirm | opened * (Android's installer screen, an engine without sessions) | error */final class AutoUpdate{ public const FIRST_CHECK = 8.0; public const EVERY = 6 * 3600.0; public string $state = 'idle'; public string $version = ''; public string $notes = ''; public string $error = ''; private float $clock = 0.0; /** 0..1 of the download (the splash shows it) */ public float $progress = 0.0; private ?\App\Media\FileDownload $download = null; /** @var array{url: string, sha256: string, size: int}|null */ private ?array $file = null; private float $next = self::FIRST_CHECK; /** the key of the phone's file in update.json's platforms (one APK for every ABI of the release) */ public const ANDROID = 'android'; /** the phone app's own versionCode (JUMPHP_ANDROID_VERSION_CODE; 0: unknown, the version names are compared) */ private int $versionCode; /** @var array{url: string, sha256: string, size: int, versionCode: int}|null the newer APK found (phone) */ private ?array $apk = null; /** @var (\Closure(string): bool)|null what gives the APK to Android's installer screen (tests: a fake one); null: installApk() */ public ?\Closure $installer = null; /** @var (\Closure(string): string)|null the session install (tests: a fake); null: AndroidApp::installSilently() */ public ?\Closure $sessionInstaller = null; /** @var (\Closure(): array{state: string, message: string, status: int})|null what the session became; null: AndroidApp::installState() */ public ?\Closure $installState = null; /** @var (\Closure(): ?string)|null the network: unmetered | metered | none | null (unknown); null: AndroidApp::network() */ public ?\Closure $network = null; /** @var (\Closure(): bool)|null may the app restart now (WinZik: nothing plays, or a song just started)? null: yes */ public ?\Closure $goodMoment = null; /** @var (\Closure(): void)|null just before the install (WinZik saves the song and its position) */ public ?\Closure $beforeInstall = null; /** the version whose automatic install stopped (refused, failed): only the button installs it */ private string $declined = ''; /** the install was asked by the user (the button): no waiting for a good moment */ private bool $asked = false; /** @param string|null $apkDir the phone app: where its APK is downloaded (null on a computer) */ public function __construct(private Http $http, private string $url, private string $current, private string $id, private ?string $publicKey, private ?string $executable, private ?string $apkDir = null, int $versionCode = 0) { $this->versionCode = max(0, $versionCode); if ($url === '' || $publicKey === null || ($executable === null && $apkDir === null)) { $this->state = 'off'; } } /** * The phone app's updater: its version is the APK's (JUMPHP_ANDROID_VERSION_NAME / _CODE when the engine sets * them, else project.yaml's), the APK goes to $apkDir (the app's storage). */ public static function phone(Http $http, string $url, string $version, string $id, ?string $publicKey, string $apkDir): self { $name = \JumPHP\Native\AndroidApp::versionName(); return new self($http, $url, $name !== null && $name !== '' ? $name : $version, $id, $publicKey, null, $apkDir, \JumPHP\Native\AndroidApp::versionCode() ?? 0); } /** The program replaces itself (a computer): the splash, the song of the last time and the menu wait for it. */ public function enabled(): bool { return $this->state !== 'off' && $this->apkDir === null; } /** The phone app's updater (and not off). */ public function isPhone(): bool { return $this->state !== 'off' && $this->apkDir !== null; } /** Each frame: the checks come by themselves (when $auto); the phone downloads, installs and follows its update. */ public function tick(float $dt, bool $auto): void { if ($this->apkDir !== null) { $this->tickPhone($auto); } if (!$auto || in_array($this->state, self::BUSY, true)) { return; } $this->clock += $dt; if ($this->clock >= $this->next) { $this->next = $this->clock + self::EVERY; $this->check(); } } /** no check while one of these lasts */ private const BUSY = ['off', 'checking', 'installing', 'installed', 'downloading', 'ready', 'confirm']; /** Reads update.json now (the menu: Rechercher une mise à jour). */ public function check(): void { if (in_array($this->state, self::BUSY, true)) { return; } $this->state = 'checking'; $this->next = $this->clock + self::EVERY; // asked now (the splash): the next one in 6 hours $this->http->request('GET', $this->url, null, ['Cache-Control' => 'no-cache'], 30)->then(function (HttpResponse $r): void { try { if (!$r->ok()) { throw new \RuntimeException("update.json : HTTP $r->status"); } if ($this->apkDir !== null) { $this->offer($r->body); return; } $file = $this->parse($r->body, Updater::platform()); if ($file === null) { $this->state = 'latest'; return; } $this->install($file); } catch (\Throwable $e) { $this->fail($e->getMessage()); } }, fn (\Throwable $e) => $this->fail($e->getMessage())); } /** * The signed update.json: the file of this computer when it is newer, null when there is nothing newer. * @return array{url: string, sha256: string, size: int}|null */ public function parse(string $json, string $platform): ?array { $data = json_decode($json, true); if (!is_array($data) || !is_string($data['signed'] ?? null) || !is_string($data['signature'] ?? null)) { throw new \RuntimeException("update.json : ce n'est pas un fichier de mise à jour"); } $signature = base64_decode($data['signature'], true); $key = $this->publicKey !== null ? openssl_pkey_get_public($this->publicKey) : false; if ($signature === false || $key === false || openssl_verify($data['signed'], $signature, $key, OPENSSL_ALGO_SHA256) !== 1) { throw new \RuntimeException('update.json : mauvaise signature'); } $signed = json_decode($data['signed'], true); if (!is_array($signed) || ($signed['id'] ?? null) !== $this->id || !is_string($signed['version'] ?? null)) { throw new \RuntimeException("update.json : pas celui de WinZik"); } $file = $signed['platforms'][$platform] ?? null; // the phone: Android's own order (versionCode) when both are known, else the names, as on a computer $code = is_array($file) && is_int($file['versionCode'] ?? null) ? $file['versionCode'] : 0; $newer = $platform === self::ANDROID && $code > 0 && $this->versionCode > 0 ? $code > $this->versionCode : version_compare($signed['version'], $this->current, '>'); if (!$newer) { return null; } if (!is_array($file) || !is_string($file['url'] ?? null) || !is_string($file['sha256'] ?? null)) { return null; } if (!preg_match('/^[0-9a-f]{64}$/i', $file['sha256'])) { throw new \RuntimeException('update.json : empreinte SHA-256 invalide'); } $this->version = $signed['version']; $this->notes = (string)($signed['notes'] ?? ''); $found = ['url' => $file['url'], 'sha256' => strtolower($file['sha256']), 'size' => max(0, (int)($file['size'] ?? 0))]; return $platform === self::ANDROID ? $found + ['versionCode' => $code] : $found; } // the phone app --------------------------------------------------------------------------------------------- /** update.json read (phone): its APK, when newer, is 'available' (installed only when the user asks). */ public function offer(string $json): void { try { $apk = $this->parse($json, self::ANDROID); } catch (\Throwable $e) { $this->fail($e->getMessage()); return; } if ($apk === null) { $this->state = 'latest'; $this->removeApks(); // the APK of the update installed (or of an older one): 100 MB back return; } /** @var array{url: string, sha256: string, size: int, versionCode: int} $apk */ $this->apk = $apk; $this->error = ''; $this->progress = 0.0; $this->state = 'available'; } /** * The newer APK found, for the UI: null when there is none (or not a phone). * @return array{version: string, notes: string, size: int, state: string, progress: float, error: string}|null */ public function androidUpdate(): ?array { if ($this->apk === null || $this->apkDir === null) { return null; } // the UI knows available | downloading | opened | error: downloaded and installing are "opened" (its button // "Ouvrir l'installateur" installs at once); phase: the real state $state = in_array($this->state, ['ready', 'installing', 'confirm'], true) ? 'opened' : $this->state; return ['version' => $this->version, 'notes' => $this->notes, 'size' => $this->apk['size'], 'state' => $state, 'progress' => $this->progress, 'error' => $this->state === 'error' ? $this->error : '', 'phase' => $this->state]; } /** Where the APK of the newer version is downloaded (phone). */ public function apkPath(): string { $code = (int)($this->apk['versionCode'] ?? 0); return rtrim((string)$this->apkDir, '/') . '/WinZik-android-' . preg_replace('/[^0-9A-Za-z.\-]/', '', $this->version) . ($code > 0 ? '-' . $code : '') . '.apk'; } private function removeApks(): void { foreach (glob(rtrim((string)$this->apkDir, '/') . '/WinZik-android-*.apk') ?: [] as $old) { @unlink($old); } } /** * Downloads the newer APK (phone; poll() follows it), checks it, then opens Android's installer. Already * downloaded and still right (the installer was closed without installing): opened again at once. * False: nothing to install (or already downloading). */ public function installAndroidUpdate(): bool { if ($this->apk === null || $this->apkDir === null || in_array($this->state, ['downloading', 'installing'], true)) { return false; } $this->asked = true; $this->declined = ''; return $this->fetchApk(); } /** The APK checked in the app's storage (downloaded first when it is not there yet): then installed or 'ready'. */ private function fetchApk(): bool { if ($this->apk === null) { return false; } $this->error = ''; $path = $this->apkPath(); if (is_file($path) && $this->apkIsRight($path)) { $this->progress = 1.0; $this->downloaded($path); return true; } @unlink($path); $this->state = 'downloading'; $this->progress = 0.0; $this->download = new \App\Media\FileDownload($this->apk['url'], $path, $this->apk['size'], $this->apk['size'] > 0 ? $this->apk['size'] : self::MAX_SIZE); return true; } /** the APK downloaded is the one signed in update.json: its size and its SHA-256 */ private function apkIsRight(string $path): bool { if ($this->apk === null) { return false; } clearstatcache(true, $path); if ($this->apk['size'] > 0 && filesize($path) !== $this->apk['size']) { return false; } return hash_equals($this->apk['sha256'], (string)hash_file('sha256', $path)); } private function apkDownloaded(\App\Media\FileDownload $d): void { if (!$d->ok()) { @unlink($d->target); $this->fail('Téléchargement de la mise à jour impossible : ' . $d->error); return; } if (!$this->apkIsRight($d->target)) { @unlink($d->target); $this->fail("La mise à jour téléchargée n'est pas la bonne (taille ou empreinte SHA-256) : elle n'est pas installée"); return; } $this->progress = 1.0; $this->downloaded($d->target); } /** the APK is there and right: installed now (asked by the user), else 'ready' for a good moment */ private function downloaded(string $path): void { if ($this->asked) { $this->openApk($path); return; } $this->state = 'ready'; } /** * The phone, each frame: the automatic download (Wi-Fi) and install (a good moment), and what Android does with the * session. */ private function tickPhone(bool $auto): void { if (in_array($this->state, ['installing', 'confirm'], true)) { $this->followInstall(); return; } if (!$auto || $this->apk === null || $this->declined === $this->version) { return; } if ($this->state === 'available') { $network = $this->network !== null ? ($this->network)() : \JumPHP\Native\AndroidApp::network(); if ($network !== 'metered' && $network !== 'none') { $this->fetchApk(); } } elseif ($this->state === 'ready' && ($this->goodMoment === null || ($this->goodMoment)())) { $this->openApk($this->apkPath()); } } /** what Android did with the session (installing -> confirm -> the app restarts; refused or failed: error) */ private function followInstall(): void { $s = $this->installState !== null ? ($this->installState)() : \JumPHP\Native\AndroidApp::installState(); switch ($s['state']) { case 'confirm': $this->state = 'confirm'; break; case 'failed': $this->declined = $this->version; // no automatic retry of this version: the button stays $this->asked = false; $this->fail(in_array($s['status'], [3, -3], true) ? 'mise à jour annulée' : "Android n'a pas installé la mise à jour" . ($s['message'] !== '' ? ' (' . $s['message'] . ')' : '')); break; } } /** * Gives the checked APK to Android: a PackageInstaller session (no question once WinZik is its own installer; the * app restarts by itself), else (an engine without sessions) the installer's screen. */ private function openApk(string $path): void { if (!is_file($path) || !$this->apkIsRight($path)) { $this->state = 'available'; // removed meanwhile: downloaded again return; } if ($this->beforeInstall !== null) { ($this->beforeInstall)(); } $session = $this->sessionInstaller !== null ? (string)($this->sessionInstaller)($path) : \JumPHP\Native\AndroidApp::installSilently($path); if ($session === \JumPHP\Native\AndroidApp::STARTED) { $this->state = 'installing'; return; } $ok = $this->installer !== null ? (bool)($this->installer)($path) : self::installApk($path); if ($ok) { $this->state = 'opened'; } else { $this->fail("Android n'a pas pu ouvrir l'installation de la mise à jour"); } } /** * Gives an APK to Android's installer (JumPHP\Native\AndroidApp::install: the user confirms there; "install * unknown apps" not allowed yet: Android opens that setting, then the install goes on). The APK is in the app's * storage, signed with the same key, with a higher versionCode. */ public static function installApk(string $path): bool { return \JumPHP\Native\AndroidApp::supportsInstall() && \JumPHP\Native\AndroidApp::install($path); } /** @param array{url: string, sha256: string, size: int} $file */ private function install(array $file): void { $this->state = 'installing'; $this->progress = 0.0; // to a file, with its progress (the splash shows it), then put in place of the running program $this->file = $file; // next to the executable (it must be writable there anyway), never a name anyone can guess in the shared /tmp // (a link put there by another user would have the download written over one of this user's files); no byte // more than the signed size $this->download = new \App\Media\FileDownload($file['url'], $this->downloadPath(), $file['size'], $file['size'] > 0 ? $file['size'] : self::MAX_SIZE); } /** the most an executable without its size in update.json may weigh */ public const MAX_SIZE = 512 * 1024 * 1024; /** Where the new executable is downloaded before its SHA-256 is checked. */ public function downloadPath(): string { return (string)$this->executable . '.download'; } /** Each frame (the download of the new version). */ public function poll(): void { if ($this->download === null) { return; } $this->progress = $this->download->progress; if (!$this->download->poll()) { return; } $d = $this->download; $file = $this->file; $this->download = null; if ($this->apkDir !== null) { $this->apkDownloaded($d); return; } try { if (!$d->ok() || $file === null) { throw new \RuntimeException('téléchargement : ' . $d->error); } Updater::replace((string)$this->executable, (string)file_get_contents($d->target), $file['sha256']); $this->progress = 1.0; $this->state = 'installed'; } catch (\Throwable $e) { $this->fail($e->getMessage()); } finally { @unlink($d->target); } } /** Starts the new executable (the engine quits this one). */ public function relaunch(): bool { if ($this->state !== 'installed' || $this->executable === null) { return false; } return Relaunch::afterExit([(string)$this->executable]); } private function fail(string $message): void { $this->state = 'error'; $this->error = $message; // the Android app (PHP embedded) has no STDERR constant: error_log() goes to logcat there defined('STDERR') ? fwrite(STDERR, "[update] $message\n") : error_log("[update] $message"); }}