Compare commits

3 Commits

Author SHA1 Message Date
OctoWoW eecda9381a OctoLauncher 1.3.6 2026-08-14 14:04:57 +00:00
OctoWoW f9d89601f1 OctoLauncher 1.3.5 2026-08-14 11:37:18 +00:00
OctoWoW 5dca94a3fc 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.
2026-08-14 01:45:50 +00:00
51 changed files with 3326 additions and 1578 deletions
+2
View File
@@ -1,2 +1,4 @@
MAIN_VITE_SERVER_URL=https://octowow.st MAIN_VITE_SERVER_URL=https://octowow.st
MAIN_VITE_CLIENT_VERSION=latest MAIN_VITE_CLIENT_VERSION=latest
MAIN_VITE_CLIENT_TORRENT_URL=https://dl.octowow.st/download/client.torrent
MAIN_VITE_RAID_VISUALS_URL=https://dl.octowow.st/client/latest/Data/patch-O.mpq
+11 -11
View File
@@ -8,10 +8,10 @@ The project as checked out does **not** build on a default up-to-date Windows de
1. **Added a Node version manager (`fnm`) and installed Node 20** alongside the existing Node 24. Node 24 was the system default and caused `nan` / `dll-inject` compile failures. Node 20 is now the fnm default but Node 24 is still available via `fnm use system`. 1. **Added a Node version manager (`fnm`) and installed Node 20** alongside the existing Node 24. Node 24 was the system default and caused `nan` / `dll-inject` compile failures. Node 20 is now the fnm default but Node 24 is still available via `fnm use system`.
2. **Installed Visual Studio 2022 Build Tools** with the `VCTools` workload and Windows 11 SDK. Machine already had VS2026 (v18), but `node-gyp` v10 (shipped with Node 20's npm) doesn't detect it. VS2022 now lives side-by-side under `C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools`. 2. **Installed Visual Studio 2022 Build Tools** with the `VCTools` workload and Windows 11 SDK. Machine already had VS2026 (v18), but `node-gyp` v10 (shipped with Node 20's npm) doesn't detect it. VS2022 now lives side-by-side under `C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools`.
3. **Unset `ELECTRON_RUN_AS_NODE`** per-shell before launching Electron. This var is set globally by VSCode's integrated terminal (inherited from the extension host) it is not something we can remove permanently without breaking VSCode. It has to be unset in each shell that runs `npm run dev` / `dist`. 3. **Unset `ELECTRON_RUN_AS_NODE`** per-shell before launching Electron. This var is set globally by VSCode's integrated terminal (inherited from the extension host): it is not something we can remove permanently without breaking VSCode. It has to be unset in each shell that runs `npm run dev` / `dist`.
4. **Populated `node_modules`** in both `main/` and `main/server/`. The tree was checked in empty. 4. **Populated `node_modules`** in both `main/` and `main/server/`. The tree was checked in empty.
Nothing in the repo itself was modified all fixes were environmental. If another developer checks this repo out, they need to apply items 14 on their own machine. The sections below are that recipe. Nothing in the repo itself was modified; all fixes were environmental. If another developer checks this repo out, they need to apply items 1-4 on their own machine. The sections below are that recipe.
--- ---
@@ -19,7 +19,7 @@ Nothing in the repo itself was modified — all fixes were environmental. If ano
### 1. Node.js 20 (not 22, not 24) ### 1. Node.js 20 (not 22, not 24)
Node 24 breaks the `dll-inject` native module its `nan` C++ bindings don't compile against V8 in Node 22+. Stick to Node 20 LTS. Node 24 breaks the `dll-inject` native module; its `nan` C++ bindings don't compile against V8 in Node 22+. Stick to Node 20 LTS.
Install via `fnm` so you can keep your system Node separate: Install via `fnm` so you can keep your system Node separate:
@@ -33,7 +33,7 @@ Verify: `node -v` should print `v20.x.x`.
### 2. Visual Studio 2022 Build Tools (C++ workload) ### 2. Visual Studio 2022 Build Tools (C++ workload)
`dll-inject` and `stormlib-node` compile native addons via `node-gyp`. `node-gyp` v10 (bundled with Node 20's npm) only recognizes VS20172022 newer VS versions (2026 / v18) are not detected. `dll-inject` and `stormlib-node` compile native addons via `node-gyp`. `node-gyp` v10 (bundled with Node 20's npm) only recognizes VS2017-2022; newer VS versions (2026 / v18) are not detected.
```bash ```bash
winget install Microsoft.VisualStudio.2022.BuildTools \ winget install Microsoft.VisualStudio.2022.BuildTools \
@@ -75,7 +75,7 @@ cd ..
## Critical env var: `ELECTRON_RUN_AS_NODE` ## Critical env var: `ELECTRON_RUN_AS_NODE`
**VSCode's integrated terminal sets `ELECTRON_RUN_AS_NODE=1`** (inherited from VSCode's extension host). This makes Electron binaries launch as plain Node, so `require('electron')` returns a path string instead of the API the app crashes with `TypeError: Cannot read properties of undefined (reading 'isPackaged')`. **VSCode's integrated terminal sets `ELECTRON_RUN_AS_NODE=1`** (inherited from VSCode's extension host). This makes Electron binaries launch as plain Node, so `require('electron')` returns a path string instead of the API: the app crashes with `TypeError: Cannot read properties of undefined (reading 'isPackaged')`.
Before any `npm run dev` / `npm run build` / `npm run dist`: Before any `npm run dev` / `npm run build` / `npm run dist`:
@@ -87,7 +87,7 @@ unset ELECTRON_RUN_AS_NODE
Remove-Item Env:ELECTRON_RUN_AS_NODE Remove-Item Env:ELECTRON_RUN_AS_NODE
``` ```
An external terminal (Windows Terminal, cmd, plain PowerShell) doesn't have this problem the variable is only set inside VSCode. An external terminal (Windows Terminal, cmd, plain PowerShell) doesn't have this problem; the variable is only set inside VSCode.
## Running in dev ## Running in dev
@@ -99,8 +99,8 @@ Starts electron-vite, builds main + preload + renderer, opens an Electron window
You'll see benign warnings in the console: You'll see benign warnings in the console:
- `ERROR:cache_util_win.cc ... Access is denied` OneDrive sync locking Electron's user-data cache. Cosmetic. To silence, move the project out of OneDrive or set a custom user-data dir. - `ERROR:cache_util_win.cc ... Access is denied`: OneDrive sync locking Electron's user-data cache. Cosmetic. To silence, move the project out of OneDrive or set a custom user-data dir.
- `Browserslist: caniuse-lite is outdated` cosmetic. - `Browserslist: caniuse-lite is outdated`: cosmetic.
## Building for distribution ## Building for distribution
@@ -113,14 +113,14 @@ npm run dist
Outputs land in `dist/`: Outputs land in `dist/`:
- `OctoLauncher.exe` portable single-file build - `OctoLauncher.exe`: portable single-file build
- `OctoLauncher_Installer.exe` NSIS installer - `OctoLauncher_Installer.exe`: NSIS installer
Targets are configured in [electron-builder.yml](electron-builder.yml). Targets are configured in [electron-builder.yml](electron-builder.yml).
### Before publishing ### Before publishing
- The build uses `.env.production` (committed) which already points to `https://octowow.st` no `.env` file needed for production builds. - The build uses `.env.production` (committed) which already points to `https://octowow.st`: no `.env` file needed for production builds.
- Code signing is not configured. Unsigned Windows builds trigger SmartScreen warnings. To sign, add a `win.certificateFile` + password (or use env-based signing) to the electron-builder config. - Code signing is not configured. Unsigned Windows builds trigger SmartScreen warnings. To sign, add a `win.certificateFile` + password (or use env-based signing) to the electron-builder config.
## Troubleshooting ## Troubleshooting
+10 -10
View File
@@ -1,6 +1,6 @@
# News feed # News feed
**Note:** The launcher no longer uses a static `news.json` file. The News tab now pulls live from the OctoWoW announcements forum via the website's `/news.json` endpoint, which is backed by `ForumFeedService` on the Laravel side. To publish a news item in the launcher, simply post in the configured announcements forum the launcher will pick it up within the cache TTL (default 10 minutes). There is no JSON file to edit or deploy. **Note:** The launcher no longer uses a static `news.json` file. The News tab now pulls live from the OctoWoW announcements forum via the website's `/news.json` endpoint, which is backed by `ForumFeedService` on the Laravel side. To publish a news item in the launcher, post in the configured announcements forum; the launcher will pick it up within the cache TTL (default 10 minutes). There is no JSON file to edit or deploy.
The launcher's News tab fetches `${MAIN_VITE_SERVER_URL}/news.json` and renders the entries on the landing screen. The endpoint is dynamic: it mirrors the same forum posts the website's homepage shows in its "Recent forum posts" cards, so updating the forum updates the launcher. The launcher's News tab fetches `${MAIN_VITE_SERVER_URL}/news.json` and renders the entries on the landing screen. The endpoint is dynamic: it mirrors the same forum posts the website's homepage shows in its "Recent forum posts" cards, so updating the forum updates the launcher.
@@ -12,7 +12,7 @@ The launcher's News tab fetches `${MAIN_VITE_SERVER_URL}/news.json` and renders
The route is served by Laravel (`routes/web.php``news.json`) and reads from `App\Services\ForumFeedService`, which fetches the configured phpBB Atom feed (`FORUM_FEED_BASE_URL`/`FORUM_FEED_MODE`/`FORUM_FEED_FORUM_ID` in `config/customs.php``forum_feed`). The same service backs the homepage's `recent-forum-posts` Livewire component, so what shows in the launcher is exactly what shows on the site. The route is served by Laravel (`routes/web.php``news.json`) and reads from `App\Services\ForumFeedService`, which fetches the configured phpBB Atom feed (`FORUM_FEED_BASE_URL`/`FORUM_FEED_MODE`/`FORUM_FEED_FORUM_ID` in `config/customs.php``forum_feed`). The same service backs the homepage's `recent-forum-posts` Livewire component, so what shows in the launcher is exactly what shows on the site.
No auth. The launcher times out after 8 seconds and validates the body against the schema below malformed payloads surface as the "Couldn't reach the news feed" error state (with a Try again button). No auth. The launcher times out after 8 seconds and validates the body against the schema below; malformed payloads surface as the "Couldn't reach the news feed" error state (with a Try again button).
## Payload contract ## Payload contract
@@ -34,7 +34,7 @@ No auth. The launcher times out after 8 seconds and validates the body against t
Source of truth for the schema: [src/common/schemas.ts](src/common/schemas.ts) (`NewsItemSchema`, `NewsFeedSchema`). If you change the contract, update both ends. Source of truth for the schema: [src/common/schemas.ts](src/common/schemas.ts) (`NewsItemSchema`, `NewsFeedSchema`). If you change the contract, update both ends.
Notes: Notes:
- `items` is rendered in the order returned sort newest-first on the server. - `items` is rendered in the order returned: sort newest-first on the server.
- `body` is rendered as plain text with `whitespace-pre-wrap`. No HTML/markdown. - `body` is rendered as plain text with `whitespace-pre-wrap`. No HTML/markdown.
- `url`, when present, becomes a "Read more" button that opens in the user's default browser via `shell.openExternal`. Skip it for inline-only posts. - `url`, when present, becomes a "Read more" button that opens in the user's default browser via `shell.openExternal`. Skip it for inline-only posts.
- `id` should never change for an existing post (stable React keys, future bookmarking/read-state). - `id` should never change for an existing post (stable React keys, future bookmarking/read-state).
@@ -43,8 +43,8 @@ Notes:
There is no static file to edit anymore. To change what the launcher shows, post on the forum (`FORUM_FEED_BASE_URL`, e.g. `https://octowow.st/forum`). The next launcher fetch picks it up subject to two cache layers: There is no static file to edit anymore. To change what the launcher shows, post on the forum (`FORUM_FEED_BASE_URL`, e.g. `https://octowow.st/forum`). The next launcher fetch picks it up subject to two cache layers:
- `forum_feed.cache_ttl` (default 600 s, env `FORUM_FEED_CACHE_TTL`) Laravel server-side cache of the parsed Atom feed. - `forum_feed.cache_ttl` (default 600 s, env `FORUM_FEED_CACHE_TTL`): Laravel server-side cache of the parsed Atom feed.
- `Cache-Control: public, max-age=120` on the `/news.json` response short edge cache so launcher launches in a burst don't all hit Laravel. - `Cache-Control: public, max-age=120` on the `/news.json` response: short edge cache so launcher launches in a burst don't all hit Laravel.
The launcher's react-query cache also holds for 5 minutes per session; users can hit the refresh icon in the News header to force a re-fetch (which still hits the two cache layers above). The launcher's react-query cache also holds for 5 minutes per session; users can hit the refresh icon in the News header to force a re-fetch (which still hits the two cache layers above).
@@ -62,11 +62,11 @@ The launcher's react-query cache also holds for 5 minutes per session; users can
curl -s ${MAIN_VITE_SERVER_URL}/news.json | jq . curl -s ${MAIN_VITE_SERVER_URL}/news.json | jq .
``` ```
Expected: a `{"items": [...]}` body. An empty `items: []` means the forum feed is reachable but has nothing matching the configured mode (or the cache is still warm with an empty result bust it by `php artisan cache:clear` inside the website container, or wait `FORUM_FEED_CACHE_TTL` seconds). Expected: a `{"items": [...]}` body. An empty `items: []` means the forum feed is reachable but has nothing matching the configured mode (or the cache is still warm with an empty result; bust it by `php artisan cache:clear` inside the website container, or wait `FORUM_FEED_CACHE_TTL` seconds).
**No items / errors:** **No items / errors:**
- `{"items": []}` `FORUM_FEED_BASE_URL` is unset, the feed returned non-2xx, the body wasn't parseable Atom XML, or the configured forum has no posts. Check the website container's `storage/logs/laravel.log` for `ForumFeedService` warnings. - `{"items": []}`: `FORUM_FEED_BASE_URL` is unset, the feed returned non-2xx, the body wasn't parseable Atom XML, or the configured forum has no posts. Check the website container's `storage/logs/laravel.log` for `ForumFeedService` warnings.
- `Couldn't reach the news feed` in the launcher Laravel returned a 5xx (route exception, missing `ForumFeedService` binding) or the schema validator rejected the body. Check the launcher's main-process log at `%APPDATA%\octo-launcher\logs\main.log` for `Malformed news feed`. - `Couldn't reach the news feed` in the launcher: Laravel returned a 5xx (route exception, missing `ForumFeedService` binding) or the schema validator rejected the body. Check the launcher's main-process log at `%APPDATA%\octo-launcher\logs\main.log` for `Malformed news feed`.
**End-to-end check in the launcher:** **End-to-end check in the launcher:**
1. Open the launcher (the News tab is the default view when no other tab is selected). 1. Open the launcher (the News tab is the default view when no other tab is selected).
@@ -78,11 +78,11 @@ Expected: a `{"items": [...]}` body. An empty `items: []` means the forum feed i
| Server response | UI behaviour | | Server response | UI behaviour |
| --- | --- | | --- | --- |
| `200` with valid JSON | Renders entries | | `200` with valid JSON | Renders entries |
| `200` with empty `items: []` | "No news yet check back later." | | `200` with empty `items: []` | "No news yet: check back later." |
| `200` with malformed JSON or missing required fields | Error state + Try again. Reason logged in main-process logs (`%APPDATA%\octo-launcher\logs\main.log`). | | `200` with malformed JSON or missing required fields | Error state + Try again. Reason logged in main-process logs (`%APPDATA%\octo-launcher\logs\main.log`). |
| `404`, `5xx`, network unreachable, > 8s timeout | Error state + Try again. | | `404`, `5xx`, network unreachable, > 8s timeout | Error state + Try again. |
You don't need to ship a placeholder `news.json` to avoid 404s the empty/error state is intentional. You don't need to ship a placeholder `news.json` to avoid 404s; the empty/error state is intentional.
## Where the code lives ## Where the code lives
+12 -12
View File
@@ -18,7 +18,7 @@ Desktop launcher for the OctoWoW (World of Warcraft 1.12.1 private server) clien
2. Run it and set your WoW client directory when prompted. 2. Run it and set your WoW client directory when prompted.
3. Click **Verify** to download any missing game files, then **Play**. 3. Click **Verify** to download any missing game files, then **Play**.
No server configuration needed the launcher connects to `octowow.st` by default. No server configuration needed; the launcher connects to `octowow.st` by default.
--- ---
@@ -28,8 +28,8 @@ No server configuration needed — the launcher connects to `octowow.st` by defa
| Requirement | Version | Notes | | Requirement | Version | Notes |
|---|---|---| |---|---|---|
| Node.js | 20 LTS | Node 22+ breaks `dll-inject` native bindings use Node 20 | | Node.js | 20 LTS | Node 22+ breaks `dll-inject` native bindings: use Node 20 |
| VS 2022 Build Tools | C++ workload + Win SDK | `node-gyp` v10 only detects VS20172022 | | VS 2022 Build Tools | C++ workload + Win SDK | `node-gyp` v10 only detects VS2017-2022 |
| Python | 3.x | Required by `node-gyp` | | Python | 3.x | Required by `node-gyp` |
Install Node 20 with `fnm`: Install Node 20 with `fnm`:
@@ -51,7 +51,7 @@ winget install Microsoft.VisualStudio.2022.BuildTools `
npm install npm install
``` ```
`postinstall` rebuilds the native modules (`dll-inject`, `stormlib-node`) against the Electron ABI expect C++ compiler output. `postinstall` rebuilds the native modules (`dll-inject`, `stormlib-node`) against the Electron ABI; expect C++ compiler output.
### Run in development ### Run in development
@@ -64,7 +64,7 @@ npm install
npm run dev npm run dev
``` ```
Opens the app in a hot-reloading Electron window. The dev build points to `http://localhost:5000` by default create a `.env` file from `.env.example` if you want to run against a local server, otherwise it falls back to `https://octowow.st`. Opens the app in a hot-reloading Electron window. The dev build points to `http://localhost:5000` by default; create a `.env` file from `.env.example` if you want to run against a local server, otherwise it falls back to `https://octowow.st`.
### Build for distribution ### Build for distribution
@@ -74,8 +74,8 @@ npm run dist
``` ```
Outputs to `dist/`: Outputs to `dist/`:
- `OctoLauncher.exe` portable single-file - `OctoLauncher.exe`: portable single-file
- `OctoLauncher_Installer.exe` NSIS installer - `OctoLauncher_Installer.exe`: NSIS installer
The production build uses `.env.production` (committed) which points to `https://octowow.st`. No `.env` file needed. The production build uses `.env.production` (committed) which points to `https://octowow.st`. No `.env` file needed.
@@ -98,7 +98,7 @@ npm run dev
The server listens on `http://localhost:5000` and serves: The server listens on `http://localhost:5000` and serves:
- `GET /api/file/:version/manifest.json` - `GET /api/file/:version/manifest.json`
- `GET /client/:version/*` per-file downloads - `GET /client/:version/*`: per-file downloads
- `GET /api/addons.json` - `GET /api/addons.json`
--- ---
@@ -107,11 +107,11 @@ The server listens on `http://localhost:5000` and serves:
Three Vite bundles tied together by tRPC over Electron IPC: Three Vite bundles tied together by tRPC over Electron IPC:
- **Main** ([src/main/](src/main/)) Electron main process; owns all filesystem/native work and the tRPC router - **Main** ([src/main/](src/main/)): Electron main process; owns all filesystem/native work and the tRPC router
- **Preload** ([src/preload/](src/preload/)) secure IPC bridge via `exposeElectronTRPC()` - **Preload** ([src/preload/](src/preload/)): secure IPC bridge via `exposeElectronTRPC()`
- **Renderer** ([src/renderer/](src/renderer/)) React 18 + Tailwind UI; no direct Node access - **Renderer** ([src/renderer/](src/renderer/)): React 18 + Tailwind UI; no direct Node access
All cross-process data shapes are Zod schemas in [src/common/schemas.ts](src/common/schemas.ts). All renderer→main calls go through tRPC procedures in [src/main/api/routers/](src/main/api/routers/) never raw `ipcMain.handle`. All cross-process data shapes are Zod schemas in [src/common/schemas.ts](src/common/schemas.ts). All renderer→main calls go through tRPC procedures in [src/main/api/routers/](src/main/api/routers/); never raw `ipcMain.handle`.
--- ---
+1 -1
View File
@@ -14,4 +14,4 @@ cd Tools\launcher
Output: `dist\OctoLauncher.exe` (portable) and `dist\OctoLauncher_Installer.exe` (NSIS). Output: `dist\OctoLauncher.exe` (portable) and `dist\OctoLauncher_Installer.exe` (NSIS).
The `node/` directory is gitignored it is recreated by `install.ps1`. The `node/` directory is gitignored; it is recreated by `install.ps1`.
+4 -4
View File
@@ -1,4 +1,4 @@
# opentracker OctoWow launcher torrent swarm # opentracker: OctoWow launcher torrent swarm
BitTorrent tracker the launcher's webtorrent clients announce to. Runs BitTorrent tracker the launcher's webtorrent clients announce to. Runs
on your VPS alongside the companion update server. Tiny (~2 MB RSS), on your VPS alongside the companion update server. Tiny (~2 MB RSS),
@@ -7,7 +7,7 @@ near-zero CPU, zero disk IO after boot.
**Why your own tracker**: public trackers (opentrackr.org, etc.) are **Why your own tracker**: public trackers (opentrackr.org, etc.) are
reliable enough for hobby swarms but add a single-point-of-failure you reliable enough for hobby swarms but add a single-point-of-failure you
don't control, and often rate-limit new info-hashes. The launcher also don't control, and often rate-limit new info-hashes. The launcher also
announces over DHT, so your tracker is redundant with DHT but it's announces over DHT, so your tracker is redundant with DHT, but it is
the fastest path for a fresh peer to find the swarm before DHT has the fastest path for a fresh peer to find the swarm before DHT has
warmed up. warmed up.
@@ -21,7 +21,7 @@ chmod +x install.sh
./install.sh ./install.sh
``` ```
`install.sh` is idempotent re-run to update. It builds opentracker `install.sh` is idempotent; re-run to update. It builds opentracker
from CVS (only distribution upstream offers), installs it under from CVS (only distribution upstream offers), installs it under
`/opt/opentracker/bin/`, drops a hardened systemd unit, and starts the `/opt/opentracker/bin/`, drops a hardened systemd unit, and starts the
service bound to `0.0.0.0:6969`. service bound to `0.0.0.0:6969`.
@@ -51,7 +51,7 @@ TRACKER_URL=http://<your-vps-ip>:6969/announce npm run server
Default is `http://127.0.0.1:6969/announce` (assumes tracker + companion Default is `http://127.0.0.1:6969/announce` (assumes tracker + companion
server run on the same VPS, which is the normal deployment). server run on the same VPS, which is the normal deployment).
Clients pull the `.torrent` blob from the companion server the URL Clients pull the `.torrent` blob from the companion server; the URL
is already baked in by `create-torrent` at generation time, so no is already baked in by `create-torrent` at generation time, so no
launcher-side config needed. launcher-side config needed.
+2 -2
View File
@@ -1,5 +1,5 @@
[Unit] [Unit]
Description=opentracker BitTorrent tracker for OctoWow launcher swarm Description=opentracker: BitTorrent tracker for OctoWow launcher swarm
After=network.target After=network.target
[Service] [Service]
@@ -11,7 +11,7 @@ ExecStart=/opt/opentracker/bin/opentracker -i 0.0.0.0 -p 6969 -P 6969
Restart=on-failure Restart=on-failure
RestartSec=5 RestartSec=5
# Hardening opentracker does no filesystem IO after boot, so most of # Hardening: opentracker does no filesystem IO after boot, so most of
# the namespace can be locked down. # the namespace can be locked down.
NoNewPrivileges=true NoNewPrivileges=true
PrivateTmp=true PrivateTmp=true
+6 -2
View File
@@ -11,6 +11,7 @@ files:
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,.prettierrc.cjs,dev-app-update.yml}' - '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,.prettierrc.cjs,dev-app-update.yml}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}' - '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}' - '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
- '!*.tsbuildinfo'
- '!{tailwind.config.ts,postcss.config.cjs}' - '!{tailwind.config.ts,postcss.config.cjs}'
- '!dist*/**' - '!dist*/**'
- '!out/main/chunks/**' - '!out/main/chunks/**'
@@ -29,13 +30,16 @@ files:
- '!**/node_modules/**/*.{vcxproj,vcxproj.filters}' - '!**/node_modules/**/*.{vcxproj,vcxproj.filters}'
npmRebuild: false npmRebuild: false
electronLanguages: en electronLanguages: en
extraResources:
- from: resources/aria2c.exe
to: aria2c.exe
win: win:
artifactName: ${productName}.${ext} artifactName: ${productName}.${ext}
target: target:
- portable
- nsis - nsis
nsis: nsis:
artifactName: ${productName}_Installer.${ext} # versioned: differential updates need the old blockmap to stay fetchable
artifactName: ${productName}_Installer-${version}.${ext}
uninstallDisplayName: ${productName} uninstallDisplayName: ${productName}
oneClick: false oneClick: false
removeDefaultUninstallWelcomePage: true removeDefaultUninstallWelcomePage: true
+22 -11
View File
@@ -2,6 +2,7 @@ import { resolve } from 'path';
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'; import { defineConfig, externalizeDepsPlugin } from 'electron-vite';
import react from '@vitejs/plugin-react'; import react from '@vitejs/plugin-react';
import { loadEnv } from 'vite';
const alias = { const alias = {
'~common': resolve('src/common'), '~common': resolve('src/common'),
@@ -10,16 +11,26 @@ const alias = {
'~build': resolve('build') '~build': resolve('build')
}; };
export default defineConfig({ export default defineConfig(({ mode }) => {
main: { if (mode === 'ptr') {
resolve: { alias }, const realm = loadEnv(mode, process.cwd(), 'MAIN_VITE_')
plugins: [externalizeDepsPlugin()] .MAIN_VITE_PTR_REALMLIST;
}, if (!realm || realm === 'octowow.st')
preload: { throw new Error(
plugins: [externalizeDepsPlugin()] 'PTR build needs MAIN_VITE_PTR_REALMLIST set to a non-prod realm host'
}, );
renderer: {
resolve: { alias },
plugins: [react()]
} }
return {
main: {
resolve: { alias },
plugins: [externalizeDepsPlugin()]
},
preload: {
plugins: [externalizeDepsPlugin()]
},
renderer: {
resolve: { alias },
plugins: [react()]
}
};
}); });
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "octo-launcher", "name": "octo-launcher",
"version": "1.2.1", "version": "1.3.6",
"description": "An Electron application for launching and updating the OctoWoW client", "description": "An Electron application for launching and updating the OctoWoW client",
"author": "OctoWoW", "author": "OctoWoW",
"copyright": "Copyright © 2026 OctoWoW", "copyright": "Copyright © 2026 OctoWoW",
+97
View File
@@ -0,0 +1,97 @@
const fs = require('fs');
const os = require('os');
const path = require('path');
const FILL = 0x78;
function pathVariants(p) {
const set = new Set([p, p.replace(/\\/g, '/'), p.replace(/\//g, '\\')]);
return [...set].filter(Boolean);
}
const root = process.cwd();
const home = os.homedir();
let username = '';
try {
username = os.userInfo().username;
} catch {
username = '';
}
const secrets = [];
if (root.length > 2) secrets.push(...pathVariants(root));
if (home.length > 2 && home !== root) secrets.push(...pathVariants(home));
if (username.length >= 4) secrets.push(username);
const needles = [...new Set(secrets)]
.filter(s => s.length > 0)
.map(s => s.toLowerCase())
.sort((a, b) => b.length - a.length);
function scanAndFill(buf, s, stride) {
const n = s.length;
const span = n * stride;
if (span === 0 || span > buf.length) return 0;
let hits = 0;
outer: for (let i = 0; i + span <= buf.length; i++) {
for (let j = 0; j < n; j++) {
const at = i + j * stride;
let b = buf[at];
if (b >= 0x41 && b <= 0x5a) b += 0x20;
if (b !== s.charCodeAt(j)) continue outer;
if (stride === 2 && buf[at + 1] !== 0x00) continue outer;
}
buf.fill(FILL, i, i + span);
hits++;
i += span - 1;
}
return hits;
}
function redact(buf) {
let hits = 0;
for (const s of needles) {
hits += scanAndFill(buf, s, 1);
hits += scanAndFill(buf, s, 2);
}
return hits;
}
function collect(dir, out) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
const p = path.join(dir, e.name);
if (e.isDirectory()) collect(p, out);
else if (e.isFile() && p.endsWith('.node')) out.push(p);
}
}
const addons = [];
collect(path.join(root, 'node_modules'), addons);
let files = 0;
let total = 0;
const redacted = [];
for (const file of addons) {
try {
const buf = fs.readFileSync(file);
const hits = redact(buf);
if (hits > 0) {
fs.writeFileSync(file, buf);
files++;
total += hits;
redacted.push(`${path.relative(root, file)} (${hits})`);
}
} catch (err) {
console.warn(`scrub-native-paths: skipped ${path.basename(file)} (${err.message})`);
}
}
console.log(`scrub-native-paths: redacted ${total} path reference(s) across ${files} addon(s)`);
for (const r of redacted) console.log(` ${r}`);
+7 -1
View File
@@ -15,7 +15,13 @@ export const defaultSources: AddonSource[] = [
git: 'https://github.com/McPewPew/ArcHUD2.git', git: 'https://github.com/McPewPew/ArcHUD2.git',
description: 'Combat HUD showing health and power as arcs around your character' description: 'Combat HUD showing health and power as arcs around your character'
}, },
{ git: 'https://github.com/CosminPOP/AtlasLoot.git', name: 'AtlasLoot' }, {
git: 'https://octowow.st/git/shaga/AtlasLoot.git',
name: 'AtlasLoot',
branch: 'main',
description:
'Loot browser for every dungeon and raid, including the custom OctoWoW instances (Windhorn Canyon, Dragonmaw Retreat, and more)'
},
{ {
git: 'https://github.com/byCFM2/Atlas-TW.git', git: 'https://github.com/byCFM2/Atlas-TW.git',
name: 'Atlas-CFM' name: 'Atlas-CFM'
+9 -1
View File
@@ -15,6 +15,7 @@ const allowedExtra = [
]; ];
const vanillaFixes = ['VfPatcher.dll', 'd3d9.dll', 'dxvk.conf']; const vanillaFixes = ['VfPatcher.dll', 'd3d9.dll', 'dxvk.conf'];
const raidVisuals = ['patch-O.mpq'];
const skipFiles = new Set([ const skipFiles = new Set([
'manifest.json', 'manifest.json',
@@ -45,7 +46,7 @@ const isSkipDir = (...filePath: string[]) =>
skipDirsPosix.has(filePath.join('/')); skipDirsPosix.has(filePath.join('/'));
type FolderTags = 'allowExtra'; type FolderTags = 'allowExtra';
type FileTags = 'vanillaFixes'; type FileTags = 'vanillaFixes' | 'raidVisuals';
type FileManifest = { name: string } & ( type FileManifest = { name: string } & (
| { type: 'dir'; files: FileManifest[]; tags?: FolderTags[] } | { type: 'dir'; files: FileManifest[]; tags?: FolderTags[] }
@@ -191,6 +192,12 @@ export const buildCache = async (
if (stats.isDirectory()) { if (stats.isDirectory()) {
if (isSkipDir(...filePath, file)) continue; if (isSkipDir(...filePath, file)) continue;
if (file.match(/patch-./)) { if (file.match(/patch-./)) {
if (raidVisuals.includes(`${file}.mpq`))
throw new Error(
`${file}/ exists beside ${file}.mpq. Opt-in archives must stay ` +
'whole-file: an mpq node carries no tags, so this would ' +
'ship the patch to every player regardless of preference.'
);
patches.push(file); patches.push(file);
const mpqRelPath = path const mpqRelPath = path
.join(...filePath, `${file}.mpq`) .join(...filePath, `${file}.mpq`)
@@ -243,6 +250,7 @@ export const buildCache = async (
const tags: FileTags[] = []; const tags: FileTags[] = [];
vanillaFixes.includes(file) && tags.push('vanillaFixes'); vanillaFixes.includes(file) && tags.push('vanillaFixes');
raidVisuals.includes(file) && tags.push('raidVisuals');
tree.push({ tree.push({
type: 'file', type: 'file',
+36
View File
@@ -4,6 +4,7 @@ export const ModIdSchema = z.enum([
'dxvk', 'dxvk',
'nampower', 'nampower',
'multiMonitorFix', 'multiMonitorFix',
'superWow',
'transmogFix', 'transmogFix',
'unitXp', 'unitXp',
'vanillaFixes', 'vanillaFixes',
@@ -19,6 +20,7 @@ export type ModSource =
apiUrl?: string; apiUrl?: string;
pinnedTag?: string; pinnedTag?: string;
assetName: string; assetName: string;
sha256?: string;
} }
| { | {
kind: 'archive'; kind: 'archive';
@@ -28,6 +30,7 @@ export type ModSource =
pinnedTag?: string; pinnedTag?: string;
format: 'zip' | 'tar.gz'; format: 'zip' | 'tar.gz';
extractMap: Record<string, string>; extractMap: Record<string, string>;
sha256?: string;
} }
| { kind: 'managed' }; | { kind: 'managed' };
@@ -41,6 +44,8 @@ export type ModEntry = {
repoUrl: string; repoUrl: string;
source: ModSource; source: ModSource;
registerInDllsTxt?: string; registerInDllsTxt?: string;
// hidden from the Mods tab, never enabled on fresh installs; existing installs keep it
disabled?: boolean;
}; };
export const MODS: ModEntry[] = [ export const MODS: ModEntry[] = [
@@ -98,6 +103,30 @@ export const MODS: ModEntry[] = [
}, },
registerInDllsTxt: 'VanillaMultiMonitorFix.dll' registerInDllsTxt: 'VanillaMultiMonitorFix.dll'
}, },
{
id: 'superWow',
name: 'SuperWoW',
version: '2.2',
description:
'Extends the client Lua API with unit GUIDs and other data many addons rely on.',
repoUrl: 'https://github.com/balakethelock/SuperWoW',
requires: ['vanillaFixes'],
source: {
kind: 'archive',
url: 'https://github.com/balakethelock/SuperWoW/releases/download/Release/SuperWoW.release.2.2.zip',
apiUrl:
'https://api.github.com/repos/balakethelock/SuperWoW/releases/latest',
parseLatest: 'githubRelease',
pinnedTag: '2.2',
format: 'zip',
extractMap: {
'SuperWoWhook.dll': 'SuperWoWhook.dll'
}
},
registerInDllsTxt: 'SuperWoWhook.dll',
// disabled 2026-08-08 pending distribution permission; delete this line to re-enable
disabled: true
},
{ {
id: 'transmogFix', id: 'transmogFix',
name: 'transmogFix', name: 'transmogFix',
@@ -177,3 +206,10 @@ export const MODS: ModEntry[] = [
export const getMod = (id: ModId): ModEntry | undefined => export const getMod = (id: ModId): ModEntry | undefined =>
MODS.find(m => m.id === id); MODS.find(m => m.id === id);
// fallback for profiles with no stored state: enabled, so legacy installs
// keep their mods; fresh installs seed explicit off rows instead (do NOT
// flip this list to change defaults, it strips mods from legacy profiles)
export const DEFAULT_ENABLED_MODS: ModId[] = MODS.filter(m => !m.disabled).map(
m => m.id
);
+10
View File
@@ -17,6 +17,7 @@ const f = {
export const ConfigWtfSchema = z.object({ export const ConfigWtfSchema = z.object({
vanillaFixes: f.boolean(), vanillaFixes: f.boolean(),
raidVisuals: f.boolean(),
largeAddress: f.boolean(true), largeAddress: f.boolean(true),
nameplateRange: f.number(41), nameplateRange: f.number(41),
alwaysAutoLoot: f.boolean(), alwaysAutoLoot: f.boolean(),
@@ -57,11 +58,20 @@ export const PreferencesSchema = z.object({
expectedPatchedWowHash: z.string().optional(), expectedPatchedWowHash: z.string().optional(),
minimizeToTrayOnPlay: f.boolean(true), minimizeToTrayOnPlay: f.boolean(true),
cleanWdb: f.boolean(true), cleanWdb: f.boolean(true),
shareDownloads: f.boolean(true),
locale: z locale: z
.enum(['enUS', 'deDE', 'zhCN', 'esES', 'ptBR', 'ruRU']) .enum(['enUS', 'deDE', 'zhCN', 'esES', 'ptBR', 'ruRU'])
.default('enUS'), .default('enUS'),
localePatchLetter: z.string().optional(), localePatchLetter: z.string().optional(),
localePatchLocale: z.string().optional(), localePatchLocale: z.string().optional(),
patchedLocale: z.string().optional(),
syncedTorrentHash: z.string().optional(),
activeTorrentHash: z.string().optional(),
activeClientDir: z.string().optional(),
raidVisualsHash: z.string().optional(),
clientPatchHash: z.string().optional(),
vmmfWrittenIndex: z.number().int().nonnegative().optional(),
lastWrittenResolution: z.string().optional(),
rememberPosition: f.boolean(), rememberPosition: f.boolean(),
windowPosition: z windowPosition: z
.object({ .object({
+2 -2
View File
@@ -47,7 +47,7 @@ export const asyncMap = async <T, U>(
export const isNotUndef = <T>(obj: T): obj is Exclude<T, undefined> => export const isNotUndef = <T>(obj: T): obj is Exclude<T, undefined> =>
obj !== undefined; obj !== undefined;
export const formatFileSize = (bytes: number) => { export const formatFileSize = (bytes: number, decimals = 2) => {
const units = ['B', 'KB', 'MB', 'GB', 'TB']; const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let size = bytes; let size = bytes;
let unitIndex = 0; let unitIndex = 0;
@@ -57,7 +57,7 @@ export const formatFileSize = (bytes: number) => {
unitIndex++; unitIndex++;
} }
return `${size.toFixed(2)} ${units[unitIndex]}`; return `${parseFloat(size.toFixed(decimals))} ${units[unitIndex]}`;
}; };
export const formatDuration = (remaining: number) => { export const formatDuration = (remaining: number) => {
+5 -2
View File
@@ -1,7 +1,10 @@
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import Logger from 'electron-log/main'; import Logger from 'electron-log/main';
import { ForumAnnouncementSchema, type ForumAnnouncement } from '~common/schemas'; import {
ForumAnnouncementSchema,
type ForumAnnouncement
} from '~common/schemas';
import { createTRPCRouter, publicProcedure } from '../trpc'; import { createTRPCRouter, publicProcedure } from '../trpc';
@@ -9,7 +12,7 @@ const FETCH_TIMEOUT_MS = 8_000;
const fetchLatestAnnouncement = async (): Promise<ForumAnnouncement | null> => { const fetchLatestAnnouncement = async (): Promise<ForumAnnouncement | null> => {
const url = `${ const url = `${
import.meta.env.MAIN_VITE_SERVER_URL || 'https://octowow.st' import.meta.env.MAIN_VITE_FORUM_URL || 'https://octowow.st'
}/forum/octonews.php?forum=35&mode=full`; }/forum/octonews.php?forum=35&mode=full`;
const controller = new AbortController(); const controller = new AbortController();
const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
+10 -3
View File
@@ -1,10 +1,15 @@
import path from 'node:path';
import { app, dialog, shell } from 'electron'; import { app, dialog, shell } from 'electron';
import Logger from 'electron-log/main'; import Logger from 'electron-log/main';
import { z } from 'zod'; import { z } from 'zod';
import { mainWindow } from '~main/index'; import { mainWindow } from '~main/index';
import Preferences from '~main/modules/preferences'; import Preferences from '~main/modules/preferences';
import { addDefenderExclusions } from '~main/modules/defender'; import {
addDefenderExclusions,
detectAntivirusBlocks
} from '~main/modules/defender';
import { detectHardware, recommendFarClip } from '~main/modules/hardware'; import { detectHardware, recommendFarClip } from '~main/modules/hardware';
import { createTRPCRouter, publicProcedure } from '../trpc'; import { createTRPCRouter, publicProcedure } from '../trpc';
@@ -26,14 +31,16 @@ export const generalRouter = createTRPCRouter({
.input(z.string().url()) .input(z.string().url())
.mutation(({ input }) => shell.openExternal(input)), .mutation(({ input }) => shell.openExternal(input)),
openInstallFolder: publicProcedure.mutation(() => { openInstallFolder: publicProcedure.mutation(() => {
// Explorer needs native separators; a stored forward-slash path fails to open.
const dir = Preferences.data.clientDir; const dir = Preferences.data.clientDir;
if (dir) shell.openPath(dir); if (dir) shell.openPath(path.normalize(dir));
}), }),
openLogFile: publicProcedure.mutation(() => { openLogFile: publicProcedure.mutation(() => {
const file = Logger.transports.file.getFile().path; const file = Logger.transports.file.getFile().path;
shell.openPath(file); shell.openPath(path.normalize(file));
}), }),
addDefenderExclusion: publicProcedure.mutation(() => addDefenderExclusions()), addDefenderExclusion: publicProcedure.mutation(() => addDefenderExclusions()),
antivirusBlocks: publicProcedure.query(() => detectAntivirusBlocks()),
filePicker: publicProcedure filePicker: publicProcedure
.input( .input(
z.object({ z.object({
+133 -70
View File
@@ -7,9 +7,15 @@ import Logger from 'electron-log/main';
import Preferences from '~main/modules/preferences'; import Preferences from '~main/modules/preferences';
import Mods from '~main/modules/mods'; import Mods from '~main/modules/mods';
import { mainWindow } from '~main/index'; import { mainWindow } from '~main/index';
import { isGameRunning } from '~main/modules/updater'; import Updater, { isGameRunning } from '~main/modules/updater';
import { patchConfig } from '~main/modules/patcher'; import {
import { applyLocalePatch } from '~main/modules/localePatch'; 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 { minimizeToTray, restoreFromTray } from '~main/modules/tray';
import { getMod } from '~common/mods'; import { getMod } from '~common/mods';
@@ -31,79 +37,136 @@ const chainloaderNeeded = async (clientDir: string): Promise<boolean> => {
type StartResult = { ok: boolean; error?: string }; type StartResult = { ok: boolean; error?: string };
const delay = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
let starting = false;
export const launcherRouter = createTRPCRouter({ export const launcherRouter = createTRPCRouter({
start: publicProcedure.mutation(async (): Promise<StartResult> => { start: publicProcedure.mutation(async (): Promise<StartResult> => {
const { cleanWdb, minimizeToTrayOnPlay, clientDir } = Preferences.data; if (starting) return { ok: false, error: 'The game is already launching.' };
if (!clientDir) return { ok: false, error: 'No game folder is set.' }; starting = true;
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 (cleanWdb) {
Logger.log('Cleaning up WDB...');
await fs.remove(path.join(clientDir, 'WDB'));
}
Logger.log('Checking Config.wtf...');
await patchConfig();
Logger.log('Applying UI language...');
await applyLocalePatch(clientDir, Preferences.data.locale);
const loaderPath = path.join(clientDir, 'VanillaFixes.exe');
const needsLoader = await chainloaderNeeded(clientDir);
const useLoader = needsLoader && (await fs.pathExists(loaderPath));
if (needsLoader && !useLoader)
Logger.warn(
'VanillaFixes.exe is missing but mods/dlls.txt expect a chainloader; ' +
'launching WoW.exe directly (mods will not load).'
);
const octoLocale = Preferences.data.locale || 'enUS';
const gameEnv = { ...process.env, OCTO_LOCALE: octoLocale };
Logger.log(
useLoader
? `Launching via VanillaFixes (OCTO_LOCALE=${octoLocale})...`
: `Launching ${exePath} (OCTO_LOCALE=${octoLocale})...`
);
const child = useLoader
? spawn(loaderPath, ['WoW.exe'], {
env: gameEnv,
cwd: clientDir,
detached: !minimizeToTrayOnPlay
})
: spawn(exePath, {
env: gameEnv,
cwd: clientDir,
detached: !minimizeToTrayOnPlay
});
try { try {
await new Promise<void>((resolve, reject) => { const { cleanWdb, minimizeToTrayOnPlay, clientDir } = Preferences.data;
child.once('spawn', resolve); if (!clientDir) return { ok: false, error: 'No game folder is set.' };
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)); 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 (!minimizeToTrayOnPlay) { if (Mods.status.dirty)
mainWindow?.close(); 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 }; 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;
} }
minimizeToTray();
child.on('exit', () => {
Logger.log('WoW stopped');
restoreFromTray();
});
return { ok: true };
}) })
}); });
+6
View File
@@ -15,6 +15,12 @@ export const modsRouter = createTRPCRouter({
toggle: publicProcedure toggle: publicProcedure
.input(z.object({ id: ModIdSchema, enabled: z.boolean() })) .input(z.object({ id: ModIdSchema, enabled: z.boolean() }))
.mutation(({ input }) => Mods.toggle(input.id, input.enabled)), .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 setIgnoreUpdates: publicProcedure
.input(z.object({ id: ModIdSchema, ignore: z.boolean() })) .input(z.object({ id: ModIdSchema, ignore: z.boolean() }))
.mutation(({ input }) => Mods.setIgnoreUpdates(input.id, input.ignore)), .mutation(({ input }) => Mods.setIgnoreUpdates(input.id, input.ignore)),
+22 -12
View File
@@ -1,3 +1,4 @@
import { z } from 'zod';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import Logger from 'electron-log/main'; import Logger from 'electron-log/main';
@@ -7,10 +8,14 @@ import { createTRPCRouter, publicProcedure } from '../trpc';
const FETCH_TIMEOUT_MS = 8_000; const FETCH_TIMEOUT_MS = 8_000;
const fetchNews = async (): Promise<NewsItem[]> => { // 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 = `${ const url = `${
import.meta.env.MAIN_VITE_SERVER_URL || 'https://octowow.st' import.meta.env.MAIN_VITE_FORUM_URL || 'https://octowow.st'
}/forum/octonews.php?mode=list&forum=2&limit=3`; }/forum/octonews.php?mode=list&forum=${f}&limit=5`;
const controller = new AbortController(); const controller = new AbortController();
const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try { try {
@@ -18,7 +23,10 @@ const fetchNews = async (): Promise<NewsItem[]> => {
if (!res.ok) throw Error(`HTTP ${res.status}`); if (!res.ok) throw Error(`HTTP ${res.status}`);
const parsed = NewsFeedSchema.safeParse(await res.json()); const parsed = NewsFeedSchema.safeParse(await res.json());
if (!parsed.success) { if (!parsed.success) {
Logger.error('News feed failed schema validation', parsed.error.flatten()); Logger.error(
'News feed failed schema validation',
parsed.error.flatten()
);
throw Error('Malformed news feed'); throw Error('Malformed news feed');
} }
return parsed.data.items; return parsed.data.items;
@@ -28,12 +36,14 @@ const fetchNews = async (): Promise<NewsItem[]> => {
}; };
export const newsRouter = createTRPCRouter({ export const newsRouter = createTRPCRouter({
list: publicProcedure.query(async () => { list: publicProcedure
try { .input(z.object({ forum: z.number() }).optional())
return await fetchNews(); .query(async ({ input }) => {
} catch (e) { try {
Logger.error('Failed to fetch news', e); return await fetchNews(input?.forum ?? 2);
throw e; } catch (e) {
} Logger.error('Failed to fetch news', e);
}) throw e;
}
})
}); });
+11 -4
View File
@@ -2,14 +2,21 @@ import { patchConfig, patchExecutable } from '~main/modules/patcher';
import Preferences from '~main/modules/preferences'; import Preferences from '~main/modules/preferences';
import Updater from '~main/modules/updater'; import Updater from '~main/modules/updater';
import { getClientVersion } from '~main/utils'; import { getClientVersion } from '~main/utils';
import { stopSeeding } from '~main/modules/aria2';
import { createTRPCRouter, publicProcedure } from '../trpc'; import { createTRPCRouter, publicProcedure } from '../trpc';
export const patcherRouter = createTRPCRouter({ export const patcherRouter = createTRPCRouter({
apply: publicProcedure.mutation(async () => { apply: publicProcedure.mutation(async () => {
await patchExecutable(); // release the seeder's file handles so the patchers can write
await patchConfig(true); stopSeeding();
await Updater.recordPatchedWow(); try {
Preferences.data = { version: await getClientVersion() }; await patchExecutable();
await patchConfig(true);
await Updater.recordPatchedWow();
Preferences.data = { version: await getClientVersion() };
} finally {
await Updater.refreshSeeding();
}
}) })
}); });
+4 -3
View File
@@ -2,7 +2,7 @@ import { z } from 'zod';
import { PreferencesSchema } from '~common/schemas'; import { PreferencesSchema } from '~common/schemas';
import Preferences from '~main/modules/preferences'; import Preferences from '~main/modules/preferences';
import { applyLocalePatch } from '~main/modules/localePatch'; import Updater from '~main/modules/updater';
import { createTRPCRouter, publicProcedure } from '../trpc'; import { createTRPCRouter, publicProcedure } from '../trpc';
@@ -11,9 +11,10 @@ export const preferencesRouter = createTRPCRouter({
set: publicProcedure set: publicProcedure
.input(PreferencesSchema.partial()) .input(PreferencesSchema.partial())
.mutation(async ({ input }) => { .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; Preferences.data = input;
if (input.locale !== undefined) if (input.shareDownloads !== undefined) void Updater.refreshSeeding();
await applyLocalePatch(Preferences.data.clientDir, input.locale);
return Preferences.data; return Preferences.data;
}), }),
isValidClientDir: publicProcedure isValidClientDir: publicProcedure
+1
View File
@@ -6,6 +6,7 @@ import { createTRPCRouter, publicProcedure } from '../trpc';
export const updaterRouter = createTRPCRouter({ export const updaterRouter = createTRPCRouter({
verify: publicProcedure.mutation(() => Updater.verify()), verify: publicProcedure.mutation(() => Updater.verify()),
syncRaidVisuals: publicProcedure.mutation(() => Updater.syncRaidVisuals()),
update: publicProcedure update: publicProcedure
.input(z.boolean().optional()) .input(z.boolean().optional())
.mutation(async ({ input }) => Updater.update(input)), .mutation(async ({ input }) => Updater.update(input)),
+22 -1
View File
@@ -6,8 +6,10 @@ import { createIPCHandler } from 'electron-trpc/main';
import Logger from 'electron-log/main'; import Logger from 'electron-log/main';
import icon from '~build/icon.png?asset'; import icon from '~build/icon.png?asset';
import { PreferencesSchema } from '~common/schemas';
import { appRouter } from './api/root'; import { appRouter } from './api/root';
import { stopSyncing, stopSeeding } from './modules/aria2';
import Preferences from './modules/preferences'; import Preferences from './modules/preferences';
import Updater from './modules/updater'; import Updater from './modules/updater';
import Addons from './modules/addons'; import Addons from './modules/addons';
@@ -21,6 +23,7 @@ import {
Logger.initialize(); Logger.initialize();
Logger.errorHandler.startCatching(); Logger.errorHandler.startCatching();
Logger.transports.ipc.level = false;
Logger.info('Launcher starting...'); Logger.info('Launcher starting...');
app.disableHardwareAcceleration(); app.disableHardwareAcceleration();
@@ -132,7 +135,13 @@ if (!gotSingleInstanceLock) {
}); });
app.whenReady().then(async () => { app.whenReady().then(async () => {
Preferences.data = await Preferences.load(); // 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(); Addons.verify();
Updater.verify(); Updater.verify();
@@ -191,6 +200,18 @@ if (!gotSingleInstanceLock) {
await createWindow(); await createWindow();
}); });
let settingsFlushed = false;
app.on('before-quit', event => {
stopSyncing();
stopSeeding();
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.on('window-all-closed', () => {
app.quit(); app.quit();
}); });
+1 -1
View File
@@ -195,7 +195,7 @@ class AddonsClass extends Observable<AddonsStatus> {
: []; : [];
const addons: AddonsStatus['addons'] = Object.fromEntries( const addons: AddonsStatus['addons'] = Object.fromEntries(
dirs dirs
.filter(d => !d.startsWith('Blizzard_')) .filter(d => !d.startsWith('Blizzard_') && !/\.(tmp|bak)$/.test(d))
.map(name => [name, { status: 'fetching' as const, folder: name }]) .map(name => [name, { status: 'fetching' as const, folder: name }])
); );
+514
View File
@@ -0,0 +1,514 @@
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
};
};
let syncChild: ChildProcess | undefined;
// aria2's --stop-with-process is unreliable on Windows; kill the download
// child explicitly on quit or it keeps running headless
export const stopSyncing = (): void => {
syncChild?.kill();
syncChild = undefined;
};
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 });
syncChild = child;
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 (syncChild === child) syncChild = undefined;
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())
);
};
// archives the old client shipped under names the current one no longer uses;
// matched by name AND exact size so player mods reusing a name are never touched
const LEGACY_ARCHIVES: Record<string, number> = {
'patch-6.mpq': 451195806,
'patch-7.mpq': 175256564,
'patch-8.mpq': 484649870,
'patch-9.mpq': 506808141,
'patch-a.mpq': 241751337
};
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;
if (LEGACY_ARCHIVES[lc] !== st.size) continue;
await fs.remove(full);
removed.push(name);
}
return removed;
} catch (e) {
Logger.warn('Prune of stale archives failed', e);
return [];
}
};
// files the torrent ships but a mod toggle owns; the sync must not re-add
// them or count their absence as an incomplete tree
const LAUNCHER_OWNED_FILES = new Set(['d3d9.dll']);
const isLauncherOwned = (parts: string[]) =>
parts.length === 1 && LAUNCHER_OWNED_FILES.has(parts[0].toLowerCase());
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[] = [];
let missing = false;
for (let i = 0; i < files.length; i++) {
const f = files[i];
if (!f.path?.length || typeof f.length !== 'number') return null;
if (isLauncherOwned(f.path)) continue;
const dest = path.join(clientDir, ...f.path);
const st = await fs.stat(dest).catch(() => null);
if (!st) {
missing = true;
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);
}
}
// a deleted file poisons the resume state (its pieces are marked
// done, so aria2 skips them forever); partial files keep it so an
// interrupted download resumes instead of restarting
if (missing) await clearTorrentResumeState().catch(() => undefined);
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;
if (isLauncherOwned(f.path)) continue;
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',
// no prealloc: the seeder must not recreate missing files as zeros
'--file-allocation=none',
'--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;
}
};
+142 -23
View File
@@ -1,4 +1,5 @@
import { spawn } from 'node:child_process'; import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
@@ -29,21 +30,38 @@ export const addDefenderExclusions = async (): Promise<ExclusionResult> => {
process.env.PORTABLE_EXECUTABLE_DIR ?? path.dirname(app.getPath('exe')); process.env.PORTABLE_EXECUTABLE_DIR ?? path.dirname(app.getPath('exe'));
const paths = [...new Set([clientDir, launcherDir])]; 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 = [ const inner = [
'$ErrorActionPreference = "Stop"',
'try {', 'try {',
...paths.map(p => `Add-MpPreference -ExclusionPath ${psSingleQuote(p)}`), ...paths.map(
'Add-MpPreference -ExclusionProcess "WoW.exe"', p =>
'Add-MpPreference -ExclusionProcess "VanillaFixes.exe"', ` Add-MpPreference -ExclusionPath ${psSingleQuote(
'exit 0', p
'} catch { exit 2 }' )} -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'); ].join('\n');
const encoded = Buffer.from(inner, 'utf16le').toString('base64'); const encoded = Buffer.from(inner, 'utf16le').toString('base64');
const outer = const outer =
'try { $p = Start-Process powershell -Verb RunAs -WindowStyle Hidden ' + 'try { Start-Process powershell -Verb RunAs -WindowStyle Hidden -Wait ' +
"-Wait -PassThru -ArgumentList '-NoProfile','-NonInteractive'," + "-ArgumentList '-NoProfile','-NonInteractive'," +
`'-EncodedCommand','${encoded}'; exit $p.ExitCode } catch { exit 1 }`; `'-EncodedCommand','${encoded}' } catch { exit 1 }`;
return new Promise<ExclusionResult>(resolve => { return new Promise<ExclusionResult>(resolve => {
const child = spawn( const child = spawn(
@@ -58,23 +76,124 @@ export const addDefenderExclusions = async (): Promise<ExclusionResult> => {
resolve({ ok: false, error: 'Could not run Windows PowerShell.' }); resolve({ ok: false, error: 'Could not run Windows PowerShell.' });
}); });
child.on('exit', code => { child.on('exit', code => {
if (code === 0) { 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(', ')}`); Logger.info(`Added Defender exclusions: ${paths.join(', ')}`);
resolve({ ok: true, paths }); resolve({ ok: true, paths });
} else if (code === 1) { return;
resolve({
ok: false,
error:
'No permission granted. Click Yes on the Windows prompt to add the exclusion.'
});
} else {
Logger.error(`Defender exclusion failed (code ${code}): ${stderr}`);
resolve({
ok: false,
error:
'Could not add the exclusion automatically. You may need to add it in Windows Security manually.'
});
} }
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) {
// d3d9.dll is deliberately parked while dxvk is off, not blocked
if (
name === 'd3d9.dll' &&
Preferences.data.mods?.dxvk?.enabled === false
)
continue;
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];
};
+91 -21
View File
@@ -3,8 +3,21 @@ import { spawn } from 'node:child_process';
import Logger from 'electron-log/main'; 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 = [ const SCRIPT = [
'$ErrorActionPreference = "Stop"', '$ErrorActionPreference = "Stop"',
"$ProgressPreference = 'SilentlyContinue'",
"Add-Type -TypeDefinition @'", "Add-Type -TypeDefinition @'",
'using System;', 'using System;',
'using System.Runtime.InteropServices;', 'using System.Runtime.InteropServices;',
@@ -18,30 +31,79 @@ const SCRIPT = [
' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string DeviceID;', ' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string DeviceID;',
' [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string DeviceKey;', ' [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)]', ' [DllImport("user32.dll", EntryPoint="EnumDisplayDevicesA", CharSet=CharSet.Ansi)]',
' public static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);', ' 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);',
'}', '}',
"'@", "'@",
'$dd = New-Object VmmfDisplays+DISPLAY_DEVICE', 'for ($i = 0; ; $i++) {',
'$dd.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($dd)', ' $dd = New-Object VmmfDisplays+DISPLAY_DEVICE',
'for ($i = 0; [VmmfDisplays]::EnumDisplayDevices([NullString]::Value, $i, [ref]$dd, 0); $i++) {', ' $dd.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($dd)',
' if ($dd.StateFlags -band 4) { Write-Output $i; exit 0 }', ' if (-not [VmmfDisplays]::EnumDisplayDevices([NullString]::Value, $i, [ref]$dd, 0)) { break }',
'}', ' $dm = New-Object VmmfDisplays+DEVMODE',
'exit 1' ' $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'); ].join('\n');
export const detectPrimaryDisplayIndex = (): Promise<number> => { const parseRow = (line: string): DisplayDevice | undefined => {
if (os.platform() !== 'win32') return Promise.resolve(0); 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'); const encoded = Buffer.from(SCRIPT, 'utf16le').toString('base64');
return new Promise(resolve => { return new Promise(resolve => {
let settled = false; let settled = false;
const finish = (index: number) => { const finish = (v: DisplayDevice[] | null) => {
if (settled) return; if (settled) return;
settled = true; settled = true;
clearTimeout(timer); clearTimeout(timer);
resolve(index); resolve(v);
}; };
const child = spawn( const child = spawn(
@@ -52,25 +114,33 @@ export const detectPrimaryDisplayIndex = (): Promise<number> => {
const timer = setTimeout(() => { const timer = setTimeout(() => {
child.kill(); child.kill();
Logger.warn('Primary display detection timed out'); Logger.warn('Display enumeration timed out');
finish(0); finish(null);
}, 8000); }, 10000);
let stdout = ''; let stdout = '';
child.stdout.on('data', d => (stdout += String(d))); child.stdout.on('data', d => (stdout += String(d)));
child.on('error', e => { child.on('error', e => {
Logger.warn('Primary display detection failed to launch PowerShell', e); Logger.warn('Display enumeration failed to launch PowerShell', e);
finish(0); finish(null);
}); });
child.on('exit', code => { child.on('exit', code => {
const index = Number(stdout.trim()); const devices = stdout
if (code === 0 && Number.isInteger(index) && index >= 0) { .split(/\r?\n/)
Logger.info(`Detected primary display at device index ${index}`); .map(parseRow)
finish(index); .filter((d): d is DisplayDevice => d !== undefined);
if (code === 0 && devices.length) {
Logger.info(`Enumerated ${devices.length} display device(s)`);
finish(devices);
} else { } else {
Logger.warn('Primary display detection failed, defaulting to 0'); Logger.warn('Display enumeration returned nothing usable');
finish(0); finish(null);
} }
}); });
}); });
}; };
export const detectPrimaryDisplayIndex = async (): Promise<number | null> => {
const devices = await enumerateDisplays();
return devices?.find(d => d.primary && d.attached)?.index ?? null;
};
+24
View File
@@ -19,16 +19,37 @@ const readLines = async (clientDir: string): Promise<string[]> => {
return text.split(/\r?\n/); 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 writeLines = async (clientDir: string, lines: string[]) => {
const file = dllsPath(clientDir); const file = dllsPath(clientDir);
const trimmed = lines.join('\n').replace(/\n+$/, ''); const trimmed = lines.join('\n').replace(/\n+$/, '');
if (!trimmed.trim()) { if (!trimmed.trim()) {
if (await fs.pathExists(file)) await fs.remove(file); if (await fs.pathExists(file)) await fs.remove(file);
await writeCache(clientDir, []);
return; return;
} }
await fs.writeFile(file, trimmed + '\n', 'utf8'); 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) => const matches = (line: string, name: string) =>
line.trim().toLowerCase() === name.toLowerCase(); line.trim().toLowerCase() === name.toLowerCase();
@@ -53,3 +74,6 @@ export const hasDll = (clientDir: string, name: string) =>
const lines = await readLines(clientDir); const lines = await readLines(clientDir);
return lines.some(l => matches(l, name)); return lines.some(l => matches(l, name));
}); });
export const listDlls = (clientDir: string): Promise<string[]> =>
serial(async () => dllNames(await readLines(clientDir)));
+20 -76
View File
@@ -11,16 +11,13 @@ import Logger from 'electron-log/main';
import Preferences from './preferences'; import Preferences from './preferences';
const PREFERRED = 'L'; // old installs may have a copied patch-<letter>.mpq that overrides patch-5; sweep by marker
const LETTERS = 'BCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); const ALL_LETTERS = 'BCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
const MARKER = 'octolocale.marker'; const MARKER = 'octolocale.marker';
const patchFile = (dataDir: string, letter: string) => const patchFile = (dataDir: string, letter: string) =>
path.join(dataDir, `patch-${letter}.mpq`); path.join(dataDir, `patch-${letter}.mpq`);
const prebuiltFor = (dataDir: string, locale: string) =>
path.join(dataDir, locale, 'patch-L.mpq');
const isOurPatch = (mpqPath: string): boolean => { const isOurPatch = (mpqPath: string): boolean => {
if (!fs.existsSync(mpqPath)) return false; if (!fs.existsSync(mpqPath)) return false;
try { try {
@@ -35,82 +32,29 @@ const isOurPatch = (mpqPath: string): boolean => {
} }
}; };
const usableSlot = (dataDir: string, letter: string): boolean => { // remove locale patches we copied in (marker-carrying archives only); never throws
if (fs.existsSync(path.join(dataDir, `patch-${letter}.MPQ`))) return false; export const removeLegacyLocalePatches = async (
const f = patchFile(dataDir, letter); clientDir: string | undefined
return !fs.existsSync(f) || isOurPatch(f); ): Promise<void> => {
}; if (!clientDir) return;
const dataDir = path.join(clientDir, 'Data');
if (!(await fs.pathExists(dataDir))) return;
const removeOurPatch = async (dataDir: string) => { for (const letter of ALL_LETTERS) {
for (const l of LETTERS) { const f = patchFile(dataDir, letter);
const f = patchFile(dataDir, l); if (!isOurPatch(f)) continue;
if (isOurPatch(f)) await fs.remove(f).catch(() => {}); 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) if (Preferences.data.localePatchLetter || Preferences.data.localePatchLocale)
Preferences.data = { Preferences.data = {
localePatchLetter: undefined, localePatchLetter: undefined,
localePatchLocale: undefined localePatchLocale: undefined
}; };
}; };
export const applyLocalePatch = async (
clientDir: string | undefined,
locale: string | undefined
): Promise<void> => {
if (!clientDir) return;
const dataDir = path.join(clientDir, 'Data');
const nextLocale = !locale || locale === 'enUS' ? undefined : locale;
if (Preferences.data.localePatchLocale !== nextLocale)
await fs.remove(path.join(clientDir, 'WDB')).catch(() => {});
if (!locale || locale === 'enUS') {
await removeOurPatch(dataDir);
return;
}
const source = prebuiltFor(dataDir, locale);
if (!(await fs.pathExists(source))) {
Logger.warn(
`Locale patch: no prebuilt patch-L for ${locale}; leaving UI as-is`
);
return;
}
const tracked = Preferences.data.localePatchLetter;
const letter =
(tracked && usableSlot(dataDir, tracked) ? tracked : undefined) ??
(usableSlot(dataDir, PREFERRED)
? PREFERRED
: LETTERS.find(l => usableSlot(dataDir, l)));
if (!letter) {
Logger.warn('Locale patch: no usable patch slot');
return;
}
const target = patchFile(dataDir, letter);
try {
if (
Preferences.data.localePatchLocale === locale &&
isOurPatch(target) &&
fs.statSync(target).mtimeMs >= fs.statSync(source).mtimeMs
)
return;
} catch {
}
try {
for (const l of LETTERS) {
if (l === letter) continue;
const f = patchFile(dataDir, l);
if (isOurPatch(f)) await fs.remove(f).catch(() => {});
}
await fs.copy(source, target, { overwrite: true });
Preferences.data = { localePatchLetter: letter, localePatchLocale: locale };
Logger.log(
`Locale patch: swapped prebuilt ${locale} -> patch-${letter}.mpq`
);
} catch (e) {
Logger.error('Locale patch: failed to swap in prebuilt patch', e);
}
};
+398 -16
View File
@@ -1,4 +1,5 @@
import path from 'path'; import path from 'path';
import { createHash } from 'crypto';
import fs from 'fs-extra'; import fs from 'fs-extra';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
@@ -6,20 +7,71 @@ import AdmZip from 'adm-zip';
import * as tar from 'tar'; import * as tar from 'tar';
import Logger from 'electron-log/main'; import Logger from 'electron-log/main';
import { MODS, type ModEntry, type ModId, getMod } from '~common/mods'; import {
MODS,
DEFAULT_ENABLED_MODS,
type ModEntry,
type ModId,
getMod
} from '~common/mods';
import { type ModState } from '~common/schemas'; import { type ModState } from '~common/schemas';
import Preferences from './preferences'; import Preferences from './preferences';
import { isTorrentMode, stopSeeding } from './aria2';
import Observable from './observable'; import Observable from './observable';
import Updater from './updater'; import Updater from './updater';
import { addDll, removeDll } from './dllsTxt'; import { addDll, removeDll, listDlls } from './dllsTxt';
import { detectPrimaryDisplayIndex } from './displays'; import { enumerateDisplays } from './displays';
const MOD_DOWNLOAD_TIMEOUT_MS = 60_000; 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 = const AV_ERROR =
'Windows Defender blocked this download. Use "Allow through antivirus" and apply again.'; 'Windows Defender blocked this download. Use "Allow through antivirus" and apply again.';
// pinned dxvk-gplasync v2.7.1-1 x32 d3d9.dll (same build the client ships)
const DXVK_DLL_SHA256 =
'a2cd6841e102f37189527c118ec416fa5071ac4d3120762973d9a0c6c5fd067e';
const fileSha256 = async (p: string): Promise<string | null> => {
try {
return createHash('sha256')
.update(await fs.readFile(p))
.digest('hex');
} catch {
return null;
}
};
const looksLikeAvBlock = (msg: string) => const looksLikeAvBlock = (msg: string) =>
/windows defender|virus|potentially unwanted/i.test(msg); /windows defender|virus|potentially unwanted/i.test(msg);
@@ -39,19 +91,31 @@ export type ModRowStatus = {
error?: string; error?: string;
}; };
export type CustomMod = { name: string; enabled: boolean };
export type ModsStatus = { export type ModsStatus = {
state: 'verifying' | 'idle' | 'busy'; state: 'verifying' | 'idle' | 'busy';
dirty: boolean; dirty: boolean;
mods: ModRowStatus[]; mods: ModRowStatus[];
custom: CustomMod[];
// enabled mods whose files are missing (AV quarantine or incomplete sync)
missingFiles: string[];
}; };
class ModsClass extends Observable<ModsStatus> { class ModsClass extends Observable<ModsStatus> {
protected _value: ModsStatus = { protected _value: ModsStatus = {
state: 'verifying', state: 'verifying',
dirty: false, dirty: false,
mods: [] 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 { get status(): ModsStatus {
return this._value; return this._value;
} }
@@ -83,6 +147,7 @@ class ModsClass extends Observable<ModsStatus> {
} }
#computeDirty(): boolean { #computeDirty(): boolean {
if (this.#customDesired.size > 0) return true;
return this._value.mods.some(r => { return this._value.mods.some(r => {
const wantInstalled = r.enabled; const wantInstalled = r.enabled;
const isInstalled = !!r.installedVersion; const isInstalled = !!r.installedVersion;
@@ -101,10 +166,121 @@ class ModsClass extends Observable<ModsStatus> {
this._value = { this._value = {
state: 'verifying', state: 'verifying',
dirty: false, dirty: false,
mods: MODS.map(m => this.#initialRow(m)) 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() { async verify() {
this.load(); this.load();
this._notifyObservers(); this._notifyObservers();
@@ -112,18 +288,84 @@ class ModsClass extends Observable<ModsStatus> {
const clientDir = Preferences.data?.clientDir; const clientDir = Preferences.data?.clientDir;
if (clientDir) { if (clientDir) {
const vmmfDll = path.join(clientDir, 'VanillaMultiMonitorFix.dll'); await this.#syncPreferredMonitor(clientDir);
const vmmfCfg = path.join(clientDir, 'VMMFix_preferred_monitor.txt');
if ((await fs.pathExists(vmmfDll)) && !(await fs.pathExists(vmmfCfg))) {
const index = await detectPrimaryDisplayIndex();
await fs.writeFile(vmmfCfg, `${index}\n`, 'utf8').catch(() => {});
}
} }
const missing: string[] = [];
let dxvkRepair = false;
for (const m of MODS) { 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]; const state = Preferences.data?.mods?.[m.id];
let installedVersion = state?.installedVersion; let installedVersion = state?.installedVersion;
// torrent mode: DLLs ship in the client; a missing file goes to `missing`, not dirty
if (isTorrentMode()) {
const enabled = state?.enabled ?? DEFAULT_ENABLED_MODS.includes(m.id);
// dxvk loads by file presence and torrent piece spillover can
// corrupt it; hash-verify every state: park/restore verified
// copies only, delete junk, re-download the pin when needed
if (m.id === 'dxvk' && clientDir) {
const live = path.join(clientDir, 'd3d9.dll');
const off = path.join(clientDir, 'd3d9.dll.off');
const liveSha = await fileSha256(live);
if (!enabled) {
if (
liveSha === DXVK_DLL_SHA256 &&
!(await fs.pathExists(off))
) {
await fs
.move(live, off)
.then(() => Logger.info('dxvk disabled: parked d3d9.dll'))
.catch(e => Logger.warn('Could not park d3d9.dll', e));
} else if (liveSha !== null) {
await fs.remove(live).catch(() => undefined);
}
} else if (liveSha !== DXVK_DLL_SHA256) {
if (liveSha !== null) {
Logger.warn('dxvk: d3d9.dll failed verification; replacing');
await fs.remove(live).catch(() => undefined);
}
const offSha = await fileSha256(off);
if (offSha === DXVK_DLL_SHA256) {
await fs
.move(off, live)
.then(() => Logger.info('dxvk enabled: restored d3d9.dll'))
.catch(e => Logger.warn('Could not restore d3d9.dll', e));
} else {
if (offSha !== null)
await fs.remove(off).catch(() => undefined);
dxvkRepair = true;
}
}
}
const files = modTargetFiles(m);
const present =
!!clientDir &&
files.length > 0 &&
(
await Promise.all(
files.map(rel => fs.pathExists(path.join(clientDir, rel)))
)
).every(Boolean);
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) { if (clientDir && installedVersion) {
const filesPresent = await Promise.all( const filesPresent = await Promise.all(
(state?.installedFiles ?? []).map(rel => (state?.installedFiles ?? []).map(rel =>
@@ -155,14 +397,72 @@ class ModsClass extends Observable<ModsStatus> {
}); });
} }
if (dxvkRepair) {
const dm = getMod('dxvk');
if (dm)
await this.#install(dm).catch(e =>
Logger.warn('dxvk repair download failed', e)
);
}
this._value = { this._value = {
...this._value, ...this._value,
state: 'idle', state: 'idle',
dirty: this.#computeDirty() dirty: this.#computeDirty(),
custom: clientDir ? await this.#detectCustomDlls(clientDir) : [],
missingFiles: missing
}; };
this._notifyObservers(); 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) { async toggle(id: ModId, enabled: boolean) {
const cur = Preferences.data?.mods?.[id]; const cur = Preferences.data?.mods?.[id];
await this.#savePref(id, { await this.#savePref(id, {
@@ -191,6 +491,38 @@ class ModsClass extends Observable<ModsStatus> {
Logger.warn('No clientDir set; cannot apply mods.'); Logger.warn('No clientDir set; cannot apply mods.');
return; 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; reconcile dlls.txt. The
// seeder holds files open, so release it for the dxvk park/restore.
if (isTorrentMode()) {
stopSeeding();
try {
await this.verify();
} finally {
await Updater.refreshSeeding().catch(() => undefined);
}
return;
}
if (this._value.state === 'busy') { if (this._value.state === 'busy') {
Logger.warn('applyAll already running; ignoring re-entrant call.'); Logger.warn('applyAll already running; ignoring re-entrant call.');
return; return;
@@ -243,6 +575,32 @@ class ModsClass extends Observable<ModsStatus> {
async #install(m: ModEntry) { async #install(m: ModEntry) {
const clientDir = Preferences.data?.clientDir; const clientDir = Preferences.data?.clientDir;
// dxvk: restoring a parked copy is the only enable path that works in
// torrent mode (nothing is fetched there, the sync ignores d3d9.dll)
if (m.id === 'dxvk' && clientDir) {
const live = path.join(clientDir, 'd3d9.dll');
const off = path.join(clientDir, 'd3d9.dll.off');
if (!(await fs.pathExists(live)) && (await fs.pathExists(off))) {
Logger.info('Restoring parked d3d9.dll for dxvk');
await fs.move(off, live);
await this.#savePref(m.id, {
enabled: true,
installedVersion: m.version,
installedFiles: ['d3d9.dll'],
ignoreUpdates:
Preferences.data?.mods?.[m.id]?.ignoreUpdates ?? false
});
this.#patchRow(m.id, {
state: 'idle',
installedVersion: m.version,
progress: 1
});
return;
}
}
// torrent mode ships mod binaries with the client; dxvk is the
// exception (unsynced), a fresh enable with no parked copy downloads
if (isTorrentMode() && m.id !== 'dxvk') return;
if (!clientDir) throw new Error('No client dir'); if (!clientDir) throw new Error('No client dir');
if (m.source.kind === 'managed') return; if (m.source.kind === 'managed') return;
@@ -258,7 +616,7 @@ class ModsClass extends Observable<ModsStatus> {
if (m.source.kind === 'directFile') { if (m.source.kind === 'directFile') {
const dest = path.join(clientDir, m.source.assetName); const dest = path.join(clientDir, m.source.assetName);
await this.#downloadTo(m.source.url, dest); await this.#downloadTo(m.source.url, dest, m.source.sha256);
written.push(m.source.assetName); written.push(m.source.assetName);
} else if (m.source.kind === 'archive') { } else if (m.source.kind === 'archive') {
const scratch = path.join(clientDir, '.octolauncher-tmp'); const scratch = path.join(clientDir, '.octolauncher-tmp');
@@ -267,7 +625,7 @@ class ModsClass extends Observable<ModsStatus> {
scratch, scratch,
`${m.id}-${Date.now()}.${m.source.format}` `${m.id}-${Date.now()}.${m.source.format}`
); );
await this.#downloadTo(m.source.url, tmp); await this.#downloadTo(m.source.url, tmp, m.source.sha256);
this.#patchRow(m.id, { state: 'installing' }); this.#patchRow(m.id, { state: 'installing' });
const map = m.source.extractMap; const map = m.source.extractMap;
@@ -337,7 +695,20 @@ class ModsClass extends Observable<ModsStatus> {
this.#patchRow(m.id, { state: 'uninstalling', error: undefined }); this.#patchRow(m.id, { state: 'uninstalling', error: undefined });
const cur = Preferences.data?.mods?.[m.id]; const cur = Preferences.data?.mods?.[m.id];
const files = cur?.installedFiles ?? []; // dxvk: park instead of delete so re-enable is instant and offline
const files = [...(cur?.installedFiles ?? [])].filter(
f => !(m.id === 'dxvk' && /d3d9\.dll$/i.test(f))
);
if (m.id === 'dxvk') {
const live = path.join(clientDir, 'd3d9.dll');
const off = path.join(clientDir, 'd3d9.dll.off');
if (await fs.pathExists(live)) {
await fs.remove(off).catch(() => undefined);
await fs
.move(live, off)
.catch(err => Logger.warn(`Couldn't park ${live}:`, err));
}
}
for (const rel of files) { for (const rel of files) {
const fullPath = path.join(clientDir, rel); const fullPath = path.join(clientDir, rel);
@@ -360,7 +731,7 @@ class ModsClass extends Observable<ModsStatus> {
this.#patchRow(m.id, { state: 'idle', installedVersion: undefined }); this.#patchRow(m.id, { state: 'idle', installedVersion: undefined });
} }
async #downloadTo(url: string, dest: string) { async #downloadTo(url: string, dest: string, sha256?: string) {
const res = await fetch(url, { const res = await fetch(url, {
headers: { 'User-Agent': 'OctoLauncher' }, headers: { 'User-Agent': 'OctoLauncher' },
timeout: MOD_DOWNLOAD_TIMEOUT_MS timeout: MOD_DOWNLOAD_TIMEOUT_MS
@@ -368,6 +739,17 @@ class ModsClass extends Observable<ModsStatus> {
if (!res.ok) throw new Error(`Download failed ${res.status}: ${url}`); if (!res.ok) throw new Error(`Download failed ${res.status}: ${url}`);
await fs.ensureDir(path.dirname(dest)); await fs.ensureDir(path.dirname(dest));
const buf = await res.arrayBuffer(); 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)); await fs.writeFile(dest, Buffer.from(buf));
if (!(await fs.pathExists(dest))) if (!(await fs.pathExists(dest)))
throw new Error( throw new Error(
+353 -63
View File
@@ -7,7 +7,8 @@ import Logger from 'electron-log/main';
import Preferences from '~main/modules/preferences'; import Preferences from '~main/modules/preferences';
import { ConfigWtfSchema, type PreferencesSchema } from '~common/schemas'; import { ConfigWtfSchema, type PreferencesSchema } from '~common/schemas';
import { isNotUndef } from '~common/utils'; import { isNotUndef } from '~common/utils';
import { fetchFile } from '~main/modules/updater'; import { readPristineWow } from '~main/modules/aria2';
import { enumerateDisplays } from '~main/modules/displays';
const Servers = { const Servers = {
live: { live: {
@@ -16,12 +17,39 @@ const Servers = {
realmName: 'OctoWoW' realmName: 'OctoWoW'
}, },
ptr: { ptr: {
realmList: 'octowow.st', realmList: import.meta.env.MAIN_VITE_PTR_REALMLIST || 'octowow.st',
patchList: 'octowow.st', patchList: import.meta.env.MAIN_VITE_PTR_REALMLIST || 'octowow.st',
realmName: 'OctoWoW PTR' realmName: 'OctoWoW PTR'
} }
} as const; } 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 = type TweakKey =
| { synthetic?: false; key: keyof PreferencesSchema['config'] } | { synthetic?: false; key: keyof PreferencesSchema['config'] }
| { synthetic: true; key: string }; | { synthetic: true; key: string };
@@ -32,7 +60,7 @@ type Tweak = TweakKey & {
} & ( } & (
| { | {
type: 'bytes'; type: 'bytes';
tweaks: [number, number[]][]; tweaks: [number, number[], number[]?][];
} }
| { | {
type: 'int8' | 'uint16' | 'float'; type: 'int8' | 'uint16' | 'float';
@@ -41,17 +69,57 @@ type Tweak = TweakKey & {
} }
); );
const hex = (bytes: number[]) =>
bytes.map(b => b.toString(16).padStart(2, '0')).join(' ');
export const patchExecutable = async () => { export const patchExecutable = async () => {
Logger.log('Patching WoW.exe...'); Logger.log('Patching WoW.exe...');
const { clientDir, config } = Preferences.data; const { clientDir, config, locale } = Preferences.data;
if (!clientDir) return; if (!clientDir) return;
const exePath = path.join(clientDir, 'WoW.exe'); const exePath = path.join(clientDir, 'WoW.exe');
try { try {
Logger.log('Fetching clean WoW.exe...'); Logger.log('Reading clean WoW.exe base...');
const file = await fetchFile('WoW.exe'); const buffer = await readPristineWow(clientDir);
const buffer = Buffer.from(file);
const loc = LOCALES[locale];
// revert any previous locale patch to the pristine bytes first, so a
// language switch (or an adopted pre-patched exe) can re-patch cleanly
const TAG_OFFSET = 0x1b2115;
const INDEX_OFFSET = 0x253c;
const PRISTINE_TAG = [0xa1, 0xa4, 0xa2, 0xc2, 0x00];
const PRISTINE_INDEX = [0x33, 0xf6, 0x8b, 0xff, 0x8b, 0x04, 0xb5];
if (
buffer[TAG_OFFSET] === 0xb8 &&
buffer[INDEX_OFFSET] === 0xbe &&
buffer[INDEX_OFFSET + 5] === 0xeb
) {
const prevIndex = buffer[INDEX_OFFSET + 1];
const prevCarrier = LOCALE_NAMES[prevIndex] as string | undefined;
const prevTag = prevCarrier
? Buffer.from([
0xb8,
...Buffer.from(prevCarrier, 'latin1').reverse()
])
: undefined;
if (
prevCarrier &&
prevTag &&
buffer.subarray(TAG_OFFSET, TAG_OFFSET + 5).equals(prevTag)
) {
Logger.log(
`Reverting previous locale patch (index ${prevIndex}) to the clean base`
);
Buffer.from(PRISTINE_TAG).copy(buffer, TAG_OFFSET);
Buffer.from(PRISTINE_INDEX).copy(buffer, INDEX_OFFSET);
Buffer.from(prevCarrier, 'latin1').copy(
buffer,
localeNameOffset(prevIndex)
);
}
}
const Tweaks = [ const Tweaks = [
{ {
@@ -78,25 +146,16 @@ export const patchExecutable = async () => {
default: false default: false
}, },
{ {
// shipped exe carries the enabled bytes; off must write 0x74 back
key: 'alwaysAutoLoot', key: 'alwaysAutoLoot',
type: 'bytes', type: 'bytes',
tweaks: [ tweaks: [
[0x0c1ecf, [0x75]], [0x0c1ecf, [0x75], [0x74]],
[0x0c2b25, [0x75]] [0x0c2b25, [0x75], [0x74]]
] ]
}, },
{ key: 'nameplateRange', type: 'float', offset: 0x40c448 }, { key: 'nameplateRange', type: 'float', offset: 0x40c448 },
{ key: 'cameraDistance', type: 'float', offset: 0x4089a4 }, { key: 'cameraDistance', type: 'float', offset: 0x4089a4 },
{
synthetic: true,
key: 'crossFactionResurrect',
type: 'bytes',
default: true,
tweaks: [
[0x006e5fb8, [0x006e5fb9]],
[0x006e62a8, [0x006e62a9]]
]
},
{ {
synthetic: true, synthetic: true,
key: 'skillUiGateHijack', key: 'skillUiGateHijack',
@@ -137,11 +196,53 @@ export const patchExecutable = async () => {
[ [
0x45ccd8, 0x45ccd8,
[ [
0x6f, 0x63, 0x74, 0x6f, 0x77, 0x6f, 0x77, 0x2e, 0x73, 0x74, 0x6f, 0x63, 0x74, 0x6f, 0x77, 0x6f, 0x77, 0x2e, 0x73, 0x74, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 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[]; ] satisfies Tweak[];
@@ -159,25 +260,163 @@ export const patchExecutable = async () => {
if (!t.forced && !val) return; if (!t.forced && !val) return;
buffer.writeUInt16LE(t.value ?? (val as number), t.offset); buffer.writeUInt16LE(t.value ?? (val as number), t.offset);
} else if (t.type === 'bytes') { } else if (t.type === 'bytes') {
if (!t.forced && !val) return; if (!t.forced && !val) {
t.tweaks.forEach(([offset, bytes]) => // disabled: revert sites carrying the enabled bytes to the
Buffer.from(bytes).copy(buffer, offset) // stock bytes when known; unknown bytes stay untouched
t.tweaks.forEach(
([offset, bytes, expect]: [number, number[], number[]?]) => {
if (!expect) return;
const current = buffer.subarray(
offset,
offset + bytes.length
);
if (current.equals(Buffer.from(bytes)))
Buffer.from(expect).copy(buffer, offset);
}
);
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); await fs.writeFile(exePath, buffer);
Logger.log('WoW.exe successfully patched'); Preferences.data = { patchedLocale: locale };
Logger.log(`WoW.exe successfully patched (language: ${locale})`);
} catch (e) { } catch (e) {
Logger.error('Failed to patch WoW.exe', e); Logger.error('Failed to patch WoW.exe', e);
throw e instanceof Error ? e : new Error('Failed to patch WoW.exe'); 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) => {
// already correct: leave it alone (the seeder may hold the file open)
const current = await fs
.readFile(target, { encoding: 'utf-8' })
.catch(() => null);
if (current === body) return;
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)}`);
}
}
};
// rewrite realmlist.wtf when missing, empty, or wrong; an interrupted sync
// can leave a 0-byte placeholder that disconnects direct game launches
export const healRealmlist = async (clientDir: string) => {
const server: keyof typeof Servers = import.meta.env.MAIN_VITE_PTR_REALMLIST
? 'ptr'
: 'live';
const expected = `set realmlist "${Servers[server].realmList}"\n`;
const target = path.join(clientDir, 'realmlist.wtf');
const current = await fs
.readFile(target, { encoding: 'utf-8' })
.catch(() => null);
if (current === expected) return;
Logger.log(
`realmlist.wtf ${
current === null ? 'missing' : current.trim() ? 'wrong' : 'empty'
}; rewriting`
);
await applyRealmlist(clientDir, Servers[server].realmList);
};
export const patchConfig = async (forceTweaks = false) => { export const patchConfig = async (forceTweaks = false) => {
const { clientDir, server, config, locale } = Preferences.data; const { clientDir, config, locale } = Preferences.data;
if (!clientDir) return; 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'); const configPath = path.join(clientDir, 'WTF', 'Config.wtf');
await fs.ensureDir(path.dirname(configPath)); await fs.ensureDir(path.dirname(configPath));
const raw = (await fs.pathExists(configPath)) const raw = (await fs.pathExists(configPath))
@@ -194,50 +433,73 @@ export const patchConfig = async (forceTweaks = false) => {
.filter(isNotUndef) .filter(isNotUndef)
); );
const isFirstRun = Object.keys(configWtf).length === 0;
const primaryDisplay = screen.getPrimaryDisplay(); const primaryDisplay = screen.getPrimaryDisplay();
const scale = primaryDisplay.scaleFactor || 1; const scale = primaryDisplay.scaleFactor || 1;
const width = Math.round(primaryDisplay.bounds.width * scale); const width = Math.round(primaryDisplay.bounds.width * scale);
const height = Math.round(primaryDisplay.bounds.height * scale); const height = Math.round(primaryDisplay.bounds.height * scale);
const parsed = { const seededResolution = `${width}x${height}`;
scriptMemory: 512000,
gxResolution: `${width}x${height}`, const seed = isFirstRun
gxColorBits: primaryDisplay.colorDepth, ? {
gxDepthBits: primaryDisplay.colorDepth, scriptMemory: 512000,
gxRefresh: 60, gxResolution: seededResolution,
gxMultisample: 8, gxColorBits: primaryDisplay.colorDepth,
gxMultisampleQuality: 0, gxDepthBits: primaryDisplay.colorDepth,
gxTripleBuffer: 1, gxRefresh: 60,
anisotropic: 16, gxMultisample: 8,
frillDensity: 48, gxMultisampleQuality: 0,
fullAlpha: 1, gxTripleBuffer: 1,
SmallCull: 0.01, anisotropic: 16,
DistCull: 888.8, frillDensity: 48,
shadowLevel: 0, fullAlpha: 1,
trilinear: 1, SmallCull: 0.01,
specular: 1, DistCull: 888.8,
pixelShaders: 1, shadowLevel: 0,
M2UsePixelShaders: 1, trilinear: 1,
particleDensity: 1, specular: 1,
unitDrawDist: 300, pixelShaders: 1,
weatherDensity: 3, M2UsePixelShaders: 1,
movieSubtitle: 1, M2UseShaders: 1,
minimapZoom: 0, particleDensity: 1,
minimapInsideZoom: 0, unitDrawDist: 300,
SoundZoneMusicNoDelay: 1, 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, patchList: configWtf['patchList'] ?? Servers[server].patchList,
realmName: configWtf['realmName'] ?? Servers[server].realmName, realmName: configWtf['realmName'] ?? Servers[server].realmName,
gxWindow: configWtf['gxWindow'] ?? 1,
gxMaximize: configWtf['gxMaximize'] ?? 1,
gxCursor: configWtf['gxCursor'] ?? 1,
checkAddonVersion: configWtf['checkAddonVersion'] ?? 0,
farClip: configWtf['farClip'] ?? config.farClip,
CameraDistanceMax: configWtf['CameraDistanceMax'] ?? config.cameraDistance,
...configWtf,
locale,
realmList: Servers[server].realmList,
hwDetect: 0, hwDetect: 0,
M2UseShaders: 1, BackgroundSound: config.soundInBackground ? 1 : 0
};
const repaired = await repairResolution(
clientDir,
configWtf['gxResolution'],
Preferences.data.lastWrittenResolution
);
const parsed = {
...seed,
...configWtf,
...repaired,
...owned,
...(forceTweaks ...(forceTweaks
? { farClip: config.farClip, CameraDistanceMax: config.cameraDistance } ? { farClip: config.farClip, CameraDistanceMax: config.cameraDistance }
: {}) : {})
@@ -245,10 +507,38 @@ export const patchConfig = async (forceTweaks = false) => {
const body = Object.entries(parsed) const body = Object.entries(parsed)
.filter(v => v[1] !== undefined && v[1] !== null) .filter(v => v[1] !== undefined && v[1] !== null)
.filter(([k]) => !/^realmlist$/i.test(k))
.map(l => `SET ${l[0]} "${l[1]}"`) .map(l => `SET ${l[0]} "${l[1]}"`)
.join('\n'); .join('\n');
const tmpPath = `${configPath}.tmp`; const tmpPath = `${configPath}.tmp`;
await fs.writeFile(tmpPath, body); await fs.writeFile(tmpPath, body);
await fs.move(tmpPath, configPath, { overwrite: true }); 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'); 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');
};
+198 -36
View File
@@ -6,40 +6,144 @@ import { app } from 'electron';
import Logger from 'electron-log/main'; import Logger from 'electron-log/main';
import { PreferencesSchema } from '~common/schemas'; import { PreferencesSchema } from '~common/schemas';
import { DEFAULT_ENABLED_MODS } from '~common/mods';
import { omit } from '~common/utils'; import { omit } from '~common/utils';
import { isTorrentMode } from '~main/modules/aria2';
const portableDir = process.env.PORTABLE_EXECUTABLE_DIR; 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 { abstract class Preferences {
static #data: z.infer<typeof PreferencesSchema>; static #data: z.infer<typeof PreferencesSchema>;
static #writeChain: Promise<void> = Promise.resolve(); static #writeChain: Promise<void> = Promise.resolve();
static #readOnly = false;
static #rememberedClientDir?: string;
static #freshInstall = false;
static readonly userDataDir = process.env.PORTABLE_EXECUTABLE_DIR static readonly userDataDir = process.env.PORTABLE_EXECUTABLE_DIR
? path.join(process.env.PORTABLE_EXECUTABLE_DIR, '.launcher') ? path.join(process.env.PORTABLE_EXECUTABLE_DIR, '.launcher')
: app.getPath('userData'); : app.getPath('userData');
static async load() { static readonly #settingsPath = path.join(
await fs.ensureDir(this.userDataDir); Preferences.userDataDir,
const settingsPath = path.join(this.userDataDir, 'settings.json'); 'settings.json'
);
let json: Record<string, unknown>; 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;
// fresh installs seed every mod EXPLICITLY off; a missing row falls
// back to enabled, which keeps legacy profiles untouched
const mods = { ...data.mods };
for (const id of DEFAULT_ENABLED_MODS)
mods[id] = { enabled: false, installedFiles: [], ignoreUpdates: false };
Logger.info('Fresh install: all mods start disabled (opt-in)');
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 { try {
json = await fs.readJSON(settingsPath); json = await readJsonRetrying(settingsPath);
} catch { } catch (e) {
return PreferencesSchema.parse({ if (isLocked(e)) {
isPortable: !!portableDir, this.#readOnly = true;
clientDir: portableDir 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 = { const merged = dropUndefined({
...json, ...json,
isPortable: !!portableDir, isPortable: !!portableDir,
clientDir: portableDir ?? json.clientDir clientDir: portableDir ?? json.clientDir
}; });
const parsed = PreferencesSchema.safeParse(merged); const parsed = PreferencesSchema.safeParse(merged);
if (parsed.success) return parsed.data; if (parsed.success)
return this.#withKnownClientDir(
this.#withFreshInstallDefaults(parsed.data)
);
Logger.warn( Logger.warn(
'settings.json failed validation; salvaging valid fields', 'settings.json failed validation; salvaging valid fields',
@@ -47,17 +151,48 @@ abstract class Preferences {
); );
await fs.copy(settingsPath, `${settingsPath}.corrupt`).catch(() => {}); await fs.copy(settingsPath, `${settingsPath}.corrupt`).catch(() => {});
const salvaged: Record<string, unknown> = { const salvaged: Record<string, unknown> = dropUndefined({
isPortable: !!portableDir, isPortable: !!portableDir,
clientDir: portableDir ?? json.clientDir // 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; const shape = PreferencesSchema.shape;
for (const key of Object.keys(shape) as (keyof typeof shape)[]) { for (const key of Object.keys(shape) as (keyof typeof shape)[]) {
if (!(key in merged)) continue; if (!(key in merged)) continue;
const value = (merged as Record<string, unknown>)[key]; const value = (merged as Record<string, unknown>)[key];
if (shape[key].safeParse(value).success) salvaged[key] = value; if (shape[key].safeParse(value).success) salvaged[key] = value;
} }
return PreferencesSchema.parse(salvaged); // 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 { static get data(): PreferencesSchema {
@@ -67,31 +202,50 @@ abstract class Preferences {
static set data(newData: Partial<Omit<PreferencesSchema, 'portableDir'>>) { static set data(newData: Partial<Omit<PreferencesSchema, 'portableDir'>>) {
this.#data = { ...this.#data, ...newData }; this.#data = { ...this.#data, ...newData };
const settingsPath = path.join(this.userDataDir, 'settings.json'); if (this.#readOnly) return;
const delta = omit(
newData, const settingsPath = this.#settingsPath;
portableDir ? ['isPortable', 'clientDir'] : ['isPortable'] const dropped = portableDir ? ['isPortable', 'clientDir'] : ['isPortable'];
const delta = dropUndefined(
omit(newData, dropped as (keyof typeof newData)[])
); );
const snapshot = omit( const snapshot = dropUndefined(
this.#data, omit(this.#data, dropped as (keyof PreferencesSchema)[])
portableDir ? ['isPortable', 'clientDir'] : ['isPortable']
); );
this.#writeChain = this.#writeChain this.#writeChain = this.#writeChain
.then(async () => { .then(async () => {
let onDisk: unknown = null; let base: Record<string, unknown> | null = null;
try { try {
onDisk = await fs.readJSON(settingsPath); const onDisk = await readJsonRetrying(settingsPath);
} catch { base =
onDisk = null; !!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 base =
!!onDisk && typeof onDisk === 'object' && !Array.isArray(onDisk)
? (onDisk as Record<string, unknown>)
: null;
const merged = base ? { ...base, ...delta } : snapshot; const merged = base ? { ...base, ...delta } : snapshot;
const tmp = `${settingsPath}.tmp`; await writeJsonAtomic(settingsPath, merged);
await fs.writeJSON(tmp, merged, { spaces: 2 });
await fs.move(tmp, settingsPath, { overwrite: true }); 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)); .catch(e => Logger.error('Failed to persist settings.json', e));
} }
@@ -101,7 +255,15 @@ abstract class Preferences {
} }
static async isValidClientDir(clientDir?: string) { static async isValidClientDir(clientDir?: string) {
return !!clientDir && (await fs.exists(path.join(clientDir, 'WoW.exe'))); 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;
} }
} }
File diff suppressed because it is too large Load Diff
+374
View File
@@ -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 =>
({ '<': '&lt;', '>': '&gt;', '&': '&amp;', "'": '&apos;', '"': '&quot;' }[
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;
}
};
+2 -1
View File
@@ -3,7 +3,8 @@ export { type UpdaterStatus } from './modules/updater';
export { type AddonsStatus, type AddonData } from './modules/addons'; export { type AddonsStatus, type AddonData } from './modules/addons';
export { export {
type ModsStatus, type ModsStatus,
type ModRowStatus type ModRowStatus,
type CustomMod
} from './modules/mods'; } from './modules/mods';
export { export {
type NewsItem, type NewsItem,
+13 -2
View File
@@ -10,6 +10,7 @@ if (!port) throw new Error('IllegalState');
const { dir, url, ref } = workerData; const { dir, url, ref } = workerData;
const tmpDir = `${dir}.tmp`; const tmpDir = `${dir}.tmp`;
const bakDir = `${dir}.bak`;
const run = async () => { const run = async () => {
await fs.remove(tmpDir); await fs.remove(tmpDir);
@@ -23,8 +24,18 @@ const run = async () => {
onProgress: (...args) => port.postMessage({ cb: 'onProgress', args }) onProgress: (...args) => port.postMessage({ cb: 'onProgress', args })
}); });
await fs.remove(dir); await fs.remove(bakDir);
await fs.move(tmpDir, dir); 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() run()
+44 -8
View File
@@ -3,7 +3,7 @@ import { ShieldAlert, HelpCircle } from 'lucide-react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import { api } from '~renderer/utils/api'; import { api } from '~renderer/utils/api';
import { type ModsStatus } from '~main/types'; import { type ModsStatus, type UpdaterStatus } from '~main/types';
import { useT } from '~renderer/i18n'; import { useT } from '~renderer/i18n';
import TextButton from './styled/TextButton'; import TextButton from './styled/TextButton';
@@ -15,11 +15,34 @@ const AntivirusModal = () => {
const [status, setStatus] = useState<ModsStatus>(); const [status, setStatus] = useState<ModsStatus>();
api.mods.observe.useSubscription(undefined, { onData: setStatus }); api.mods.observe.useSubscription(undefined, { onData: setStatus });
// re-scan for AV blocks once the updater settles (not mid-download); catches an aborted
// download or a file quarantined after the fact
const [updateState, setUpdateState] = useState<UpdaterStatus['state']>();
api.updater.observe.useSubscription(undefined, {
onData: s => setUpdateState(s?.state)
});
const settled =
!!updateState && updateState !== 'verifying' && updateState !== 'updating';
const { data: quarantined, refetch: refetchQuarantined } =
api.general.antivirusBlocks.useQuery(undefined, {
enabled: false,
refetchOnWindowFocus: false,
staleTime: Infinity
});
useEffect(() => {
if (settled) refetchQuarantined();
}, [updateState, settled, refetchQuarantined]);
const addExclusion = api.general.addDefenderExclusion.useMutation(); const addExclusion = api.general.addDefenderExclusion.useMutation();
const blocked = (status?.mods ?? []) const blocked = [
.filter(m => m.state === 'error' && m.error?.includes('Defender')) ...new Set([
.map(m => m.name); ...(quarantined ?? []),
...(status?.mods ?? [])
.filter(m => m.state === 'error' && m.error?.includes('Defender'))
.map(m => m.name)
])
];
const blockedKey = blocked.join(','); const blockedKey = blocked.join(',');
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
@@ -27,7 +50,8 @@ const AntivirusModal = () => {
useEffect(() => { useEffect(() => {
if (view) { if (view) {
dialogRef.current?.showModal(); // showModal() throws (and crashes to the error screen) if already open, e.g. the av<->why switch
if (!dialogRef.current?.open) dialogRef.current?.showModal();
(document.activeElement as HTMLElement | null)?.blur(); (document.activeElement as HTMLElement | null)?.blur();
} else dialogRef.current?.close(); } else dialogRef.current?.close();
}, [view]); }, [view]);
@@ -36,6 +60,13 @@ const AntivirusModal = () => {
if (blockedKey) setView('av'); if (blockedKey) setView('av');
}, [blockedKey]); }, [blockedKey]);
// The settings dialog opens the explainer straight from its antivirus button.
useEffect(() => {
const open = () => setView('why');
window.addEventListener('av-help', open);
return () => window.removeEventListener('av-help', open);
}, []);
const names = blockedKey ? blockedKey.split(',') : []; const names = blockedKey ? blockedKey.split(',') : [];
return createPortal( return createPortal(
@@ -177,9 +208,14 @@ const AntivirusModal = () => {
</div> </div>
</div> </div>
<div className="flex items-center justify-end gap-3"> <div className="flex items-center justify-end gap-3">
<TextButton onClick={() => setView('av')} className="text-blueGray"> {names.length > 0 && (
{t('av.back')} <TextButton
</TextButton> onClick={() => setView('av')}
className="text-blueGray"
>
{t('av.back')}
</TextButton>
)}
<TextButton onClick={() => setView(null)} className="text-green"> <TextButton onClick={() => setView(null)} className="text-green">
{t('av.close')} {t('av.close')}
</TextButton> </TextButton>
+30 -1
View File
@@ -1,5 +1,5 @@
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { useEffect } from 'react'; import { useEffect, useState } from 'react';
import { PreferencesSchema } from '~common/schemas'; import { PreferencesSchema } from '~common/schemas';
import zodResolver from '~renderer/utils/zodResolver'; import zodResolver from '~renderer/utils/zodResolver';
@@ -8,6 +8,7 @@ import { useT } from '~renderer/i18n';
import TextButton from './styled/TextButton'; import TextButton from './styled/TextButton';
import FilePickerInput from './form/FilePickerInput'; import FilePickerInput from './form/FilePickerInput';
import CheckboxInput from './form/CheckboxInput';
import CloseButton from './styled/CloseButton'; import CloseButton from './styled/CloseButton';
type Props = { close: () => void }; type Props = { close: () => void };
@@ -36,6 +37,19 @@ const ClientDirDialog = ({ close }: Props) => {
resolver: zodResolver(PreferencesSchema.pick({ clientDir: true })) resolver: zodResolver(PreferencesSchema.pick({ clientDir: true }))
}); });
const chosen = watch('clientDir');
const [acceptEmpty, setAcceptEmpty] = useState(false);
const chosenIsClient = api.preferences.isValidClientDir.useQuery(chosen, {
enabled: !!chosen && !pref?.isPortable
});
const needsEmptyConfirm =
!!chosen && chosenIsClient.isFetched && chosenIsClient.data === false;
useEffect(() => {
setAcceptEmpty(false);
}, [chosen]);
useEffect(() => { useEffect(() => {
pref && reset(pref); pref && reset(pref);
}, [reset, pref]); }, [reset, pref]);
@@ -62,6 +76,7 @@ const ClientDirDialog = ({ close }: Props) => {
<form <form
className="tw-dialog" className="tw-dialog"
onSubmit={handleSubmit(async ({ clientDir }) => { onSubmit={handleSubmit(async ({ clientDir }) => {
if (needsEmptyConfirm && !acceptEmpty) return;
try { try {
await setPref.mutateAsync({ clientDir }); await setPref.mutateAsync({ clientDir });
verify.mutate(); verify.mutate();
@@ -105,9 +120,23 @@ const ClientDirDialog = ({ close }: Props) => {
</p> </p>
)} )}
{needsEmptyConfirm && (
<>
<p className="text-secondary text-sm">
{t('prefs.noClientHere', { exe: 'WoW.exe' })}
</p>
<CheckboxInput
value={acceptEmpty}
setValue={setAcceptEmpty}
label={t('prefs.noClientHereConfirm')}
/>
</>
)}
<TextButton <TextButton
type="submit" type="submit"
loading={formState.isSubmitting} loading={formState.isSubmitting}
disabled={needsEmptyConfirm && !acceptEmpty}
className="self-end text-green" className="self-end text-green"
> >
{t('prefs.confirm')} {t('prefs.confirm')}
@@ -1,218 +0,0 @@
import DOMPurify from 'dompurify';
import { AlertTriangle, ExternalLink, RefreshCw } from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { api } from '~renderer/utils/api';
import { useT } from '~renderer/i18n';
import useScrollHint from '~renderer/utils/useScrollHint';
import Parchment from '~renderer/assets/parchment.jpg';
import IconSpinner from './styled/IconSpinner';
import TextButton from './styled/TextButton';
const SANITIZE_CONFIG = {
ALLOWED_TAGS: [
'b', 'strong', 'i', 'em', 'u', 's', 'strike', 'a', 'ul', 'ol', 'li',
'blockquote', 'cite', 'span', 'div', 'img', 'br', 'p', 'code', 'pre',
'dl', 'dt', 'dd', 'hr', 'sub', 'sup', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'table', 'thead', 'tbody', 'tr', 'td', 'th'
],
ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'style'],
ALLOWED_URI_REGEXP: /^(?:https?:|mailto:)/i,
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form', 'input', 'style', 'link', 'meta']
};
const LIGHT_NAMED = new Set([
'white', 'snow', 'ivory', 'floralwhite', 'ghostwhite', 'seashell', 'beige',
'linen', 'cornsilk', 'lightyellow', 'lightgoldenrodyellow', 'lemonchiffon',
'yellow', 'aqua', 'cyan', 'lime', 'aquamarine', 'azure', 'mintcream',
'honeydew', 'lavender', 'lavenderblush', 'aliceblue', 'whitesmoke',
'gainsboro', 'silver', 'lightgray', 'lightgrey', 'antiquewhite', 'papayawhip',
'blanchedalmond', 'bisque', 'moccasin', 'navajowhite', 'peachpuff', 'khaki',
'wheat', 'greenyellow', 'chartreuse', 'springgreen', 'palegoldenrod', 'gold'
]);
const LIGHT_THRESHOLD = 165;
const SAFE_STYLE_PROPS = new Set([
'color',
'background-color',
'font-weight',
'font-style',
'text-decoration',
'text-align',
'font-size'
]);
const colorIsTooLight = (raw: string): boolean => {
const v = raw.trim().toLowerCase();
const lum = (r: number, g: number, b: number) => 0.2126 * r + 0.7152 * g + 0.0722 * b;
const hex = v.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/);
if (hex) {
const h =
hex[1].length === 3
? hex[1]
.split('')
.map(c => c + c)
.join('')
: hex[1];
return (
lum(
parseInt(h.slice(0, 2), 16),
parseInt(h.slice(2, 4), 16),
parseInt(h.slice(4, 6), 16)
) > LIGHT_THRESHOLD
);
}
const rgb = v.match(/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/);
if (rgb) return lum(+rgb[1], +rgb[2], +rgb[3]) > LIGHT_THRESHOLD;
return LIGHT_NAMED.has(v);
};
const clampFontSize = (val: string): string => {
const m = val.match(/^(\d+(?:\.\d+)?)(px|pt|%|em|rem)$/i);
if (!m) return val;
const n = parseFloat(m[1]);
const unit = m[2].toLowerCase();
const max = unit === 'px' ? 28 : unit === 'pt' ? 21 : unit === '%' ? 200 : 2;
return `${Math.min(n, max)}${unit}`;
};
DOMPurify.addHook('afterSanitizeAttributes', node => {
if (node.tagName === 'IMG') node.setAttribute('loading', 'lazy');
const style = node.getAttribute('style');
if (!style) return;
const kept: string[] = [];
for (const decl of style.split(';')) {
const idx = decl.indexOf(':');
if (idx < 0) continue;
const prop = decl.slice(0, idx).trim().toLowerCase();
let val = decl.slice(idx + 1).trim();
if (!val || !SAFE_STYLE_PROPS.has(prop)) continue;
if (prop === 'color' && colorIsTooLight(val)) continue;
if (prop === 'font-size') val = clampFontSize(val);
kept.push(`${prop}:${val}`);
}
if (kept.length) node.setAttribute('style', kept.join(';'));
else node.removeAttribute('style');
});
const formatDate = (raw: string) => {
const d = new Date(raw);
if (Number.isNaN(d.getTime())) return raw;
return d.toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric'
});
};
const ForumAnnouncementPanel = () => {
const t = useT();
const openLink = api.general.openLink.useMutation();
const query = api.forum.latestAnnouncement.useQuery(undefined, {
staleTime: 10 * 60 * 1000,
refetchOnWindowFocus: false,
retry: 1
});
const scrollRef = useScrollHint<HTMLDivElement>();
const data = query.data;
const safeHtml = useMemo(
() => (data ? DOMPurify.sanitize(data.html, SANITIZE_CONFIG) : ''),
[data]
);
const onBodyClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
const anchor = (e.target as HTMLElement).closest('a[href]');
if (!anchor) return;
e.preventDefault();
const href = anchor.getAttribute('href');
if (href) openLink.mutateAsync(href);
},
[openLink]
);
return (
<aside
className="parchment-post flex min-h-0 flex-grow flex-col gap-3"
style={{ backgroundImage: `url(${Parchment})` }}
>
<div className="flex items-start justify-between gap-2">
<h4 className="parchment-post-title min-w-0 flex-1 break-words">
{data?.title ?? t('forum.title')}
</h4>
<TextButton
icon={RefreshCw}
size={18}
className="-mr-2 -mt-1 shrink-0"
loading={query.isFetching}
onClick={() => query.refetch()}
title={t('misc.refresh')}
/>
</div>
{data?.author && (
<span className="parchment-post-meta">
{t('misc.newsByAuthor', { author: data.author })} · {formatDate(data.date)}
</span>
)}
<hr />
<div
ref={scrollRef}
className="relative -mx-4 flex min-h-0 flex-grow flex-col overflow-y-auto overflow-x-hidden px-4"
>
{query.isLoading ? (
<div className="flex flex-grow flex-col items-center justify-center gap-2">
<IconSpinner className="parchment-post-muted" />
<p className="parchment-post-muted italic">{t('forum.loading')}</p>
</div>
) : query.isError ? (
<div className="flex flex-grow flex-col items-center justify-center gap-3">
<AlertTriangle size={32} className="text-red" />
<p className="parchment-post-muted italic">{t('forum.error')}</p>
<TextButton
icon={RefreshCw}
size={18}
onClick={() => query.refetch()}
>
{t('misc.tryAgain')}
</TextButton>
</div>
) : !data ? (
<div className="flex flex-grow flex-col items-center justify-center">
<p className="parchment-post-muted italic">{t('forum.empty')}</p>
</div>
) : (
<div
className="parchment-post-body"
onClick={onBodyClick}
dangerouslySetInnerHTML={{ __html: safeHtml }}
/>
)}
</div>
{data && (
<TextButton
icon={ExternalLink}
size={14}
className="-ml-2 self-start"
onClick={() => openLink.mutateAsync(data.url)}
>
{t('forum.readFullPost')}
</TextButton>
)}
</aside>
);
};
export default ForumAnnouncementPanel;
+38 -9
View File
@@ -22,7 +22,8 @@ const formatDuration = (seconds: number) => {
return minRem ? `${h}h ${minRem}m` : `${h}h`; return minRem ? `${h}h ${minRem}m` : `${h}h`;
}; };
const formatPercent = (progress: number) => `${(progress * 100).toFixed(1)}%`; const formatPercent = (progress: number) =>
`${parseFloat((progress * 100).toFixed(1))}%`;
const ProgressDetails = ({ status }: { status: UpdaterStatus }) => { const ProgressDetails = ({ status }: { status: UpdaterStatus }) => {
const t = useT(); const t = useT();
@@ -41,7 +42,7 @@ const ProgressDetails = ({ status }: { status: UpdaterStatus }) => {
· {formatFileSize(bytesDone)} / {formatFileSize(bytesTotal)} · {formatFileSize(bytesDone)} / {formatFileSize(bytesTotal)}
</span> </span>
{bytesPerSecond !== undefined && bytesPerSecond > 0 && ( {bytesPerSecond !== undefined && bytesPerSecond > 0 && (
<span> · {formatFileSize(bytesPerSecond)}/s</span> <span> · {formatFileSize(bytesPerSecond, 1)}/s</span>
)} )}
<span> <span>
{' · '} {' · '}
@@ -73,6 +74,17 @@ const LaunchPanel = () => {
const start = api.launcher.start.useMutation(); const start = api.launcher.start.useMutation();
const applyMods = api.mods.applyAll.useMutation(); const applyMods = api.mods.applyAll.useMutation();
const modRows = modsStatus?.mods ?? [];
const enabledIds = new Set(modRows.filter(m => m.enabled).map(m => m.id));
const missingDeps = [
...new Set(
modRows
.filter(m => m.enabled)
.flatMap(m => m.requires.filter(d => !enabledIds.has(d)))
)
];
const modName = (id: string) => modRows.find(m => m.id === id)?.name ?? id;
const props: Record< const props: Record<
UpdaterStatus['state'], UpdaterStatus['state'],
{ button: ReactElement; helperText?: ReactElement } { button: ReactElement; helperText?: ReactElement }
@@ -80,7 +92,9 @@ const LaunchPanel = () => {
verifying: { button: <Button disabled>{t('launch.verifying')}</Button> }, verifying: { button: <Button disabled>{t('launch.verifying')}</Button> },
serverUnreachable: { serverUnreachable: {
button: pref?.version ? ( button: pref?.version ? (
<Button onClick={() => start.mutateAsync()}>{t('launch.play')}</Button> <Button disabled={start.isLoading} onClick={() => start.mutateAsync()}>
{t('launch.play')}
</Button>
) : ( ) : (
<Button onClick={() => verify.mutateAsync()}> <Button onClick={() => verify.mutateAsync()}>
{t('launch.retry')} {t('launch.retry')}
@@ -138,8 +152,7 @@ const LaunchPanel = () => {
</span> </span>
</> </>
)} )}
<span className="break-all">{status.message}</span>{' '} <span className="break-all">{status.message}</span>
{t('launch.remaining')}
</p> </p>
</div> </div>
) )
@@ -160,21 +173,37 @@ const LaunchPanel = () => {
<Button <Button
primary primary
onClick={() => applyMods.mutateAsync()} onClick={() => applyMods.mutateAsync()}
disabled={applyMods.isLoading || modsStatus?.state === 'busy'} disabled={
applyMods.isLoading ||
modsStatus?.state === 'busy' ||
missingDeps.length > 0
}
> >
{modsStatus?.state === 'busy' {modsStatus?.state === 'busy'
? t('launch.applying') ? t('launch.applying')
: t('launch.update')} : t('mods.apply')}
</Button> </Button>
) : ( ) : (
<Button primary onClick={() => start.mutateAsync()}> <Button
primary
disabled={start.isLoading}
onClick={() => start.mutateAsync()}
>
{t('launch.play')} {t('launch.play')}
</Button> </Button>
), ),
helperText: ( helperText: (
<div className="-mb-2"> <div className="-mb-2">
{modsStatus?.dirty ? ( {modsStatus?.dirty ? (
<p>{t('launch.modsChanged')}</p> missingDeps.length ? (
<p className="text-orange">
{t('mods.enableRequired', {
mods: missingDeps.map(modName).join(', ')
})}
</p>
) : (
<p>{t('launch.modsChanged')}</p>
)
) : ( ) : (
<p>{t('launch.upToDate')}</p> <p>{t('launch.upToDate')}</p>
)} )}
+39 -13
View File
@@ -3,6 +3,7 @@ import { useEffect, useState } from 'react';
import { import {
FilePen, FilePen,
FolderOpen, FolderOpen,
HelpCircle,
RefreshCw, RefreshCw,
ScrollText, ScrollText,
ShieldAlert, ShieldAlert,
@@ -53,6 +54,7 @@ const PreferencesDialog = ({ close }: Props) => {
defaultValues: pref ?? {}, defaultValues: pref ?? {},
resolver: zodResolver(PreferencesSchema) resolver: zodResolver(PreferencesSchema)
}); });
const [saveError, setSaveError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
pref && reset(pref); pref && reset(pref);
@@ -69,11 +71,17 @@ const PreferencesDialog = ({ close }: Props) => {
<form <form
className="tw-dialog !w-fit min-w-[480px] max-w-[640px] !gap-1" className="tw-dialog !w-fit min-w-[480px] max-w-[640px] !gap-1"
onSubmit={handleSubmit(async v => { onSubmit={handleSubmit(async v => {
await setPref.mutateAsync({ setSaveError(null);
cleanWdb: v.cleanWdb, try {
minimizeToTrayOnPlay: v.minimizeToTrayOnPlay await setPref.mutateAsync({
}); cleanWdb: v.cleanWdb,
close(); minimizeToTrayOnPlay: v.minimizeToTrayOnPlay,
shareDownloads: v.shareDownloads
});
close();
} catch (e) {
setSaveError(e instanceof Error ? e.message : String(e));
}
})} })}
> >
<CloseButton <CloseButton
@@ -160,14 +168,24 @@ const PreferencesDialog = ({ close }: Props) => {
> >
{t('prefs.openLogFile')} {t('prefs.openLogFile')}
</TextButton> </TextButton>
<TextButton <div className="flex items-start">
icon={ShieldAlert} <TextButton
onClick={() => addExclusion.mutateAsync()} icon={ShieldAlert}
loading={addExclusion.isLoading} onClick={() => addExclusion.mutateAsync()}
className="!items-start text-left text-orange" loading={addExclusion.isLoading}
> className="!items-start text-left text-orange"
{t('prefs.allowThroughAntivirus')} >
</TextButton> {t('prefs.allowThroughAntivirus')}
</TextButton>
{/* sits on the label's first line even when a locale wraps it */}
<TextButton
icon={HelpCircle}
size={14}
onClick={() => window.dispatchEvent(new Event('av-help'))}
title={t('av.whatAllowDoesTitle')}
className="mt-[14px] !p-0 text-yellow hocus:!text-yellow"
/>
</div>
{addExclusion.data?.ok === true && ( {addExclusion.data?.ok === true && (
<span className="s1 text-warmGreen"> <span className="s1 text-warmGreen">
{t('prefs.exclusionAdded')} {t('prefs.exclusionAdded')}
@@ -190,9 +208,17 @@ const PreferencesDialog = ({ close }: Props) => {
setValue={setBool('minimizeToTrayOnPlay')} setValue={setBool('minimizeToTrayOnPlay')}
label={t('prefs.minimizeToTray')} label={t('prefs.minimizeToTray')}
/> />
<CheckboxInput
value={watch('shareDownloads') !== false}
setValue={setBool('shareDownloads')}
label={t('prefs.shareDownloads')}
/>
</div> </div>
</div> </div>
{saveError && (
<span className="s1 self-end text-orange">{saveError}</span>
)}
<TextButton type="submit" className="mt-1 self-end text-green"> <TextButton type="submit" className="mt-1 self-end text-green">
{t('prefs.save')} {t('prefs.save')}
</TextButton> </TextButton>
+4 -4
View File
@@ -5,10 +5,10 @@ import TweaksTab from './tabs/TweaksTab';
import TabErrorBoundary from './TabErrorBoundary'; import TabErrorBoundary from './TabErrorBoundary';
const Tabs = { const Tabs = {
'news': NewsTab, news: NewsTab,
'tweaks': TweaksTab, tweaks: TweaksTab,
'addons': AddonsTab, addons: AddonsTab,
'mods': ModsTab mods: ModsTab
} as const; } as const;
export const TabNames = Object.keys(Tabs) as TabType[]; export const TabNames = Object.keys(Tabs) as TabType[];
@@ -3,6 +3,7 @@ import { type ReactNode } from 'react';
import TextButton from '../styled/TextButton'; import TextButton from '../styled/TextButton';
// mt centers this 16px box on the 26px label line box
const Checkbox = () => ( const Checkbox = () => (
<svg <svg
width={16} width={16}
@@ -10,7 +11,7 @@ const Checkbox = () => (
viewBox="0 0 12 12" viewBox="0 0 12 12"
fill="none" fill="none"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
className="shrink-0" className="mt-[5px] shrink-0"
> >
<rect <rect
x="1" x="1"
+26 -8
View File
@@ -1,21 +1,39 @@
type Run = { text: string; color?: string }; type Run = { text: string; color?: string };
// Keep the WoW "|c" color runs, strip every other "|" escape (textures, links, pipes).
const ESCAPE_RE =
/\|\||\|c([0-9a-f]{8})|\|r|\|T[^|]*\|t|\|H[^|]*\|h|\|h|\|./gi;
const tokenize = (s: string): Run[] => { const tokenize = (s: string): Run[] => {
const runs: Run[] = []; const runs: Run[] = [];
const re = /\|c([0-9a-fA-F]{8})|\|r/g;
let i = 0;
let color: string | undefined; let color: string | undefined;
let buf = '';
let i = 0;
const flush = () => {
if (buf) runs.push({ text: buf, color });
buf = '';
};
let m: RegExpExecArray | null; let m: RegExpExecArray | null;
while ((m = re.exec(s)) !== null) { while ((m = ESCAPE_RE.exec(s)) !== null) {
if (m.index > i) runs.push({ text: s.slice(i, m.index), color }); buf += s.slice(i, m.index);
if (m[0].toLowerCase() === '|r') { i = ESCAPE_RE.lastIndex;
color = undefined;
const tok = m[0];
if (tok === '||') {
buf += '|';
} else if (m[1]) { } else if (m[1]) {
// drop the leading alpha byte, keep RGB
flush();
color = `#${m[1].slice(2).toLowerCase()}`; color = `#${m[1].slice(2).toLowerCase()}`;
} else if (tok.toLowerCase() === '|r') {
flush();
color = undefined;
} }
i = re.lastIndex;
} }
if (i < s.length) runs.push({ text: s.slice(i), color }); buf += s.slice(i);
flush();
return runs.filter(r => r.text.length > 0); return runs.filter(r => r.text.length > 0);
}; };
+114 -13
View File
@@ -6,7 +6,11 @@ import cls from 'classnames';
import { api } from '~renderer/utils/api'; import { api } from '~renderer/utils/api';
import useScrollHint from '~renderer/utils/useScrollHint'; import useScrollHint from '~renderer/utils/useScrollHint';
import { useT } from '~renderer/i18n'; import { useT } from '~renderer/i18n';
import { type ModRowStatus, type ModsStatus } from '~main/types'; import {
type ModRowStatus,
type ModsStatus,
type CustomMod
} from '~main/types';
import TextButton from '../styled/TextButton'; import TextButton from '../styled/TextButton';
import CheckboxInput from '../form/CheckboxInput'; import CheckboxInput from '../form/CheckboxInput';
@@ -73,6 +77,52 @@ const ModRow = ({ row }: { row: ModRowStatus }) => {
); );
}; };
const CustomRow = ({ row }: { row: CustomMod }) => {
const toggle = api.mods.toggleCustom.useMutation();
return (
<>
<span className="break-all">{row.name}</span>
<CheckboxInput
value={row.enabled}
setValue={v => toggle.mutate({ name: row.name, enabled: v })}
className="justify-self-center"
/>
</>
);
};
const AddDllButton = () => {
const t = useT();
const pick = api.general.filePicker.useMutation();
const add = api.mods.addCustomDll.useMutation();
const [error, setError] = useState<string | null>(null);
const onClick = async () => {
setError(null);
const res = await pick.mutateAsync({
title: t('mods.addDllTitle'),
filters: [{ name: 'DLL', extensions: ['dll'] }],
properties: ['openFile']
});
if (res.canceled) return;
const result = await add.mutateAsync({ path: res.path[0] });
if (!result.ok) setError(result.error ?? t('mods.addDllFailed'));
};
return (
<div className="flex items-center gap-2">
{error && <span className="s1 text-orange">{error}</span>}
<TextButton
onClick={onClick}
loading={pick.isLoading || add.isLoading}
className="text-green"
>
{t('mods.addDll')}
</TextButton>
</div>
);
};
const ModsTab = () => { const ModsTab = () => {
const t = useT(); const t = useT();
const [status, setStatus] = useState<ModsStatus>(); const [status, setStatus] = useState<ModsStatus>();
@@ -88,6 +138,8 @@ const ModsTab = () => {
}, [list.data, status]); }, [list.data, status]);
const apply = api.mods.applyAll.useMutation(); const apply = api.mods.applyAll.useMutation();
const resync = api.updater.update.useMutation();
const revalidate = api.mods.verify.useMutation();
const scrollRef = useScrollHint<HTMLDivElement>(); const scrollRef = useScrollHint<HTMLDivElement>();
@@ -116,17 +168,24 @@ const ModsTab = () => {
useEffect(() => { useEffect(() => {
if (shownDepMessage) { if (shownDepMessage) {
dialogRef.current?.showModal(); if (!dialogRef.current?.open) dialogRef.current?.showModal();
(document.activeElement as HTMLElement | null)?.blur(); (document.activeElement as HTMLElement | null)?.blur();
} else dialogRef.current?.close(); } else dialogRef.current?.close();
}, [shownDepMessage]); }, [shownDepMessage]);
const onApply = () => { const [applied, setApplied] = useState(false);
const appliedTimer = useRef<number>();
useEffect(() => () => window.clearTimeout(appliedTimer.current), []);
const onApply = async () => {
if (missingDeps.length) { if (missingDeps.length) {
setShownDepMessage(pendingDepMessage); setShownDepMessage(pendingDepMessage);
return; return;
} }
apply.mutateAsync(); setApplied(false);
await apply.mutateAsync();
setApplied(true);
window.clearTimeout(appliedTimer.current);
appliedTimer.current = window.setTimeout(() => setApplied(false), 2500);
}; };
const showApply = const showApply =
@@ -136,9 +195,11 @@ const ModsTab = () => {
<div className="tw-surface flex min-h-0 flex-grow flex-col gap-3"> <div className="tw-surface flex min-h-0 flex-grow flex-col gap-3">
<div className="flex items-baseline justify-between"> <div className="flex items-baseline justify-between">
<h4 className="tw-color">{t('mods.title')}</h4> <h4 className="tw-color">{t('mods.title')}</h4>
{status?.dirty && ( {status?.dirty ? (
<span className="s1 text-pink">{t('mods.unsavedChanges')}</span> <span className="s1 text-pink">{t('mods.unsavedChanges')}</span>
)} ) : applied ? (
<span className="s1 text-warmGreen">{t('mods.applied')}</span>
) : null}
</div> </div>
<p className="s1 text-blueGray"> <p className="s1 text-blueGray">
<span className="text-orange"></span> {t('mods.warning')} <span className="text-orange"></span> {t('mods.warning')}
@@ -151,23 +212,63 @@ const ModsTab = () => {
})} })}
</p> </p>
)} )}
{!!status?.missingFiles?.length && (
<div className="s1 flex flex-col items-start gap-1 text-orange">
<span>
{t('mods.missingFiles', { mods: status.missingFiles.join(', ') })}
</span>
<TextButton
onClick={async () => {
await resync.mutateAsync();
await revalidate.mutateAsync();
}}
loading={resync.isLoading || revalidate.isLoading}
className="text-warmGreen"
>
{t('mods.reverify')}
</TextButton>
</div>
)}
<hr /> <hr />
<div <div
ref={scrollRef} ref={scrollRef}
className="relative -m-4 -mt-0 grid flex-grow grid-cols-[auto_auto_1fr_auto] content-start items-center gap-x-4 gap-y-2 overflow-y-auto p-4 pt-0" className="relative -m-4 -mt-0 flex flex-grow flex-col gap-3 overflow-y-auto p-4 pt-0"
> >
{status?.mods.map(row => ( <div className="grid grid-cols-[auto_auto_1fr_auto] content-start items-center gap-x-4 gap-y-2">
<ModRow key={row.id} row={row} /> {status?.mods.map(row => (
))} <ModRow key={row.id} row={row} />
))}
</div>
<hr />
<div className="flex items-baseline justify-between gap-2">
<h4 className="tw-color">{t('mods.yourDlls')}</h4>
<AddDllButton />
</div>
{status?.custom?.length ? (
<div className="grid grid-cols-[1fr_auto] items-center gap-x-4 gap-y-1">
{status.custom.map(c => (
<CustomRow key={c.name} row={c} />
))}
</div>
) : (
<p className="s1 text-blueGray">{t('mods.yourDllsEmpty')}</p>
)}
</div> </div>
<hr /> <hr />
<div className="-mb-4 -mt-3 flex items-center gap-2 py-2"> <div className="-mb-4 -mt-3 flex items-center gap-2 py-2">
<p className="s1 flex-grow text-blueGray"> <p className="s1 flex-grow text-blueGray">
<span className="text-warmGreen">{t('mods.highlighted')}</span>{' '} {status?.dirty ? (
{t('mods.highlightedRecommended')} <span className="text-pink">{t('mods.unsavedChanges')}</span>
) : applied ? (
<span className="text-warmGreen">{t('mods.applied')}</span>
) : (
<>
<span className="text-warmGreen">{t('mods.highlighted')}</span>{' '}
{t('mods.highlightedRecommended')}
</>
)}
</p> </p>
<TextButton <TextButton
type="button"
loading={apply.isLoading || status?.state === 'busy'} loading={apply.isLoading || status?.state === 'busy'}
onClick={onApply} onClick={onApply}
className={cls('text-green', !showApply && 'invisible')} className={cls('text-green', !showApply && 'invisible')}
+20 -19
View File
@@ -5,7 +5,6 @@ import { api } from '~renderer/utils/api';
import { useT } from '~renderer/i18n'; import { useT } from '~renderer/i18n';
import useScrollHint from '~renderer/utils/useScrollHint'; import useScrollHint from '~renderer/utils/useScrollHint';
import ForumAnnouncementPanel from '../ForumAnnouncementPanel';
import IconSpinner from '../styled/IconSpinner'; import IconSpinner from '../styled/IconSpinner';
import TextButton from '../styled/TextButton'; import TextButton from '../styled/TextButton';
@@ -50,20 +49,22 @@ const NewsEntry = ({ item }: { item: NewsItem }) => {
); );
}; };
// The "Announcements" list — most-recent forum topics as short previews + links. const NewsColumn = ({ forum, title }: { forum: number; title: string }) => {
const AnnouncementsBox = () => {
const t = useT(); const t = useT();
const query = api.news.list.useQuery(undefined, { const query = api.news.list.useQuery(
staleTime: 5 * 60 * 1000, { forum },
refetchOnWindowFocus: false, {
retry: 1 staleTime: 5 * 60 * 1000,
}); refetchOnWindowFocus: false,
retry: 1
}
);
const scrollRef = useScrollHint<HTMLDivElement>(); const scrollRef = useScrollHint<HTMLDivElement>();
return ( return (
<div className="tw-surface flex min-h-0 w-[360px] shrink-0 flex-col gap-3"> <div className="tw-surface flex min-h-0 flex-1 flex-col gap-3">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h4 className="tw-color">{t('misc.announcementsTitle')}</h4> <h4 className="tw-color">{title}</h4>
<TextButton <TextButton
icon={RefreshCw} icon={RefreshCw}
size={18} size={18}
@@ -108,14 +109,14 @@ const AnnouncementsBox = () => {
); );
}; };
// The News tab holds both boxes side by side: the parchment "newsletter" (the const NewsTab = () => {
// featured Nautilus News Network post, biggest) and the "Announcements" list. const t = useT();
// Living inside the tab means they only show on News — not on Tweaks/Addons/Mods. return (
const NewsTab = () => ( <div className="flex min-h-0 flex-grow gap-3">
<div className="flex min-h-0 flex-grow gap-3"> <NewsColumn forum={2} title={t('misc.announcementsTitle')} />
<ForumAnnouncementPanel /> <NewsColumn forum={4} title={t('misc.patchNotesTitle')} />
<AnnouncementsBox /> </div>
</div> );
); };
export default NewsTab; export default NewsTab;
+18 -5
View File
@@ -70,7 +70,7 @@ const TweaksTab = () => {
const setPref = api.preferences.set.useMutation(); const setPref = api.preferences.set.useMutation();
const applyPatch = api.patcher.apply.useMutation(); const applyPatch = api.patcher.apply.useMutation();
const verify = api.updater.verify.useMutation(); const syncRaidVisuals = api.updater.syncRaidVisuals.useMutation();
const form = useForm<ConfigWtfSchema>({ const form = useForm<ConfigWtfSchema>({
defaultValues: pref?.config ?? {}, defaultValues: pref?.config ?? {},
@@ -88,7 +88,7 @@ const TweaksTab = () => {
: ''); : '');
const isApplying = const isApplying =
setPref.isLoading || applyPatch.isLoading || verify.isLoading; setPref.isLoading || applyPatch.isLoading || syncRaidVisuals.isLoading;
useEffect(() => { useEffect(() => {
pref && reset(pref.config); pref && reset(pref.config);
@@ -101,7 +101,7 @@ const TweaksTab = () => {
onSubmit={handleSubmit(async config => { onSubmit={handleSubmit(async config => {
await setPref.mutateAsync({ config, farClipUserSet: true }); await setPref.mutateAsync({ config, farClipUserSet: true });
await applyPatch.mutateAsync(); await applyPatch.mutateAsync();
await verify.mutateAsync(); await syncRaidVisuals.mutateAsync();
reset(config); reset(config);
})} })}
@@ -117,6 +117,12 @@ const TweaksTab = () => {
label={t('tweaks.alwaysAutoLoot.label')} label={t('tweaks.alwaysAutoLoot.label')}
text={t('tweaks.alwaysAutoLoot.text')} text={t('tweaks.alwaysAutoLoot.text')}
/> />
<Item
form={form}
id="raidVisuals"
label={t('tweaks.raidVisuals.label')}
text={t('tweaks.raidVisuals.text')}
/>
<Item <Item
form={form} form={form}
id="largeAddress" id="largeAddress"
@@ -214,8 +220,15 @@ const TweaksTab = () => {
onClick={async () => { onClick={async () => {
const config = const config =
recommendedFarClip != null recommendedFarClip != null
? { ...ConfigWtfSchema.parse({}), farClip: recommendedFarClip } ? {
: ConfigWtfSchema.parse({}); ...ConfigWtfSchema.parse({}),
farClip: recommendedFarClip,
raidVisuals: form.getValues('raidVisuals')
}
: {
...ConfigWtfSchema.parse({}),
raidVisuals: form.getValues('raidVisuals')
};
await setPref.mutateAsync({ config, farClipUserSet: false }); await setPref.mutateAsync({ config, farClipUserSet: false });
reset(config); reset(config);
}} }}
+10
View File
@@ -2,5 +2,15 @@
interface ImportMetaEnv { interface ImportMetaEnv {
readonly MAIN_VITE_SERVER_URL: string; readonly MAIN_VITE_SERVER_URL: string;
// forum base for the news feed; defaults to the live forum so PTR shows real posts
readonly MAIN_VITE_FORUM_URL: string;
readonly MAIN_VITE_CLIENT_VERSION: string; readonly MAIN_VITE_CLIENT_VERSION: string;
// PTR realm/patch host; only set for PTR builds, live falls back to octowow.st.
readonly MAIN_VITE_PTR_REALMLIST: string;
// When set, sync the client from this web-seeded .torrent instead of the manifest.
readonly MAIN_VITE_CLIENT_TORRENT_URL: string;
// optional raid-visuals patch (patch-O.mpq); a ".sha256" sidecar drives change detection
readonly MAIN_VITE_RAID_VISUALS_URL: string;
// the content patch (patch-5.mpq), served outside the torrent; kept current by a ".sha256" sidecar
readonly MAIN_VITE_CLIENT_PATCH_URL: string;
} }
+57 -6
View File
@@ -34,6 +34,9 @@ const enUS: Dict = {
'launch.remaining': 'remaining', 'launch.remaining': 'remaining',
'launch.calculating': 'calculating…', 'launch.calculating': 'calculating…',
'launch.onDisk': 'on disk', 'launch.onDisk': 'on disk',
'tweaks.raidVisuals.label': 'Updated Raid Visuals',
'tweaks.raidVisuals.text':
'Optional ~9 MB download. Adds clearer ground markers and sounds for raid boss abilities, kept in sync with the server automatically. (AKA Patch-O)',
'tweaks.alwaysAutoLoot.label': 'Always auto-loot', 'tweaks.alwaysAutoLoot.label': 'Always auto-loot',
'tweaks.alwaysAutoLoot.text': 'tweaks.alwaysAutoLoot.text':
'Reverses auto-loot behavior to always auto-loot and disable auto-with bound key.', 'Reverses auto-loot behavior to always auto-loot and disable auto-with bound key.',
@@ -67,6 +70,7 @@ const enUS: Dict = {
'tweaks.apply': 'Apply', 'tweaks.apply': 'Apply',
'misc.newsTitle': 'News', 'misc.newsTitle': 'News',
'misc.announcementsTitle': 'Announcements', 'misc.announcementsTitle': 'Announcements',
'misc.patchNotesTitle': 'Patch Notes',
'misc.newsByAuthor': 'by {author}', 'misc.newsByAuthor': 'by {author}',
'misc.newsReadMore': 'Read more', 'misc.newsReadMore': 'Read more',
'misc.refresh': 'Refresh', 'misc.refresh': 'Refresh',
@@ -100,9 +104,19 @@ const enUS: Dict = {
'Enabling custom mods may not provide any performance benefits or may even cause game crashes depending on your system. Please try disabling them if you experience any issues.', 'Enabling custom mods may not provide any performance benefits or may even cause game crashes depending on your system. Please try disabling them if you experience any issues.',
'mods.enableRequired': 'Enable {mods}, required by your selected mods.', 'mods.enableRequired': 'Enable {mods}, required by your selected mods.',
'mods.depRequired': '{mod} must be enabled. It is required by {requiredBy}.', 'mods.depRequired': '{mod} must be enabled. It is required by {requiredBy}.',
'mods.missingFiles':
'Missing game files for: {mods}. Re-sync your client to restore them. If antivirus is blocking them, allow them through first.',
'mods.reverify': 'Re-sync client',
'mods.yourDlls': 'Your DLL mods',
'mods.yourDllsEmpty':
'Drop a .dll into your game folder, or add one below, to toggle it here.',
'mods.addDll': 'Add DLL',
'mods.addDllTitle': 'Choose a DLL mod',
'mods.addDllFailed': 'Failed to add DLL.',
'mods.highlighted': 'Highlighted', 'mods.highlighted': 'Highlighted',
'mods.highlightedRecommended': 'mods are recommended.', 'mods.highlightedRecommended': 'mods are recommended.',
'mods.apply': 'Apply', 'mods.apply': 'Apply',
'mods.applied': 'Applied',
'mods.cantApplyYet': "CAN'T APPLY YET", 'mods.cantApplyYet': "CAN'T APPLY YET",
'mods.close': 'Close', 'mods.close': 'Close',
'av.blockedTitle': 'BLOCKED BY ANTIVIRUS', 'av.blockedTitle': 'BLOCKED BY ANTIVIRUS',
@@ -116,7 +130,7 @@ const enUS: Dict = {
'av.close': 'Close', 'av.close': 'Close',
'av.whyTitle': 'WHY ANTIVIRUS FLAGS MODS', 'av.whyTitle': 'WHY ANTIVIRUS FLAGS MODS',
'av.whyIntro': 'av.whyIntro':
'Some of these mods get flagged by Windows Defender (or other antivirus) as a threat such as "{detection}". This is a', 'Some of the mods the launcher installs get flagged by Windows Defender (or other antivirus) as a threat such as "{detection}". This is a',
'av.falsePositive': 'false positive', 'av.falsePositive': 'false positive',
'av.whatSetsItOff': 'What sets it off', 'av.whatSetsItOff': 'What sets it off',
'av.whatSetsItOffIntro': 'av.whatSetsItOffIntro':
@@ -212,6 +226,7 @@ const enUS: Dict = {
'prefs.generalSettings': 'GENERAL SETTINGS:', 'prefs.generalSettings': 'GENERAL SETTINGS:',
'prefs.cleanWdb': 'Clean WDB on each launch', 'prefs.cleanWdb': 'Clean WDB on each launch',
'prefs.minimizeToTray': 'Minimize to tray while playing', 'prefs.minimizeToTray': 'Minimize to tray while playing',
'prefs.shareDownloads': 'Help share downloads with other players',
'prefs.save': 'Save', 'prefs.save': 'Save',
'prefs.installLocationTitle': 'Install location', 'prefs.installLocationTitle': 'Install location',
'prefs.portableInfo': 'prefs.portableInfo':
@@ -224,6 +239,10 @@ const enUS: Dict = {
'prefs.upgradeExisting': 'prefs.upgradeExisting':
'You may also choose a directory with an existing Turtle WoW or Vanilla WoW installation, and it will be automatically upgraded.', 'You may also choose a directory with an existing Turtle WoW or Vanilla WoW installation, and it will be automatically upgraded.',
'prefs.installDirectory': 'Install directory:', 'prefs.installDirectory': 'Install directory:',
'prefs.noClientHere':
'No {exe} in this folder. The launcher will download a fresh client here, and it will not contain your existing addons or settings. If you already have an install, pick that folder instead.',
'prefs.noClientHereConfirm':
'I understand — download a fresh client into this folder',
'prefs.confirm': 'Confirm' 'prefs.confirm': 'Confirm'
}; };
@@ -260,6 +279,9 @@ const deDE: Dict = {
'launch.remaining': 'verbleibend', 'launch.remaining': 'verbleibend',
'launch.calculating': 'wird berechnet…', 'launch.calculating': 'wird berechnet…',
'launch.onDisk': 'auf der Festplatte', 'launch.onDisk': 'auf der Festplatte',
'tweaks.raidVisuals.label': 'Aktualisierte Raid-Effekte',
'tweaks.raidVisuals.text':
'Optionaler Download (~9 MB). Fügt deutlichere Bodenmarkierungen und Sounds für Raidboss-Fähigkeiten hinzu, automatisch mit dem Server synchron gehalten. (auch bekannt als Patch-O)',
'tweaks.alwaysAutoLoot.label': 'Immer automatisch plündern', 'tweaks.alwaysAutoLoot.label': 'Immer automatisch plündern',
'tweaks.alwaysAutoLoot.text': 'tweaks.alwaysAutoLoot.text':
'Kehrt das Auto-Plündern-Verhalten um, sodass immer automatisch geplündert wird und das Auto-Plündern per Tastenkombination deaktiviert ist.', 'Kehrt das Auto-Plündern-Verhalten um, sodass immer automatisch geplündert wird und das Auto-Plündern per Tastenkombination deaktiviert ist.',
@@ -319,7 +341,7 @@ const deDE: Dict = {
'av.close': 'Schließen', 'av.close': 'Schließen',
'av.whyTitle': 'WARUM ANTIVIRENPROGRAMME MODS MELDEN', 'av.whyTitle': 'WARUM ANTIVIRENPROGRAMME MODS MELDEN',
'av.whyIntro': 'av.whyIntro':
'Einige dieser Mods werden von Windows Defender (oder anderen Antivirenprogrammen) als Bedrohung wie z. B. "{detection}" gemeldet. Dabei handelt es sich um einen', 'Einige der vom Launcher installierten Mods werden von Windows Defender (oder anderen Antivirenprogrammen) als Bedrohung wie z. B. "{detection}" gemeldet. Dabei handelt es sich um einen',
'av.falsePositive': 'Fehlalarm', 'av.falsePositive': 'Fehlalarm',
'av.whatSetsItOff': 'Was den Alarm auslöst', 'av.whatSetsItOff': 'Was den Alarm auslöst',
'av.whatSetsItOffIntro': 'av.whatSetsItOffIntro':
@@ -429,6 +451,10 @@ const deDE: Dict = {
'prefs.upgradeExisting': 'prefs.upgradeExisting':
'Du kannst auch ein Verzeichnis mit einer vorhandenen Turtle-WoW- oder Vanilla-WoW-Installation wählen, und es wird automatisch aktualisiert.', 'Du kannst auch ein Verzeichnis mit einer vorhandenen Turtle-WoW- oder Vanilla-WoW-Installation wählen, und es wird automatisch aktualisiert.',
'prefs.installDirectory': 'Installationsverzeichnis:', 'prefs.installDirectory': 'Installationsverzeichnis:',
'prefs.noClientHere':
'In diesem Ordner ist keine {exe}. Der Launcher lädt hier einen neuen Client herunter, der deine vorhandenen Addons und Einstellungen nicht enthält. Wenn du bereits eine Installation hast, wähle stattdessen deren Ordner.',
'prefs.noClientHereConfirm':
'Verstanden — einen neuen Client in diesen Ordner herunterladen',
'prefs.confirm': 'Bestätigen', 'prefs.confirm': 'Bestätigen',
'misc.newsTitle': 'Neuigkeiten', 'misc.newsTitle': 'Neuigkeiten',
'misc.newsByAuthor': 'von {author}', 'misc.newsByAuthor': 'von {author}',
@@ -485,6 +511,9 @@ const zhCN: Dict = {
'launch.remaining': '剩余', 'launch.remaining': '剩余',
'launch.calculating': '计算中…', 'launch.calculating': '计算中…',
'launch.onDisk': '在磁盘上', 'launch.onDisk': '在磁盘上',
'tweaks.raidVisuals.label': '团队副本视觉增强',
'tweaks.raidVisuals.text':
'可选下载(约 9 MB)。为团队首领技能添加更清晰的地面标记和音效,并自动与服务器保持同步。(又称 Patch-O)',
'tweaks.alwaysAutoLoot.label': '始终自动拾取', 'tweaks.alwaysAutoLoot.label': '始终自动拾取',
'tweaks.alwaysAutoLoot.text': 'tweaks.alwaysAutoLoot.text':
'反转自动拾取行为,改为始终自动拾取,并禁用按住绑定键的自动拾取。', '反转自动拾取行为,改为始终自动拾取,并禁用按住绑定键的自动拾取。',
@@ -539,7 +568,7 @@ const zhCN: Dict = {
'av.close': '关闭', 'av.close': '关闭',
'av.whyTitle': '为什么杀毒软件会标记 Mods', 'av.whyTitle': '为什么杀毒软件会标记 Mods',
'av.whyIntro': 'av.whyIntro':
'其中一些 Mods 会被 Windows Defender(或其他杀毒软件)标记为威胁,例如“{detection}”。这是一个', '启动器安装的部分 Mods 会被 Windows Defender(或其他杀毒软件)标记为威胁,例如“{detection}”。这是一个',
'av.falsePositive': '误报', 'av.falsePositive': '误报',
'av.whatSetsItOff': '触发原因', 'av.whatSetsItOff': '触发原因',
'av.whatSetsItOffIntro': 'av.whatSetsItOffIntro':
@@ -638,6 +667,9 @@ const zhCN: Dict = {
'prefs.upgradeExisting': 'prefs.upgradeExisting':
'你也可以选择一个已有 Turtle WoW 或 Vanilla WoW 安装的目录,它将被自动升级。', '你也可以选择一个已有 Turtle WoW 或 Vanilla WoW 安装的目录,它将被自动升级。',
'prefs.installDirectory': '安装目录:', 'prefs.installDirectory': '安装目录:',
'prefs.noClientHere':
'此文件夹中没有 {exe}。启动器将在此处下载全新的客户端,其中不会包含你现有的插件和设置。如果你已经安装过,请改为选择原有的安装目录。',
'prefs.noClientHereConfirm': '我已了解——在此文件夹下载全新客户端',
'prefs.confirm': '确认', 'prefs.confirm': '确认',
'misc.newsTitle': '新闻', 'misc.newsTitle': '新闻',
'misc.newsByAuthor': '作者:{author}', 'misc.newsByAuthor': '作者:{author}',
@@ -693,6 +725,9 @@ const esES: Dict = {
'launch.remaining': 'restante', 'launch.remaining': 'restante',
'launch.calculating': 'calculando…', 'launch.calculating': 'calculando…',
'launch.onDisk': 'en disco', 'launch.onDisk': 'en disco',
'tweaks.raidVisuals.label': 'Efectos de banda mejorados',
'tweaks.raidVisuals.text':
'Descarga opcional de ~9 MB. Añade marcadores de suelo y sonidos más claros para las habilidades de los jefes de banda, sincronizados automáticamente con el servidor. (también conocido como Patch-O)',
'tweaks.alwaysAutoLoot.label': 'Saqueo automático siempre', 'tweaks.alwaysAutoLoot.label': 'Saqueo automático siempre',
'tweaks.alwaysAutoLoot.text': 'tweaks.alwaysAutoLoot.text':
'Invierte el comportamiento del saqueo automático para saquear siempre de forma automática y desactivar el saqueo automático con tecla asignada.', 'Invierte el comportamiento del saqueo automático para saquear siempre de forma automática y desactivar el saqueo automático con tecla asignada.',
@@ -752,7 +787,7 @@ const esES: Dict = {
'av.close': 'Cerrar', 'av.close': 'Cerrar',
'av.whyTitle': 'POR QUÉ EL ANTIVIRUS MARCA LOS MODS', 'av.whyTitle': 'POR QUÉ EL ANTIVIRUS MARCA LOS MODS',
'av.whyIntro': 'av.whyIntro':
'Algunos de estos mods son marcados por Windows Defender (u otro antivirus) como una amenaza, por ejemplo «{detection}». Se trata de un', 'Algunos de los mods que instala el launcher son marcados por Windows Defender (u otro antivirus) como una amenaza, por ejemplo «{detection}». Se trata de un',
'av.falsePositive': 'falso positivo', 'av.falsePositive': 'falso positivo',
'av.whatSetsItOff': 'Qué lo provoca', 'av.whatSetsItOff': 'Qué lo provoca',
'av.whatSetsItOffIntro': 'av.whatSetsItOffIntro':
@@ -861,6 +896,10 @@ const esES: Dict = {
'prefs.upgradeExisting': 'prefs.upgradeExisting':
'También puedes elegir un directorio con una instalación existente de Turtle WoW o Vanilla WoW, y se actualizará automáticamente.', 'También puedes elegir un directorio con una instalación existente de Turtle WoW o Vanilla WoW, y se actualizará automáticamente.',
'prefs.installDirectory': 'Directorio de instalación:', 'prefs.installDirectory': 'Directorio de instalación:',
'prefs.noClientHere':
'No hay ningún {exe} en esta carpeta. El launcher descargará aquí un cliente nuevo, que no incluirá tus addons ni tu configuración actuales. Si ya tienes una instalación, elige esa carpeta.',
'prefs.noClientHereConfirm':
'Lo entiendo: descargar un cliente nuevo en esta carpeta',
'prefs.confirm': 'Confirmar', 'prefs.confirm': 'Confirmar',
'misc.newsTitle': 'Noticias', 'misc.newsTitle': 'Noticias',
'misc.newsByAuthor': 'por {author}', 'misc.newsByAuthor': 'por {author}',
@@ -919,6 +958,9 @@ const ptBR: Dict = {
'launch.remaining': 'restante', 'launch.remaining': 'restante',
'launch.calculating': 'calculando…', 'launch.calculating': 'calculando…',
'launch.onDisk': 'no disco', 'launch.onDisk': 'no disco',
'tweaks.raidVisuals.label': 'Efeitos de raide atualizados',
'tweaks.raidVisuals.text':
'Download opcional de ~9 MB. Adiciona marcações de chão e sons mais claros para as habilidades dos chefes de raide, mantidos em sincronia com o servidor automaticamente. (também conhecido como Patch-O)',
'tweaks.alwaysAutoLoot.label': 'Saque automático sempre ativo', 'tweaks.alwaysAutoLoot.label': 'Saque automático sempre ativo',
'tweaks.alwaysAutoLoot.text': 'tweaks.alwaysAutoLoot.text':
'Inverte o comportamento do saque automático para saquear sempre automaticamente e desativa o saque automático com a tecla atribuída.', 'Inverte o comportamento do saque automático para saquear sempre automaticamente e desativa o saque automático com a tecla atribuída.',
@@ -976,7 +1018,7 @@ const ptBR: Dict = {
'av.close': 'Fechar', 'av.close': 'Fechar',
'av.whyTitle': 'POR QUE O ANTIVÍRUS SINALIZA OS MODS', 'av.whyTitle': 'POR QUE O ANTIVÍRUS SINALIZA OS MODS',
'av.whyIntro': 'av.whyIntro':
'Alguns destes mods são sinalizados pelo Windows Defender (ou outro antivírus) como uma ameaça, por exemplo "{detection}". Isso é um', 'Alguns dos mods que o launcher instala são sinalizados pelo Windows Defender (ou outro antivírus) como uma ameaça, por exemplo "{detection}". Isso é um',
'av.falsePositive': 'falso positivo', 'av.falsePositive': 'falso positivo',
'av.whatSetsItOff': 'O que dispara o alerta', 'av.whatSetsItOff': 'O que dispara o alerta',
'av.whatSetsItOffIntro': 'av.whatSetsItOffIntro':
@@ -1086,6 +1128,9 @@ const ptBR: Dict = {
'prefs.upgradeExisting': 'prefs.upgradeExisting':
'Você também pode escolher um diretório com uma instalação existente do Turtle WoW ou Vanilla WoW, que será atualizada automaticamente.', 'Você também pode escolher um diretório com uma instalação existente do Turtle WoW ou Vanilla WoW, que será atualizada automaticamente.',
'prefs.installDirectory': 'Diretório de instalação:', 'prefs.installDirectory': 'Diretório de instalação:',
'prefs.noClientHere':
'Não há {exe} nesta pasta. O launcher vai baixar um cliente novo aqui, sem os seus addons e configurações atuais. Se você já tem uma instalação, escolha a pasta dela.',
'prefs.noClientHereConfirm': 'Entendi — baixar um cliente novo nesta pasta',
'prefs.confirm': 'Confirmar', 'prefs.confirm': 'Confirmar',
'misc.newsTitle': 'Notícias', 'misc.newsTitle': 'Notícias',
'misc.newsByAuthor': 'por {author}', 'misc.newsByAuthor': 'por {author}',
@@ -1142,6 +1187,9 @@ const ruRU: Dict = {
'launch.remaining': 'осталось', 'launch.remaining': 'осталось',
'launch.calculating': 'вычисление…', 'launch.calculating': 'вычисление…',
'launch.onDisk': 'на диске', 'launch.onDisk': 'на диске',
'tweaks.raidVisuals.label': 'Улучшенные эффекты рейдов',
'tweaks.raidVisuals.text':
'Дополнительная загрузка (~9 МБ). Добавляет более заметные отметки на земле и звуки для способностей рейдовых боссов, автоматически синхронизируется с сервером. (также известен как Patch-O)',
'tweaks.alwaysAutoLoot.label': 'Всегда автосбор', 'tweaks.alwaysAutoLoot.label': 'Всегда автосбор',
'tweaks.alwaysAutoLoot.text': 'tweaks.alwaysAutoLoot.text':
'Меняет поведение автосбора на противоположное: всегда автоматически собирать добычу, а ручной сбор включается зажатой клавишей.', 'Меняет поведение автосбора на противоположное: всегда автоматически собирать добычу, а ручной сбор включается зажатой клавишей.',
@@ -1198,7 +1246,7 @@ const ruRU: Dict = {
'av.close': 'Закрыть', 'av.close': 'Закрыть',
'av.whyTitle': 'ПОЧЕМУ АНТИВИРУС ПОМЕЧАЕТ МОДЫ', 'av.whyTitle': 'ПОЧЕМУ АНТИВИРУС ПОМЕЧАЕТ МОДЫ',
'av.whyIntro': 'av.whyIntro':
'Некоторые из этих модов помечаются Windows Defender (или другим антивирусом) как угроза, например «{detection}». Это', 'Некоторые из модов, устанавливаемых лаунчером, помечаются Windows Defender (или другим антивирусом) как угроза, например «{detection}». Это',
'av.falsePositive': 'ложное срабатывание', 'av.falsePositive': 'ложное срабатывание',
'av.whatSetsItOff': 'Что вызывает срабатывание', 'av.whatSetsItOff': 'Что вызывает срабатывание',
'av.whatSetsItOffIntro': 'av.whatSetsItOffIntro':
@@ -1305,6 +1353,9 @@ const ruRU: Dict = {
'prefs.upgradeExisting': 'prefs.upgradeExisting':
'Вы также можете выбрать папку с уже установленным Turtle WoW или Vanilla WoW, и она будет автоматически обновлена.', 'Вы также можете выбрать папку с уже установленным Turtle WoW или Vanilla WoW, и она будет автоматически обновлена.',
'prefs.installDirectory': 'Папка установки:', 'prefs.installDirectory': 'Папка установки:',
'prefs.noClientHere':
'В этой папке нет {exe}. Лаунчер скачает сюда новый клиент, в котором не будет ваших текущих аддонов и настроек. Если игра уже установлена, выберите её папку.',
'prefs.noClientHereConfirm': 'Понятно — скачать новый клиент в эту папку',
'prefs.confirm': 'Подтвердить', 'prefs.confirm': 'Подтвердить',
'misc.newsTitle': 'Новости', 'misc.newsTitle': 'Новости',
'misc.newsByAuthor': 'от {author}', 'misc.newsByAuthor': 'от {author}',