feat(launcher): show official gallery and local game wallpapers

The window background now comes from two sources, served to the window
over a wto-art:// scheme from the launcher's cache:

- Website wallpapers: the newest entries of the public wallpaper gallery
  on warthunder.com (two pages), list refreshed at most daily, each
  1920x1080 picture downloaded when first shown and kept in the cache.
  No cookies, no sign-in; a setting turns it off. Without a connection
  the pictures downloaded before stay available.
- Game pictures: the nation pictures the game's own launcher keeps in
  launcherr.dat next to the game, extracted from the installed copy
  (fflate) once per archive version.

Without either, the window keeps its drawn background. The settings
choose a random picture per start or a fixed one (thumbnail grid); the
home page shows the picture's name with previous / next.

Checked: launcher typecheck, electron-vite build. Ran the window from a
scratch user data folder with a fake copy holding a copy of the real
launcherr.dat: 18 website wallpapers and 9 game pictures listed, both
sizes and the game pictures load through wto-art://, an unknown picture
is refused, stepping saves the choice, turning wallpapers off leaves
the game pictures, no console errors.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 07:45:26 +08:00
1 parent 81c900a61d
commit d82f9856f6
21 files changed
+693 -8

No files matched your search

@@ -0,0 +1,7 @@
import { join } from 'node:path';
import { app } from 'electron';
/** Where background pictures are cached: `<user data>/cache/background-art/<source>`. */
export function artCacheFolder(source: 'game' | 'official'): string {
return join(app.getPath('userData'), 'cache', 'background-art', source);
}
@@ -0,0 +1,32 @@
import type { BackgroundPicture } from '@shared/schemas/background.ts';
import { gameArtUrl, officialWallpaperUrl } from './art-protocol.ts';
import { listGameArt } from './game-art.ts';
import { listOfficialWallpapers } from './official-wallpapers.ts';
/**
* Every background picture the window may show: the website's wallpapers (when the player allows
* fetching them) and the pictures of the installed game copy. Empty when neither is available;
* the window then draws its own background.
*/
export async function listBackgroundPictures(copyPath: string | null, officialWallpapers: boolean): Promise<BackgroundPicture[]> {
const [official, game] = await Promise.all([
officialWallpapers ? listOfficialWallpapers() : Promise.resolve([]),
copyPath ? listGameArt(copyPath) : Promise.resolve([]),
]);
return [
...official.map((wallpaper) => ({
key: `official:${wallpaper.id}`,
source: 'official' as const,
label: wallpaper.title,
url: officialWallpaperUrl(wallpaper.id, false),
thumbnailUrl: officialWallpaperUrl(wallpaper.id, true),
})),
...game.map((name) => ({
key: `game:${name}`,
source: 'game' as const,
label: name,
url: gameArtUrl(name),
thumbnailUrl: gameArtUrl(name),
})),
];
}
@@ -0,0 +1,50 @@
import { pathToFileURL } from 'node:url';
import { net, protocol } from 'electron';
import { gameArtFile } from './game-art.ts';
import { officialWallpaperFile } from './official-wallpapers.ts';
/**
* wto-art://: the cached background pictures. A custom scheme because the window loads from the
* development server or from a file, and neither may read the user data folder.
*
* wto-art://game/<name>.jpg a picture from the game copy
* wto-art://official/<id>.jpg a wallpaper from the website gallery
* wto-art://official/<id>.thumb.jpg its thumbnail
*/
export const ART_SCHEME = 'wto-art';
/** Before the app is ready. */
export function registerArtScheme(): void {
protocol.registerSchemesAsPrivileged([{ scheme: ART_SCHEME, privileges: { standard: true, secure: true } }]);
}
/** After the app is ready. */
export function handleArtProtocol(): void {
protocol.handle(ART_SCHEME, async (request) => {
const url = new URL(request.url);
const file = await resolve(url.hostname, url.pathname);
if (!file) return new Response(null, { status: 404 });
return net.fetch(pathToFileURL(file).toString());
});
}
async function resolve(source: string, path: string): Promise<string | null> {
if (source === 'game') {
const name = /^\/([a-z]+)\.jpg$/.exec(path)?.[1];
return name ? gameArtFile(name) : null;
}
if (source === 'official') {
const match = /^\/([0-9a-f]{24})(\.thumb)?\.jpg$/.exec(path);
return match?.[1] ? officialWallpaperFile(match[1], match[2] !== undefined) : null;
}
return null;
}
export function gameArtUrl(name: string): string {
return `${ART_SCHEME}://game/${name}.jpg`;
}
export function officialWallpaperUrl(id: string, thumbnail: boolean): string {
return `${ART_SCHEME}://official/${id}${thumbnail ? '.thumb' : ''}.jpg`;
}
@@ -0,0 +1,91 @@
import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { unzip, type Unzipped } from 'fflate';
import { artCacheFolder } from './art-cache.ts';
/**
* Background pictures from the game copy: the game's own launcher keeps one per nation in
* `launcherr.dat` (a zip archive) next to the game. They are extracted into the cache once per
* archive version. The launcher ships no game pictures.
*
* img/main_window_bg_art.jpg -> default
* img/main_window_bg_art_<nation>.jpg -> <nation>
*/
const ARCHIVE = 'launcherr.dat';
const ENTRY = /^img\/main_window_bg_art(?:_([a-z]+))?\.jpg$/;
/** Picture names are entry suffixes only: lower-case letters. */
export const GAME_ART_NAME = /^[a-z]+$/;
const DEFAULT_NAME = 'default';
function cacheRoot(): string {
return artCacheFolder('game');
}
let current: { folder: string; names: string[] } | null = null;
/** The picture names available from the copy at `copyPath`; empty when it has no readable archive. */
export async function listGameArt(copyPath: string): Promise<string[]> {
const archive = join(copyPath, ARCHIVE);
let key: string;
try {
const info = await stat(archive);
// Size and modification time identify the archive version; a game update replaces it.
key = `${info.size}-${Math.floor(info.mtimeMs)}`;
} catch {
current = null;
return [];
}
const folder = join(cacheRoot(), key);
try {
if ((await cachedNames(folder)).length === 0) await extract(archive, folder);
current = { folder, names: await cachedNames(folder) };
await removeOtherVersions(key);
return current.names;
} catch (error) {
console.warn('[background-art] extracting the game pictures failed:', error);
current = null;
return [];
}
}
/** The cached file of a picture listed by the last listGameArt call, or null. */
export function gameArtFile(name: string): string | null {
if (!current || !GAME_ART_NAME.test(name) || !current.names.includes(name)) return null;
return join(current.folder, `${name}.jpg`);
}
async function cachedNames(folder: string): Promise<string[]> {
try {
return (await readdir(folder))
.filter((file) => file.endsWith('.jpg'))
.map((file) => file.slice(0, -4))
.filter((name) => GAME_ART_NAME.test(name))
.sort();
} catch {
return [];
}
}
async function extract(archive: string, folder: string): Promise<void> {
const files = await unzipEntries(await readFile(archive));
await mkdir(folder, { recursive: true });
for (const [entry, bytes] of Object.entries(files)) {
const match = ENTRY.exec(entry);
if (match) await writeFile(join(folder, `${match[1] ?? DEFAULT_NAME}.jpg`), bytes);
}
}
function unzipEntries(bytes: Uint8Array): Promise<Unzipped> {
return new Promise((resolve, reject) => {
unzip(bytes, { filter: (file) => ENTRY.test(file.name) }, (error, files) => (error ? reject(error) : resolve(files)));
});
}
/** Pictures of archive versions other than `key` are stale. */
async function removeOtherVersions(key: string): Promise<void> {
const entries = await readdir(cacheRoot()).catch(() => [] as string[]);
for (const entry of entries) {
if (entry !== key) await rm(join(cacheRoot(), entry), { recursive: true, force: true });
}
}
@@ -0,0 +1,166 @@
import { mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { net } from 'electron';
import { z } from 'zod';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { artCacheFolder } from './art-cache.ts';
/**
* Background pictures from the game website's public wallpaper gallery (the player may turn this
* off). Only public pictures are fetched: no sign-in, no cookies. The list of the newest
* wallpapers is refreshed at most once a day; a picture is downloaded when it is first shown and
* kept in the cache, so pictures seen once stay available without a connection.
*
* Each gallery entry is a `showcase__item` with a `data-identity` id, a 279x157 thumbnail and a
* 1920x1080 download on staticfiles.warthunder.com.
*/
const GALLERY_PAGES = ['https://warthunder.com/en/media/wallpapers/', 'https://warthunder.com/en/media/wallpapers/page/2'];
const PICTURE_HOST = 'staticfiles.warthunder.com';
const LIST_MAX_AGE_MS = 24 * 60 * 60 * 1000;
const PAGE_TIMEOUT_MS = 4000;
const PICTURE_TIMEOUT_MS = 20000;
/** Downloaded pictures kept beyond the current list, newest first. */
const KEEP_PICTURES = 40;
/** Gallery entry ids are 24 hex digits. */
export const OFFICIAL_ID = /^[0-9a-f]{24}$/;
const OfficialWallpaperSchema = z.object({
id: z.string().regex(OFFICIAL_ID),
/** The picture's name taken from its file name, e.g. "ztz 96b". */
title: z.string(),
pictureUrl: z.string(),
thumbnailUrl: z.string(),
});
export type OfficialWallpaper = z.output<typeof OfficialWallpaperSchema>;
const ListFileSchema = z.object({
fetchedAt: z.number(),
wallpapers: z.array(OfficialWallpaperSchema),
});
type ListFile = z.output<typeof ListFileSchema>;
function folder(): string {
return artCacheFolder('official');
}
function listPath(): string {
return join(folder(), 'list.json');
}
let current: readonly OfficialWallpaper[] = [];
/**
* The newest gallery wallpapers. A stale list is refreshed when the website answers in time;
* otherwise the cached list is used, reduced to the pictures already downloaded.
*/
export async function listOfficialWallpapers(): Promise<readonly OfficialWallpaper[]> {
const cached = await readCachedList();
let list = cached?.wallpapers ?? [];
let online = cached !== null && Date.now() - cached.fetchedAt < LIST_MAX_AGE_MS;
if (!online) {
try {
list = await fetchGallery();
await mkdir(folder(), { recursive: true });
await writeJsonAtomic(listPath(), { fetchedAt: Date.now(), wallpapers: list } satisfies ListFile);
online = true;
} catch (error) {
console.warn('[background-art] the wallpaper gallery is not reachable:', String(error));
}
}
const downloaded = new Set(await downloadedIds());
current = online ? list : list.filter((wallpaper) => downloaded.has(wallpaper.id));
await pruneDownloads(new Set(list.map((wallpaper) => wallpaper.id)));
return current;
}
/** The cached picture (`thumbnail` for the small one), downloaded first when missing; null if unavailable. */
export async function officialWallpaperFile(id: string, thumbnail: boolean): Promise<string | null> {
const wallpaper = current.find((entry) => entry.id === id);
if (!wallpaper) return null;
const path = join(folder(), thumbnail ? `${id}.thumb.jpg` : `${id}.jpg`);
if (await stat(path).then(() => true, () => false)) return path;
try {
const bytes = await download(thumbnail ? wallpaper.thumbnailUrl : wallpaper.pictureUrl, PICTURE_TIMEOUT_MS);
await mkdir(folder(), { recursive: true });
await writeFile(`${path}.part`, bytes);
await rename(`${path}.part`, path);
return path;
} catch (error) {
console.warn('[background-art] downloading a wallpaper failed:', id, String(error));
return null;
}
}
async function readCachedList(): Promise<ListFile | null> {
try {
const parsed = ListFileSchema.safeParse(await readJsonOr(listPath(), null));
return parsed.success ? parsed.data : null;
} catch {
return null;
}
}
async function fetchGallery(): Promise<OfficialWallpaper[]> {
const found = new Map<string, OfficialWallpaper>();
for (const page of GALLERY_PAGES) {
const html = new TextDecoder().decode(await download(page, PAGE_TIMEOUT_MS));
for (const wallpaper of parseGallery(html)) if (!found.has(wallpaper.id)) found.set(wallpaper.id, wallpaper);
}
if (found.size === 0) throw new Error('the gallery pages list no wallpapers');
return [...found.values()];
}
/** The entries of one gallery page; entries without both picture sizes are skipped. */
export function parseGallery(html: string): OfficialWallpaper[] {
const wallpapers: OfficialWallpaper[] = [];
const items = html.split('class="showcase__item').slice(1);
for (const item of items) {
const id = /data-identity="([0-9a-f]{24})"/.exec(item)?.[1];
const thumbnailUrl = /data-src="(https:\/\/[^"]+\/_thumbs\/279x157\/[^"]+\.jpg)"/.exec(item)?.[1];
// The first link is the 999x562 preview, which also carries "1920x1080_" in its file name.
const pictureUrl = [...item.matchAll(/href="(https:\/\/[^"]+\/1920x1080_[^"/]+\.jpg)"/g)]
.map((match) => match[1] ?? '')
.find((url) => !url.includes('/_thumbs/'));
if (!id || !thumbnailUrl || !pictureUrl || !onPictureHost(thumbnailUrl) || !onPictureHost(pictureUrl)) continue;
wallpapers.push({ id, title: titleOf(pictureUrl), pictureUrl, thumbnailUrl });
}
return wallpapers;
}
/** "…/1920x1080_ztz_96b_logo_657a….jpg" -> "ztz 96b"; a language suffix after "logo" goes too. */
function titleOf(pictureUrl: string): string {
const file = pictureUrl.slice(pictureUrl.lastIndexOf('/') + 1);
return file
.replace(/^1920x1080_/, '')
.replace(/_[0-9a-f]{32}\.jpg$/, '')
.replace(/_logo(?:_[a-z]+)?$/, '')
.replace(/_/g, ' ');
}
function onPictureHost(url: string): boolean {
return new URL(url).hostname === PICTURE_HOST;
}
async function download(url: string, timeoutMs: number): Promise<Uint8Array> {
const response = await net.fetch(url, { credentials: 'omit', signal: AbortSignal.timeout(timeoutMs) });
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
return new Uint8Array(await response.arrayBuffer());
}
async function downloadedIds(): Promise<string[]> {
const files = await readdir(folder()).catch(() => [] as string[]);
return files.filter((file) => /^[0-9a-f]{24}\.jpg$/.test(file)).map((file) => file.slice(0, 24));
}
/** Drop downloads that left the list, beyond the KEEP_PICTURES most recently downloaded. */
async function pruneDownloads(listed: ReadonlySet<string>): Promise<void> {
const unlisted = (await downloadedIds()).filter((id) => !listed.has(id));
const dated = await Promise.all(unlisted.map(async (id) => ({ id, time: (await stat(join(folder(), `${id}.jpg`))).mtimeMs })));
dated.sort((a, b) => b.time - a.time);
for (const { id } of dated.slice(KEEP_PICTURES)) {
await rm(join(folder(), `${id}.jpg`), { force: true });
await rm(join(folder(), `${id}.thumb.jpg`), { force: true });
}
}