Improve desktop app !

This commit is contained in:
2026-09-27 20:30:34 -03:00
parent 2207eea1e1
commit c74ebcda4e
6 changed files with 332 additions and 13 deletions
+175
View File
@@ -0,0 +1,175 @@
// keeps the desktop app's client (build/client and build/assets) the same as the site's, like a game launcher: the
// build writes a manifest of every file's hash, the app downloads the site's when it's different and plays that
// copy from its data folder. the singleplayer server is part of the app and can't update this way, so a client for
// a different protocol is never used. anything that goes wrong leaves the app on the client it has
import { join } from "@std/path";
// where the manifest is, in a build folder and on the site
export const CLIENT_MANIFEST = "client/manifest.json";
export interface ClientManifest {
// the protocol the client speaks, see common/protocol.ts
protocol: number;
// changes whenever any file does
build: string;
// path in the build folder to its sha-256, as hex
files: Record<string, string>;
}
export async function sha256(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
export async function client_manifest(files: Record<string, string>, protocol: number): Promise<ClientManifest> {
const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)));
const listing = Object.entries(sorted).map(([path, hash]) => `${path} ${hash}`).join("\n");
return { protocol, build: (await sha256(new TextEncoder().encode(listing))).slice(0, 16), files: sorted };
}
export interface ClientUpdateOptions {
// the site, like https://bworld.moder.fans
source: string;
// the client the app was built with
bundled_dir: string;
// where downloaded clients go, one folder per build
cache_dir: string;
// what the app's singleplayer server speaks
protocol: number;
fetch?: typeof fetch;
}
// the folder to serve the client from: the site's if it could be had, else the last one downloaded, else the bundled
// one. clients for another protocol are skipped
export async function update_client(options: ClientUpdateOptions): Promise<string> {
const fallback = () => current_client(options);
const bundled = read_manifest(options.bundled_dir);
let remote: ClientManifest;
try {
const response = await (options.fetch ?? fetch)(`${options.source}/${CLIENT_MANIFEST}`);
if (!response.ok) throw new Error(`manifest: ${response.status}`);
remote = await response.json();
} catch (e) {
console.log(`Couldn't check for a newer client: ${(e as Error).message}`);
return fallback();
}
if (remote.protocol !== options.protocol) {
console.log(`The site's client speaks protocol ${remote.protocol}, this app's server ${options.protocol}`);
return fallback();
}
if (remote.build === bundled?.build) {
return options.bundled_dir;
}
const folder = join(options.cache_dir, remote.build);
if (read_manifest(folder)?.build === remote.build) {
return folder;
}
try {
await download_client(remote, folder, options).catch((e) => {
remove(`${folder}.partial`);
throw e;
});
console.log(`Updated the client to ${remote.build}`);
remove_old_clients(options.cache_dir);
return folder;
} catch (e) {
console.log(`Couldn't update the client: ${(e as Error).message}`);
return fallback();
}
}
// every file into a temporary folder, taking the ones that didn't change from the bundled client or an older
// download, then the folder is renamed into place so a half done download is never used
async function download_client(manifest: ClientManifest, folder: string, options: ClientUpdateOptions) {
const partial = `${folder}.partial`;
remove(partial);
const known = local_files(options);
for (const [path, hash] of Object.entries(manifest.files)) {
if (path.split("/").includes("..")) throw new Error(`bad path ${path}`);
let bytes = known.get(hash)?.();
if (!bytes) {
const response = await (options.fetch ?? fetch)(`${options.source}/${path}`);
if (!response.ok) throw new Error(`${path}: ${response.status}`);
bytes = new Uint8Array(await response.arrayBuffer());
}
if (await sha256(bytes) !== hash) throw new Error(`${path} doesn't match the manifest`);
const target = join(partial, path);
Deno.mkdirSync(join(target, ".."), { recursive: true });
Deno.writeFileSync(target, bytes);
}
Deno.writeTextFileSync(join(partial, CLIENT_MANIFEST), JSON.stringify(manifest));
remove(folder);
Deno.renameSync(partial, folder);
}
// files the app already has, by hash, read only if they're needed
function local_files(options: ClientUpdateOptions) {
const files = new Map<string, () => Uint8Array<ArrayBuffer> | undefined>();
const folders = [options.bundled_dir, ...cache_folders(options.cache_dir)];
for (const folder of folders) {
for (const [path, hash] of Object.entries(read_manifest(folder)?.files ?? {})) {
if (!files.has(hash)) files.set(hash, () => try_read(join(folder, path)));
}
}
return files;
}
// the newest download for this protocol
function cached_client(options: ClientUpdateOptions): string | undefined {
return cache_folders(options.cache_dir)
.filter((folder) => read_manifest(folder)?.protocol === options.protocol)
.sort(by_newest)[0];
}
// what to play without checking the site, like when checking takes too long
export function current_client(options: ClientUpdateOptions): string {
return cached_client(options) ?? options.bundled_dir;
}
// the newest two are kept: the one just downloaded, and the one the app may still be playing if the download took
// longer than it waited
function remove_old_clients(cache_dir: string) {
const newest_first = cache_folders(cache_dir).sort(by_newest);
for (const folder of newest_first.slice(2)) remove(folder);
}
function by_newest(a: string, b: string) {
return Deno.statSync(b).mtime!.getTime() - Deno.statSync(a).mtime!.getTime();
}
function cache_folders(cache_dir: string): string[] {
try {
return [...Deno.readDirSync(cache_dir)]
.filter((entry) => entry.isDirectory && !entry.name.endsWith(".partial"))
.map((entry) => join(cache_dir, entry.name));
} catch {
return [];
}
}
function read_manifest(folder: string): ClientManifest | undefined {
const bytes = try_read(join(folder, CLIENT_MANIFEST));
try {
return bytes && JSON.parse(new TextDecoder().decode(bytes));
} catch {
return undefined;
}
}
function remove(path: string) {
try {
Deno.removeSync(path, { recursive: true });
} catch (e) {
if (!(e instanceof Deno.errors.NotFound)) throw e;
}
}
function try_read(path: string): Uint8Array<ArrayBuffer> | undefined {
try {
return Deno.readFileSync(path);
} catch {
return undefined;
}
}
+2 -1
View File
@@ -1,3 +1,4 @@
{
"server": "bworld.moder.fans"
"server": "bworld.moder.fans",
"client_updates": "https://bworld.moder.fans"
}
+31 -10
View File
@@ -5,17 +5,38 @@
// singleplayer, like minecraft java. build it with deno task desktop, see the desktop/ docs for how deno desktop works
import { fromFileUrl, join } from "@std/path";
import { type Host, serve_static, start_host } from "../server/host.ts";
import { PROTOCOL_VERSION } from "../common/protocol.ts";
import { current_client, update_client } from "./client_updates.ts";
// where the project was built from: build/ and server_mods/ (the .bmod files) are bundled into the app with --include
const ROOT = fromFileUrl(new URL("../", import.meta.url));
const BUILD_DIR = join(ROOT, "build");
// the server the address field starts with. "" leaves it empty for the player to fill in
const config: { server?: string } = JSON.parse(
const config: { server?: string; client_updates?: string } = JSON.parse(
await Deno.readTextFile(new URL("./config.json", import.meta.url)),
);
const default_server = Deno.env.get("BWORLD_SERVER") ?? config.server ?? "";
// the site the client updates from, see client_updates.ts. BWORLD_CLIENT_UPDATES=off plays the client the app was
// built with (to test a local build), or it can point at a local server to test updating
const updates_from = (Deno.env.get("BWORLD_CLIENT_UPDATES") ?? config.client_updates ?? "off").replace(/\/+$/, "");
// how long the first page waits for an update, a slower one is played next time
const UPDATE_WAIT_MS = 3000;
const client_options = {
source: updates_from,
bundled_dir: BUILD_DIR,
cache_dir: join(data_dir(), "client"),
protocol: PROTOCOL_VERSION,
};
const client_dir: Promise<string> = updates_from === "off" || updates_from === ""
? Promise.resolve(BUILD_DIR)
: Promise.race([
update_client(client_options),
new Promise<string>((resolve) => setTimeout(() => resolve(current_client(client_options)), UPDATE_WAIT_MS)),
]);
client_dir.then((dir) => console.log(`Playing the client in ${dir}`));
const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 });
// the singleplayer game server, started the first time singleplayer connects so players who only join other servers
@@ -40,16 +61,16 @@ function singleplayer_host(): Promise<Host> {
return host;
}
// the world gets saved before the app closes
// the world gets saved before the app closes. it always exits by itself: deno desktop's own shutdown freezes on the
// last frame when chromium's ctrl+w closed the window, and Deno.serve keeps the process alive anyway
win.addEventListener("close", async (event) => {
if (!host) {
return;
}
event.preventDefault();
try {
await (await host).shutdown();
} catch (e) {
console.error((e as Error).message);
if (host) {
try {
await (await host).shutdown();
} catch (e) {
console.error((e as Error).message);
}
}
Deno.exit(0);
});
@@ -76,7 +97,7 @@ Deno.serve(async (req) => {
return new Response((e as Error).message, { status: 500 });
}
}
return serve_static(BUILD_DIR, req, url);
return serve_static(await client_dir, req, url);
});
// where the app keeps its worlds, the usual place for app data on each os