| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- // Self-update of the packaged game (readme §2). Looks at the builds published in the git
- // repository, downloads the newest one into userData/game/<version>/ and points
- // userData/game/current.json at it. boot.ts runs it on the next launch; the Electron runtime
- // that came with the installer stays as is.
- import { createHash } from 'node:crypto';
- import { join } from 'node:path';
- import { net } from 'electron';
- // original-fs: plain fs, without Electron's asar handling (we write files named app.asar).
- import * as fs from 'original-fs';
- import type { UpdateStatus } from '../preload/api';
- import { CURRENT_FILE, MANIFEST_FILE, newestBuild, parseAdvertisedRefs, parseManifest, rawFileUrl, sameElectronMajor, type ManifestFile } from './updates';
- export interface UpdaterOptions {
- repoUrl: string;
- /** Version of the game running now. */
- current: string;
- /** userData/game: one folder per downloaded version. */
- gamesDir: string;
- /** Folder of the running game (app.asar, assets/...): files that did not change are copied from it. */
- runningRoot: string;
- onStatus(status: UpdateStatus): void;
- }
- async function fetchOk(url: string): Promise<Response> {
- const res = await net.fetch(url, { headers: { 'Cache-Control': 'no-cache' } });
- if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
- return res;
- }
- function sha256(data: Uint8Array): string {
- return createHash('sha256').update(data).digest('hex');
- }
- /** The file of the running game when it is byte-identical to the one wanted, else null. */
- function reusable(runningRoot: string, file: ManifestFile): Buffer | null {
- try {
- const path = join(runningRoot, ...file.path.split('/'));
- if (fs.statSync(path).size !== file.size) return null;
- const data = fs.readFileSync(path);
- return sha256(data) === file.sha256 ? data : null;
- } catch {
- return null;
- }
- }
- /** Checks for a newer build and downloads it. Never throws: failures are reported as a status. */
- export async function checkForUpdate(opts: UpdaterOptions): Promise<void> {
- try {
- fs.mkdirSync(opts.gamesDir, { recursive: true });
- const refs = parseAdvertisedRefs(await (await fetchOk(`${opts.repoUrl}.git/info/refs?service=git-upload-pack`)).text());
- const build = newestBuild(refs, opts.current);
- if (!build) return;
- const target = join(opts.gamesDir, build.version);
- if (fs.existsSync(join(target, MANIFEST_FILE))) {
- // Already downloaded by an earlier launch.
- writeCurrent(opts.gamesDir, build.version);
- opts.onStatus({ state: 'ready', version: build.version });
- return;
- }
- const manifest = parseManifest(await (await fetchOk(rawFileUrl(opts.repoUrl, build.sha, MANIFEST_FILE))).json(), build.version);
- if (!sameElectronMajor(manifest.electron, process.versions.electron)) {
- opts.onStatus({ state: 'manual', version: build.version });
- return;
- }
- const partial = `${target}.part`;
- fs.rmSync(partial, { recursive: true, force: true });
- const total = manifest.files.reduce((sum, f) => sum + f.size, 0) || 1;
- let done = 0;
- opts.onStatus({ state: 'downloading', version: build.version, progress: 0 });
- for (const file of manifest.files) {
- let data = reusable(opts.runningRoot, file);
- if (!data) {
- data = Buffer.from(await (await fetchOk(rawFileUrl(opts.repoUrl, build.sha, file.path))).arrayBuffer());
- if (data.length !== file.size || sha256(data) !== file.sha256) throw new Error(`${file.path} is corrupted`);
- }
- const path = join(partial, ...file.path.split('/'));
- fs.mkdirSync(join(path, '..'), { recursive: true });
- fs.writeFileSync(path, data);
- done += file.size;
- opts.onStatus({ state: 'downloading', version: build.version, progress: done / total });
- }
- // The manifest goes last: its presence marks a complete download.
- fs.writeFileSync(join(partial, MANIFEST_FILE), JSON.stringify(manifest));
- fs.rmSync(target, { recursive: true, force: true });
- fs.renameSync(partial, target);
- writeCurrent(opts.gamesDir, build.version);
- removeOldVersions(opts.gamesDir, [build.version, opts.current]);
- opts.onStatus({ state: 'ready', version: build.version });
- } catch (err) {
- console.error('[update]', err);
- opts.onStatus({ state: 'error', message: err instanceof Error ? err.message : String(err) });
- }
- }
- function writeCurrent(gamesDir: string, version: string): void {
- fs.writeFileSync(join(gamesDir, CURRENT_FILE), JSON.stringify({ version }));
- }
- /** Deletes downloaded versions other than `keep` (the running one may be in use). */
- function removeOldVersions(gamesDir: string, keep: string[]): void {
- for (const entry of fs.readdirSync(gamesDir, { withFileTypes: true })) {
- if (!entry.isDirectory() || keep.includes(entry.name)) continue;
- try {
- fs.rmSync(join(gamesDir, entry.name), { recursive: true, force: true });
- } catch {
- // A folder still locked by another running instance: removed on a later update.
- }
- }
- }
|