OctoLauncher 1.3.1
Manifest-based CDN updater and mod manager for the OctoWoW 1.12.1 client: launcher-owned realmlist, torrent-backed content sync with bundled aria2c, antivirus and Defender exclusion handling, hardware-aware render distance, optional client tweaks and mods, and the in-launcher news feed.
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { createTRPCRouter } from './trpc';
|
||||
import { addonsRouter } from './routers/addonts';
|
||||
import { launcherRouter } from './routers/launcher';
|
||||
import { updaterRouter } from './routers/updater';
|
||||
import { patcherRouter } from './routers/patcher';
|
||||
import { generalRouter } from './routers/general';
|
||||
import { preferencesRouter } from './routers/preferences';
|
||||
import { newsRouter } from './routers/news';
|
||||
import { forumRouter } from './routers/forum';
|
||||
import { modsRouter } from './routers/mods';
|
||||
import { selfUpdaterRouter } from './routers/selfUpdater';
|
||||
|
||||
export const appRouter = createTRPCRouter({
|
||||
addons: addonsRouter,
|
||||
general: generalRouter,
|
||||
preferences: preferencesRouter,
|
||||
launcher: launcherRouter,
|
||||
patcher: patcherRouter,
|
||||
updater: updaterRouter,
|
||||
news: newsRouter,
|
||||
forum: forumRouter,
|
||||
mods: modsRouter,
|
||||
selfUpdater: selfUpdaterRouter
|
||||
});
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import Addons from '~main/modules/addons';
|
||||
import { AddonDataSchema } from '~common/schemas';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
export const addonsRouter = createTRPCRouter({
|
||||
verify: publicProcedure.mutation(() => {
|
||||
Addons.verify();
|
||||
}),
|
||||
update: publicProcedure
|
||||
.input(z.object({ toUpdate: z.array(z.string()).optional() }))
|
||||
.mutation(({ input }) => Addons.update(input.toUpdate)),
|
||||
install: publicProcedure
|
||||
.input(AddonDataSchema)
|
||||
.mutation(({ input }) => Addons.install(input)),
|
||||
remove: publicProcedure
|
||||
.input(z.object({ toDelete: z.array(z.string()) }))
|
||||
.mutation(({ input }) => Addons.remove(input.toDelete)),
|
||||
checkGitUrl: publicProcedure
|
||||
.input(z.string())
|
||||
.query(({ input }) => Addons.checkGitUrl(input)),
|
||||
observe: publicProcedure.subscription(() => Addons.observe())
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import fetch from 'node-fetch';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import {
|
||||
ForumAnnouncementSchema,
|
||||
type ForumAnnouncement
|
||||
} from '~common/schemas';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
const FETCH_TIMEOUT_MS = 8_000;
|
||||
|
||||
const fetchLatestAnnouncement = async (): Promise<ForumAnnouncement | null> => {
|
||||
const url = `${
|
||||
import.meta.env.MAIN_VITE_FORUM_URL || 'https://octowow.st'
|
||||
}/forum/octonews.php?forum=35&mode=full`;
|
||||
const controller = new AbortController();
|
||||
const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const res = await fetch(url, { signal: controller.signal });
|
||||
if (!res.ok) throw Error(`HTTP ${res.status}`);
|
||||
const json = (await res.json()) as unknown;
|
||||
if (!json || typeof json !== 'object' || !('id' in json)) return null;
|
||||
const parsed = ForumAnnouncementSchema.safeParse(json);
|
||||
if (!parsed.success) {
|
||||
Logger.error(
|
||||
'Forum announcement failed schema validation',
|
||||
parsed.error.flatten()
|
||||
);
|
||||
throw Error('Malformed forum announcement');
|
||||
}
|
||||
return parsed.data;
|
||||
} finally {
|
||||
clearTimeout(t);
|
||||
}
|
||||
};
|
||||
|
||||
export const forumRouter = createTRPCRouter({
|
||||
latestAnnouncement: publicProcedure.query(async () => {
|
||||
try {
|
||||
return await fetchLatestAnnouncement();
|
||||
} catch (e) {
|
||||
Logger.error('Failed to fetch forum announcement', e);
|
||||
throw e;
|
||||
}
|
||||
})
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import { app, dialog, shell } from 'electron';
|
||||
import Logger from 'electron-log/main';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { mainWindow } from '~main/index';
|
||||
import Preferences from '~main/modules/preferences';
|
||||
import {
|
||||
addDefenderExclusions,
|
||||
detectAntivirusBlocks
|
||||
} from '~main/modules/defender';
|
||||
import { detectHardware, recommendFarClip } from '~main/modules/hardware';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
export const generalRouter = createTRPCRouter({
|
||||
appVersion: publicProcedure.query(() => app.getVersion()),
|
||||
hardware: publicProcedure.query(() => {
|
||||
const hardware = Preferences.data.hardware ?? null;
|
||||
return { hardware, recommendedFarClip: recommendFarClip(hardware) };
|
||||
}),
|
||||
redetectHardware: publicProcedure.mutation(async () => {
|
||||
const hardware = await detectHardware();
|
||||
Preferences.data = { hardware };
|
||||
return { hardware, recommendedFarClip: recommendFarClip(hardware) };
|
||||
}),
|
||||
quit: publicProcedure.mutation(() => app.quit()),
|
||||
minimize: publicProcedure.mutation(() => mainWindow?.minimize()),
|
||||
openLink: publicProcedure
|
||||
.input(z.string().url())
|
||||
.mutation(({ input }) => shell.openExternal(input)),
|
||||
openInstallFolder: publicProcedure.mutation(() => {
|
||||
// Explorer needs native separators; a stored forward-slash path fails to open.
|
||||
const dir = Preferences.data.clientDir;
|
||||
if (dir) shell.openPath(path.normalize(dir));
|
||||
}),
|
||||
openLogFile: publicProcedure.mutation(() => {
|
||||
const file = Logger.transports.file.getFile().path;
|
||||
shell.openPath(path.normalize(file));
|
||||
}),
|
||||
addDefenderExclusion: publicProcedure.mutation(() => addDefenderExclusions()),
|
||||
antivirusBlocks: publicProcedure.query(() => detectAntivirusBlocks()),
|
||||
filePicker: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
title: z.string().optional(),
|
||||
message: z.string().optional(),
|
||||
filters: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
extensions: z.array(z.string())
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
properties: z
|
||||
.array(
|
||||
z.enum([
|
||||
'openDirectory',
|
||||
'openFile',
|
||||
'multiSelections',
|
||||
'showHiddenFiles',
|
||||
'createDirectory',
|
||||
'promptToCreate',
|
||||
'noResolveAliases',
|
||||
'treatPackageAsDirectory',
|
||||
'dontAddToRecent'
|
||||
])
|
||||
)
|
||||
.optional()
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
if (!mainWindow) return { canceled: true } as const;
|
||||
const { canceled, filePaths } = await dialog.showOpenDialog(
|
||||
mainWindow,
|
||||
input
|
||||
);
|
||||
|
||||
return canceled
|
||||
? ({ canceled: true } as const)
|
||||
: ({
|
||||
canceled: false,
|
||||
path: filePaths as [string, ...string[]]
|
||||
} as const);
|
||||
})
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import path from 'path';
|
||||
import { spawn } from 'child_process';
|
||||
|
||||
import fs from 'fs-extra';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import Preferences from '~main/modules/preferences';
|
||||
import Mods from '~main/modules/mods';
|
||||
import { mainWindow } from '~main/index';
|
||||
import Updater, { isGameRunning } from '~main/modules/updater';
|
||||
import {
|
||||
patchConfig,
|
||||
patchExecutable,
|
||||
ensureDxvkConf
|
||||
} from '~main/modules/patcher';
|
||||
import { removeLegacyLocalePatches } from '~main/modules/localePatch';
|
||||
import { syncVanillaFixesCache } from '~main/modules/dllsTxt';
|
||||
import { stopSeeding } from '~main/modules/aria2';
|
||||
import { minimizeToTray, restoreFromTray } from '~main/modules/tray';
|
||||
import { getMod } from '~common/mods';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
const chainloaderNeeded = async (clientDir: string): Promise<boolean> => {
|
||||
const installed = Mods.status.mods.filter(r => r.installedVersion);
|
||||
if (installed.some(r => r.id === 'vanillaFixes')) return true;
|
||||
if (installed.some(r => getMod(r.id)?.requires?.includes('vanillaFixes')))
|
||||
return true;
|
||||
|
||||
const dllsPath = path.join(clientDir, 'dlls.txt');
|
||||
if (await fs.pathExists(dllsPath)) {
|
||||
const raw = await fs.readFile(dllsPath, 'utf8');
|
||||
return raw.split(/\r?\n/).some(l => l.trim() && !l.trim().startsWith('#'));
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
type StartResult = { ok: boolean; error?: string };
|
||||
|
||||
const delay = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
|
||||
|
||||
let starting = false;
|
||||
|
||||
export const launcherRouter = createTRPCRouter({
|
||||
start: publicProcedure.mutation(async (): Promise<StartResult> => {
|
||||
if (starting) return { ok: false, error: 'The game is already launching.' };
|
||||
starting = true;
|
||||
try {
|
||||
const { cleanWdb, minimizeToTrayOnPlay, clientDir } = Preferences.data;
|
||||
if (!clientDir) return { ok: false, error: 'No game folder is set.' };
|
||||
|
||||
const exePath = path.join(clientDir, 'WoW.exe');
|
||||
if (!(await fs.pathExists(exePath)))
|
||||
return {
|
||||
ok: false,
|
||||
error: 'WoW.exe was not found in the game folder.'
|
||||
};
|
||||
if (await isGameRunning(exePath))
|
||||
return { ok: false, error: 'WoW is already running.' };
|
||||
|
||||
if (Mods.status.dirty)
|
||||
return {
|
||||
ok: false,
|
||||
error: 'You have unapplied mod changes. Click Apply first.'
|
||||
};
|
||||
|
||||
stopSeeding();
|
||||
|
||||
if (cleanWdb) {
|
||||
Logger.log('Cleaning up WDB...');
|
||||
await fs.remove(path.join(clientDir, 'WDB'));
|
||||
}
|
||||
|
||||
Logger.log('Syncing preferred monitor...');
|
||||
await Mods.verify();
|
||||
|
||||
Logger.log('Checking Config.wtf...');
|
||||
await patchConfig();
|
||||
await ensureDxvkConf(clientDir);
|
||||
|
||||
await removeLegacyLocalePatches(clientDir);
|
||||
|
||||
if (Preferences.data.patchedLocale !== Preferences.data.locale) {
|
||||
Logger.log(
|
||||
`Applying the client language (${Preferences.data.locale})...`
|
||||
);
|
||||
try {
|
||||
await patchExecutable();
|
||||
await patchConfig(true);
|
||||
await Updater.recordPatchedWow();
|
||||
if (!cleanWdb)
|
||||
await fs.remove(path.join(clientDir, 'WDB')).catch(() => {});
|
||||
} catch (e) {
|
||||
Logger.error(
|
||||
'Could not apply the client language; launching with the previous one',
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const loaderPath = path.join(clientDir, 'VanillaFixes.exe');
|
||||
const needsLoader = await chainloaderNeeded(clientDir);
|
||||
const useLoader = needsLoader && (await fs.pathExists(loaderPath));
|
||||
if (useLoader) await syncVanillaFixesCache(clientDir);
|
||||
if (needsLoader && !useLoader)
|
||||
Logger.warn(
|
||||
'VanillaFixes.exe is missing but mods/dlls.txt expect a chainloader; ' +
|
||||
'launching WoW.exe directly (mods will not load).'
|
||||
);
|
||||
|
||||
Logger.log(
|
||||
useLoader ? 'Launching via VanillaFixes...' : `Launching ${exePath}...`
|
||||
);
|
||||
const child = useLoader
|
||||
? spawn(loaderPath, ['WoW.exe'], {
|
||||
cwd: clientDir,
|
||||
detached: !minimizeToTrayOnPlay
|
||||
})
|
||||
: spawn(exePath, {
|
||||
cwd: clientDir,
|
||||
detached: !minimizeToTrayOnPlay
|
||||
});
|
||||
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once('spawn', resolve);
|
||||
child.once('error', reject);
|
||||
});
|
||||
} catch (e) {
|
||||
Logger.error('Failed to launch the game', e);
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
return { ok: false, error: `Failed to launch the game: ${message}` };
|
||||
}
|
||||
|
||||
child.on('error', e => Logger.error('Game process error', e));
|
||||
|
||||
if (!minimizeToTrayOnPlay) {
|
||||
mainWindow?.close();
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
minimizeToTray();
|
||||
if (useLoader) {
|
||||
void (async () => {
|
||||
try {
|
||||
const started = Date.now();
|
||||
while (
|
||||
Date.now() - started < 30_000 &&
|
||||
!(await isGameRunning(exePath))
|
||||
)
|
||||
await delay(1000);
|
||||
while (await isGameRunning(exePath)) await delay(3000);
|
||||
} finally {
|
||||
Logger.log('WoW stopped');
|
||||
restoreFromTray();
|
||||
}
|
||||
})();
|
||||
} else {
|
||||
child.on('exit', () => {
|
||||
Logger.log('WoW stopped');
|
||||
restoreFromTray();
|
||||
});
|
||||
}
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
Logger.error('Failed to start the game', e);
|
||||
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
||||
} finally {
|
||||
starting = false;
|
||||
}
|
||||
})
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import path from 'path';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
import Mods from '~main/modules/mods';
|
||||
import Preferences from '~main/modules/preferences';
|
||||
import { isGameRunning } from '~main/modules/updater';
|
||||
import { ModIdSchema } from '~common/mods';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
export const modsRouter = createTRPCRouter({
|
||||
list: publicProcedure.query(() => Mods.status),
|
||||
verify: publicProcedure.mutation(() => Mods.verify()),
|
||||
toggle: publicProcedure
|
||||
.input(z.object({ id: ModIdSchema, enabled: z.boolean() }))
|
||||
.mutation(({ input }) => Mods.toggle(input.id, input.enabled)),
|
||||
toggleCustom: publicProcedure
|
||||
.input(z.object({ name: z.string(), enabled: z.boolean() }))
|
||||
.mutation(({ input }) => Mods.toggleCustom(input.name, input.enabled)),
|
||||
addCustomDll: publicProcedure
|
||||
.input(z.object({ path: z.string() }))
|
||||
.mutation(({ input }) => Mods.addCustomDll(input.path)),
|
||||
setIgnoreUpdates: publicProcedure
|
||||
.input(z.object({ id: ModIdSchema, ignore: z.boolean() }))
|
||||
.mutation(({ input }) => Mods.setIgnoreUpdates(input.id, input.ignore)),
|
||||
applyAll: publicProcedure.mutation(() => Mods.applyAll()),
|
||||
repair: publicProcedure.mutation(async () => {
|
||||
const clientDir = Preferences.data?.clientDir;
|
||||
if (clientDir) {
|
||||
const exePath = path.join(clientDir, 'WoW.exe');
|
||||
if (await isGameRunning(exePath))
|
||||
throw new Error('Please close WoW first before verifying files.');
|
||||
}
|
||||
return Mods.applyAll({ repairOnly: true });
|
||||
}),
|
||||
observe: publicProcedure.subscription(() => Mods.observe())
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { z } from 'zod';
|
||||
import fetch from 'node-fetch';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import { NewsFeedSchema, type NewsItem } from '~common/schemas';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
const FETCH_TIMEOUT_MS = 8_000;
|
||||
|
||||
// Boards octonews.php exposes as a list: 2 = Announcements, 4 = Patch Notes.
|
||||
const FEED_FORUMS = [2, 4];
|
||||
|
||||
const fetchNews = async (forum: number): Promise<NewsItem[]> => {
|
||||
const f = FEED_FORUMS.includes(forum) ? forum : 2;
|
||||
const url = `${
|
||||
import.meta.env.MAIN_VITE_FORUM_URL || 'https://octowow.st'
|
||||
}/forum/octonews.php?mode=list&forum=${f}&limit=5`;
|
||||
const controller = new AbortController();
|
||||
const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const res = await fetch(url, { signal: controller.signal });
|
||||
if (!res.ok) throw Error(`HTTP ${res.status}`);
|
||||
const parsed = NewsFeedSchema.safeParse(await res.json());
|
||||
if (!parsed.success) {
|
||||
Logger.error(
|
||||
'News feed failed schema validation',
|
||||
parsed.error.flatten()
|
||||
);
|
||||
throw Error('Malformed news feed');
|
||||
}
|
||||
return parsed.data.items;
|
||||
} finally {
|
||||
clearTimeout(t);
|
||||
}
|
||||
};
|
||||
|
||||
export const newsRouter = createTRPCRouter({
|
||||
list: publicProcedure
|
||||
.input(z.object({ forum: z.number() }).optional())
|
||||
.query(async ({ input }) => {
|
||||
try {
|
||||
return await fetchNews(input?.forum ?? 2);
|
||||
} catch (e) {
|
||||
Logger.error('Failed to fetch news', e);
|
||||
throw e;
|
||||
}
|
||||
})
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { patchConfig, patchExecutable } from '~main/modules/patcher';
|
||||
import Preferences from '~main/modules/preferences';
|
||||
import Updater from '~main/modules/updater';
|
||||
import { getClientVersion } from '~main/utils';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
export const patcherRouter = createTRPCRouter({
|
||||
apply: publicProcedure.mutation(async () => {
|
||||
await patchExecutable();
|
||||
await patchConfig(true);
|
||||
await Updater.recordPatchedWow();
|
||||
Preferences.data = { version: await getClientVersion() };
|
||||
})
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { PreferencesSchema } from '~common/schemas';
|
||||
import Preferences from '~main/modules/preferences';
|
||||
import Updater from '~main/modules/updater';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
export const preferencesRouter = createTRPCRouter({
|
||||
get: publicProcedure.output(PreferencesSchema).query(() => Preferences.data),
|
||||
set: publicProcedure
|
||||
.input(PreferencesSchema.partial())
|
||||
.mutation(async ({ input }) => {
|
||||
// Language change no longer touches the game folder; the exe is re-patched on
|
||||
// the next Play (launcher router), so this stays network-free and can't fail.
|
||||
Preferences.data = input;
|
||||
if (input.shareDownloads !== undefined) void Updater.refreshSeeding();
|
||||
return Preferences.data;
|
||||
}),
|
||||
isValidClientDir: publicProcedure
|
||||
.input(z.string().optional())
|
||||
.query(({ input }) => Preferences.isValidClientDir(input))
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import SelfUpdater from '~main/modules/selfUpdater';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
export const selfUpdaterRouter = createTRPCRouter({
|
||||
observe: publicProcedure.subscription(() => SelfUpdater.observe()),
|
||||
install: publicProcedure.mutation(() => SelfUpdater.triggerInstall())
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import Updater from '~main/modules/updater';
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from '../trpc';
|
||||
|
||||
export const updaterRouter = createTRPCRouter({
|
||||
verify: publicProcedure.mutation(() => Updater.verify()),
|
||||
syncRaidVisuals: publicProcedure.mutation(() => Updater.syncRaidVisuals()),
|
||||
update: publicProcedure
|
||||
.input(z.boolean().optional())
|
||||
.mutation(async ({ input }) => Updater.update(input)),
|
||||
observe: publicProcedure.subscription(() => Updater.observe())
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { initTRPC } from '@trpc/server';
|
||||
import superjson from 'superjson';
|
||||
import { ZodError } from 'zod';
|
||||
|
||||
const t = initTRPC.create({
|
||||
transformer: superjson,
|
||||
errorFormatter: ({ shape, error }) => ({
|
||||
...shape,
|
||||
data: {
|
||||
...shape.data,
|
||||
zodError: error.cause instanceof ZodError ? error.cause.flatten() : null
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
export const createTRPCRouter = t.router;
|
||||
|
||||
export const publicProcedure = t.procedure;
|
||||
@@ -0,0 +1,215 @@
|
||||
import { join } from 'path';
|
||||
|
||||
import { app, shell, session, BrowserWindow, screen } from 'electron';
|
||||
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
|
||||
import { createIPCHandler } from 'electron-trpc/main';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import icon from '~build/icon.png?asset';
|
||||
import { PreferencesSchema } from '~common/schemas';
|
||||
|
||||
import { appRouter } from './api/root';
|
||||
import Preferences from './modules/preferences';
|
||||
import Updater from './modules/updater';
|
||||
import Addons from './modules/addons';
|
||||
import Mods from './modules/mods';
|
||||
import { initSelfUpdater } from './modules/selfUpdater';
|
||||
import {
|
||||
detectHardware,
|
||||
recommendFarClip,
|
||||
HARDWARE_SCHEMA_VERSION
|
||||
} from './modules/hardware';
|
||||
|
||||
Logger.initialize();
|
||||
Logger.errorHandler.startCatching();
|
||||
Logger.transports.ipc.level = false;
|
||||
Logger.info('Launcher starting...');
|
||||
|
||||
app.disableHardwareAcceleration();
|
||||
|
||||
export let mainWindow: BrowserWindow | null = null;
|
||||
|
||||
const isOnScreen = (
|
||||
pos?: {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
} | null
|
||||
) => {
|
||||
if (!pos) return false;
|
||||
return screen.getAllDisplays().some(d => {
|
||||
const a = d.workArea;
|
||||
return (
|
||||
pos.x < a.x + a.width &&
|
||||
pos.x + pos.width > a.x &&
|
||||
pos.y < a.y + a.height &&
|
||||
pos.y + pos.height > a.y
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const createWindow = async () => {
|
||||
const saved =
|
||||
Preferences.data.rememberPosition &&
|
||||
isOnScreen(Preferences.data.windowPosition)
|
||||
? Preferences.data.windowPosition
|
||||
: undefined;
|
||||
const position = saved ?? { width: 1000, height: 700 };
|
||||
|
||||
mainWindow = new BrowserWindow({
|
||||
...position,
|
||||
minWidth: 1000,
|
||||
minHeight: 700,
|
||||
icon,
|
||||
frame: false,
|
||||
maximizable: false,
|
||||
fullscreenable: false,
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
contextIsolation: true,
|
||||
sandbox: false,
|
||||
devTools: true
|
||||
}
|
||||
});
|
||||
|
||||
mainWindow.webContents.on('render-process-gone', (_e, details) => {
|
||||
Logger.error('Renderer process gone:', details);
|
||||
});
|
||||
mainWindow.webContents.on('unresponsive', () => {
|
||||
Logger.error('Renderer unresponsive');
|
||||
});
|
||||
|
||||
mainWindow.webContents.on(
|
||||
'console-message',
|
||||
(_e, level, message, line, sourceId) => {
|
||||
const lvl = level === 3 ? 'error' : level === 2 ? 'warn' : 'info';
|
||||
Logger[lvl](`[renderer:${lvl}] ${message} (${sourceId}:${line})`);
|
||||
}
|
||||
);
|
||||
|
||||
mainWindow.webContents.on('before-input-event', (_e, input) => {
|
||||
if (input.type !== 'keyDown') return;
|
||||
if (input.key === 'F12') {
|
||||
mainWindow?.webContents.toggleDevTools();
|
||||
return;
|
||||
}
|
||||
if ((input.control || input.meta) && input.key.toLowerCase() === 'c')
|
||||
mainWindow?.webContents.copy();
|
||||
});
|
||||
|
||||
createIPCHandler({ router: appRouter, windows: [mainWindow] });
|
||||
|
||||
mainWindow.on('ready-to-show', () => {
|
||||
mainWindow?.show();
|
||||
});
|
||||
mainWindow.webContents.setWindowOpenHandler(details => {
|
||||
shell.openExternal(details.url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
mainWindow.on('close', () => {
|
||||
if (!mainWindow) return;
|
||||
const [x = 0, y = 0] = mainWindow.getPosition();
|
||||
const [width = 0, height = 0] = mainWindow.getSize();
|
||||
Preferences.data = { windowPosition: { x, y, width, height } };
|
||||
});
|
||||
|
||||
if (is.dev && process.env.ELECTRON_RENDERER_URL) {
|
||||
mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL);
|
||||
} else {
|
||||
mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
|
||||
}
|
||||
};
|
||||
|
||||
const gotSingleInstanceLock = is.dev || app.requestSingleInstanceLock();
|
||||
|
||||
if (!gotSingleInstanceLock) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on('second-instance', () => {
|
||||
if (!mainWindow) return;
|
||||
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||
if (!mainWindow.isVisible()) mainWindow.show();
|
||||
mainWindow.focus();
|
||||
});
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
// defaults on failure so createWindow() below still runs
|
||||
try {
|
||||
Preferences.data = await Preferences.load();
|
||||
} catch (e) {
|
||||
Logger.error('Preferences.load() failed; starting on defaults', e);
|
||||
Preferences.data = PreferencesSchema.parse({});
|
||||
}
|
||||
|
||||
Addons.verify();
|
||||
Updater.verify();
|
||||
Mods.verify();
|
||||
initSelfUpdater();
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
let hardware = Preferences.data.hardware;
|
||||
if (!hardware || hardware.schemaVersion < HARDWARE_SCHEMA_VERSION) {
|
||||
hardware = await detectHardware();
|
||||
Preferences.data = { hardware };
|
||||
}
|
||||
const rec = recommendFarClip(hardware ?? null);
|
||||
if (
|
||||
Preferences.data.farClipUserSet !== true &&
|
||||
Preferences.data.config.farClip !== rec
|
||||
)
|
||||
Preferences.data = {
|
||||
config: { ...Preferences.data.config, farClip: rec }
|
||||
};
|
||||
} catch (e) {
|
||||
Logger.error('Hardware detection / farClip recommendation failed', e);
|
||||
}
|
||||
})();
|
||||
|
||||
electronApp.setAppUserModelId('st.octowow.launcher');
|
||||
|
||||
if (app.isPackaged) {
|
||||
const serverOrigin = new URL(
|
||||
import.meta.env.MAIN_VITE_SERVER_URL || 'https://octowow.st'
|
||||
).origin;
|
||||
session.defaultSession.webRequest.onHeadersReceived((details, cb) => {
|
||||
cb({
|
||||
responseHeaders: {
|
||||
...details.responseHeaders,
|
||||
'Content-Security-Policy': [
|
||||
[
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
`img-src 'self' data: https://octowow.st https://forum.octowow.st ${serverOrigin}`,
|
||||
"font-src 'self' data:",
|
||||
"connect-src 'self'"
|
||||
].join('; ')
|
||||
]
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
app.on('browser-window-created', (_, window) => {
|
||||
optimizer.watchWindowShortcuts(window);
|
||||
});
|
||||
|
||||
await createWindow();
|
||||
});
|
||||
|
||||
let settingsFlushed = false;
|
||||
app.on('before-quit', event => {
|
||||
if (settingsFlushed) return;
|
||||
settingsFlushed = true;
|
||||
event.preventDefault();
|
||||
Promise.race([Preferences.save(), new Promise(r => setTimeout(r, 3000))])
|
||||
.catch(e => Logger.error('Failed to flush settings before quit', e))
|
||||
.finally(() => app.quit());
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import git, { type ProgressCallback } from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/node';
|
||||
import fs from 'fs-extra';
|
||||
import fetch from 'node-fetch';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import { isNotUndef } from '~common/utils';
|
||||
import { type AddonData, type TocData } from '~common/schemas';
|
||||
import { runWorker } from '~main/utils';
|
||||
import gitPull from '~main/workers/gitPull?nodeWorker';
|
||||
import gitClone from '~main/workers/gitClone?nodeWorker';
|
||||
|
||||
import Preferences from './preferences';
|
||||
import Observable from './observable';
|
||||
|
||||
export type AddonsStatus = {
|
||||
state: 'verifying' | 'done';
|
||||
addons: { [name: string]: AddonData };
|
||||
available: AddonData[];
|
||||
};
|
||||
|
||||
type AddonsList = {
|
||||
name: string;
|
||||
owner: string;
|
||||
branch?: string;
|
||||
ref?: string;
|
||||
git: string;
|
||||
toc?: TocData;
|
||||
description?: string;
|
||||
lastUpdated?: string;
|
||||
stars?: number;
|
||||
dependencies?: string[];
|
||||
}[];
|
||||
|
||||
const readTocData = (content: string) =>
|
||||
(content.charCodeAt(0) === 0xfeff ? content.slice(1) : content)
|
||||
.split('\n')
|
||||
.filter(l => l.startsWith('## '))
|
||||
.map(l => l.slice(3))
|
||||
.map(l => {
|
||||
const idx = l.indexOf(':');
|
||||
if (idx === -1) return null;
|
||||
return [l.slice(0, idx).trim(), l.slice(idx + 1).trim()] as const;
|
||||
})
|
||||
.filter((e): e is readonly [string, string] => !!e)
|
||||
.reduce((acc, [key, value]) => {
|
||||
acc[key] = value;
|
||||
return acc;
|
||||
}, {} as TocData);
|
||||
|
||||
const isUnsafeFolder = (name?: string) =>
|
||||
!name || name === '.' || name === '..' || /[/\\]/.test(name);
|
||||
|
||||
const ALLOWED_GIT_HOSTS = [
|
||||
'github.com',
|
||||
'gitlab.com',
|
||||
'gitea.com',
|
||||
'codeberg.org',
|
||||
'octowow.st'
|
||||
];
|
||||
|
||||
const isAllowedGitUrl = (url: string) => {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol !== 'https:') return false;
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
return ALLOWED_GIT_HOSTS.some(h => host === h || host.endsWith('.' + h));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const fetchAddons = async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${
|
||||
import.meta.env.MAIN_VITE_SERVER_URL || 'https://octowow.st'
|
||||
}/api/addons.json`
|
||||
);
|
||||
return (await response.json()) as AddonsList;
|
||||
} catch (e) {
|
||||
Logger.error('Failed to reach update server', e);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
class AddonsClass extends Observable<AddonsStatus> {
|
||||
protected _value: AddonsStatus = {
|
||||
state: 'done',
|
||||
addons: {},
|
||||
available: []
|
||||
};
|
||||
|
||||
get status() {
|
||||
return this._value;
|
||||
}
|
||||
private set status(v: AddonsStatus) {
|
||||
this._value = v;
|
||||
this._notifyObservers(v);
|
||||
}
|
||||
|
||||
#onProgress =
|
||||
(folder: string, data: AddonData): ProgressCallback =>
|
||||
progress => {
|
||||
const getPhase = (step: string) => {
|
||||
switch (step) {
|
||||
case 'Counting objects':
|
||||
return 1;
|
||||
case 'Compressing objects':
|
||||
return 2;
|
||||
case 'Receiving objects':
|
||||
return 3;
|
||||
case 'Resolving deltas':
|
||||
return 4;
|
||||
case 'Analyzing workdir':
|
||||
return 5;
|
||||
case 'Updating workdir':
|
||||
return 6;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
this.#setAddon(folder, {
|
||||
...data,
|
||||
progress: `${Math.round(
|
||||
(progress.loaded / (progress.total ?? progress.loaded)) * 100
|
||||
)}% (${getPhase(progress.phase)}/6)`
|
||||
});
|
||||
};
|
||||
|
||||
async checkGitUrl(url: string) {
|
||||
const clean = url.trim().replace(/\/+$/, '');
|
||||
const gitUrl = clean.endsWith('.git') ? clean : `${clean}.git`;
|
||||
if (!isAllowedGitUrl(gitUrl)) return undefined;
|
||||
try {
|
||||
await git.getRemoteInfo({
|
||||
http,
|
||||
url: gitUrl
|
||||
});
|
||||
|
||||
let preview: string | undefined;
|
||||
try {
|
||||
if (isAllowedGitUrl(url)) {
|
||||
const response = await fetch(url).then(r => r.text());
|
||||
preview = response.match(
|
||||
/property="og:image" content="([^"]*)"/
|
||||
)?.[1];
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
|
||||
const folder = gitUrl.slice(0, -4).split('/').at(-1);
|
||||
if (isUnsafeFolder(folder)) return undefined;
|
||||
return {
|
||||
status: 'available',
|
||||
folder,
|
||||
git: gitUrl,
|
||||
preview
|
||||
} as AddonData;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async verify() {
|
||||
if (this.status.state !== 'done') return;
|
||||
|
||||
this.status = {
|
||||
...this.status,
|
||||
state: 'verifying'
|
||||
};
|
||||
|
||||
const remoteAddons = await fetchAddons();
|
||||
const available: AddonData[] = remoteAddons.map(a => ({
|
||||
status: 'available',
|
||||
git: a.git,
|
||||
toc: a.toc,
|
||||
description: a.description,
|
||||
folder: a.name,
|
||||
branch: a.branch,
|
||||
ref: a.ref
|
||||
}));
|
||||
|
||||
const clientPath = Preferences.data.clientDir;
|
||||
if (!clientPath) {
|
||||
this.status = { state: 'done', addons: {}, available };
|
||||
return;
|
||||
}
|
||||
|
||||
const addonsPath = path.join(clientPath, 'Interface', 'Addons');
|
||||
const dirs = (await fs.pathExists(addonsPath))
|
||||
? await fs.readdir(addonsPath)
|
||||
: [];
|
||||
const addons: AddonsStatus['addons'] = Object.fromEntries(
|
||||
dirs
|
||||
.filter(d => !d.startsWith('Blizzard_') && !/\.(tmp|bak)$/.test(d))
|
||||
.map(name => [name, { status: 'fetching' as const, folder: name }])
|
||||
);
|
||||
|
||||
this.status = { state: 'verifying', addons, available };
|
||||
|
||||
const verifyOne = async (folder: string) => {
|
||||
const dir = path.join(addonsPath, folder);
|
||||
|
||||
if (!fs.existsSync(path.join(dir, `${folder}.toc`))) {
|
||||
this.#setAddon(folder, {
|
||||
status: 'invalid',
|
||||
error: 'Missing .toc file',
|
||||
folder
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const toc = await readTocData(
|
||||
await fs.readFile(path.join(dir, `${folder}.toc`), 'utf-8')
|
||||
);
|
||||
|
||||
const remote = await git
|
||||
.listRemotes({ fs, dir })
|
||||
.then(r => r[0])
|
||||
.catch(() => null);
|
||||
|
||||
const avail = remoteAddons.find(a => a.name === folder);
|
||||
if (!remote) {
|
||||
Logger.log(`Addon "${folder}" is not a git repository`);
|
||||
this.#setAddon(
|
||||
folder,
|
||||
avail
|
||||
? {
|
||||
status: 'outOfDate',
|
||||
git: avail.git,
|
||||
toc,
|
||||
description: avail.description,
|
||||
folder
|
||||
}
|
||||
: { status: 'unknown', toc, folder }
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await git.fetch({ fs, dir, http, tags: true });
|
||||
|
||||
const branch = await git.currentBranch({ fs, dir });
|
||||
|
||||
const localCommit = await git
|
||||
.log({ fs, dir, ref: 'HEAD', depth: 1 })
|
||||
.then(r => r[0].oid)
|
||||
.catch(() => null);
|
||||
|
||||
const remoteCommit = avail?.ref
|
||||
? await git.resolveRef({ fs, dir, ref: avail.ref }).catch(() => null)
|
||||
: await git
|
||||
.log({ fs, dir, ref: `${remote.remote}/${branch}`, depth: 1 })
|
||||
.then(r => r[0].oid)
|
||||
.catch(() => null);
|
||||
|
||||
const status = await git.statusMatrix({ fs, dir });
|
||||
const hasChanges = status.some(
|
||||
([_, HEAD, index, workdir]) => HEAD !== index || index !== workdir
|
||||
);
|
||||
|
||||
const isUpToDate =
|
||||
!hasChanges && remoteCommit && localCommit === remoteCommit;
|
||||
this.#setAddon(folder, {
|
||||
git: remote.url,
|
||||
status: isUpToDate ? 'upToDate' : 'outOfDate',
|
||||
toc,
|
||||
description: avail?.description,
|
||||
ref: avail?.ref,
|
||||
folder
|
||||
});
|
||||
|
||||
Logger.log(
|
||||
isUpToDate
|
||||
? `Addon "${folder}" is up to date${
|
||||
avail?.ref ? ` (pinned ${avail.ref})` : ''
|
||||
}`
|
||||
: `Addon "${folder}" has an update available`
|
||||
);
|
||||
} catch (e) {
|
||||
this.#setAddon(folder, {
|
||||
git: remote.url,
|
||||
status: 'invalid',
|
||||
error: 'Failed to verify',
|
||||
toc,
|
||||
folder
|
||||
});
|
||||
Logger.error(`Addon "${folder}" failed to verify`, e);
|
||||
}
|
||||
};
|
||||
|
||||
const folders = Object.keys(addons);
|
||||
const VERIFY_CONCURRENCY = 6;
|
||||
let idx = 0;
|
||||
await Promise.all(
|
||||
Array.from(
|
||||
{ length: Math.min(VERIFY_CONCURRENCY, folders.length) },
|
||||
async () => {
|
||||
while (true) {
|
||||
const i = idx++;
|
||||
if (i >= folders.length) return;
|
||||
await verifyOne(folders[i]);
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
this.status = { ...this.status, state: 'done' };
|
||||
}
|
||||
|
||||
async update(
|
||||
toUpdate = Object.values(this.status.addons)
|
||||
.filter(e => e.status === 'outOfDate')
|
||||
.map(e => e.folder)
|
||||
.filter(isNotUndef)
|
||||
) {
|
||||
const clientPath = Preferences.data.clientDir;
|
||||
if (!clientPath) return;
|
||||
if (this.status.state !== 'done') return;
|
||||
|
||||
const addonsPath = path.join(clientPath, 'Interface', 'Addons');
|
||||
|
||||
for (const folder of toUpdate) {
|
||||
if (this.status.addons[folder]?.status === 'downloading') continue;
|
||||
const dir = path.join(addonsPath, folder);
|
||||
|
||||
const avail = this.status.available.find(a => a.folder === folder);
|
||||
const data: AddonData = {
|
||||
...avail,
|
||||
...this.status.addons[folder],
|
||||
status: 'downloading'
|
||||
};
|
||||
this.#setAddon(folder, data);
|
||||
|
||||
const remote = await git
|
||||
.listRemotes({ fs, dir })
|
||||
.then(r => r?.[0])
|
||||
.catch(() => null);
|
||||
|
||||
try {
|
||||
if (!remote) {
|
||||
await runWorker(
|
||||
gitClone,
|
||||
{ dir, url: data.git, ref: data.ref ?? data.branch },
|
||||
{ onProgress: this.#onProgress(folder, data) }
|
||||
);
|
||||
} else {
|
||||
const branch =
|
||||
(await git.currentBranch({ fs, dir })) ?? avail?.branch ?? 'master';
|
||||
await runWorker(
|
||||
gitPull,
|
||||
{
|
||||
dir,
|
||||
remote: remote.remote,
|
||||
branch,
|
||||
ref: avail?.ref
|
||||
},
|
||||
{ onProgress: this.#onProgress(folder, data) }
|
||||
);
|
||||
}
|
||||
const toc = readTocData(
|
||||
await fs.readFile(path.join(dir, `${folder}.toc`), 'utf-8')
|
||||
);
|
||||
|
||||
this.#setAddon(folder, { ...data, toc, status: 'upToDate' });
|
||||
Logger.log(`Updated addon "${folder}"`);
|
||||
} catch (e) {
|
||||
this.#setAddon(folder, {
|
||||
...data,
|
||||
status: 'invalid',
|
||||
error: 'Failed to update'
|
||||
});
|
||||
Logger.error(`Addon "${folder}" failed to update`, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async remove(toRemove: string[]) {
|
||||
const clientPath = Preferences.data.clientDir;
|
||||
if (!clientPath) return;
|
||||
if (this.status.state !== 'done') return;
|
||||
|
||||
for (const folder of toRemove) {
|
||||
const dir = path.join(clientPath, 'Interface', 'Addons', folder);
|
||||
if (fs.existsSync(dir)) await fs.remove(dir);
|
||||
this.#setAddon(folder);
|
||||
Logger.log(`Removed addon "${folder}"`);
|
||||
}
|
||||
}
|
||||
|
||||
async install(data: AddonData) {
|
||||
const clientPath = Preferences.data.clientDir;
|
||||
if (!clientPath) return;
|
||||
if (isUnsafeFolder(data.folder)) {
|
||||
Logger.error(`Refusing addon with unsafe folder name: "${data.folder}"`);
|
||||
this.#setAddon(data.folder, {
|
||||
...data,
|
||||
status: 'invalid',
|
||||
error: 'Invalid addon name'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.git || !isAllowedGitUrl(data.git)) {
|
||||
Logger.error(`Refusing addon from disallowed git host: "${data.git}"`);
|
||||
this.#setAddon(data.folder, {
|
||||
...data,
|
||||
status: 'invalid',
|
||||
error: 'Addon URL is not from an allowed git host'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const addonsPath = path.join(clientPath, 'Interface', 'Addons');
|
||||
const dir = path.join(addonsPath, data.folder);
|
||||
try {
|
||||
await runWorker(
|
||||
gitClone,
|
||||
{ dir, url: data.git, ref: data.ref ?? data.branch },
|
||||
{ onProgress: this.#onProgress(data.folder, data) }
|
||||
);
|
||||
const toc = await readTocData(
|
||||
await fs.readFile(path.join(dir, `${data.folder}.toc`), 'utf-8')
|
||||
);
|
||||
this.#setAddon(data.folder, { ...data, toc, status: 'upToDate' });
|
||||
Logger.log(`Installed addon "${data.folder}"`);
|
||||
} catch (e) {
|
||||
this.#setAddon(data.folder, {
|
||||
...data,
|
||||
status: 'invalid',
|
||||
error: 'Failed to install'
|
||||
});
|
||||
Logger.error(`Addon "${data.folder}" failed to install`, e);
|
||||
}
|
||||
}
|
||||
|
||||
#setAddon(folder: string, data?: AddonData) {
|
||||
const { [folder]: _, ...addons } = this.status.addons;
|
||||
this.status = {
|
||||
...this.status,
|
||||
addons: data ? { ...addons, [folder]: data } : addons
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const Addons = new AddonsClass();
|
||||
export default Addons;
|
||||
@@ -0,0 +1,476 @@
|
||||
import crypto from 'crypto';
|
||||
import path from 'path';
|
||||
import { spawn, type ChildProcess } from 'child_process';
|
||||
|
||||
import { app } from 'electron';
|
||||
import fs from 'fs-extra';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import { mapPort, type PortMapping } from './upnp';
|
||||
|
||||
const TORRENT_NAME = 'client';
|
||||
|
||||
const bin = () =>
|
||||
app.isPackaged
|
||||
? path.join(process.resourcesPath, 'aria2c.exe')
|
||||
: path.join(app.getAppPath(), 'resources', 'aria2c.exe');
|
||||
|
||||
type SyncOpts = {
|
||||
torrentUrl: string;
|
||||
clientDir: string;
|
||||
totalBytes?: number;
|
||||
checkIntegrity?: boolean;
|
||||
seedTime?: number;
|
||||
selectFiles?: number[];
|
||||
onProgress?: (p: SyncProgress) => void;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
export type SyncProgress = {
|
||||
progress: number;
|
||||
bytesDone: number;
|
||||
bytesTotal: number;
|
||||
bytesPerSecond: number;
|
||||
};
|
||||
|
||||
const ensureJunction = async (clientDir: string): Promise<string> => {
|
||||
await fs.ensureDir(clientDir);
|
||||
const staging = path.join(app.getPath('userData'), 'torrent-root');
|
||||
await fs.ensureDir(staging);
|
||||
const link = path.join(staging, TORRENT_NAME);
|
||||
|
||||
const target = path.resolve(clientDir);
|
||||
try {
|
||||
const cur = await fs.lstat(link);
|
||||
if (cur.isSymbolicLink() || cur.isDirectory()) {
|
||||
const resolved = await fs.realpath(link).catch(() => '');
|
||||
if (path.resolve(resolved) === target) return staging;
|
||||
}
|
||||
await fs.remove(link);
|
||||
} catch {}
|
||||
await fs.symlink(target, link, 'junction');
|
||||
return staging;
|
||||
};
|
||||
|
||||
const SIZE_UNITS: Record<string, number> = {
|
||||
B: 1,
|
||||
KiB: 1024,
|
||||
MiB: 1024 ** 2,
|
||||
GiB: 1024 ** 3,
|
||||
TiB: 1024 ** 4
|
||||
};
|
||||
|
||||
const toBytes = (s: string): number => {
|
||||
const m = /^([\d.]+)(B|KiB|MiB|GiB|TiB)$/.exec(s.trim());
|
||||
if (!m) return 0;
|
||||
return parseFloat(m[1]) * (SIZE_UNITS[m[2]] ?? 1);
|
||||
};
|
||||
|
||||
const parseProgress = (
|
||||
line: string,
|
||||
totalHint: number
|
||||
): SyncProgress | undefined => {
|
||||
const frac =
|
||||
/([\d.]+(?:B|KiB|MiB|GiB|TiB))\/([\d.]+(?:B|KiB|MiB|GiB|TiB))\((\d+)%\)/.exec(
|
||||
line
|
||||
);
|
||||
if (!frac) return undefined;
|
||||
const dl = /DL:([\d.]+(?:B|KiB|MiB|GiB|TiB))/.exec(line);
|
||||
return {
|
||||
progress: parseInt(frac[3], 10) / 100,
|
||||
bytesDone: toBytes(frac[1]),
|
||||
bytesTotal: toBytes(frac[2]) || totalHint,
|
||||
bytesPerSecond: dl ? toBytes(dl[1]) : 0
|
||||
};
|
||||
};
|
||||
|
||||
export const syncClient = (opts: SyncOpts): Promise<void> =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
let child: ChildProcess | undefined;
|
||||
ensureJunction(opts.clientDir)
|
||||
.then(dir => {
|
||||
const args = [
|
||||
`--dir=${dir}`,
|
||||
`--seed-time=${opts.seedTime ?? 0}`,
|
||||
`--check-integrity=${opts.checkIntegrity ? 'true' : 'false'}`,
|
||||
'--bt-save-metadata=true',
|
||||
'--bt-remove-unselected-file=false',
|
||||
'--continue=true',
|
||||
'--allow-overwrite=true',
|
||||
'--auto-file-renaming=false',
|
||||
'--file-allocation=none',
|
||||
'--disk-cache=128M',
|
||||
'--stream-piece-selector=inorder',
|
||||
'--max-tries=0',
|
||||
'--retry-wait=5',
|
||||
'--bt-stop-timeout=120',
|
||||
'--auto-save-interval=15',
|
||||
'--summary-interval=1',
|
||||
'--console-log-level=warn',
|
||||
'--enable-dht=true',
|
||||
'--bt-enable-lpd=true',
|
||||
'--max-connection-per-server=8',
|
||||
'--split=16',
|
||||
'--min-split-size=1M',
|
||||
...(opts.selectFiles?.length
|
||||
? [`--select-file=${opts.selectFiles.join(',')}`]
|
||||
: []),
|
||||
'--stop-with-process=' + process.pid,
|
||||
opts.torrentUrl
|
||||
];
|
||||
Logger.log(`aria2c ${args.join(' ')}`);
|
||||
child = spawn(bin(), args, { windowsHide: true });
|
||||
|
||||
const onLine = (buf: Buffer) => {
|
||||
for (const line of buf.toString().split(/\r?\n/)) {
|
||||
if (!line.trim()) continue;
|
||||
const p = parseProgress(line, opts.totalBytes ?? 0);
|
||||
if (p) opts.onProgress?.(p);
|
||||
else Logger.log(`[aria2] ${line}`);
|
||||
}
|
||||
};
|
||||
child.stdout?.on('data', onLine);
|
||||
child.stderr?.on('data', onLine);
|
||||
|
||||
opts.signal?.addEventListener('abort', () => child?.kill());
|
||||
|
||||
child.on('error', reject);
|
||||
child.on('close', code => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`aria2c exited with code ${code}`));
|
||||
});
|
||||
})
|
||||
.catch(reject);
|
||||
});
|
||||
|
||||
export const aria2Available = () => fs.pathExists(bin());
|
||||
|
||||
export const downloadIsComplete = async (): Promise<boolean> => {
|
||||
const control = path.join(
|
||||
app.getPath('userData'),
|
||||
'torrent-root',
|
||||
`${TORRENT_NAME}.aria2`
|
||||
);
|
||||
return !(await fs.pathExists(control));
|
||||
};
|
||||
|
||||
export const clearTorrentResumeState = async (): Promise<void> => {
|
||||
const dir = path.join(app.getPath('userData'), 'torrent-root');
|
||||
await Promise.all([
|
||||
fs.remove(path.join(dir, `${TORRENT_NAME}.aria2`)),
|
||||
fs.remove(path.join(dir, `${TORRENT_NAME}.torrent`))
|
||||
]);
|
||||
};
|
||||
|
||||
export const torrentUrl = (): string | undefined =>
|
||||
import.meta.env.MAIN_VITE_CLIENT_TORRENT_URL || undefined;
|
||||
|
||||
export const isTorrentMode = (): boolean => !!torrentUrl();
|
||||
|
||||
export const raidVisualsUrl = (): string | undefined =>
|
||||
import.meta.env.MAIN_VITE_RAID_VISUALS_URL || undefined;
|
||||
|
||||
export const clientPatchUrl = (): string | undefined =>
|
||||
import.meta.env.MAIN_VITE_CLIENT_PATCH_URL || undefined;
|
||||
|
||||
export const fetchTorrentSha = async (url: string): Promise<string> => {
|
||||
const r = await fetch(url);
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
const buf = Buffer.from(await r.arrayBuffer());
|
||||
return crypto.createHash('sha1').update(buf).digest('hex');
|
||||
};
|
||||
|
||||
const bdecode = (buf: Buffer, pos = 0): [unknown, number] => {
|
||||
if (pos >= buf.length) throw new Error('bencode: unexpected end of data');
|
||||
const ch = buf[pos];
|
||||
if (ch === 0x69) {
|
||||
const end = buf.indexOf(0x65, pos);
|
||||
if (end === -1) throw new Error('bencode: unterminated integer');
|
||||
return [parseInt(buf.toString('latin1', pos + 1, end), 10), end + 1];
|
||||
}
|
||||
if (ch === 0x6c) {
|
||||
const list: unknown[] = [];
|
||||
let p = pos + 1;
|
||||
while (buf[p] !== 0x65) {
|
||||
if (p >= buf.length) throw new Error('bencode: unterminated list');
|
||||
const [v, np] = bdecode(buf, p);
|
||||
list.push(v);
|
||||
p = np;
|
||||
}
|
||||
return [list, p + 1];
|
||||
}
|
||||
if (ch === 0x64) {
|
||||
const dict: Record<string, unknown> = {};
|
||||
let p = pos + 1;
|
||||
while (buf[p] !== 0x65) {
|
||||
if (p >= buf.length) throw new Error('bencode: unterminated dict');
|
||||
const [k, kp] = bdecode(buf, p);
|
||||
const [v, vp] = bdecode(buf, kp);
|
||||
dict[k as string] = v;
|
||||
p = vp;
|
||||
}
|
||||
return [dict, p + 1];
|
||||
}
|
||||
const colon = buf.indexOf(0x3a, pos);
|
||||
if (colon === -1) throw new Error('bencode: unterminated string length');
|
||||
const len = parseInt(buf.toString('latin1', pos, colon), 10);
|
||||
if (!Number.isInteger(len) || len < 0 || colon + 1 + len > buf.length)
|
||||
throw new Error('bencode: invalid string length');
|
||||
const start = colon + 1;
|
||||
return [buf.toString('latin1', start, start + len), start + len];
|
||||
};
|
||||
|
||||
const torrentDataArchives = (torrentBytes: Buffer): Set<string> => {
|
||||
const [torrent] = bdecode(torrentBytes) as [
|
||||
{ info?: { files?: { path?: string[] }[] } },
|
||||
number
|
||||
];
|
||||
const files = torrent?.info?.files ?? [];
|
||||
return new Set(
|
||||
files
|
||||
.filter(
|
||||
f =>
|
||||
f.path?.length === 2 &&
|
||||
f.path[0] === 'Data' &&
|
||||
/\.mpq$/i.test(f.path[1])
|
||||
)
|
||||
.map(f => f.path![1].toLowerCase())
|
||||
);
|
||||
};
|
||||
|
||||
const LOCALE_DIRS = new Set([
|
||||
'enus',
|
||||
'engb',
|
||||
'encn',
|
||||
'entw',
|
||||
'kokr',
|
||||
'frfr',
|
||||
'dede',
|
||||
'zhcn',
|
||||
'zhtw',
|
||||
'eses',
|
||||
'esmx',
|
||||
'ruru',
|
||||
'ptbr',
|
||||
'ptpt',
|
||||
'itit'
|
||||
]);
|
||||
|
||||
const torrentDataDirs = (torrentBytes: Buffer): Set<string> => {
|
||||
const [torrent] = bdecode(torrentBytes) as [
|
||||
{ info?: { files?: { path?: string[] }[] } },
|
||||
number
|
||||
];
|
||||
const files = torrent?.info?.files ?? [];
|
||||
return new Set(
|
||||
files
|
||||
.filter(f => (f.path?.length ?? 0) >= 3 && f.path![0] === 'Data')
|
||||
.map(f => f.path![1].toLowerCase())
|
||||
);
|
||||
};
|
||||
|
||||
export const pruneStaleArchives = async (
|
||||
clientDir: string,
|
||||
url: string,
|
||||
_owned: Set<string>
|
||||
): Promise<string[]> => {
|
||||
try {
|
||||
const r = await fetch(url);
|
||||
if (!r.ok) return [];
|
||||
const bytes = Buffer.from(await r.arrayBuffer());
|
||||
const expected = torrentDataArchives(bytes);
|
||||
if (!expected.size) return [];
|
||||
for (const u of [clientPatchUrl(), raidVisualsUrl()])
|
||||
if (u) expected.add(path.basename(u).toLowerCase());
|
||||
const usedDirs = torrentDataDirs(bytes);
|
||||
const dataDir = path.join(clientDir, 'Data');
|
||||
const onDisk = await fs.readdir(dataDir).catch(() => []);
|
||||
const removed: string[] = [];
|
||||
for (const name of onDisk) {
|
||||
const lc = name.toLowerCase();
|
||||
const full = path.join(dataDir, name);
|
||||
const st = await fs.stat(full).catch(() => null);
|
||||
if (!st) continue;
|
||||
if (st.isDirectory()) {
|
||||
if (LOCALE_DIRS.has(lc) && !usedDirs.has(lc)) {
|
||||
await fs.remove(full);
|
||||
removed.push(name + '/');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!/\.mpq$/i.test(name) || expected.has(lc)) continue;
|
||||
await fs.remove(full);
|
||||
removed.push(name);
|
||||
}
|
||||
return removed;
|
||||
} catch (e) {
|
||||
Logger.warn('Prune of stale archives failed', e);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const torrentDownloadSelection = async (
|
||||
clientDir: string,
|
||||
url: string,
|
||||
dropMismatched = false
|
||||
): Promise<number[] | null> => {
|
||||
try {
|
||||
const r = await fetch(url);
|
||||
if (!r.ok) return null;
|
||||
const [torrent] = bdecode(Buffer.from(await r.arrayBuffer())) as [
|
||||
{ info?: { files?: { path?: string[]; length?: number }[] } },
|
||||
number
|
||||
];
|
||||
const files = torrent?.info?.files ?? [];
|
||||
if (!files.length) return null;
|
||||
const need: number[] = [];
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const f = files[i];
|
||||
if (!f.path?.length || typeof f.length !== 'number') return null;
|
||||
const dest = path.join(clientDir, ...f.path);
|
||||
const st = await fs.stat(dest).catch(() => null);
|
||||
if (!st) {
|
||||
need.push(i + 1);
|
||||
continue;
|
||||
}
|
||||
if (st.size !== f.length) {
|
||||
if (dropMismatched || st.size > f.length)
|
||||
await fs.remove(dest).catch(() => {});
|
||||
need.push(i + 1);
|
||||
}
|
||||
}
|
||||
return need;
|
||||
} catch (e) {
|
||||
Logger.warn('Torrent selection computation failed', e);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const torrentTreeIntact = async (
|
||||
clientDir: string,
|
||||
url: string
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const r = await fetch(url);
|
||||
if (!r.ok) return false;
|
||||
const [torrent] = bdecode(Buffer.from(await r.arrayBuffer())) as [
|
||||
{ info?: { files?: { path?: string[]; length?: number }[] } },
|
||||
number
|
||||
];
|
||||
const files = torrent?.info?.files ?? [];
|
||||
if (!files.length) return false;
|
||||
for (const f of files) {
|
||||
if (!f.path?.length || typeof f.length !== 'number') return false;
|
||||
const st = await fs
|
||||
.stat(path.join(clientDir, ...f.path))
|
||||
.catch(() => null);
|
||||
if (!st || st.size !== f.length) return false;
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
Logger.warn('Torrent tree check failed', e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const LOCALE_ASSERT_OFFSET = 0x1b2115;
|
||||
const pristineWowPath = () =>
|
||||
path.join(app.getPath('userData'), 'base-WoW.exe');
|
||||
|
||||
export const refreshPristineWow = async (clientDir: string): Promise<void> => {
|
||||
const exe = path.join(clientDir, 'WoW.exe');
|
||||
if (!(await fs.pathExists(exe))) return;
|
||||
const fd = await fs.open(exe, 'r');
|
||||
try {
|
||||
const b = Buffer.alloc(1);
|
||||
await fs.read(fd, b, 0, 1, LOCALE_ASSERT_OFFSET);
|
||||
if (b[0] === 0xa1) {
|
||||
await fs.copy(exe, pristineWowPath(), { overwrite: true });
|
||||
Logger.log('Cached pristine WoW.exe base');
|
||||
}
|
||||
} finally {
|
||||
await fs.close(fd);
|
||||
}
|
||||
};
|
||||
|
||||
export const readPristineWow = async (clientDir: string): Promise<Buffer> => {
|
||||
const cache = pristineWowPath();
|
||||
if (await fs.pathExists(cache)) return fs.readFile(cache);
|
||||
return fs.readFile(path.join(clientDir, 'WoW.exe'));
|
||||
};
|
||||
|
||||
let seeder: ChildProcess | undefined;
|
||||
let mapping: Promise<PortMapping> | undefined;
|
||||
let wantSeeding = false;
|
||||
let starting = false;
|
||||
|
||||
const SEED_PORT = 6881;
|
||||
const SEED_TIME_MINUTES = 525600;
|
||||
|
||||
export const isSeeding = (): boolean => !!seeder;
|
||||
|
||||
const releaseMapping = (): void => {
|
||||
const m = mapping;
|
||||
mapping = undefined;
|
||||
if (m) void m.then(x => x.stop()).catch(() => {});
|
||||
};
|
||||
|
||||
export const stopSeeding = (): void => {
|
||||
wantSeeding = false;
|
||||
seeder?.kill();
|
||||
seeder = undefined;
|
||||
releaseMapping();
|
||||
};
|
||||
|
||||
export const startSeeding = async (
|
||||
clientDir: string,
|
||||
uploadLimit = '2M'
|
||||
): Promise<void> => {
|
||||
wantSeeding = true;
|
||||
if (seeder || starting) return;
|
||||
starting = true;
|
||||
try {
|
||||
const url = torrentUrl();
|
||||
if (!url) return;
|
||||
const dir = await ensureJunction(clientDir);
|
||||
if (!wantSeeding || seeder) return;
|
||||
const args = [
|
||||
`--dir=${dir}`,
|
||||
'--bt-seed-unverified=true',
|
||||
`--seed-time=${SEED_TIME_MINUTES}`,
|
||||
'--check-integrity=false',
|
||||
'--continue=true',
|
||||
'--bt-save-metadata=true',
|
||||
'--enable-dht=true',
|
||||
'--bt-enable-lpd=true',
|
||||
`--listen-port=${SEED_PORT}`,
|
||||
`--dht-listen-port=${SEED_PORT}`,
|
||||
`--max-overall-upload-limit=${uploadLimit}`,
|
||||
'--summary-interval=0',
|
||||
'--console-log-level=warn',
|
||||
'--stop-with-process=' + process.pid,
|
||||
url
|
||||
];
|
||||
Logger.log('aria2c (seed) ' + args.join(' '));
|
||||
const child = spawn(bin(), args, { windowsHide: true });
|
||||
seeder = child;
|
||||
const onExit = () => {
|
||||
if (seeder === child) {
|
||||
seeder = undefined;
|
||||
releaseMapping();
|
||||
}
|
||||
};
|
||||
child.on('close', onExit);
|
||||
child.on('error', e => {
|
||||
Logger.warn('Seeder failed', e);
|
||||
onExit();
|
||||
});
|
||||
|
||||
mapping = mapPort(SEED_PORT, { description: 'OctoWoW' });
|
||||
void mapping.catch(() => undefined);
|
||||
} catch (e) {
|
||||
Logger.warn('startSeeding failed', e);
|
||||
} finally {
|
||||
starting = false;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,192 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { app } from 'electron';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import Preferences from './preferences';
|
||||
|
||||
export type ExclusionResult = { ok: boolean; error?: string; paths?: string[] };
|
||||
|
||||
const psSingleQuote = (s: string) => `'${s.replace(/'/g, "''")}'`;
|
||||
|
||||
export const addDefenderExclusions = async (): Promise<ExclusionResult> => {
|
||||
if (os.platform() !== 'win32')
|
||||
return {
|
||||
ok: false,
|
||||
error: 'Antivirus exclusions are only needed on Windows.'
|
||||
};
|
||||
|
||||
const clientDir = Preferences.data.clientDir;
|
||||
if (!clientDir)
|
||||
return {
|
||||
ok: false,
|
||||
error: 'Set your game folder first, then add the exclusion.'
|
||||
};
|
||||
|
||||
const launcherDir =
|
||||
process.env.PORTABLE_EXECUTABLE_DIR ?? path.dirname(app.getPath('exe'));
|
||||
const paths = [...new Set([clientDir, launcherDir])];
|
||||
|
||||
const resultFile = path.join(
|
||||
os.tmpdir(),
|
||||
`octo-defender-${process.pid}-${Date.now()}.txt`
|
||||
);
|
||||
const write = (v: string) =>
|
||||
`Set-Content -LiteralPath ${psSingleQuote(
|
||||
resultFile
|
||||
)} -Value "${v}" -Encoding ASCII`;
|
||||
|
||||
const inner = [
|
||||
'try {',
|
||||
...paths.map(
|
||||
p =>
|
||||
` Add-MpPreference -ExclusionPath ${psSingleQuote(
|
||||
p
|
||||
)} -ErrorAction Stop`
|
||||
),
|
||||
' Add-MpPreference -ExclusionProcess "WoW.exe" -ErrorAction Stop',
|
||||
' Add-MpPreference -ExclusionProcess "VanillaFixes.exe" -ErrorAction Stop',
|
||||
` ${write('OK')}`,
|
||||
'} catch {',
|
||||
' $t = $false',
|
||||
' try { $t = (Get-MpComputerStatus).IsTamperProtected } catch {}',
|
||||
` if ($t) { ${write('TAMPER')} } else { ${write('FAIL')} }`,
|
||||
'}'
|
||||
].join('\n');
|
||||
const encoded = Buffer.from(inner, 'utf16le').toString('base64');
|
||||
|
||||
const outer =
|
||||
'try { Start-Process powershell -Verb RunAs -WindowStyle Hidden -Wait ' +
|
||||
"-ArgumentList '-NoProfile','-NonInteractive'," +
|
||||
`'-EncodedCommand','${encoded}' } catch { exit 1 }`;
|
||||
|
||||
return new Promise<ExclusionResult>(resolve => {
|
||||
const child = spawn(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-NonInteractive', '-Command', outer],
|
||||
{ windowsHide: true }
|
||||
);
|
||||
let stderr = '';
|
||||
child.stderr.on('data', d => (stderr += String(d)));
|
||||
child.on('error', e => {
|
||||
Logger.error('Failed to launch PowerShell for Defender exclusion', e);
|
||||
resolve({ ok: false, error: 'Could not run Windows PowerShell.' });
|
||||
});
|
||||
child.on('exit', code => {
|
||||
let result: string | null = null;
|
||||
try {
|
||||
result = fs.readFileSync(resultFile, 'utf8').trim();
|
||||
} catch {}
|
||||
try {
|
||||
fs.rmSync(resultFile, { force: true });
|
||||
} catch {}
|
||||
|
||||
if (result === 'OK') {
|
||||
Logger.info(`Added Defender exclusions: ${paths.join(', ')}`);
|
||||
resolve({ ok: true, paths });
|
||||
return;
|
||||
}
|
||||
if (result === 'TAMPER') {
|
||||
Logger.error('Defender exclusion blocked by Tamper Protection');
|
||||
resolve({
|
||||
ok: false,
|
||||
error:
|
||||
'Windows Security Tamper Protection is blocking this. Turn it off in Windows Security, or add your game folder by hand under Exclusions.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (result === 'FAIL') {
|
||||
Logger.error(`Defender exclusion failed: ${stderr}`.trim());
|
||||
resolve({
|
||||
ok: false,
|
||||
error:
|
||||
'Windows would not add the exclusion. You can add your game folder by hand in Windows Security, under Exclusions.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
Logger.warn(
|
||||
`Defender exclusion: no result (exit ${code}) ${stderr}`.trim()
|
||||
);
|
||||
resolve({
|
||||
ok: false,
|
||||
error:
|
||||
'Windows did not grant permission. Click Yes on the User Account Control prompt to add the exclusion.'
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const SENSITIVE_FILES = [
|
||||
'WoW.exe',
|
||||
'VanillaFixes.exe',
|
||||
'd3d9.dll',
|
||||
'UnitXP_SP3.dll',
|
||||
'nampower.dll',
|
||||
'VfPatcher.dll',
|
||||
'VanillaHelpers.dll',
|
||||
'VanillaMultiMonitorFix.dll',
|
||||
'transmogfix.dll'
|
||||
];
|
||||
|
||||
export const detectAntivirusBlocks = async (): Promise<string[]> => {
|
||||
if (os.platform() !== 'win32') return [];
|
||||
|
||||
const clientDir = Preferences.data.clientDir;
|
||||
const launcherDir =
|
||||
process.env.PORTABLE_EXECUTABLE_DIR ?? path.dirname(app.getPath('exe'));
|
||||
const roots = [clientDir, launcherDir]
|
||||
.filter((p): p is string => !!p)
|
||||
.map(p => p.toLowerCase());
|
||||
if (!roots.length) return [];
|
||||
|
||||
const blocked = new Set<string>();
|
||||
|
||||
if (clientDir && Preferences.data.syncedTorrentHash)
|
||||
for (const name of SENSITIVE_FILES)
|
||||
if (!fs.existsSync(path.join(clientDir, name))) blocked.add(name);
|
||||
|
||||
const script =
|
||||
'Get-MpThreatDetection | Where-Object ' +
|
||||
'{ $_.InitialDetectionTime -gt (Get-Date).AddHours(-12) } | ' +
|
||||
'Select-Object -ExpandProperty Resources';
|
||||
await new Promise<void>(resolve => {
|
||||
const child = spawn(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-NonInteractive', '-Command', script],
|
||||
{ windowsHide: true }
|
||||
);
|
||||
let out = '';
|
||||
let settled = false;
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {}
|
||||
}, 15_000);
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
child.stdout.on('data', d => (out += String(d)));
|
||||
child.on('error', finish);
|
||||
child.on('exit', () => {
|
||||
for (const line of out.split(/\r?\n/)) {
|
||||
const m = /^file:_?(.+)$/.exec(line.trim());
|
||||
if (!m) continue;
|
||||
const full = m[1];
|
||||
if (
|
||||
roots.some(r => full.toLowerCase().startsWith(r)) &&
|
||||
!fs.existsSync(full)
|
||||
)
|
||||
blocked.add(path.basename(full));
|
||||
}
|
||||
finish();
|
||||
});
|
||||
});
|
||||
|
||||
return [...blocked];
|
||||
};
|
||||
@@ -0,0 +1,146 @@
|
||||
import os from 'node:os';
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
export type DisplayDevice = {
|
||||
index: number;
|
||||
deviceName: string;
|
||||
deviceString: string;
|
||||
attached: boolean;
|
||||
primary: boolean;
|
||||
width: number;
|
||||
height: number;
|
||||
refresh: number;
|
||||
modes: string[];
|
||||
};
|
||||
|
||||
const SCRIPT = [
|
||||
'$ErrorActionPreference = "Stop"',
|
||||
"$ProgressPreference = 'SilentlyContinue'",
|
||||
"Add-Type -TypeDefinition @'",
|
||||
'using System;',
|
||||
'using System.Runtime.InteropServices;',
|
||||
'public static class VmmfDisplays {',
|
||||
' [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]',
|
||||
' public struct DISPLAY_DEVICE {',
|
||||
' public int cb;',
|
||||
' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string DeviceName;',
|
||||
' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string DeviceString;',
|
||||
' public int StateFlags;',
|
||||
' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string DeviceID;',
|
||||
' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string DeviceKey;',
|
||||
' }',
|
||||
' [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]',
|
||||
' public struct DEVMODE {',
|
||||
' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string dmDeviceName;',
|
||||
' public short dmSpecVersion; public short dmDriverVersion; public short dmSize; public short dmDriverExtra;',
|
||||
' public int dmFields; public int dmPositionX; public int dmPositionY;',
|
||||
' public int dmDisplayOrientation; public int dmDisplayFixedOutput;',
|
||||
' public short dmColor; public short dmDuplex; public short dmYResolution; public short dmTTOption; public short dmCollate;',
|
||||
' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string dmFormName;',
|
||||
' public short dmLogPixels; public int dmBitsPerPel; public int dmPelsWidth; public int dmPelsHeight;',
|
||||
' public int dmDisplayFlags; public int dmDisplayFrequency;',
|
||||
' public int dmICMMethod; public int dmICMIntent; public int dmMediaType; public int dmDitherType;',
|
||||
' public int dmReserved1; public int dmReserved2; public int dmPanningWidth; public int dmPanningHeight;',
|
||||
' }',
|
||||
' [DllImport("user32.dll", EntryPoint="EnumDisplayDevicesA", CharSet=CharSet.Ansi)]',
|
||||
' public static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);',
|
||||
' [DllImport("user32.dll", EntryPoint="EnumDisplaySettingsA", CharSet=CharSet.Ansi)]',
|
||||
' public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);',
|
||||
'}',
|
||||
"'@",
|
||||
'for ($i = 0; ; $i++) {',
|
||||
' $dd = New-Object VmmfDisplays+DISPLAY_DEVICE',
|
||||
' $dd.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($dd)',
|
||||
' if (-not [VmmfDisplays]::EnumDisplayDevices([NullString]::Value, $i, [ref]$dd, 0)) { break }',
|
||||
' $dm = New-Object VmmfDisplays+DEVMODE',
|
||||
' $dm.dmSize = [System.Runtime.InteropServices.Marshal]::SizeOf($dm)',
|
||||
' $cur = ""',
|
||||
' if ([VmmfDisplays]::EnumDisplaySettings($dd.DeviceName, -1, [ref]$dm)) {',
|
||||
' $cur = "$($dm.dmPelsWidth)|$($dm.dmPelsHeight)|$($dm.dmDisplayFrequency)"',
|
||||
' }',
|
||||
' $modes = New-Object System.Collections.Generic.HashSet[string]',
|
||||
' for ($m = 0; ; $m++) {',
|
||||
' $d2 = New-Object VmmfDisplays+DEVMODE',
|
||||
' $d2.dmSize = [System.Runtime.InteropServices.Marshal]::SizeOf($d2)',
|
||||
' if (-not [VmmfDisplays]::EnumDisplaySettings($dd.DeviceName, $m, [ref]$d2)) { break }',
|
||||
' [void]$modes.Add("$($d2.dmPelsWidth)x$($d2.dmPelsHeight)")',
|
||||
' }',
|
||||
' Write-Output ("{0}`t{1}`t{2}`t{3}`t{4}`t{5}" -f $i, $dd.DeviceName, $dd.DeviceString, $dd.StateFlags, $cur, ($modes -join ","))',
|
||||
'}'
|
||||
].join('\n');
|
||||
|
||||
const parseRow = (line: string): DisplayDevice | undefined => {
|
||||
const f = line.split('\t');
|
||||
if (f.length < 6) return undefined;
|
||||
const index = Number(f[0]);
|
||||
const stateFlags = Number(f[3]);
|
||||
if (!Number.isInteger(index) || index < 0 || !Number.isInteger(stateFlags))
|
||||
return undefined;
|
||||
const [w, h, hz] = (f[4] || '').split('|').map(Number);
|
||||
return {
|
||||
index,
|
||||
deviceName: f[1],
|
||||
deviceString: f[2],
|
||||
attached: (stateFlags & 1) !== 0,
|
||||
primary: (stateFlags & 4) !== 0,
|
||||
width: Number.isFinite(w) ? w : 0,
|
||||
height: Number.isFinite(h) ? h : 0,
|
||||
refresh: Number.isFinite(hz) ? hz : 0,
|
||||
modes: (f[5] || '').split(',').filter(Boolean)
|
||||
};
|
||||
};
|
||||
|
||||
export const enumerateDisplays = (): Promise<DisplayDevice[] | null> => {
|
||||
if (os.platform() !== 'win32') return Promise.resolve(null);
|
||||
|
||||
const encoded = Buffer.from(SCRIPT, 'utf16le').toString('base64');
|
||||
|
||||
return new Promise(resolve => {
|
||||
let settled = false;
|
||||
const finish = (v: DisplayDevice[] | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(v);
|
||||
};
|
||||
|
||||
const child = spawn(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
|
||||
{ windowsHide: true }
|
||||
);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
child.kill();
|
||||
Logger.warn('Display enumeration timed out');
|
||||
finish(null);
|
||||
}, 10000);
|
||||
|
||||
let stdout = '';
|
||||
child.stdout.on('data', d => (stdout += String(d)));
|
||||
child.on('error', e => {
|
||||
Logger.warn('Display enumeration failed to launch PowerShell', e);
|
||||
finish(null);
|
||||
});
|
||||
child.on('exit', code => {
|
||||
const devices = stdout
|
||||
.split(/\r?\n/)
|
||||
.map(parseRow)
|
||||
.filter((d): d is DisplayDevice => d !== undefined);
|
||||
if (code === 0 && devices.length) {
|
||||
Logger.info(`Enumerated ${devices.length} display device(s)`);
|
||||
finish(devices);
|
||||
} else {
|
||||
Logger.warn('Display enumeration returned nothing usable');
|
||||
finish(null);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const detectPrimaryDisplayIndex = async (): Promise<number | null> => {
|
||||
const devices = await enumerateDisplays();
|
||||
return devices?.find(d => d.primary && d.attached)?.index ?? null;
|
||||
};
|
||||
@@ -0,0 +1,79 @@
|
||||
import path from 'path';
|
||||
|
||||
import fs from 'fs-extra';
|
||||
|
||||
let queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
const serial = <T>(fn: () => Promise<T>): Promise<T> => {
|
||||
const next = queue.then(fn, fn);
|
||||
queue = next.catch(() => {});
|
||||
return next;
|
||||
};
|
||||
|
||||
const dllsPath = (clientDir: string) => path.join(clientDir, 'dlls.txt');
|
||||
|
||||
const readLines = async (clientDir: string): Promise<string[]> => {
|
||||
const file = dllsPath(clientDir);
|
||||
if (!(await fs.pathExists(file))) return [];
|
||||
const text = await fs.readFile(file, 'utf8');
|
||||
return text.split(/\r?\n/);
|
||||
};
|
||||
|
||||
const dllNames = (lines: string[]) =>
|
||||
lines.map(l => l.trim()).filter(l => l && !l.startsWith('#'));
|
||||
|
||||
// keep VanillaFixes' consent cache in step with dlls.txt so it won't re-prompt
|
||||
const writeCache = async (clientDir: string, names: string[]) => {
|
||||
const cache = path.join(clientDir, 'dlls.txt.cache');
|
||||
if (!names.length) {
|
||||
await fs.remove(cache).catch(() => {});
|
||||
return;
|
||||
}
|
||||
const body = names.map(n => path.win32.join(clientDir, n)).join('\r\n');
|
||||
await fs.writeFile(cache, body, 'utf8').catch(() => {});
|
||||
};
|
||||
|
||||
const writeLines = async (clientDir: string, lines: string[]) => {
|
||||
const file = dllsPath(clientDir);
|
||||
const trimmed = lines.join('\n').replace(/\n+$/, '');
|
||||
if (!trimmed.trim()) {
|
||||
if (await fs.pathExists(file)) await fs.remove(file);
|
||||
await writeCache(clientDir, []);
|
||||
return;
|
||||
}
|
||||
await fs.writeFile(file, trimmed + '\n', 'utf8');
|
||||
await writeCache(clientDir, dllNames(lines));
|
||||
};
|
||||
|
||||
export const syncVanillaFixesCache = (clientDir: string) =>
|
||||
serial(async () =>
|
||||
writeCache(clientDir, dllNames(await readLines(clientDir)))
|
||||
);
|
||||
|
||||
const matches = (line: string, name: string) =>
|
||||
line.trim().toLowerCase() === name.toLowerCase();
|
||||
|
||||
export const addDll = (clientDir: string, name: string) =>
|
||||
serial(async () => {
|
||||
const lines = await readLines(clientDir);
|
||||
if (lines.some(l => matches(l, name))) return;
|
||||
lines.push(name);
|
||||
await writeLines(clientDir, lines);
|
||||
});
|
||||
|
||||
export const removeDll = (clientDir: string, name: string) =>
|
||||
serial(async () => {
|
||||
const lines = await readLines(clientDir);
|
||||
const next = lines.filter(l => !matches(l, name));
|
||||
if (next.length === lines.length) return;
|
||||
await writeLines(clientDir, next);
|
||||
});
|
||||
|
||||
export const hasDll = (clientDir: string, name: string) =>
|
||||
serial(async () => {
|
||||
const lines = await readLines(clientDir);
|
||||
return lines.some(l => matches(l, name));
|
||||
});
|
||||
|
||||
export const listDlls = (clientDir: string): Promise<string[]> =>
|
||||
serial(async () => dllNames(await readLines(clientDir)));
|
||||
@@ -0,0 +1,132 @@
|
||||
import os from 'node:os';
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
import { app } from 'electron';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import type { HardwareInfo } from '~common/schemas';
|
||||
|
||||
export const HARDWARE_SCHEMA_VERSION = 1;
|
||||
|
||||
export const FARCLIP_FLOOR = 777;
|
||||
export const FARCLIP_CEILING = 3000;
|
||||
|
||||
const VIDEO_CLASS_GUID = '{4d36e968-e325-11ce-bfc1-08002be10318}';
|
||||
|
||||
const getVramMb = (): Promise<{
|
||||
mb: number | null;
|
||||
source: HardwareInfo['vramSource'];
|
||||
}> => {
|
||||
if (os.platform() !== 'win32')
|
||||
return Promise.resolve({ mb: null, source: 'none' });
|
||||
|
||||
const script = [
|
||||
'$ErrorActionPreference = "Stop"',
|
||||
`$base = 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Class\\${VIDEO_CLASS_GUID}'`,
|
||||
'$max = [int64]0',
|
||||
'Get-ChildItem $base -ErrorAction SilentlyContinue | ForEach-Object {',
|
||||
' $p = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue',
|
||||
' $v = [int64]0',
|
||||
" if ($p.'HardwareInformation.qwMemorySize') { $v = [int64]$p.'HardwareInformation.qwMemorySize' }",
|
||||
" elseif ($p.'HardwareInformation.MemorySize') {",
|
||||
" $m = $p.'HardwareInformation.MemorySize'",
|
||||
' if ($m -is [byte[]]) { $v = [int64][System.BitConverter]::ToUInt32($m, 0) } else { $v = [int64]$m }',
|
||||
' }',
|
||||
' if ($v -gt $max) { $max = $v }',
|
||||
'}',
|
||||
'Write-Output $max'
|
||||
].join('\n');
|
||||
const encoded = Buffer.from(script, 'utf16le').toString('base64');
|
||||
|
||||
return new Promise(resolve => {
|
||||
let settled = false;
|
||||
const finish = (mb: number | null, source: HardwareInfo['vramSource']) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve({ mb, source });
|
||||
};
|
||||
|
||||
const child = spawn(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
|
||||
{ windowsHide: true }
|
||||
);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
child.kill();
|
||||
Logger.warn('VRAM detection timed out');
|
||||
finish(null, 'none');
|
||||
}, 8000);
|
||||
|
||||
let stdout = '';
|
||||
child.stdout.on('data', d => (stdout += String(d)));
|
||||
child.on('error', e => {
|
||||
Logger.warn('VRAM detection failed to launch PowerShell', e);
|
||||
finish(null, 'none');
|
||||
});
|
||||
child.on('exit', code => {
|
||||
const bytes = Number(stdout.trim());
|
||||
if (code === 0 && Number.isFinite(bytes) && bytes > 0)
|
||||
finish(Math.round(bytes / 1024 / 1024), 'registry');
|
||||
else finish(null, 'none');
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const getGpuModel = async (): Promise<string> => {
|
||||
try {
|
||||
const info = (await app.getGPUInfo('complete')) as {
|
||||
auxAttributes?: { glRenderer?: string };
|
||||
gpuDevice?: { active?: boolean; vendorId?: number; deviceId?: number }[];
|
||||
};
|
||||
const renderer = info?.auxAttributes?.glRenderer?.trim();
|
||||
if (renderer) return renderer;
|
||||
const active = info?.gpuDevice?.find(d => d.active) ?? info?.gpuDevice?.[0];
|
||||
if (active) return `vendor ${active.vendorId} device ${active.deviceId}`;
|
||||
} catch (e) {
|
||||
Logger.warn('GPU info detection failed', e);
|
||||
}
|
||||
return 'unknown';
|
||||
};
|
||||
|
||||
export const detectHardware = async (): Promise<HardwareInfo> => {
|
||||
const cpus = os.cpus();
|
||||
const [vram, gpuModel] = await Promise.all([getVramMb(), getGpuModel()]);
|
||||
|
||||
const info: HardwareInfo = {
|
||||
totalRamMb: Math.round(os.totalmem() / 1024 / 1024),
|
||||
cpuCores: cpus.length,
|
||||
cpuModel: cpus[0]?.model?.trim() || 'unknown',
|
||||
gpuModel,
|
||||
vramMb: vram.mb,
|
||||
vramSource: vram.source,
|
||||
detectedAt: new Date().toISOString(),
|
||||
schemaVersion: HARDWARE_SCHEMA_VERSION
|
||||
};
|
||||
Logger.info('Detected hardware', info);
|
||||
return info;
|
||||
};
|
||||
|
||||
const clampFarClip = (n: number) =>
|
||||
Math.min(FARCLIP_CEILING, Math.max(FARCLIP_FLOOR, Math.round(n)));
|
||||
|
||||
export const recommendFarClip = (hw: HardwareInfo | null): number => {
|
||||
if (!hw) return clampFarClip(1000);
|
||||
|
||||
const ramGb = hw.totalRamMb / 1024;
|
||||
const cores = hw.cpuCores;
|
||||
const vramTrusted = hw.vramSource !== 'none' && hw.vramMb != null;
|
||||
const vramGb = vramTrusted ? (hw.vramMb as number) / 1024 : null;
|
||||
|
||||
if (ramGb < 6 || cores <= 2) return clampFarClip(FARCLIP_FLOOR);
|
||||
|
||||
if (vramGb === null)
|
||||
return clampFarClip(ramGb >= 8 && cores >= 4 ? 1500 : 1000);
|
||||
|
||||
if (ramGb < 8 || vramGb < 2) return clampFarClip(1000);
|
||||
if (ramGb >= 32 && vramGb >= 8 && cores >= 8) return clampFarClip(3000);
|
||||
if (ramGb >= 16 && vramGb >= 4 && cores >= 6) return clampFarClip(2200);
|
||||
if (ramGb >= 8 && vramGb >= 2 && cores >= 4) return clampFarClip(1500);
|
||||
return clampFarClip(1000);
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import fs from 'fs-extra';
|
||||
import {
|
||||
SFileOpenArchive,
|
||||
SFileCloseArchive,
|
||||
SFileHasFile
|
||||
} from 'stormlib-node';
|
||||
import { STREAM_FLAG } from 'stormlib-node/dist/enums';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import Preferences from './preferences';
|
||||
|
||||
// old installs may have a copied patch-<letter>.mpq that overrides patch-5; sweep by marker
|
||||
const ALL_LETTERS = 'BCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
|
||||
const MARKER = 'octolocale.marker';
|
||||
|
||||
const patchFile = (dataDir: string, letter: string) =>
|
||||
path.join(dataDir, `patch-${letter}.mpq`);
|
||||
|
||||
const isOurPatch = (mpqPath: string): boolean => {
|
||||
if (!fs.existsSync(mpqPath)) return false;
|
||||
try {
|
||||
const h = SFileOpenArchive(mpqPath, STREAM_FLAG.READ_ONLY);
|
||||
try {
|
||||
return SFileHasFile(h, MARKER);
|
||||
} finally {
|
||||
SFileCloseArchive(h);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// remove locale patches we copied in (marker-carrying archives only); never throws
|
||||
export const removeLegacyLocalePatches = async (
|
||||
clientDir: string | undefined
|
||||
): Promise<void> => {
|
||||
if (!clientDir) return;
|
||||
const dataDir = path.join(clientDir, 'Data');
|
||||
if (!(await fs.pathExists(dataDir))) return;
|
||||
|
||||
for (const letter of ALL_LETTERS) {
|
||||
const f = patchFile(dataDir, letter);
|
||||
if (!isOurPatch(f)) continue;
|
||||
try {
|
||||
await fs.remove(f);
|
||||
Logger.log(`Removed the retired locale patch patch-${letter}.mpq`);
|
||||
} catch (e) {
|
||||
Logger.error(`Could not remove patch-${letter}.mpq`, e);
|
||||
}
|
||||
}
|
||||
|
||||
// clear the stale tracking keys
|
||||
if (Preferences.data.localePatchLetter || Preferences.data.localePatchLocale)
|
||||
Preferences.data = {
|
||||
localePatchLetter: undefined,
|
||||
localePatchLocale: undefined
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,665 @@
|
||||
import path from 'path';
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
import fs from 'fs-extra';
|
||||
import fetch from 'node-fetch';
|
||||
import AdmZip from 'adm-zip';
|
||||
import * as tar from 'tar';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import {
|
||||
MODS,
|
||||
DEFAULT_ENABLED_MODS,
|
||||
type ModEntry,
|
||||
type ModId,
|
||||
getMod
|
||||
} from '~common/mods';
|
||||
import { type ModState } from '~common/schemas';
|
||||
|
||||
import Preferences from './preferences';
|
||||
import { isTorrentMode } from './aria2';
|
||||
import Observable from './observable';
|
||||
import Updater from './updater';
|
||||
import { addDll, removeDll, listDlls } from './dllsTxt';
|
||||
import { enumerateDisplays } from './displays';
|
||||
|
||||
const MOD_DOWNLOAD_TIMEOUT_MS = 60_000;
|
||||
|
||||
/** Files a mod installs on disk. */
|
||||
const modTargetFiles = (m: ModEntry): string[] => {
|
||||
if (m.source.kind === 'directFile') return [m.source.assetName];
|
||||
if (m.source.kind === 'archive') return Object.values(m.source.extractMap);
|
||||
return [];
|
||||
};
|
||||
|
||||
// client-shipped DLLs that aren't injectable mods; not counted as custom mods
|
||||
const RESERVED_DLLS = new Set([
|
||||
'ace.dll',
|
||||
'divxdecoder.dll',
|
||||
'discordoverlay.dll',
|
||||
'discord_game_sdk.dll',
|
||||
'dbghelp.dll',
|
||||
'fmod.dll',
|
||||
'ijl15.dll',
|
||||
'sdl.dll',
|
||||
'scan.dll',
|
||||
'unicows.dll',
|
||||
'zlib1.dll'
|
||||
]);
|
||||
|
||||
// files owned by an active built-in mod; a disabled mod's files are fair game to add by hand
|
||||
const KNOWN_DLLS = new Set(
|
||||
MODS.filter(m => !m.disabled)
|
||||
.flatMap(m => [m.registerInDllsTxt, ...modTargetFiles(m)])
|
||||
.filter((f): f is string => !!f)
|
||||
.map(f => f.toLowerCase())
|
||||
);
|
||||
|
||||
const AV_ERROR =
|
||||
'Windows Defender blocked this download. Use "Allow through antivirus" and apply again.';
|
||||
|
||||
const looksLikeAvBlock = (msg: string) =>
|
||||
/windows defender|virus|potentially unwanted/i.test(msg);
|
||||
|
||||
export type ModRowStatus = {
|
||||
id: ModId;
|
||||
name: string;
|
||||
description: string;
|
||||
repoUrl: string;
|
||||
recommended: boolean;
|
||||
requires: ModId[];
|
||||
enabled: boolean;
|
||||
ignoreUpdates: boolean;
|
||||
installedVersion?: string;
|
||||
latestVersion: string;
|
||||
state: 'idle' | 'downloading' | 'installing' | 'uninstalling' | 'error';
|
||||
progress?: number;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type CustomMod = { name: string; enabled: boolean };
|
||||
|
||||
export type ModsStatus = {
|
||||
state: 'verifying' | 'idle' | 'busy';
|
||||
dirty: boolean;
|
||||
mods: ModRowStatus[];
|
||||
custom: CustomMod[];
|
||||
// enabled mods whose files are missing (AV quarantine or incomplete sync)
|
||||
missingFiles: string[];
|
||||
};
|
||||
|
||||
class ModsClass extends Observable<ModsStatus> {
|
||||
protected _value: ModsStatus = {
|
||||
state: 'verifying',
|
||||
dirty: false,
|
||||
mods: [],
|
||||
custom: [],
|
||||
missingFiles: []
|
||||
};
|
||||
|
||||
// staged custom-DLL toggles, keyed lower-case; #customApplied mirrors dlls.txt
|
||||
#customDesired = new Map<string, boolean>();
|
||||
#customApplied = new Map<string, boolean>();
|
||||
#customNames = new Map<string, string>();
|
||||
|
||||
get status(): ModsStatus {
|
||||
return this._value;
|
||||
}
|
||||
|
||||
#initialRow(m: ModEntry): ModRowStatus {
|
||||
const state = Preferences.data?.mods?.[m.id];
|
||||
return {
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
description: m.description,
|
||||
repoUrl: m.repoUrl,
|
||||
recommended: !!m.recommended,
|
||||
requires: m.requires ?? [],
|
||||
enabled: !!state?.enabled,
|
||||
ignoreUpdates: !!state?.ignoreUpdates,
|
||||
installedVersion: state?.installedVersion,
|
||||
latestVersion: m.version,
|
||||
state: 'idle'
|
||||
};
|
||||
}
|
||||
|
||||
#patchRow(id: ModId, patch: Partial<ModRowStatus>) {
|
||||
this._value = {
|
||||
...this._value,
|
||||
mods: this._value.mods.map(r => (r.id === id ? { ...r, ...patch } : r))
|
||||
};
|
||||
this._value = { ...this._value, dirty: this.#computeDirty() };
|
||||
this._notifyObservers();
|
||||
}
|
||||
|
||||
#computeDirty(): boolean {
|
||||
if (this.#customDesired.size > 0) return true;
|
||||
return this._value.mods.some(r => {
|
||||
const wantInstalled = r.enabled;
|
||||
const isInstalled = !!r.installedVersion;
|
||||
if (wantInstalled !== isInstalled) return true;
|
||||
if (
|
||||
r.installedVersion &&
|
||||
r.installedVersion !== r.latestVersion &&
|
||||
!r.ignoreUpdates
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
load() {
|
||||
this._value = {
|
||||
state: 'verifying',
|
||||
dirty: false,
|
||||
mods: MODS.filter(m => !m.disabled).map(m => this.#initialRow(m)),
|
||||
custom: this._value.custom,
|
||||
missingFiles: []
|
||||
};
|
||||
}
|
||||
|
||||
// DLLs in the client dir we neither ship nor own
|
||||
async #detectCustomDlls(clientDir: string): Promise<CustomMod[]> {
|
||||
const inDllsTxt = await listDlls(clientDir);
|
||||
const enabled = new Set(inDllsTxt.map(n => n.toLowerCase()));
|
||||
const found = new Map<string, string>();
|
||||
const consider = (name: string) => {
|
||||
const lc = name.toLowerCase();
|
||||
if (RESERVED_DLLS.has(lc) || KNOWN_DLLS.has(lc) || found.has(lc)) return;
|
||||
found.set(lc, name);
|
||||
};
|
||||
for (const f of await fs.readdir(clientDir).catch(() => [] as string[]))
|
||||
if (/\.dll$/i.test(f)) consider(f);
|
||||
inDllsTxt.forEach(consider);
|
||||
const names = [...found.values()].sort((a, b) => a.localeCompare(b));
|
||||
this.#customApplied = new Map(
|
||||
names.map(n => [n.toLowerCase(), enabled.has(n.toLowerCase())])
|
||||
);
|
||||
this.#customNames = new Map(names.map(n => [n.toLowerCase(), n]));
|
||||
// drop staged changes for DLLs no longer present
|
||||
const present = new Set(names.map(n => n.toLowerCase()));
|
||||
for (const lc of [...this.#customDesired.keys()])
|
||||
if (!present.has(lc)) this.#customDesired.delete(lc);
|
||||
return names.map(name => {
|
||||
const lc = name.toLowerCase();
|
||||
return {
|
||||
name,
|
||||
enabled: this.#customDesired.has(lc)
|
||||
? !!this.#customDesired.get(lc)
|
||||
: !!this.#customApplied.get(lc)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// flush staged custom-DLL changes to dlls.txt; a failed write stays staged (still pending)
|
||||
async #applyCustomDlls(clientDir: string) {
|
||||
for (const [lc, enabled] of [...this.#customDesired]) {
|
||||
const name = this.#customNames.get(lc) ?? lc;
|
||||
try {
|
||||
await (enabled ? addDll(clientDir, name) : removeDll(clientDir, name));
|
||||
this.#customDesired.delete(lc);
|
||||
} catch (e) {
|
||||
Logger.warn(`custom dll apply failed for ${name}`, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #syncPreferredMonitor(clientDir: string) {
|
||||
const vmmfDll = path.join(clientDir, 'VanillaMultiMonitorFix.dll');
|
||||
if (!(await fs.pathExists(vmmfDll))) return;
|
||||
|
||||
const vmmfCfg = path.join(clientDir, 'VMMFix_preferred_monitor.txt');
|
||||
const existsCfg = await fs.pathExists(vmmfCfg);
|
||||
const current = existsCfg
|
||||
? Number(
|
||||
await fs
|
||||
.readFile(vmmfCfg, 'utf8')
|
||||
.then(s => s.trim())
|
||||
.catch(() => '')
|
||||
)
|
||||
: NaN;
|
||||
const hasCurrent = Number.isInteger(current);
|
||||
const ours = Preferences.data?.vmmfWrittenIndex;
|
||||
|
||||
const devices = await enumerateDisplays();
|
||||
const usable = devices?.filter(d => d.attached && d.width > 0);
|
||||
if (!devices || !usable?.length) {
|
||||
Logger.warn('Could not enumerate displays; preferred monitor unchanged');
|
||||
return;
|
||||
}
|
||||
const primary = usable.find(d => d.primary) ?? usable[0];
|
||||
|
||||
if (hasCurrent && ours === undefined) {
|
||||
const pinned = devices.find(d => d.index === current);
|
||||
const broken = !pinned || !pinned.attached || !pinned.primary;
|
||||
if (!broken) {
|
||||
Preferences.data = { vmmfWrittenIndex: current };
|
||||
Logger.info(`Adopting existing preferred monitor ${current} as chosen`);
|
||||
return;
|
||||
}
|
||||
Logger.warn(
|
||||
`Preferred monitor ${current} (${
|
||||
pinned ? pinned.deviceName : 'missing'
|
||||
}) is ${
|
||||
!pinned || !pinned.attached
|
||||
? 'not attached'
|
||||
: 'not the primary display'
|
||||
}; healing to ${primary.index}`
|
||||
);
|
||||
} else if (hasCurrent && current !== ours) {
|
||||
Logger.info(
|
||||
`Preferred monitor ${current} was set manually; leaving it alone`
|
||||
);
|
||||
Preferences.data = { vmmfWrittenIndex: current };
|
||||
return;
|
||||
} else if (hasCurrent && current === primary.index) {
|
||||
return;
|
||||
}
|
||||
|
||||
await fs
|
||||
.writeFile(vmmfCfg, `${primary.index}\n`, 'utf8')
|
||||
.then(() => {
|
||||
Preferences.data = { vmmfWrittenIndex: primary.index };
|
||||
Logger.info(
|
||||
`Preferred monitor set to ${primary.index} (${primary.deviceName} ${primary.width}x${primary.height})`
|
||||
);
|
||||
})
|
||||
.catch(e => Logger.warn('Failed to write preferred monitor', e));
|
||||
}
|
||||
|
||||
async verify() {
|
||||
this.load();
|
||||
this._notifyObservers();
|
||||
|
||||
const clientDir = Preferences.data?.clientDir;
|
||||
|
||||
if (clientDir) {
|
||||
await this.#syncPreferredMonitor(clientDir);
|
||||
}
|
||||
|
||||
const missing: string[] = [];
|
||||
for (const m of MODS) {
|
||||
// disabled mods: leave dlls.txt and installed state untouched
|
||||
if (m.disabled) continue;
|
||||
|
||||
const state = Preferences.data?.mods?.[m.id];
|
||||
let installedVersion = state?.installedVersion;
|
||||
|
||||
// torrent mode: DLLs ship in the client; a missing file goes to `missing`, not dirty
|
||||
if (isTorrentMode()) {
|
||||
const files = modTargetFiles(m);
|
||||
const present =
|
||||
!!clientDir &&
|
||||
files.length > 0 &&
|
||||
(
|
||||
await Promise.all(
|
||||
files.map(rel => fs.pathExists(path.join(clientDir, rel)))
|
||||
)
|
||||
).every(Boolean);
|
||||
const enabled = state?.enabled ?? DEFAULT_ENABLED_MODS.includes(m.id);
|
||||
installedVersion = enabled ? m.version : undefined;
|
||||
if (enabled && files.length > 0 && !present) missing.push(m.name);
|
||||
// only point dlls.txt at a file actually on disk
|
||||
if (clientDir && m.registerInDllsTxt)
|
||||
await (present && enabled
|
||||
? addDll(clientDir, m.registerInDllsTxt)
|
||||
: removeDll(clientDir, m.registerInDllsTxt)
|
||||
).catch(e => Logger.warn(`dlls.txt update failed for ${m.id}`, e));
|
||||
this.#patchRow(m.id, {
|
||||
installedVersion,
|
||||
latestVersion: m.version,
|
||||
enabled,
|
||||
ignoreUpdates: true
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (clientDir && installedVersion) {
|
||||
const filesPresent = await Promise.all(
|
||||
(state?.installedFiles ?? []).map(rel =>
|
||||
fs.pathExists(path.join(clientDir, rel))
|
||||
)
|
||||
);
|
||||
if (state?.installedFiles?.length && !filesPresent.every(Boolean)) {
|
||||
installedVersion = undefined;
|
||||
await this.#savePref(m.id, {
|
||||
enabled: state?.enabled ?? false,
|
||||
installedVersion: undefined,
|
||||
installedFiles: [],
|
||||
ignoreUpdates: state?.ignoreUpdates ?? false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (clientDir && m.registerInDllsTxt)
|
||||
await (installedVersion
|
||||
? addDll(clientDir, m.registerInDllsTxt)
|
||||
: removeDll(clientDir, m.registerInDllsTxt)
|
||||
).catch(() => {});
|
||||
|
||||
this.#patchRow(m.id, {
|
||||
installedVersion,
|
||||
latestVersion: m.version,
|
||||
enabled: !!state?.enabled,
|
||||
ignoreUpdates: !!state?.ignoreUpdates
|
||||
});
|
||||
}
|
||||
|
||||
this._value = {
|
||||
...this._value,
|
||||
state: 'idle',
|
||||
dirty: this.#computeDirty(),
|
||||
custom: clientDir ? await this.#detectCustomDlls(clientDir) : [],
|
||||
missingFiles: missing
|
||||
};
|
||||
this._notifyObservers();
|
||||
}
|
||||
|
||||
async toggleCustom(name: string, enabled: boolean) {
|
||||
const clientDir = Preferences.data?.clientDir;
|
||||
if (!clientDir) return;
|
||||
// stage; matching dlls.txt clears the pending change
|
||||
const lc = name.toLowerCase();
|
||||
if (enabled === !!this.#customApplied.get(lc))
|
||||
this.#customDesired.delete(lc);
|
||||
else this.#customDesired.set(lc, enabled);
|
||||
this._value = {
|
||||
...this._value,
|
||||
custom: await this.#detectCustomDlls(clientDir)
|
||||
};
|
||||
this._value = { ...this._value, dirty: this.#computeDirty() };
|
||||
this._notifyObservers();
|
||||
}
|
||||
|
||||
async addCustomDll(
|
||||
srcPath: string
|
||||
): Promise<{ ok: boolean; error?: string }> {
|
||||
const clientDir = Preferences.data?.clientDir;
|
||||
if (!clientDir) return { ok: false, error: 'No game folder is set.' };
|
||||
const name = path.basename(srcPath);
|
||||
if (!/\.dll$/i.test(name))
|
||||
return { ok: false, error: 'Please choose a .dll file.' };
|
||||
const lc = name.toLowerCase();
|
||||
if (RESERVED_DLLS.has(lc) || KNOWN_DLLS.has(lc))
|
||||
return {
|
||||
ok: false,
|
||||
error: `${name} is a built-in file and can't be added as a custom mod.`
|
||||
};
|
||||
try {
|
||||
const dest = path.join(clientDir, name);
|
||||
if (path.resolve(srcPath) !== path.resolve(dest))
|
||||
await fs.copy(srcPath, dest, { overwrite: true });
|
||||
} catch (e) {
|
||||
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
||||
}
|
||||
// stage enabled; Apply writes dlls.txt
|
||||
this.#customDesired.set(name.toLowerCase(), true);
|
||||
this._value = {
|
||||
...this._value,
|
||||
custom: await this.#detectCustomDlls(clientDir)
|
||||
};
|
||||
this._value = { ...this._value, dirty: this.#computeDirty() };
|
||||
this._notifyObservers();
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async toggle(id: ModId, enabled: boolean) {
|
||||
const cur = Preferences.data?.mods?.[id];
|
||||
await this.#savePref(id, {
|
||||
enabled,
|
||||
installedVersion: cur?.installedVersion,
|
||||
installedFiles: cur?.installedFiles ?? [],
|
||||
ignoreUpdates: cur?.ignoreUpdates ?? false
|
||||
});
|
||||
this.#patchRow(id, { enabled });
|
||||
}
|
||||
|
||||
async setIgnoreUpdates(id: ModId, ignore: boolean) {
|
||||
const cur = Preferences.data?.mods?.[id];
|
||||
await this.#savePref(id, {
|
||||
enabled: cur?.enabled ?? false,
|
||||
installedVersion: cur?.installedVersion,
|
||||
installedFiles: cur?.installedFiles ?? [],
|
||||
ignoreUpdates: ignore
|
||||
});
|
||||
this.#patchRow(id, { ignoreUpdates: ignore });
|
||||
}
|
||||
|
||||
async applyAll(opts: { repairOnly?: boolean } = {}) {
|
||||
const clientDir = Preferences.data?.clientDir;
|
||||
if (!clientDir) {
|
||||
Logger.warn('No clientDir set; cannot apply mods.');
|
||||
return;
|
||||
}
|
||||
// don't commit a mod set with an unmet dependency; dirty stays set. repair is exempt.
|
||||
if (!opts.repairOnly) {
|
||||
const enabledIds = new Set(
|
||||
this._value.mods.filter(r => r.enabled).map(r => r.id)
|
||||
);
|
||||
const missingDeps = [
|
||||
...new Set(
|
||||
this._value.mods
|
||||
.filter(r => r.enabled)
|
||||
.flatMap(r => r.requires.filter(dep => !enabledIds.has(dep)))
|
||||
)
|
||||
];
|
||||
if (missingDeps.length) {
|
||||
Logger.warn(
|
||||
`Not applying mods: unmet dependencies ${missingDeps.join(', ')}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// commit the player's own DLL toggles first
|
||||
await this.#applyCustomDlls(clientDir);
|
||||
// torrent mode: mods ship in the client; just reconcile dlls.txt
|
||||
if (isTorrentMode()) {
|
||||
await this.verify();
|
||||
return;
|
||||
}
|
||||
if (this._value.state === 'busy') {
|
||||
Logger.warn('applyAll already running; ignoring re-entrant call.');
|
||||
return;
|
||||
}
|
||||
await this.verify();
|
||||
this._value = { ...this._value, state: 'busy' };
|
||||
this._notifyObservers();
|
||||
|
||||
const queue = [...this._value.mods];
|
||||
queue.sort((a, b) => {
|
||||
if (a.id === 'vanillaFixes') return -1;
|
||||
if (b.id === 'vanillaFixes') return 1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
const failures = new Map<ModId, string>();
|
||||
for (const row of queue) {
|
||||
const m = getMod(row.id);
|
||||
if (!m) continue;
|
||||
|
||||
const wantInstalled = row.enabled;
|
||||
const isInstalled = !!row.installedVersion;
|
||||
const updateAvailable =
|
||||
isInstalled &&
|
||||
row.installedVersion !== row.latestVersion &&
|
||||
!row.ignoreUpdates;
|
||||
|
||||
try {
|
||||
if (wantInstalled && !isInstalled) {
|
||||
await this.#install(m);
|
||||
} else if (!wantInstalled && isInstalled) {
|
||||
await this.#uninstall(m);
|
||||
} else if (wantInstalled && updateAvailable && !opts.repairOnly) {
|
||||
await this.#uninstall(m);
|
||||
await this.#install(m);
|
||||
}
|
||||
} catch (e) {
|
||||
Logger.error(`Failed to apply ${m.id}:`, e);
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
failures.set(m.id, looksLikeAvBlock(msg) ? AV_ERROR : msg);
|
||||
}
|
||||
}
|
||||
|
||||
this._value = { ...this._value, state: 'idle' };
|
||||
await this.verify();
|
||||
for (const [id, error] of failures)
|
||||
this.#patchRow(id, { state: 'error', error });
|
||||
await Updater.verify();
|
||||
}
|
||||
|
||||
async #install(m: ModEntry) {
|
||||
// In torrent mode the mod binaries ship with the client; nothing is fetched.
|
||||
if (isTorrentMode()) return;
|
||||
const clientDir = Preferences.data?.clientDir;
|
||||
if (!clientDir) throw new Error('No client dir');
|
||||
if (m.source.kind === 'managed') return;
|
||||
|
||||
Logger.info(`Installing mod ${m.id}...`);
|
||||
this.#patchRow(m.id, {
|
||||
state: 'downloading',
|
||||
progress: 0,
|
||||
error: undefined
|
||||
});
|
||||
|
||||
const written: string[] = [];
|
||||
const missing: string[] = [];
|
||||
|
||||
if (m.source.kind === 'directFile') {
|
||||
const dest = path.join(clientDir, m.source.assetName);
|
||||
await this.#downloadTo(m.source.url, dest, m.source.sha256);
|
||||
written.push(m.source.assetName);
|
||||
} else if (m.source.kind === 'archive') {
|
||||
const scratch = path.join(clientDir, '.octolauncher-tmp');
|
||||
await fs.ensureDir(scratch);
|
||||
const tmp = path.join(
|
||||
scratch,
|
||||
`${m.id}-${Date.now()}.${m.source.format}`
|
||||
);
|
||||
await this.#downloadTo(m.source.url, tmp, m.source.sha256);
|
||||
this.#patchRow(m.id, { state: 'installing' });
|
||||
|
||||
const map = m.source.extractMap;
|
||||
if (m.source.format === 'zip') {
|
||||
const zip = new AdmZip(tmp);
|
||||
const entries = zip.getEntries();
|
||||
for (const [src, dst] of Object.entries(map)) {
|
||||
const entry = entries.find(e => e.entryName === src);
|
||||
if (!entry) {
|
||||
missing.push(src);
|
||||
continue;
|
||||
}
|
||||
const target = path.join(clientDir, dst);
|
||||
await fs.ensureDir(path.dirname(target));
|
||||
await fs.writeFile(target, entry.getData());
|
||||
written.push(dst);
|
||||
}
|
||||
} else {
|
||||
const stagingDir = path.join(scratch, `${m.id}-${Date.now()}-extract`);
|
||||
await fs.ensureDir(stagingDir);
|
||||
await tar.x({ file: tmp, cwd: stagingDir });
|
||||
for (const [src, dst] of Object.entries(map)) {
|
||||
const srcPath = path.join(stagingDir, src);
|
||||
if (!(await fs.pathExists(srcPath))) {
|
||||
missing.push(src);
|
||||
continue;
|
||||
}
|
||||
const target = path.join(clientDir, dst);
|
||||
await fs.ensureDir(path.dirname(target));
|
||||
await fs.copy(srcPath, target);
|
||||
written.push(dst);
|
||||
}
|
||||
await fs.remove(stagingDir).catch(() => {});
|
||||
}
|
||||
await fs.remove(tmp).catch(() => {});
|
||||
}
|
||||
|
||||
if (missing.length)
|
||||
throw new Error(
|
||||
`${m.name}: download is missing expected file(s): ${missing.join(', ')}`
|
||||
);
|
||||
|
||||
if (m.registerInDllsTxt) {
|
||||
await addDll(clientDir, m.registerInDllsTxt);
|
||||
}
|
||||
|
||||
await this.#savePref(m.id, {
|
||||
enabled: true,
|
||||
installedVersion: m.version,
|
||||
installedFiles: written,
|
||||
ignoreUpdates: Preferences.data?.mods?.[m.id]?.ignoreUpdates ?? false
|
||||
});
|
||||
|
||||
this.#patchRow(m.id, {
|
||||
state: 'idle',
|
||||
installedVersion: m.version,
|
||||
progress: 1
|
||||
});
|
||||
}
|
||||
|
||||
async #uninstall(m: ModEntry) {
|
||||
const clientDir = Preferences.data?.clientDir;
|
||||
if (!clientDir) throw new Error('No client dir');
|
||||
if (m.source.kind === 'managed') return;
|
||||
|
||||
Logger.info(`Uninstalling mod ${m.id}...`);
|
||||
this.#patchRow(m.id, { state: 'uninstalling', error: undefined });
|
||||
|
||||
const cur = Preferences.data?.mods?.[m.id];
|
||||
const files = cur?.installedFiles ?? [];
|
||||
|
||||
for (const rel of files) {
|
||||
const fullPath = path.join(clientDir, rel);
|
||||
await fs
|
||||
.remove(fullPath)
|
||||
.catch(err => Logger.warn(`Couldn't remove ${fullPath}:`, err));
|
||||
}
|
||||
|
||||
if (m.registerInDllsTxt) {
|
||||
await removeDll(clientDir, m.registerInDllsTxt);
|
||||
}
|
||||
|
||||
await this.#savePref(m.id, {
|
||||
enabled: cur?.enabled ?? false,
|
||||
installedVersion: undefined,
|
||||
installedFiles: [],
|
||||
ignoreUpdates: cur?.ignoreUpdates ?? false
|
||||
});
|
||||
|
||||
this.#patchRow(m.id, { state: 'idle', installedVersion: undefined });
|
||||
}
|
||||
|
||||
async #downloadTo(url: string, dest: string, sha256?: string) {
|
||||
const res = await fetch(url, {
|
||||
headers: { 'User-Agent': 'OctoLauncher' },
|
||||
timeout: MOD_DOWNLOAD_TIMEOUT_MS
|
||||
});
|
||||
if (!res.ok) throw new Error(`Download failed ${res.status}: ${url}`);
|
||||
await fs.ensureDir(path.dirname(dest));
|
||||
const buf = await res.arrayBuffer();
|
||||
|
||||
if (sha256) {
|
||||
const got = createHash('sha256').update(Buffer.from(buf)).digest('hex');
|
||||
if (got !== sha256.toLowerCase())
|
||||
throw new Error(
|
||||
`Checksum mismatch for ${path.basename(
|
||||
dest
|
||||
)}: expected ${sha256}, got ${got}. Refusing to install.`
|
||||
);
|
||||
}
|
||||
|
||||
await fs.writeFile(dest, Buffer.from(buf));
|
||||
if (!(await fs.pathExists(dest)))
|
||||
throw new Error(
|
||||
`Downloaded file disappeared after writing: ${path.basename(dest)}. ` +
|
||||
'This is often Windows Defender quarantine; if so, use "Allow through antivirus" and apply again.'
|
||||
);
|
||||
}
|
||||
|
||||
async #savePref(id: ModId, state: ModState) {
|
||||
const allMods = { ...(Preferences.data?.mods ?? {}), [id]: state };
|
||||
Preferences.data = { mods: allMods };
|
||||
}
|
||||
}
|
||||
|
||||
const Mods = new ModsClass();
|
||||
export default Mods;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { observable } from '@trpc/server/observable';
|
||||
|
||||
type Func<T> = (arg: T) => void;
|
||||
|
||||
abstract class Observable<T> {
|
||||
private _listeners: Func<T>[] = [];
|
||||
|
||||
protected abstract _value: T;
|
||||
|
||||
protected _notifyObservers(v = this._value) {
|
||||
this._listeners = this._listeners.filter(l => {
|
||||
try {
|
||||
l(v);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('Observer threw, removing listener', err);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
observe() {
|
||||
return observable<T>(e => {
|
||||
e.next(this._value);
|
||||
this._listeners.push(e.next);
|
||||
return () => {
|
||||
this._listeners = this._listeners.filter(v => v !== e.next);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
clearObservers() {
|
||||
this._listeners = [];
|
||||
}
|
||||
}
|
||||
|
||||
export default Observable;
|
||||
@@ -0,0 +1,467 @@
|
||||
import path from 'path';
|
||||
|
||||
import { screen } from 'electron';
|
||||
import fs from 'fs-extra';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import Preferences from '~main/modules/preferences';
|
||||
import { ConfigWtfSchema, type PreferencesSchema } from '~common/schemas';
|
||||
import { isNotUndef } from '~common/utils';
|
||||
import { readPristineWow } from '~main/modules/aria2';
|
||||
import { enumerateDisplays } from '~main/modules/displays';
|
||||
|
||||
const Servers = {
|
||||
live: {
|
||||
realmList: 'octowow.st',
|
||||
patchList: 'octowow.st',
|
||||
realmName: 'OctoWoW'
|
||||
},
|
||||
ptr: {
|
||||
realmList: import.meta.env.MAIN_VITE_PTR_REALMLIST || 'octowow.st',
|
||||
patchList: import.meta.env.MAIN_VITE_PTR_REALMLIST || 'octowow.st',
|
||||
realmName: 'OctoWoW PTR'
|
||||
}
|
||||
} as const;
|
||||
|
||||
const LOCALES = {
|
||||
enUS: { tag: 'enUS', index: 0 },
|
||||
deDE: { tag: 'deDE', index: 3 },
|
||||
zhCN: { tag: 'zhCN', index: 4 },
|
||||
ruRU: { tag: 'ruRU', index: 5 },
|
||||
esES: { tag: 'esES', index: 6 },
|
||||
ptBR: { tag: 'ptBR', index: 7 }
|
||||
} as const satisfies Record<
|
||||
PreferencesSchema['locale'],
|
||||
{ tag: string; index: number }
|
||||
>;
|
||||
|
||||
const LOCALE_NAMES = [
|
||||
'enUS',
|
||||
'koKR',
|
||||
'frFR',
|
||||
'deDE',
|
||||
'zhCN',
|
||||
'zhTW',
|
||||
'esES',
|
||||
'xxYY'
|
||||
] as const;
|
||||
|
||||
const localeNameOffset = (index: number) => 0x45591c - index * 8;
|
||||
|
||||
const carrierName = (index: number) => LOCALE_NAMES[index];
|
||||
|
||||
type TweakKey =
|
||||
| { synthetic?: false; key: keyof PreferencesSchema['config'] }
|
||||
| { synthetic: true; key: string };
|
||||
|
||||
type Tweak = TweakKey & {
|
||||
default?: unknown;
|
||||
forced?: boolean;
|
||||
} & (
|
||||
| {
|
||||
type: 'bytes';
|
||||
tweaks: [number, number[], number[]?][];
|
||||
}
|
||||
| {
|
||||
type: 'int8' | 'uint16' | 'float';
|
||||
offset: number;
|
||||
value?: number;
|
||||
}
|
||||
);
|
||||
|
||||
const hex = (bytes: number[]) =>
|
||||
bytes.map(b => b.toString(16).padStart(2, '0')).join(' ');
|
||||
|
||||
export const patchExecutable = async () => {
|
||||
Logger.log('Patching WoW.exe...');
|
||||
|
||||
const { clientDir, config, locale } = Preferences.data;
|
||||
if (!clientDir) return;
|
||||
const exePath = path.join(clientDir, 'WoW.exe');
|
||||
|
||||
try {
|
||||
Logger.log('Reading clean WoW.exe base...');
|
||||
const buffer = await readPristineWow(clientDir);
|
||||
|
||||
const loc = LOCALES[locale];
|
||||
|
||||
const Tweaks = [
|
||||
{
|
||||
key: 'largeAddress',
|
||||
type: 'uint16',
|
||||
offset: 0x126,
|
||||
value: buffer.readUint16LE(0x126) | 0x20,
|
||||
default: false
|
||||
},
|
||||
{ key: 'farClip', type: 'float', offset: 0x40fed8 },
|
||||
{
|
||||
key: 'fieldOfView',
|
||||
type: 'float',
|
||||
offset: 0x4089b4,
|
||||
value: (config.fieldOfView ?? 1) * (Math.PI / 180),
|
||||
default: 90
|
||||
},
|
||||
{ key: 'frillDistance', type: 'float', offset: 0x467958 },
|
||||
{
|
||||
key: 'soundInBackground',
|
||||
type: 'int8',
|
||||
offset: 0x3a4869,
|
||||
value: config.soundInBackground ? 0x27 : 0x14,
|
||||
default: false
|
||||
},
|
||||
{
|
||||
key: 'alwaysAutoLoot',
|
||||
type: 'bytes',
|
||||
tweaks: [
|
||||
[0x0c1ecf, [0x75]],
|
||||
[0x0c2b25, [0x75]]
|
||||
]
|
||||
},
|
||||
{ key: 'nameplateRange', type: 'float', offset: 0x40c448 },
|
||||
{ key: 'cameraDistance', type: 'float', offset: 0x4089a4 },
|
||||
{
|
||||
synthetic: true,
|
||||
key: 'skillUiGateHijack',
|
||||
type: 'bytes',
|
||||
default: true,
|
||||
forced: true,
|
||||
tweaks: [
|
||||
[
|
||||
0x002ddf90,
|
||||
[
|
||||
0x55, 0x8b, 0xec, 0x83, 0xec, 0x08, 0x53, 0x56, 0x57, 0x8b, 0x3d,
|
||||
0x60, 0xab, 0xce, 0x00, 0x83, 0xff, 0xff, 0x89, 0x55, 0xfc, 0x89,
|
||||
0x4d, 0xf8, 0x74, 0x79, 0x8b, 0x75, 0x08, 0x8b, 0x15, 0x58, 0xab,
|
||||
0xce, 0x00, 0x8b, 0xc7, 0x23, 0xc6, 0x8d, 0x04, 0x40, 0x8b, 0x4c,
|
||||
0x82, 0x08, 0xf6, 0xc1, 0x01, 0x8d, 0x44, 0x82, 0x04, 0x75, 0x04,
|
||||
0x85, 0xc9, 0x75, 0x05, 0x33, 0xc9, 0x8d, 0x49, 0x00, 0xf6, 0xc1,
|
||||
0x01, 0x75, 0x4e, 0x85, 0xc9, 0x74, 0x4a, 0x39, 0x31, 0x74, 0x13,
|
||||
0x8b, 0xc7, 0x23, 0xc6, 0x8d, 0x04, 0x40, 0x8d, 0x04, 0x82, 0x8b,
|
||||
0x00, 0x03, 0xc1, 0x8b, 0x48, 0x04, 0xeb, 0xe0, 0x8b, 0x59, 0x1c,
|
||||
0x8b, 0x71, 0x18, 0x33, 0xff, 0x85, 0xdb, 0x7e, 0x27, 0x8d, 0x64,
|
||||
0x24, 0x00, 0x8b, 0x4e, 0x0c, 0x8b, 0x56, 0x08, 0x6a, 0x00, 0x6a,
|
||||
0x00, 0x51, 0x8b, 0x4d, 0xf8, 0x52, 0x8b, 0x55, 0xfc, 0xe8, 0xb9,
|
||||
0xfd, 0xff, 0xff, 0x84, 0xc0, 0x75, 0x13, 0x47, 0x83, 0xc6, 0x20,
|
||||
0x3b, 0xfb, 0x7c, 0xdd, 0x5f, 0x5e, 0x33, 0xc0, 0x5b, 0x8b, 0xe5,
|
||||
0x5d, 0xc2, 0x04, 0x00, 0x5f, 0x8b, 0xc6, 0x5e, 0x5b, 0x8b, 0xe5,
|
||||
0x5d, 0xc2, 0x04, 0x00, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90
|
||||
]
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
synthetic: true,
|
||||
key: 'octowowUrlAllowlist',
|
||||
type: 'bytes',
|
||||
default: true,
|
||||
forced: true,
|
||||
tweaks: [
|
||||
[
|
||||
0x45ccd8,
|
||||
[
|
||||
0x6f, 0x63, 0x74, 0x6f, 0x77, 0x6f, 0x77, 0x2e, 0x73, 0x74, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00
|
||||
]
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
synthetic: true,
|
||||
key: 'localeTag',
|
||||
type: 'bytes',
|
||||
default: true,
|
||||
forced: true,
|
||||
tweaks: [
|
||||
[
|
||||
0x1b2115,
|
||||
[0xb8, ...Buffer.from(carrierName(loc.index), 'latin1').reverse()],
|
||||
[0xa1, 0xa4, 0xa2, 0xc2, 0x00]
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
synthetic: true,
|
||||
key: 'localeIndex',
|
||||
type: 'bytes',
|
||||
default: true,
|
||||
forced: true,
|
||||
tweaks: [
|
||||
[
|
||||
0x253c,
|
||||
[0xbe, loc.index, 0x00, 0x00, 0x00, 0xeb, 0x1f],
|
||||
[0x33, 0xf6, 0x8b, 0xff, 0x8b, 0x04, 0xb5]
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
synthetic: true,
|
||||
key: 'localeName',
|
||||
type: 'bytes',
|
||||
default: true,
|
||||
forced: true,
|
||||
tweaks: [
|
||||
[
|
||||
localeNameOffset(loc.index),
|
||||
[...Buffer.from(loc.tag, 'latin1')],
|
||||
[...Buffer.from(LOCALE_NAMES[loc.index], 'latin1')]
|
||||
]
|
||||
]
|
||||
}
|
||||
] satisfies Tweak[];
|
||||
|
||||
Tweaks.forEach(t => {
|
||||
const val = t.synthetic
|
||||
? t.default
|
||||
: config[t.key] ?? t.default ?? ConfigWtfSchema.parse({})[t.key];
|
||||
|
||||
Logger.log(`Applying "${t.key}" patch with value: ${val}`);
|
||||
if (t.type === 'float') {
|
||||
buffer.writeFloatLE(t.value ?? (val as number), t.offset);
|
||||
} else if (t.type === 'int8') {
|
||||
buffer.writeInt8(t.value ?? (val as number), t.offset);
|
||||
} else if (t.type === 'uint16') {
|
||||
if (!t.forced && !val) return;
|
||||
buffer.writeUInt16LE(t.value ?? (val as number), t.offset);
|
||||
} else if (t.type === 'bytes') {
|
||||
if (!t.forced && !val) return;
|
||||
t.tweaks.forEach(
|
||||
([offset, bytes, expect]: [number, number[], number[]?]) => {
|
||||
if (expect) {
|
||||
const current = buffer.subarray(offset, offset + expect.length);
|
||||
if (current.equals(Buffer.from(bytes))) return;
|
||||
if (!current.equals(Buffer.from(expect)))
|
||||
throw new Error(
|
||||
`"${t.key}" expected [${hex(expect)}] at 0x${offset.toString(
|
||||
16
|
||||
)} ` +
|
||||
`but found [${hex([
|
||||
...current
|
||||
])}]; refusing to patch WoW.exe`
|
||||
);
|
||||
}
|
||||
const written = Buffer.from(bytes).copy(buffer, offset);
|
||||
if (written !== bytes.length)
|
||||
Logger.error(
|
||||
`"${t.key}" wrote ${written}/${bytes.length} bytes at ` +
|
||||
`0x${offset.toString(16)}: past end of file (${
|
||||
buffer.length
|
||||
} bytes). ` +
|
||||
'This tweak is a no-op; the offset is probably a virtual address.'
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
await fs.writeFile(exePath, buffer);
|
||||
Preferences.data = { patchedLocale: locale };
|
||||
Logger.log(`WoW.exe successfully patched (language: ${locale})`);
|
||||
} catch (e) {
|
||||
Logger.error('Failed to patch WoW.exe', e);
|
||||
throw e instanceof Error ? e : new Error('Failed to patch WoW.exe');
|
||||
}
|
||||
};
|
||||
|
||||
const repairResolution = async (
|
||||
clientDir: string,
|
||||
current: string | undefined,
|
||||
lastWritten: string | undefined
|
||||
): Promise<{ gxResolution?: string }> => {
|
||||
const devices = await enumerateDisplays();
|
||||
if (!devices?.length) return {};
|
||||
|
||||
const pinnedRaw = await fs
|
||||
.readFile(path.join(clientDir, 'VMMFix_preferred_monitor.txt'), 'utf8')
|
||||
.then(s => s.trim())
|
||||
.catch(() => '');
|
||||
const pinned = pinnedRaw ? Number(pinnedRaw) : NaN;
|
||||
const target =
|
||||
devices.find(d => d.index === pinned && d.attached) ??
|
||||
devices.find(d => d.primary && d.attached);
|
||||
if (!target?.modes.length) return {};
|
||||
|
||||
const native = `${target.width}x${target.height}`;
|
||||
if (!target.modes.includes(native)) return {};
|
||||
|
||||
let owned = !current || current === lastWritten;
|
||||
|
||||
if (!owned && lastWritten === undefined && current) {
|
||||
const width = Number(current.split('x')[0]);
|
||||
if (Number.isFinite(width) && width * 2 < target.width) {
|
||||
Logger.warn(
|
||||
`gxResolution ${current} is far below ${target.deviceName}'s ${native} and predates resolution tracking; treating it as a client fallback`
|
||||
);
|
||||
owned = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!owned) return {};
|
||||
if (current === native) return {};
|
||||
|
||||
Logger.warn(
|
||||
`gxResolution ${current ?? '<unset>'} is launcher-owned; correcting to ${
|
||||
target.deviceName
|
||||
}'s ${native}`
|
||||
);
|
||||
return { gxResolution: native };
|
||||
};
|
||||
|
||||
const applyRealmlist = async (clientDir: string, host: string) => {
|
||||
const body = `set realmlist "${host}"\n`;
|
||||
const write = async (target: string) => {
|
||||
const tmp = `${target}.tmp`;
|
||||
try {
|
||||
await fs.writeFile(tmp, body);
|
||||
await fs.move(tmp, target, { overwrite: true });
|
||||
} catch (e) {
|
||||
await fs.remove(tmp).catch(() => undefined);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
await write(path.join(clientDir, 'realmlist.wtf'));
|
||||
const dataDir = path.join(clientDir, 'Data');
|
||||
if (await fs.pathExists(dataDir))
|
||||
for (const entry of await fs.readdir(dataDir)) {
|
||||
const scoped = path.join(dataDir, entry, 'realmlist.wtf');
|
||||
if (!(await fs.pathExists(scoped))) continue;
|
||||
try {
|
||||
await write(scoped);
|
||||
} catch (e) {
|
||||
Logger.warn(`Could not rewrite ${scoped}: ${String(e)}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const patchConfig = async (forceTweaks = false) => {
|
||||
const { clientDir, config, locale } = Preferences.data;
|
||||
if (!clientDir) return;
|
||||
|
||||
const server: keyof typeof Servers = import.meta.env.MAIN_VITE_PTR_REALMLIST
|
||||
? 'ptr'
|
||||
: 'live';
|
||||
|
||||
const configPath = path.join(clientDir, 'WTF', 'Config.wtf');
|
||||
await fs.ensureDir(path.dirname(configPath));
|
||||
const raw = (await fs.pathExists(configPath))
|
||||
? await fs.readFile(configPath, { encoding: 'utf-8' })
|
||||
: '';
|
||||
|
||||
const configWtf = Object.fromEntries(
|
||||
raw
|
||||
.split(/\r?\n/)
|
||||
.map(l => {
|
||||
const [, k, v] = l.match(/SET (\w+) "(.*)"/) ?? [];
|
||||
return !k || v === undefined ? undefined : [k, v];
|
||||
})
|
||||
.filter(isNotUndef)
|
||||
);
|
||||
|
||||
const isFirstRun = Object.keys(configWtf).length === 0;
|
||||
|
||||
const primaryDisplay = screen.getPrimaryDisplay();
|
||||
const scale = primaryDisplay.scaleFactor || 1;
|
||||
const width = Math.round(primaryDisplay.bounds.width * scale);
|
||||
const height = Math.round(primaryDisplay.bounds.height * scale);
|
||||
|
||||
const seededResolution = `${width}x${height}`;
|
||||
|
||||
const seed = isFirstRun
|
||||
? {
|
||||
scriptMemory: 512000,
|
||||
gxResolution: seededResolution,
|
||||
gxColorBits: primaryDisplay.colorDepth,
|
||||
gxDepthBits: primaryDisplay.colorDepth,
|
||||
gxRefresh: 60,
|
||||
gxMultisample: 8,
|
||||
gxMultisampleQuality: 0,
|
||||
gxTripleBuffer: 1,
|
||||
anisotropic: 16,
|
||||
frillDensity: 48,
|
||||
fullAlpha: 1,
|
||||
SmallCull: 0.01,
|
||||
DistCull: 888.8,
|
||||
shadowLevel: 0,
|
||||
trilinear: 1,
|
||||
specular: 1,
|
||||
pixelShaders: 1,
|
||||
M2UsePixelShaders: 1,
|
||||
M2UseShaders: 1,
|
||||
particleDensity: 1,
|
||||
unitDrawDist: 300,
|
||||
weatherDensity: 3,
|
||||
movieSubtitle: 1,
|
||||
minimapZoom: 0,
|
||||
minimapInsideZoom: 0,
|
||||
SoundZoneMusicNoDelay: 1,
|
||||
gxWindow: 1,
|
||||
gxMaximize: 1,
|
||||
gxCursor: 1,
|
||||
checkAddonVersion: 0,
|
||||
farClip: config.farClip,
|
||||
CameraDistanceMax: config.cameraDistance,
|
||||
patchList: Servers[server].patchList,
|
||||
realmName: Servers[server].realmName
|
||||
}
|
||||
: {};
|
||||
|
||||
const owned = {
|
||||
locale: carrierName(LOCALES[locale].index),
|
||||
patchList: configWtf['patchList'] ?? Servers[server].patchList,
|
||||
realmName: configWtf['realmName'] ?? Servers[server].realmName,
|
||||
hwDetect: 0,
|
||||
BackgroundSound: config.soundInBackground ? 1 : 0
|
||||
};
|
||||
|
||||
const repaired = await repairResolution(
|
||||
clientDir,
|
||||
configWtf['gxResolution'],
|
||||
Preferences.data.lastWrittenResolution
|
||||
);
|
||||
|
||||
const parsed = {
|
||||
...seed,
|
||||
...configWtf,
|
||||
...repaired,
|
||||
...owned,
|
||||
...(forceTweaks
|
||||
? { farClip: config.farClip, CameraDistanceMax: config.cameraDistance }
|
||||
: {})
|
||||
};
|
||||
|
||||
const body = Object.entries(parsed)
|
||||
.filter(v => v[1] !== undefined && v[1] !== null)
|
||||
.filter(([k]) => !/^realmlist$/i.test(k))
|
||||
.map(l => `SET ${l[0]} "${l[1]}"`)
|
||||
.join('\n');
|
||||
const tmpPath = `${configPath}.tmp`;
|
||||
await fs.writeFile(tmpPath, body);
|
||||
await fs.move(tmpPath, configPath, { overwrite: true });
|
||||
|
||||
await applyRealmlist(clientDir, Servers[server].realmList);
|
||||
|
||||
const chosen =
|
||||
repaired.gxResolution ?? (isFirstRun ? seededResolution : undefined);
|
||||
if (chosen && chosen !== Preferences.data.lastWrittenResolution)
|
||||
Preferences.data = { lastWrittenResolution: chosen };
|
||||
|
||||
Logger.log('Config.wtf successfully patched');
|
||||
};
|
||||
|
||||
export const ensureDxvkConf = async (clientDir: string) => {
|
||||
if (!(await fs.pathExists(path.join(clientDir, 'd3d9.dll')))) return;
|
||||
const confPath = path.join(clientDir, 'dxvk.conf');
|
||||
if (await fs.pathExists(confPath)) return;
|
||||
await fs.writeFile(
|
||||
confPath,
|
||||
[
|
||||
'# Cap the texture memory the 32-bit client believes it has so it cannot',
|
||||
'# over-commit its address space (the common DXVK out-of-memory crash).',
|
||||
'd3d9.maxAvailableMemory = 2048',
|
||||
'd3d9.maxFrameLatency = 1',
|
||||
'dxvk.numCompilerThreads = 2',
|
||||
'dxvk.logLevel = none',
|
||||
''
|
||||
].join('\n')
|
||||
);
|
||||
Logger.log('Wrote dxvk.conf');
|
||||
};
|
||||
@@ -0,0 +1,270 @@
|
||||
import path from 'path';
|
||||
|
||||
import fs from 'fs-extra';
|
||||
import { type z } from 'zod';
|
||||
import { app } from 'electron';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import { PreferencesSchema } from '~common/schemas';
|
||||
import { DEFAULT_ENABLED_MODS } from '~common/mods';
|
||||
import { omit } from '~common/utils';
|
||||
import { isTorrentMode } from '~main/modules/aria2';
|
||||
|
||||
const portableDir = process.env.PORTABLE_EXECUTABLE_DIR;
|
||||
|
||||
const errCode = (e: unknown) =>
|
||||
e && typeof e === 'object' ? (e as NodeJS.ErrnoException).code : undefined;
|
||||
|
||||
const LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY', 'EMFILE', 'ENFILE'];
|
||||
const isLocked = (e: unknown) => LOCK_CODES.includes(errCode(e) ?? '');
|
||||
|
||||
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
const readJsonRetrying = async (file: string, attempts = 5) => {
|
||||
for (let i = 0; ; i++) {
|
||||
try {
|
||||
return await fs.readJSON(file);
|
||||
} catch (e) {
|
||||
if (i >= attempts - 1 || !isLocked(e)) throw e;
|
||||
await delay(60 * (i + 1));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const renameRetrying = async (from: string, to: string, attempts = 5) => {
|
||||
for (let i = 0; ; i++) {
|
||||
try {
|
||||
return await fs.rename(from, to);
|
||||
} catch (e) {
|
||||
if (i >= attempts - 1 || !isLocked(e)) throw e;
|
||||
await delay(60 * (i + 1));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const writeJsonAtomic = async (file: string, data: unknown) => {
|
||||
const tmp = `${file}.tmp`;
|
||||
await fs.writeJSON(tmp, data, { spaces: 2 });
|
||||
await renameRetrying(tmp, file);
|
||||
};
|
||||
|
||||
const dropUndefined = <T extends object>(obj: T): Partial<T> =>
|
||||
Object.fromEntries(
|
||||
Object.entries(obj).filter(([, v]) => v !== undefined)
|
||||
) as Partial<T>;
|
||||
|
||||
abstract class Preferences {
|
||||
static #data: z.infer<typeof PreferencesSchema>;
|
||||
static #writeChain: Promise<void> = Promise.resolve();
|
||||
static #readOnly = false;
|
||||
static #rememberedClientDir?: string;
|
||||
static #freshInstall = false;
|
||||
|
||||
static readonly userDataDir = process.env.PORTABLE_EXECUTABLE_DIR
|
||||
? path.join(process.env.PORTABLE_EXECUTABLE_DIR, '.launcher')
|
||||
: app.getPath('userData');
|
||||
|
||||
static readonly #settingsPath = path.join(
|
||||
Preferences.userDataDir,
|
||||
'settings.json'
|
||||
);
|
||||
|
||||
static readonly #installPath = path.join(
|
||||
Preferences.userDataDir,
|
||||
'install.json'
|
||||
);
|
||||
|
||||
static get isFreshInstall() {
|
||||
return this.#freshInstall;
|
||||
}
|
||||
|
||||
static async #detectFreshInstall() {
|
||||
const [settings, install, pending] = await Promise.all([
|
||||
fs.pathExists(this.#settingsPath),
|
||||
fs.pathExists(this.#installPath),
|
||||
fs.pathExists(`${this.#settingsPath}.tmp`)
|
||||
]);
|
||||
return !settings && !install && !pending;
|
||||
}
|
||||
|
||||
static #withFreshInstallDefaults(data: PreferencesSchema): PreferencesSchema {
|
||||
if (!this.#freshInstall || Object.keys(data.mods).length) return data;
|
||||
|
||||
const mods = { ...data.mods };
|
||||
for (const id of DEFAULT_ENABLED_MODS)
|
||||
mods[id] = { enabled: true, installedFiles: [], ignoreUpdates: false };
|
||||
|
||||
Logger.info(
|
||||
`Fresh install: enabling ${DEFAULT_ENABLED_MODS.join(', ')} by default`
|
||||
);
|
||||
return { ...data, mods };
|
||||
}
|
||||
|
||||
static async load() {
|
||||
this.#freshInstall = await this.#detectFreshInstall();
|
||||
await fs.ensureDir(this.userDataDir);
|
||||
const settingsPath = this.#settingsPath;
|
||||
|
||||
let json: Record<string, unknown> = {};
|
||||
try {
|
||||
json = await readJsonRetrying(settingsPath);
|
||||
} catch (e) {
|
||||
if (isLocked(e)) {
|
||||
this.#readOnly = true;
|
||||
Logger.error(
|
||||
`Could not read ${settingsPath} (${errCode(e)}); running on ` +
|
||||
'defaults and leaving settings untouched for this session.',
|
||||
e
|
||||
);
|
||||
} else {
|
||||
if (errCode(e) !== 'ENOENT') {
|
||||
Logger.warn(`${settingsPath} is unreadable; keeping a copy`, e);
|
||||
await fs
|
||||
.copy(settingsPath, `${settingsPath}.corrupt`)
|
||||
.catch(() => {});
|
||||
}
|
||||
const recovered = await fs
|
||||
.readJSON(`${settingsPath}.tmp`)
|
||||
.catch(() => null);
|
||||
if (recovered && typeof recovered === 'object') {
|
||||
Logger.warn(`Recovered settings from ${settingsPath}.tmp`);
|
||||
json = recovered as Record<string, unknown>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const merged = dropUndefined({
|
||||
...json,
|
||||
isPortable: !!portableDir,
|
||||
clientDir: portableDir ?? json.clientDir
|
||||
});
|
||||
|
||||
const parsed = PreferencesSchema.safeParse(merged);
|
||||
if (parsed.success)
|
||||
return this.#withKnownClientDir(
|
||||
this.#withFreshInstallDefaults(parsed.data)
|
||||
);
|
||||
|
||||
Logger.warn(
|
||||
'settings.json failed validation; salvaging valid fields',
|
||||
parsed.error
|
||||
);
|
||||
await fs.copy(settingsPath, `${settingsPath}.corrupt`).catch(() => {});
|
||||
|
||||
const salvaged: Record<string, unknown> = dropUndefined({
|
||||
isPortable: !!portableDir,
|
||||
// coerce to string/undefined; the shape loop never clears a set key, so a
|
||||
// non-string would survive and throw at the final parse
|
||||
clientDir:
|
||||
portableDir ??
|
||||
(typeof json.clientDir === 'string' ? json.clientDir : undefined)
|
||||
});
|
||||
const shape = PreferencesSchema.shape;
|
||||
for (const key of Object.keys(shape) as (keyof typeof shape)[]) {
|
||||
if (!(key in merged)) continue;
|
||||
const value = (merged as Record<string, unknown>)[key];
|
||||
if (shape[key].safeParse(value).success) salvaged[key] = value;
|
||||
}
|
||||
// defaults if even the salvaged set is invalid; never throw out of load()
|
||||
const salvagedParsed = PreferencesSchema.safeParse(salvaged);
|
||||
return this.#withKnownClientDir(
|
||||
salvagedParsed.success ? salvagedParsed.data : PreferencesSchema.parse({})
|
||||
);
|
||||
}
|
||||
|
||||
static async #withKnownClientDir(data: PreferencesSchema) {
|
||||
if (portableDir) return data;
|
||||
|
||||
const remembered = await fs
|
||||
.readJSON(this.#installPath)
|
||||
.then(j => {
|
||||
const dir = (j as { clientDir?: unknown })?.clientDir;
|
||||
return typeof dir === 'string' && dir ? dir : undefined;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
this.#rememberedClientDir = remembered;
|
||||
|
||||
if (await this.isValidClientDir(data.clientDir)) return data;
|
||||
if (!remembered || remembered === data.clientDir) return data;
|
||||
if (!(await this.isValidClientDir(remembered))) return data;
|
||||
|
||||
Logger.warn(
|
||||
`No usable clientDir in settings.json; restored "${remembered}" from ` +
|
||||
this.#installPath
|
||||
);
|
||||
return { ...data, clientDir: remembered };
|
||||
}
|
||||
|
||||
static get data(): PreferencesSchema {
|
||||
return this.#data;
|
||||
}
|
||||
|
||||
static set data(newData: Partial<Omit<PreferencesSchema, 'portableDir'>>) {
|
||||
this.#data = { ...this.#data, ...newData };
|
||||
|
||||
if (this.#readOnly) return;
|
||||
|
||||
const settingsPath = this.#settingsPath;
|
||||
const dropped = portableDir ? ['isPortable', 'clientDir'] : ['isPortable'];
|
||||
const delta = dropUndefined(
|
||||
omit(newData, dropped as (keyof typeof newData)[])
|
||||
);
|
||||
const snapshot = dropUndefined(
|
||||
omit(this.#data, dropped as (keyof PreferencesSchema)[])
|
||||
);
|
||||
this.#writeChain = this.#writeChain
|
||||
.then(async () => {
|
||||
let base: Record<string, unknown> | null = null;
|
||||
try {
|
||||
const onDisk = await readJsonRetrying(settingsPath);
|
||||
base =
|
||||
!!onDisk && typeof onDisk === 'object' && !Array.isArray(onDisk)
|
||||
? (onDisk as Record<string, unknown>)
|
||||
: null;
|
||||
} catch (e) {
|
||||
if (isLocked(e)) {
|
||||
Logger.error(
|
||||
`Skipping settings write; ${settingsPath} is locked (${errCode(
|
||||
e
|
||||
)})`,
|
||||
e
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const merged = base ? { ...base, ...delta } : snapshot;
|
||||
await writeJsonAtomic(settingsPath, merged);
|
||||
|
||||
const clientDir = (merged as { clientDir?: unknown }).clientDir;
|
||||
if (
|
||||
typeof clientDir === 'string' &&
|
||||
clientDir &&
|
||||
clientDir !== this.#rememberedClientDir
|
||||
) {
|
||||
this.#rememberedClientDir = clientDir;
|
||||
await writeJsonAtomic(this.#installPath, { clientDir }).catch(e =>
|
||||
Logger.warn(`Failed to write ${this.#installPath}`, e)
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch(e => Logger.error('Failed to persist settings.json', e));
|
||||
}
|
||||
|
||||
static save() {
|
||||
return this.#writeChain;
|
||||
}
|
||||
|
||||
static async isValidClientDir(clientDir?: string) {
|
||||
if (!clientDir) return false;
|
||||
if (await fs.exists(path.join(clientDir, 'WoW.exe'))) return true;
|
||||
// torrent mode: no WoW.exe yet, accept a dir the download can populate
|
||||
if (isTorrentMode())
|
||||
return (
|
||||
(await fs.exists(clientDir)) ||
|
||||
(await fs.exists(path.dirname(clientDir)))
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export default Preferences;
|
||||
@@ -0,0 +1,122 @@
|
||||
import { app } from 'electron';
|
||||
import { autoUpdater } from 'electron-updater';
|
||||
import Logger from 'electron-log/main';
|
||||
import { is } from '@electron-toolkit/utils';
|
||||
|
||||
import Observable from './observable';
|
||||
|
||||
export type SelfUpdaterStatus =
|
||||
| { state: 'idle'; currentVersion: string }
|
||||
| { state: 'checking'; currentVersion: string }
|
||||
| { state: 'unavailable'; currentVersion: string }
|
||||
| { state: 'available'; currentVersion: string; nextVersion: string }
|
||||
| {
|
||||
state: 'downloading';
|
||||
currentVersion: string;
|
||||
nextVersion: string;
|
||||
progress: number;
|
||||
}
|
||||
| { state: 'ready'; currentVersion: string; nextVersion: string }
|
||||
| { state: 'error'; currentVersion: string; message: string };
|
||||
|
||||
class SelfUpdaterClass extends Observable<SelfUpdaterStatus> {
|
||||
protected _value: SelfUpdaterStatus = {
|
||||
state: 'idle',
|
||||
currentVersion: app.getVersion()
|
||||
};
|
||||
|
||||
#initialized = false;
|
||||
#nextVersion: string | undefined;
|
||||
|
||||
get status(): SelfUpdaterStatus {
|
||||
return this._value;
|
||||
}
|
||||
|
||||
private set status(v: SelfUpdaterStatus) {
|
||||
this._value = v;
|
||||
this._notifyObservers();
|
||||
}
|
||||
|
||||
init() {
|
||||
if (this.#initialized) return;
|
||||
this.#initialized = true;
|
||||
|
||||
if (is.dev) {
|
||||
Logger.info('[selfUpdater] dev mode, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
const currentVersion = app.getVersion();
|
||||
|
||||
autoUpdater.logger = Logger;
|
||||
autoUpdater.autoDownload = true;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
|
||||
autoUpdater.on('checking-for-update', () => {
|
||||
Logger.info('[selfUpdater] checking');
|
||||
this.status = { state: 'checking', currentVersion };
|
||||
});
|
||||
autoUpdater.on('update-available', info => {
|
||||
Logger.info(`[selfUpdater] update available: ${info.version}`);
|
||||
this.#nextVersion = info.version;
|
||||
this.status = {
|
||||
state: 'available',
|
||||
currentVersion,
|
||||
nextVersion: info.version
|
||||
};
|
||||
});
|
||||
autoUpdater.on('update-not-available', info => {
|
||||
Logger.info(`[selfUpdater] up to date (current: ${info.version})`);
|
||||
this.status = { state: 'unavailable', currentVersion };
|
||||
});
|
||||
autoUpdater.on('error', err => {
|
||||
Logger.error('[selfUpdater] error', err);
|
||||
this.status = {
|
||||
state: 'error',
|
||||
currentVersion,
|
||||
message: err?.message ?? String(err)
|
||||
};
|
||||
});
|
||||
autoUpdater.on('download-progress', p => {
|
||||
Logger.info(`[selfUpdater] downloading ${Math.round(p.percent)}%`);
|
||||
this.status = {
|
||||
state: 'downloading',
|
||||
currentVersion,
|
||||
nextVersion: this.#nextVersion ?? '',
|
||||
progress: Math.max(0, Math.min(1, p.percent / 100))
|
||||
};
|
||||
});
|
||||
autoUpdater.on('update-downloaded', info => {
|
||||
Logger.info(
|
||||
`[selfUpdater] downloaded ${info.version}, awaiting user click`
|
||||
);
|
||||
this.status = {
|
||||
state: 'ready',
|
||||
currentVersion,
|
||||
nextVersion: info.version
|
||||
};
|
||||
});
|
||||
|
||||
autoUpdater.checkForUpdates().catch(err => {
|
||||
Logger.error('[selfUpdater] checkForUpdates failed', err);
|
||||
});
|
||||
}
|
||||
|
||||
triggerInstall() {
|
||||
if (this._value.state !== 'ready') {
|
||||
Logger.warn(
|
||||
`[selfUpdater] triggerInstall called in state ${this._value.state}, ignoring`
|
||||
);
|
||||
return;
|
||||
}
|
||||
Logger.info(
|
||||
'[selfUpdater] user clicked install, quitting + running installer'
|
||||
);
|
||||
autoUpdater.quitAndInstall(false, true);
|
||||
}
|
||||
}
|
||||
|
||||
const SelfUpdater = new SelfUpdaterClass();
|
||||
export default SelfUpdater;
|
||||
|
||||
export const initSelfUpdater = () => SelfUpdater.init();
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Tray, Menu, nativeImage, app } from 'electron';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import icon from '~build/icon.png?asset';
|
||||
|
||||
import { mainWindow } from '~main/index';
|
||||
|
||||
let tray: Tray | null = null;
|
||||
let isMinimizedToTray = false;
|
||||
|
||||
const restoreWindow = () => {
|
||||
if (!mainWindow) return;
|
||||
mainWindow.show();
|
||||
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||
mainWindow.focus();
|
||||
isMinimizedToTray = false;
|
||||
};
|
||||
|
||||
const ensureTray = () => {
|
||||
if (tray) return tray;
|
||||
const trayIcon = nativeImage.createFromPath(icon).resize({ width: 16, height: 16 });
|
||||
tray = new Tray(trayIcon);
|
||||
tray.setToolTip('OctoLauncher');
|
||||
tray.setContextMenu(
|
||||
Menu.buildFromTemplate([
|
||||
{ label: 'Show launcher', click: restoreWindow },
|
||||
{ type: 'separator' },
|
||||
{ label: 'Quit', click: () => app.quit() }
|
||||
])
|
||||
);
|
||||
tray.on('click', restoreWindow);
|
||||
return tray;
|
||||
};
|
||||
|
||||
export const minimizeToTray = () => {
|
||||
if (!mainWindow) return;
|
||||
ensureTray();
|
||||
mainWindow.hide();
|
||||
isMinimizedToTray = true;
|
||||
Logger.info('Minimized to tray');
|
||||
};
|
||||
|
||||
export const restoreFromTray = () => {
|
||||
if (!isMinimizedToTray) return;
|
||||
restoreWindow();
|
||||
};
|
||||
|
||||
export const isInTray = () => isMinimizedToTray;
|
||||
|
||||
export const destroyTray = () => {
|
||||
tray?.destroy();
|
||||
tray = null;
|
||||
};
|
||||
@@ -0,0 +1,542 @@
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { exec } from 'node:child_process';
|
||||
import os from 'node:os';
|
||||
|
||||
import { app } from 'electron';
|
||||
import fetch from 'node-fetch';
|
||||
import fs from 'fs-extra';
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
import { nestedGet, nestedSet } from '~common/utils';
|
||||
import { mainWindow } from '~main/index';
|
||||
import { getClientVersion } from '~main/utils';
|
||||
import {
|
||||
torrentUrl,
|
||||
fetchTorrentSha,
|
||||
syncClient,
|
||||
refreshPristineWow,
|
||||
clearTorrentResumeState,
|
||||
raidVisualsUrl,
|
||||
clientPatchUrl,
|
||||
pruneStaleArchives,
|
||||
torrentTreeIntact,
|
||||
torrentDownloadSelection,
|
||||
startSeeding,
|
||||
stopSeeding
|
||||
} from '~main/modules/aria2';
|
||||
|
||||
import Preferences from './preferences';
|
||||
import Observable from './observable';
|
||||
|
||||
type FolderTags = 'allowExtra';
|
||||
type FileTags = 'vanillaFixes' | 'raidVisuals';
|
||||
type FileManifest = { name: string } & (
|
||||
| { type: 'del' }
|
||||
| { type: 'dir'; files: FileManifest[]; tags?: FolderTags[] }
|
||||
| { type: 'mpq'; files: FileManifest[]; hash: string; size: number }
|
||||
| {
|
||||
type: 'file';
|
||||
hash: string;
|
||||
version?: number;
|
||||
size: number;
|
||||
tags?: FileTags[];
|
||||
}
|
||||
);
|
||||
|
||||
type CacheEntry = [hash: string, mtime: number];
|
||||
type CacheTree = { [key: string]: CacheTree & CacheEntry };
|
||||
|
||||
const getManifestItem = (
|
||||
m?: FileManifest,
|
||||
p?: string[]
|
||||
): FileManifest | undefined => {
|
||||
if (!p?.length) return m;
|
||||
|
||||
if (m?.type === 'file' || m?.type === 'del')
|
||||
throw Error(`Can't access ${p.join('.')} from file ${m.name}`);
|
||||
|
||||
const [next, ...rest] = p;
|
||||
return getManifestItem(
|
||||
m?.files.find(f => f.name === next),
|
||||
rest
|
||||
);
|
||||
};
|
||||
|
||||
const ownedDataArchives = async (): Promise<Set<string>> => {
|
||||
try {
|
||||
const j = await fs.readJSON(
|
||||
path.join(Preferences.userDataDir, 'manifest.json')
|
||||
);
|
||||
const data = getManifestItem(j?.root ?? j, ['Data']);
|
||||
if (!data || data.type === 'file' || data.type === 'del') return new Set();
|
||||
return new Set(
|
||||
data.files
|
||||
.filter(f => f.type !== 'dir' && /\.mpq$/i.test(f.name))
|
||||
.map(f => f.name.toLowerCase())
|
||||
);
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
};
|
||||
|
||||
export const isGameRunning = (executablePath: string) =>
|
||||
os.platform() === 'win32'
|
||||
? new Promise<boolean>(resolve => {
|
||||
const exeName = path.basename(executablePath);
|
||||
exec(
|
||||
`tasklist /FI "IMAGENAME eq ${exeName}" /FO CSV /NH`,
|
||||
(error, stdout) => {
|
||||
if (error) {
|
||||
Logger.warn(
|
||||
`tasklist probe for "${exeName}" failed; assuming game ` +
|
||||
`is not running. Error: ${error.message}`
|
||||
);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
resolve(
|
||||
stdout.toLowerCase().includes(`"${exeName.toLowerCase()}"`)
|
||||
);
|
||||
}
|
||||
);
|
||||
})
|
||||
: false;
|
||||
|
||||
type UpdaterState =
|
||||
| 'verifying'
|
||||
| 'serverUnreachable'
|
||||
| 'noClient'
|
||||
| 'updateAvailable'
|
||||
| 'updating'
|
||||
| 'upToDate'
|
||||
| 'failed';
|
||||
|
||||
export type UpdaterStatus = {
|
||||
state: UpdaterState;
|
||||
progress?: number;
|
||||
message?: string;
|
||||
bytesDone?: number;
|
||||
bytesTotal?: number;
|
||||
bytesPerSecond?: number;
|
||||
etaSeconds?: number;
|
||||
};
|
||||
|
||||
const SIDECAR_TIMEOUT_MS = 30_000;
|
||||
|
||||
class UpdaterClass extends Observable<UpdaterStatus> {
|
||||
#cachePath = path.join(Preferences.userDataDir, 'cache.json');
|
||||
#cache: CacheTree = this.#readCache();
|
||||
|
||||
#readCache(): CacheTree {
|
||||
try {
|
||||
return fs.existsSync(this.#cachePath)
|
||||
? fs.readJSONSync(this.#cachePath)
|
||||
: {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
async #saveCache() {
|
||||
await fs.writeJSON(this.#cachePath, this.#cache);
|
||||
}
|
||||
|
||||
async #getHash(clientPath: string, ...filePath: string[]) {
|
||||
if (!(await fs.exists(path.join(clientPath, ...filePath)))) {
|
||||
nestedSet(this.#cache, filePath, undefined);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const stats = await fs.stat(path.join(clientPath, ...filePath));
|
||||
if (stats.isDirectory())
|
||||
throw Error(`Tried to get hash of directory ${path.join(...filePath)}`);
|
||||
|
||||
const c = nestedGet<CacheEntry>(this.#cache, filePath);
|
||||
|
||||
if (c?.[0] && c[1] === stats.mtimeMs) return c[0];
|
||||
|
||||
const newHash = crypto
|
||||
.createHash('sha1')
|
||||
.update(await fs.readFile(path.join(clientPath, ...filePath)))
|
||||
.digest('hex')
|
||||
.toLocaleUpperCase();
|
||||
nestedSet(this.#cache, filePath, {
|
||||
...c,
|
||||
[0]: newHash,
|
||||
[1]: stats.mtimeMs
|
||||
});
|
||||
return newHash;
|
||||
}
|
||||
|
||||
protected _value: UpdaterStatus = { state: 'failed' };
|
||||
|
||||
get status() {
|
||||
return this._value;
|
||||
}
|
||||
private set status(v: UpdaterStatus) {
|
||||
this._value = v;
|
||||
this._notifyObservers(v);
|
||||
if (this.status.state === 'failed') {
|
||||
mainWindow?.setProgressBar(1, { mode: 'error' });
|
||||
} else if (this.status.progress === 1) {
|
||||
mainWindow?.setProgressBar(0);
|
||||
} else {
|
||||
mainWindow?.setProgressBar(this.status.progress ?? 0, {
|
||||
mode: this.status.progress === -1 ? 'indeterminate' : 'normal'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async refreshSeeding() {
|
||||
if (
|
||||
Preferences.data.shareDownloads !== false &&
|
||||
Preferences.data.clientDir &&
|
||||
this.status.state === 'upToDate'
|
||||
)
|
||||
await startSeeding(Preferences.data.clientDir);
|
||||
else stopSeeding();
|
||||
}
|
||||
|
||||
async #torrentVerify(clientPath: string) {
|
||||
const url = torrentUrl();
|
||||
if (!url) {
|
||||
this.status = { state: 'serverUnreachable' };
|
||||
return;
|
||||
}
|
||||
this.status = {
|
||||
state: 'verifying',
|
||||
progress: -1,
|
||||
message: 'Checking for updates...'
|
||||
};
|
||||
try {
|
||||
const sha = await fetchTorrentSha(url);
|
||||
await this.#reconcileClientPatch(clientPath);
|
||||
await this.#reconcileRaidVisuals(clientPath);
|
||||
const haveExe = await fs.pathExists(path.join(clientPath, 'WoW.exe'));
|
||||
if (
|
||||
haveExe &&
|
||||
sha !== Preferences.data.syncedTorrentHash &&
|
||||
(await this.#torrentFastForward(clientPath, sha, url))
|
||||
) {
|
||||
this.status = { state: 'upToDate', progress: 1 };
|
||||
await this.refreshSeeding();
|
||||
return;
|
||||
}
|
||||
const upToDate =
|
||||
haveExe &&
|
||||
sha === Preferences.data.syncedTorrentHash &&
|
||||
(await torrentTreeIntact(clientPath, url));
|
||||
if (upToDate) {
|
||||
const removed = await pruneStaleArchives(clientPath, url, new Set());
|
||||
if (removed.length)
|
||||
Logger.log(`Removed stale archives: ${removed.join(', ')}`);
|
||||
}
|
||||
this.status = upToDate
|
||||
? { state: 'upToDate', progress: 1 }
|
||||
: { state: 'updateAvailable' };
|
||||
await this.refreshSeeding();
|
||||
} catch (e) {
|
||||
Logger.error('Torrent verify failed', e);
|
||||
this.status = { state: 'serverUnreachable' };
|
||||
}
|
||||
}
|
||||
|
||||
async #fetchSidecarFile(
|
||||
url: string,
|
||||
dest: string,
|
||||
storedHash: string | undefined,
|
||||
busyMessage: string
|
||||
): Promise<string | undefined> {
|
||||
const ac = new AbortController();
|
||||
const t = setTimeout(() => ac.abort(), SIDECAR_TIMEOUT_MS);
|
||||
const sha = await fetch(`${url}.sha256`, { signal: ac.signal })
|
||||
.then(r => {
|
||||
if (!r.ok) throw new Error(`sha256 HTTP ${r.status}`);
|
||||
return r.text();
|
||||
})
|
||||
.then(s => s.trim())
|
||||
.finally(() => clearTimeout(t));
|
||||
if ((await fs.pathExists(dest)) && storedHash === sha) return undefined;
|
||||
this.status = { state: 'updating', progress: -1, message: busyMessage };
|
||||
const buf = await this.#downloadWithIdleTimeout(url);
|
||||
if (crypto.createHash('sha256').update(buf).digest('hex') !== sha)
|
||||
throw new Error('checksum mismatch');
|
||||
await fs.ensureDir(path.dirname(dest));
|
||||
await fs.writeFile(`${dest}.part`, buf);
|
||||
await fs.move(`${dest}.part`, dest, { overwrite: true });
|
||||
return sha;
|
||||
}
|
||||
|
||||
async #downloadWithIdleTimeout(url: string): Promise<Buffer> {
|
||||
const ac = new AbortController();
|
||||
let idle: ReturnType<typeof setTimeout> | undefined;
|
||||
const arm = () => {
|
||||
if (idle) clearTimeout(idle);
|
||||
idle = setTimeout(() => ac.abort(), SIDECAR_TIMEOUT_MS);
|
||||
};
|
||||
arm();
|
||||
try {
|
||||
const res = await fetch(url, { signal: ac.signal });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const body = res.body as NodeJS.ReadableStream | null;
|
||||
if (!body) throw new Error('empty response body');
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of body) {
|
||||
arm();
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
} finally {
|
||||
if (idle) clearTimeout(idle);
|
||||
}
|
||||
}
|
||||
|
||||
async #reconcileClientPatch(clientPath: string) {
|
||||
const url = clientPatchUrl();
|
||||
if (!url) return;
|
||||
const dest = path.join(clientPath, 'Data', 'patch-5.mpq');
|
||||
try {
|
||||
const sha = await this.#fetchSidecarFile(
|
||||
url,
|
||||
dest,
|
||||
Preferences.data.clientPatchHash,
|
||||
'Updating game files...'
|
||||
);
|
||||
if (sha) Preferences.data = { clientPatchHash: sha };
|
||||
} catch (e) {
|
||||
Logger.warn('Content patch reconcile failed', e);
|
||||
if (!(await fs.pathExists(dest)))
|
||||
throw new Error(
|
||||
'Could not download core game content. Please check your connection and try again.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async #reconcileRaidVisuals(clientPath: string) {
|
||||
const url = raidVisualsUrl();
|
||||
if (!url) return;
|
||||
const dest = path.join(clientPath, 'Data', 'patch-O.mpq');
|
||||
try {
|
||||
if (!Preferences.data.config?.raidVisuals) {
|
||||
if (await fs.pathExists(dest)) {
|
||||
await fs.remove(dest);
|
||||
Preferences.data = { raidVisualsHash: undefined };
|
||||
}
|
||||
return;
|
||||
}
|
||||
const sha = await this.#fetchSidecarFile(
|
||||
url,
|
||||
dest,
|
||||
Preferences.data.raidVisualsHash,
|
||||
'Updating raid visuals...'
|
||||
);
|
||||
if (sha) Preferences.data = { raidVisualsHash: sha };
|
||||
} catch (e) {
|
||||
Logger.warn('Raid visuals reconcile failed', e);
|
||||
}
|
||||
}
|
||||
|
||||
async syncRaidVisuals() {
|
||||
if (this.status?.state === 'verifying' || this.status?.state === 'updating')
|
||||
return;
|
||||
const clientPath = Preferences.data.clientDir;
|
||||
if (!clientPath) return;
|
||||
if (await isGameRunning(path.join(clientPath, 'WoW.exe'))) {
|
||||
this.status = {
|
||||
state: 'failed',
|
||||
message: 'Please close WoW first, before updating.'
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (!torrentUrl()) return this.verify();
|
||||
await this.#reconcileRaidVisuals(clientPath);
|
||||
this.status = { state: 'upToDate', progress: 1 };
|
||||
}
|
||||
|
||||
async #torrentFastForward(
|
||||
clientPath: string,
|
||||
sha: string,
|
||||
url: string
|
||||
): Promise<boolean> {
|
||||
if (!Preferences.data.syncedTorrentHash) return false;
|
||||
if (!(await torrentTreeIntact(clientPath, url))) return false;
|
||||
await refreshPristineWow(clientPath);
|
||||
const removed = await pruneStaleArchives(
|
||||
clientPath,
|
||||
url,
|
||||
await ownedDataArchives()
|
||||
);
|
||||
if (removed.length)
|
||||
Logger.log(`Removed stale archives: ${removed.join(', ')}`);
|
||||
Preferences.data = {
|
||||
syncedTorrentHash: sha,
|
||||
version: await getClientVersion()
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
async #torrentUpdate(clientPath: string, clean?: boolean) {
|
||||
const url = torrentUrl();
|
||||
if (!url) {
|
||||
this.status = { state: 'serverUnreachable' };
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stopSeeding();
|
||||
const sha = await fetchTorrentSha(url);
|
||||
if (!clean && (await this.#torrentFastForward(clientPath, sha, url))) {
|
||||
await this.#reconcileClientPatch(clientPath);
|
||||
await this.#reconcileRaidVisuals(clientPath);
|
||||
this.status = { state: 'upToDate', progress: 1 };
|
||||
await this.refreshSeeding();
|
||||
return;
|
||||
}
|
||||
const isUpdate = await fs.pathExists(path.join(clientPath, 'WoW.exe'));
|
||||
const staleContext =
|
||||
Preferences.data.activeTorrentHash !== sha ||
|
||||
Preferences.data.activeClientDir !== clientPath;
|
||||
if (staleContext) {
|
||||
await clearTorrentResumeState();
|
||||
Preferences.data = {
|
||||
activeTorrentHash: sha,
|
||||
activeClientDir: clientPath
|
||||
};
|
||||
}
|
||||
const selection = clean
|
||||
? null
|
||||
: await torrentDownloadSelection(clientPath, url, staleContext);
|
||||
const selectFiles =
|
||||
selection && selection.length > 0 ? selection : undefined;
|
||||
this.status = {
|
||||
state: 'updating',
|
||||
progress: -1,
|
||||
message: clean
|
||||
? 'Verifying game files...'
|
||||
: isUpdate
|
||||
? 'Connecting...'
|
||||
: 'Preparing download...'
|
||||
};
|
||||
let downloading = false;
|
||||
await syncClient({
|
||||
torrentUrl: url,
|
||||
clientDir: clientPath,
|
||||
checkIntegrity: !!clean,
|
||||
selectFiles,
|
||||
seedTime: 0,
|
||||
onProgress: p => {
|
||||
if (p.bytesPerSecond > 0) downloading = true;
|
||||
const phase = downloading
|
||||
? 'Downloading'
|
||||
: clean
|
||||
? 'Verifying game files'
|
||||
: isUpdate
|
||||
? 'Connecting'
|
||||
: 'Preparing';
|
||||
this.status = {
|
||||
state: 'updating',
|
||||
progress: p.progress,
|
||||
bytesDone: p.bytesDone,
|
||||
bytesTotal: p.bytesTotal,
|
||||
bytesPerSecond: p.bytesPerSecond,
|
||||
message: `${phase}...`
|
||||
};
|
||||
}
|
||||
});
|
||||
if (!(await torrentTreeIntact(clientPath, url))) {
|
||||
this.status = {
|
||||
state: 'updateAvailable',
|
||||
message: 'Download incomplete. Click update to finish.'
|
||||
};
|
||||
return;
|
||||
}
|
||||
await refreshPristineWow(clientPath);
|
||||
const removed = await pruneStaleArchives(
|
||||
clientPath,
|
||||
url,
|
||||
await ownedDataArchives()
|
||||
);
|
||||
if (removed.length)
|
||||
Logger.log(`Removed stale archives: ${removed.join(', ')}`);
|
||||
await this.#reconcileClientPatch(clientPath);
|
||||
await this.#reconcileRaidVisuals(clientPath);
|
||||
Preferences.data = {
|
||||
syncedTorrentHash: sha,
|
||||
version: await getClientVersion()
|
||||
};
|
||||
this.status = { state: 'upToDate', progress: 1 };
|
||||
await this.refreshSeeding();
|
||||
} catch (e) {
|
||||
Logger.error('Torrent update failed', e);
|
||||
this.status = {
|
||||
state: 'failed',
|
||||
message: e instanceof Error ? e.message : 'Download failed'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async verify() {
|
||||
if (this.status?.state === 'verifying' || this.status?.state === 'updating')
|
||||
return;
|
||||
|
||||
const clientPath = Preferences.data.clientDir;
|
||||
if (!clientPath) {
|
||||
this.status = { state: 'noClient' };
|
||||
return;
|
||||
}
|
||||
|
||||
if (os.platform() === 'win32' && clientPath.length > 220) {
|
||||
this.status = {
|
||||
state: 'failed',
|
||||
message:
|
||||
'Path to current install location is too long and may cause issues.'
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (await isGameRunning(path.join(clientPath, 'WoW.exe'))) {
|
||||
this.status = {
|
||||
state: 'failed',
|
||||
message: 'Please close WoW first, before updating.'
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
return this.#torrentVerify(clientPath);
|
||||
}
|
||||
|
||||
async update(clean?: boolean) {
|
||||
if (this.status?.state === 'verifying' || this.status?.state === 'updating')
|
||||
return;
|
||||
|
||||
const clientPath = Preferences.data.clientDir;
|
||||
if (!clientPath) {
|
||||
this.status = { state: 'noClient' };
|
||||
return;
|
||||
}
|
||||
|
||||
if (await isGameRunning(path.join(clientPath, 'WoW.exe'))) {
|
||||
this.status = {
|
||||
state: 'failed',
|
||||
message: 'Please close WoW first, before updating.'
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
return this.#torrentUpdate(clientPath, clean);
|
||||
}
|
||||
|
||||
async recordPatchedWow() {
|
||||
const clientPath = Preferences.data.clientDir;
|
||||
if (!clientPath) return;
|
||||
const patchedWowHash = await this.#getHash(clientPath, 'WoW.exe');
|
||||
await this.#saveCache();
|
||||
Preferences.data = {
|
||||
lastPatchedLauncherVersion: app.getVersion(),
|
||||
expectedPatchedWowHash: patchedWowHash
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const Updater = new UpdaterClass();
|
||||
export default Updater;
|
||||
@@ -0,0 +1,374 @@
|
||||
import dgram from 'dgram';
|
||||
import http from 'http';
|
||||
import os from 'os';
|
||||
|
||||
import Logger from 'electron-log/main';
|
||||
|
||||
// UPnP-IGD port mapping (best effort) for a NAT'd seeder; node builtins only, no-ops on failure.
|
||||
|
||||
export type PortMapping = { stop: () => Promise<void> };
|
||||
|
||||
const NOOP: PortMapping = { stop: async () => {} };
|
||||
|
||||
const SSDP_ADDR = '239.255.255.250';
|
||||
const SSDP_PORT = 1900;
|
||||
|
||||
const SEARCH = Buffer.from(
|
||||
[
|
||||
'M-SEARCH * HTTP/1.1',
|
||||
`HOST: ${SSDP_ADDR}:${SSDP_PORT}`,
|
||||
'MAN: "ssdp:discover"',
|
||||
'MX: 2',
|
||||
'ST: urn:schemas-upnp-org:device:InternetGatewayDevice:1',
|
||||
'',
|
||||
''
|
||||
].join('\r\n')
|
||||
);
|
||||
|
||||
// exposes AddPortMapping, newest first
|
||||
const WAN_SERVICES = [
|
||||
'urn:schemas-upnp-org:service:WANIPConnection:2',
|
||||
'urn:schemas-upnp-org:service:WANIPConnection:1',
|
||||
'urn:schemas-upnp-org:service:WANPPPConnection:1'
|
||||
];
|
||||
|
||||
type Gateway = { location: string; address: string; localAddress: string };
|
||||
type WanService = { controlUrl: string; serviceType: string };
|
||||
|
||||
class SoapError extends Error {
|
||||
code?: string;
|
||||
constructor(message: string, code?: string) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
const candidateAddresses = (): string[] =>
|
||||
Object.values(os.networkInterfaces())
|
||||
.flat()
|
||||
.filter(
|
||||
(a): a is os.NetworkInterfaceInfo =>
|
||||
!!a &&
|
||||
a.family === 'IPv4' &&
|
||||
!a.internal &&
|
||||
!a.address.startsWith('169.254.')
|
||||
)
|
||||
.map(a => a.address);
|
||||
|
||||
// a 0.0.0.0/empty host in LOCATION is really the address the datagram came from
|
||||
const fixLocation = (location: string, responder: string): string => {
|
||||
try {
|
||||
const u = new URL(location);
|
||||
if (u.hostname === '0.0.0.0' || u.hostname === '') u.hostname = responder;
|
||||
return u.toString();
|
||||
} catch {
|
||||
return location;
|
||||
}
|
||||
};
|
||||
|
||||
// M-SEARCH one interface; collect every responder (more than one can answer)
|
||||
const searchInterface = (
|
||||
localAddress: string,
|
||||
timeoutMs: number
|
||||
): Promise<Gateway[]> =>
|
||||
new Promise(resolve => {
|
||||
const socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
|
||||
const found = new Map<string, Gateway>();
|
||||
let retry: ReturnType<typeof setInterval> | undefined;
|
||||
let done = false;
|
||||
const finish = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
if (retry) clearInterval(retry);
|
||||
try {
|
||||
socket.close();
|
||||
} catch {
|
||||
// already closed
|
||||
}
|
||||
resolve([...found.values()]);
|
||||
};
|
||||
socket.on('message', (msg, rinfo) => {
|
||||
const m = /^location:\s*(\S+)/im.exec(msg.toString('utf8'));
|
||||
if (!m) return;
|
||||
const location = fixLocation(m[1].trim(), rinfo.address);
|
||||
if (!found.has(location))
|
||||
found.set(location, { location, address: rinfo.address, localAddress });
|
||||
});
|
||||
socket.on('error', () => finish());
|
||||
socket.bind(0, localAddress, () => {
|
||||
try {
|
||||
socket.setMulticastInterface(localAddress);
|
||||
} catch {
|
||||
// fall back to the default multicast interface
|
||||
}
|
||||
const send = () =>
|
||||
socket.send(SEARCH, SSDP_PORT, SSDP_ADDR, () => {
|
||||
/* fire-and-forget */
|
||||
});
|
||||
send();
|
||||
// Routers sometimes miss the first datagram; re-ask until the window closes.
|
||||
retry = setInterval(send, 700);
|
||||
setTimeout(finish, timeoutMs);
|
||||
});
|
||||
});
|
||||
|
||||
// search all interfaces: a VPN often owns the default route
|
||||
const discoverGateways = async (timeoutMs: number): Promise<Gateway[]> => {
|
||||
const perInterface = await Promise.all(
|
||||
candidateAddresses().map(a => searchInterface(a, timeoutMs))
|
||||
);
|
||||
const seen = new Set<string>();
|
||||
const gateways: Gateway[] = [];
|
||||
for (const list of perInterface)
|
||||
for (const gw of list)
|
||||
if (!seen.has(gw.location)) {
|
||||
seen.add(gw.location);
|
||||
gateways.push(gw);
|
||||
}
|
||||
return gateways;
|
||||
};
|
||||
|
||||
// build the control URL from the host we reached; routers advertise a bogus URLBase
|
||||
const controlUrlFrom = (descriptorUrl: string, controlPath: string): string => {
|
||||
const desc = new URL(descriptorUrl);
|
||||
let path: string;
|
||||
try {
|
||||
const c = new URL(controlPath, descriptorUrl);
|
||||
path = `${c.pathname}${c.search}`;
|
||||
} catch {
|
||||
path = controlPath.startsWith('/') ? controlPath : `/${controlPath}`;
|
||||
}
|
||||
return `${desc.protocol}//${desc.host}${path}`;
|
||||
};
|
||||
|
||||
// raw http, not fetch: many UPnP servers are non-compliant and undici rejects them
|
||||
const httpRequest = (
|
||||
url: string,
|
||||
opts: {
|
||||
method?: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: string;
|
||||
timeoutMs?: number;
|
||||
} = {}
|
||||
): Promise<{ status: number; body: string }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(url);
|
||||
} catch (e) {
|
||||
reject(e as Error);
|
||||
return;
|
||||
}
|
||||
const headers = { ...(opts.headers ?? {}) };
|
||||
const body = opts.body ? Buffer.from(opts.body, 'utf8') : undefined;
|
||||
if (body) headers['Content-Length'] = String(body.length);
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: u.hostname,
|
||||
port: u.port || 80,
|
||||
path: `${u.pathname}${u.search}`,
|
||||
method: opts.method ?? 'GET',
|
||||
headers
|
||||
},
|
||||
res => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', c => chunks.push(c));
|
||||
res.on('end', () =>
|
||||
resolve({
|
||||
status: res.statusCode ?? 0,
|
||||
body: Buffer.concat(chunks).toString('utf8')
|
||||
})
|
||||
);
|
||||
}
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.setTimeout(opts.timeoutMs ?? 5000, () =>
|
||||
req.destroy(new Error('request timed out'))
|
||||
);
|
||||
if (body) req.write(body);
|
||||
req.end();
|
||||
});
|
||||
|
||||
// first WAN service + control URL from a device descriptor
|
||||
const findWanService = (
|
||||
xml: string,
|
||||
descriptorUrl: string
|
||||
): WanService | undefined => {
|
||||
for (const block of xml.split(/<service>/i).slice(1)) {
|
||||
const type = /<serviceType>\s*([^<]+?)\s*<\/serviceType>/i
|
||||
.exec(block)?.[1]
|
||||
?.trim();
|
||||
const ctrl = /<controlURL>\s*([^<]+?)\s*<\/controlURL>/i
|
||||
.exec(block)?.[1]
|
||||
?.trim();
|
||||
if (
|
||||
type &&
|
||||
ctrl &&
|
||||
WAN_SERVICES.some(w => w.toLowerCase() === type.toLowerCase())
|
||||
)
|
||||
return {
|
||||
controlUrl: controlUrlFrom(descriptorUrl, ctrl),
|
||||
serviceType: type
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const xmlEscape = (s: string): string =>
|
||||
s.replace(
|
||||
/[<>&'"]/g,
|
||||
c =>
|
||||
({ '<': '<', '>': '>', '&': '&', "'": ''', '"': '"' }[
|
||||
c
|
||||
] as string)
|
||||
);
|
||||
|
||||
const arg = (name: string, value: string | number): string =>
|
||||
`<${name}>${value}</${name}>`;
|
||||
|
||||
const soap = async (
|
||||
svc: WanService,
|
||||
action: string,
|
||||
body: string
|
||||
): Promise<void> => {
|
||||
const envelope =
|
||||
'<?xml version="1.0"?>' +
|
||||
'<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
|
||||
'<s:Body>' +
|
||||
`<u:${action} xmlns:u="${svc.serviceType}">${body}</u:${action}>` +
|
||||
'</s:Body></s:Envelope>';
|
||||
const res = await httpRequest(svc.controlUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'text/xml; charset="utf-8"',
|
||||
'SOAPAction': `"${svc.serviceType}#${action}"`
|
||||
},
|
||||
body: envelope
|
||||
});
|
||||
if (res.status < 200 || res.status >= 300) {
|
||||
const code = /<errorCode>\s*(\d+)/i.exec(res.body)?.[1];
|
||||
throw new SoapError(
|
||||
`${action} failed: HTTP ${res.status}${code ? ` (UPnP ${code})` : ''}`,
|
||||
code
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const addMapping = (
|
||||
svc: WanService,
|
||||
port: number,
|
||||
protocol: 'TCP' | 'UDP',
|
||||
client: string,
|
||||
description: string,
|
||||
lease: number
|
||||
): Promise<void> =>
|
||||
soap(
|
||||
svc,
|
||||
'AddPortMapping',
|
||||
arg('NewRemoteHost', '') +
|
||||
arg('NewExternalPort', port) +
|
||||
arg('NewProtocol', protocol) +
|
||||
arg('NewInternalPort', port) +
|
||||
arg('NewInternalClient', client) +
|
||||
arg('NewEnabled', 1) +
|
||||
arg('NewPortMappingDescription', xmlEscape(description)) +
|
||||
arg('NewLeaseDuration', lease)
|
||||
);
|
||||
|
||||
const deleteMapping = (
|
||||
svc: WanService,
|
||||
port: number,
|
||||
protocol: 'TCP' | 'UDP'
|
||||
): Promise<void> =>
|
||||
soap(
|
||||
svc,
|
||||
'DeletePortMapping',
|
||||
arg('NewRemoteHost', '') +
|
||||
arg('NewExternalPort', port) +
|
||||
arg('NewProtocol', protocol)
|
||||
);
|
||||
|
||||
// map port (TCP+UDP), kept alive until stop(); returns a no-op handle when no gateway
|
||||
export const mapPort = async (
|
||||
port: number,
|
||||
opts: { description?: string; ttlSeconds?: number } = {}
|
||||
): Promise<PortMapping> => {
|
||||
const description = opts.description ?? 'OctoWoW';
|
||||
try {
|
||||
const gateways = await discoverGateways(4000);
|
||||
if (!gateways.length) {
|
||||
Logger.log('UPnP: no gateway found; seeding without a port mapping');
|
||||
return NOOP;
|
||||
}
|
||||
// take the first responder that exposes a WAN service
|
||||
const probed = await Promise.all(
|
||||
gateways.map(async gw => {
|
||||
const res = await httpRequest(gw.location).catch(() => undefined);
|
||||
const svc =
|
||||
res && res.status < 400
|
||||
? findWanService(res.body, gw.location)
|
||||
: undefined;
|
||||
return svc ? { svc, client: gw.localAddress } : undefined;
|
||||
})
|
||||
);
|
||||
const target = probed.find(Boolean);
|
||||
if (!target) {
|
||||
Logger.log('UPnP: no gateway exposes a WAN service; skipping mapping');
|
||||
return NOOP;
|
||||
}
|
||||
const { svc, client } = target;
|
||||
|
||||
// Some routers only grant permanent leases (UPnP error 725); fall back to one.
|
||||
let lease = opts.ttlSeconds ?? 3600;
|
||||
const mapped: ('TCP' | 'UDP')[] = [];
|
||||
const mapOne = async (protocol: 'TCP' | 'UDP') => {
|
||||
try {
|
||||
await addMapping(svc, port, protocol, client, description, lease);
|
||||
} catch (e) {
|
||||
if (e instanceof SoapError && e.code === '725' && lease !== 0) {
|
||||
lease = 0;
|
||||
await addMapping(svc, port, protocol, client, description, lease);
|
||||
} else throw e;
|
||||
}
|
||||
mapped.push(protocol);
|
||||
};
|
||||
try {
|
||||
await mapOne('TCP');
|
||||
await mapOne('UDP');
|
||||
} catch (e) {
|
||||
for (const p of mapped) await deleteMapping(svc, port, p).catch(() => {});
|
||||
throw e;
|
||||
}
|
||||
|
||||
// A finite lease self-heals if we exit uncleanly; renew ahead of expiry.
|
||||
let renew: ReturnType<typeof setInterval> | undefined;
|
||||
if (lease > 0) {
|
||||
const period = Math.max(60_000, (lease - 60) * 1000);
|
||||
renew = setInterval(() => {
|
||||
addMapping(svc, port, 'TCP', client, description, lease).catch(
|
||||
() => {}
|
||||
);
|
||||
addMapping(svc, port, 'UDP', client, description, lease).catch(
|
||||
() => {}
|
||||
);
|
||||
}, period);
|
||||
renew.unref?.();
|
||||
}
|
||||
|
||||
Logger.log(
|
||||
`UPnP: mapped ${port} TCP+UDP to ${client} (lease ${
|
||||
lease || 'permanent'
|
||||
})`
|
||||
);
|
||||
return {
|
||||
stop: async () => {
|
||||
if (renew) clearInterval(renew);
|
||||
await deleteMapping(svc, port, 'TCP').catch(() => {});
|
||||
await deleteMapping(svc, port, 'UDP').catch(() => {});
|
||||
}
|
||||
};
|
||||
} catch (e) {
|
||||
Logger.warn('UPnP: port mapping failed; seeding without it', e);
|
||||
return NOOP;
|
||||
}
|
||||
};
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
export { type AppRouter } from './api/root';
|
||||
export { type UpdaterStatus } from './modules/updater';
|
||||
export { type AddonsStatus, type AddonData } from './modules/addons';
|
||||
export {
|
||||
type ModsStatus,
|
||||
type ModRowStatus,
|
||||
type CustomMod
|
||||
} from './modules/mods';
|
||||
export {
|
||||
type NewsItem,
|
||||
type NewsFeed,
|
||||
type ForumAnnouncement
|
||||
} from '../common/schemas';
|
||||
@@ -0,0 +1,69 @@
|
||||
import { type Worker, type WorkerOptions } from 'node:worker_threads';
|
||||
import path from 'node:path';
|
||||
|
||||
import Logger from 'electron-log/main';
|
||||
import fs from 'fs-extra';
|
||||
|
||||
import Preferences from './modules/preferences';
|
||||
|
||||
const isCallbackResponse = (
|
||||
data: unknown
|
||||
): data is { cb: string; args: unknown[] } =>
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
'cb' in data &&
|
||||
typeof (data as { cb: unknown }).cb === 'string' &&
|
||||
'args' in data &&
|
||||
Array.isArray((data as { args: unknown }).args);
|
||||
|
||||
export const runWorker = <T>(
|
||||
worker: (o: WorkerOptions) => Worker,
|
||||
workerData: Record<string, unknown>,
|
||||
callbacks?: Record<string, (...data: any[]) => void>
|
||||
) =>
|
||||
new Promise<T>((resolve, reject) =>
|
||||
worker({ workerData })
|
||||
.on('message', (m: unknown) => {
|
||||
if (!isCallbackResponse(m)) return resolve(m as T);
|
||||
const callback = callbacks?.[m.cb];
|
||||
if (callback) callback(...m.args);
|
||||
else Logger.warn('Unknown worker callback', m.cb);
|
||||
})
|
||||
.on('error', reject)
|
||||
.on('exit', code =>
|
||||
reject(new Error(`Worker exited (code ${code}) without finishing`))
|
||||
)
|
||||
);
|
||||
|
||||
export const getClientVersion = async () => {
|
||||
Logger.log('Reading client version...');
|
||||
|
||||
const exePath = path.join(Preferences.data.clientDir ?? '', 'WoW.exe');
|
||||
|
||||
if (!(await fs.exists(exePath))) {
|
||||
Logger.log('Client not found...');
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const file = await fs.readFile(exePath);
|
||||
const buffer = Buffer.from(file);
|
||||
|
||||
const VERSION_OFFSET = 0x00437c04;
|
||||
const VERSION_LEN = 6;
|
||||
const BUILD_OFFSET = 0x00437bfc;
|
||||
const BUILD_LEN = 4;
|
||||
|
||||
const version = buffer.toString(
|
||||
'utf-8',
|
||||
VERSION_OFFSET,
|
||||
VERSION_OFFSET + VERSION_LEN
|
||||
);
|
||||
const build = buffer.toString(
|
||||
'utf-8',
|
||||
BUILD_OFFSET,
|
||||
BUILD_OFFSET + BUILD_LEN
|
||||
);
|
||||
|
||||
Logger.log(`Client version is: ${version} (${build})`);
|
||||
return `${version} (${build})`;
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import { workerData, parentPort } from 'worker_threads';
|
||||
|
||||
import git from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/node';
|
||||
import fs from 'fs-extra';
|
||||
|
||||
const port = parentPort;
|
||||
if (!port) throw new Error('IllegalState');
|
||||
|
||||
const { dir, url, ref } = workerData;
|
||||
|
||||
const tmpDir = `${dir}.tmp`;
|
||||
const bakDir = `${dir}.bak`;
|
||||
|
||||
const run = async () => {
|
||||
await fs.remove(tmpDir);
|
||||
await git.clone({
|
||||
dir: tmpDir,
|
||||
fs,
|
||||
http,
|
||||
url,
|
||||
ref,
|
||||
singleBranch: !ref || ref === 'master' || ref === 'main',
|
||||
onProgress: (...args) => port.postMessage({ cb: 'onProgress', args })
|
||||
});
|
||||
|
||||
await fs.remove(bakDir);
|
||||
const hadExisting = await fs.pathExists(dir);
|
||||
if (hadExisting) await fs.move(dir, bakDir);
|
||||
|
||||
try {
|
||||
await fs.move(tmpDir, dir);
|
||||
} catch (e) {
|
||||
if (hadExisting) await fs.move(bakDir, dir).catch(() => undefined);
|
||||
throw e;
|
||||
}
|
||||
|
||||
await fs.remove(bakDir).catch(() => undefined);
|
||||
};
|
||||
|
||||
run()
|
||||
.then(() => port.postMessage(true))
|
||||
.catch(async err => {
|
||||
await fs.remove(tmpDir).catch(() => undefined);
|
||||
throw err;
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { workerData, parentPort } from 'worker_threads';
|
||||
|
||||
import git from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/node';
|
||||
import fs from 'fs-extra';
|
||||
|
||||
const port = parentPort;
|
||||
if (!port) throw new Error('gitPull worker has no parentPort');
|
||||
|
||||
const { dir, remote, branch, ref } = workerData as {
|
||||
dir: string;
|
||||
remote: string;
|
||||
branch: string;
|
||||
ref?: string;
|
||||
};
|
||||
|
||||
const onProgress = (...args: unknown[]) =>
|
||||
port.postMessage({ cb: 'onProgress', args });
|
||||
|
||||
const run = async () => {
|
||||
if (ref) {
|
||||
await git.fetch({
|
||||
fs,
|
||||
http,
|
||||
dir,
|
||||
tags: true,
|
||||
singleBranch: false,
|
||||
onProgress
|
||||
});
|
||||
await git.checkout({ fs, dir, force: true, ref, onProgress });
|
||||
return;
|
||||
}
|
||||
|
||||
await git.checkout({
|
||||
fs,
|
||||
dir,
|
||||
force: true,
|
||||
ref: `${remote}/${branch}`,
|
||||
onProgress
|
||||
});
|
||||
await git.pull({
|
||||
fs,
|
||||
http,
|
||||
dir,
|
||||
ref: branch,
|
||||
singleBranch: true,
|
||||
author: { name: 'Octo Launcher' },
|
||||
onProgress
|
||||
});
|
||||
};
|
||||
|
||||
run()
|
||||
.then(() => port.postMessage(true))
|
||||
.catch(err => {
|
||||
throw err;
|
||||
});
|
||||
Reference in New Issue
Block a user