Files
Hytale-F2P/backend/managers/gameManager.js
AMIAY e5b44341f1 Develop (#282)
* fix: resolve cross-platform EPERM permissions errors

modManager.js:
- Switch from hardcoded 'junction' to dynamic symlink type based on OS (fixing Linux EPERM).
- Add retry logic for directory removal to handle file locking race conditions.
- Improve broken symlink detection during profile sync.

gameManager.js:
- Implement retry loop (3 attempts) for game directory removal in updateGameFiles to prevent EBUSY/EPERM errors on Windows.

paths.js:
- Prevent fs.mkdirSync failure in getModsPath by pre-checking for broken symbolic links.

* fix: missing pacman builds

* prepare release for 2.1.1

minor fix for EPERM error permission

* prepare release 2.1.1

minor fix EPERM permission error

* prepare release 2.1.1

* Update README.md Windows Prequisites for ARM64 builds

* fix: remove broken symlink after detected

* fix: add pathexists for paths.js to check symlink

* fix: isbrokenlink should be true to remove the symlink

* add arch package .pkg.tar.zst for release

* fix: release workflow for build-arch and build-linux

* build-arch job now only build arch .pkg.tar.zst package instead of the whole generic linux.
* build-linux job now exclude .pacman package since its deprecated and should not be used.

* fix: removes pacman build as it replaced by tar.zst and adds build:arch shortcut for pkgbuild

* aur: add proper VCS (-git) PKGBUILD

created clean VCS-based PKGBUILD following arch packaging conventions.

this explicitly marked as a rolling (-git) build and derives its version dynamically from git tags and commit history via pkgver(). previous hybrid approach has been changed.

key changes:
- use -git suffix to clearly indicate rolling source builds
- set pkgver=0 and compute the actual version via pkgver()
- build only a directory layout using electron-builder (--dir)
- avoid generating AppImage, deb, rpm, or pacman installers
- align build and package steps with Arch packaging guidelines

note: this PKGBUILD is intended for development and AUR use only and is not suitable for binary redistribution or release artifacts.

* ci: add fixed-version PKGBUILD for Arch Linux releases

this PKGBUILD intended for CI and GitHub release artifacts. targets tagged releases only and uses a fixed pkgver that matches the corresponding git tag. all of the VCS logic has been removed to PKGBUILD-git to ensure reproducible builds and stable versioning suitable for binary distribution.

the build process relies on electron-builder directory output (--dir) and packages only the unpacked application into a standard Arch Linux package (.pkg.tar.zst). other distro format are excluded from this path and handled separately.

this change establishes a clear separation between:
- rolling AUR development builds (-git)
- CI-generated, versioned Arch Linux release packages

the result is predictable artifact naming, correct version alignment, and Arch-compliant packaging for downstream users.

* Update README.md

adds information for Arch build

* Update README.md

BUILD.md location was changed and now this link is poiting to nothing

* Update PKGBUILD

* Update PKGBUILD-git

* chore: fix ubuntu/debian part in README.md

* Polish language support (#195)

* Update support_request.yml

Added hardware specification

* Update bug_report.yml

Add logs textfield to bug report

* chore: add changelog in README.md

* fix screenshot input in feature_request.yml

* add hardware spec input in bug_report.yml

* fix: PKGBUILD pkgname variable fix

* userdata migration [need review from other OS]

* french translate

* Add German and Swedish translations

Added de.json and sv.json locale files for German and Swedish language support. Updated i18n.js to register 'de' and 'sv' as available languages in the launcher.

* Update README.md

* chore: add offline-mode warning to the README.md

* chore: add downloads counter in README.md

* fix: Steam Deck/Ubuntu crash - use system libzstd.so

The bundled libzstd.so is incompatible with glibc 2.41's stricter heap
validation, causing "free(): invalid pointer" crashes.

Solution: Automatically replace bundled libzstd.so with system version
on Linux. The launcher detects and symlinks to /usr/lib/libzstd.so.1.

- Auto-detect system libzstd at common paths (Arch, Debian, Fedora)
- Backup bundled version as libzstd.so.bundled
- Create symlink to system version
- Add HYTALE_NO_LIBZSTD_FIX=1 to disable if needed

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: remove Windows and Linux ARM64 information on the README.md

* Update support_request.yml

* fix: improve update system UX and macOS compatibility

Update System Improvements:
- Fix duplicate update popups by disabling legacy updater.js
- Add skip button to update popup (shows after 30s, on error, or after download)
- Add macOS-specific handling with manual download as primary option
- Add missing open-download-page IPC handler
- Add missing unblockInterface() method to properly clean up after popup close
- Add quitAndInstallUpdate alias in preload for compatibility
- Remove pulse animation when download completes
- Fix manual download button to show correct status and close popup
- Sync player name to settings input after first install

Client Patcher Cleanup:
- Remove server patching code (server uses pre-patched JAR from CDN)
- Simplify to client-only patching
- Remove unused imports (crypto, AdmZip, execSync, spawn, javaManager)
- Remove unused methods (stringToUtf8, findAndReplaceDomainUtf8)
- Move localhost dev code to backup file for reference

Code Quality Fixes:
- Fix duplicate DOMContentLoaded handlers in install.js
- Fix duplicate checkForUpdates definition in preload.js
- Fix redundant if/else in onProgressUpdate callback
- Fix typo "Harwadre" -> "Hardware" in preload.js

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add Russian language support

Added Russian (ru) to the list of available languages.

* chore: drafting documentation on SERVER.md

* Some updates in Russian language localization file

* fix

* Update ru.json

* Fixed Java runtime name and fixed typo

* fixed untranslated place

* Update ru.json

* Update ru.json

* Update ru.json

* Update ru.json

* Update ru.json

* fix: timeout getLatestClient 

fixes #138

* fix: change default version to 7.pwr in main.js

* fix: change default release version to 7.pwr

* fix: change version release to 7.pwr

* docs: Add comprehensive troubleshooting guide (#209)

Add TROUBLESHOOTING.md with solutions for common issues including:

- Windows: Firewall configuration, duplicate mods, SmartScreen
- Linux: GPU detection (NVIDIA/AMD), SDL3_image/libpng dependencies,
  Wayland/X11 issues, Steam Deck support
- macOS: Rosetta 2 for Apple Silicon, code signing, quarantine
- Connection: Server boot failures, regional restrictions
- Authentication: Token errors, config reset procedures
- Avatar/Cosmetics: F2P limitations documentation
- Backup locations for all platforms
- Log locations for bug reports

Solutions compiled from closed GitHub issues (#205, #155, #90, #60,
#144, #192) and community feedback.

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>

* Standardize language codes, improve formatting, and update all locale files. (#224)

* Update German (Germany) localization

* Update Español (España) localization

* Update French (France) localization

* Update Polish (Poland) localization

* Update Portuguese (Brazil) localization

* Update Russian (Russia) localization

* Update Swedish (Sweden) localization

* Update Turkish (Turkey) localization

* Update language codes, names and alphabetical in i18n system

* Changed Spanish language name to the Formal name "Spanish (Spain)"

* Fix PKGBUILD-git

* Fix PKGBUILD

* delete cache after installation

* Enforce 16-char player name limit and update mod sync

Added a maxlength attribute to the player name input and enforced a 16-character limit in both install and settings scripts, providing user feedback if exceeded. Refactored modManager.js to replace symlink-based mod management with a copy-based system, copying enabled mods to HytaleSaves\Mods and removing legacy symlink logic to improve compatibility and avoid permission issues.

* Update installation subtitle

* chore: update quickstart link in README.md

* chore: delete warning of Ubuntu-Debian at Linux Prequisites section

* added featured server list from api

* Add Featured Servers page to GUI

* Update Discord invite URL in client patcher

* Add differential update system

* Remove launcher chat and add Discord popup

* fix: removed 'check disk space' alert on permission file error

* fix: upgrade tar to ^7.5.6 version

* fix: re-add universal arch for mac

* fix: upgrade electron/rebuild to 4.0.3

* fix: removed override tar version

* fix: pkgbuild version to 2.1.2

* fix: src.tar.zst and srcinfo missing files

* feat: add Indonesian language translation

* fix: GPU preference hint to Laptop-only

* feat: create two columns for settings page

* Add Discord invite link to rpc

* docs: add recordings form, fix OS list

* Release v2.2.0

* Release v2.2.0

* Release v2.2.0

* chore: delete icon.ico, moved to build folder

* chore: delete icon.png, moved to build folder

* fix: build and release for tag push-only in release.yml

* fix: gamescope steam deck issue fixes #186 hopefully

* Support branch selection for server patching

* chose: add auto-patch system for pre-release JAR

* fix: preserves arch x64 on linux target for #242

* fix: removed arm64 flags

* fix: redo package.json arch

* update package-lock.json

* Update release.yml

* chore: sync package-lock with package.json

* fix: reorder fedora libzstd paths to first iteration

* feat: enhance gpu detection, drafting

* fix: comprehensive UUID/username persistence bug fixes (#252)

* fix: comprehensive UUID/username persistence bug fixes

Major fixes for UUID/skin reset issues that caused players to lose cosmetics:

Core fixes:
- Username rename now preserves UUID (atomic rename, not new identity)
- Atomic config writes with backup/recovery system
- Case-insensitive UUID lookup with case-preserving storage
- Pre-launch validation blocks play if no username configured
- Removed saveUsername calls from launch/install flows

UUID Modal fixes:
- Fixed isCurrent badge showing on wrong user
- Added switch identity button to change between saved usernames
- Fixed custom UUID input using unsaved DOM username
- UUID list now refreshes when player name changes
- Enabled copy/paste in custom UUID input field

UI/UX improvements:
- Added translation keys for switch username functionality
- CSS user-select fix for UUID input fields
- Allowed Ctrl+V/C/X/A shortcuts in Electron

Files: config.js, gameLauncher.js, gameManager.js, playerManager.js,
launcher.js, settings.js, main.js, preload.js, style.css, en.json

See UUID_BUGS_FIX_PLAN.md for detailed bug list (18 bugs, 16 fixed)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(i18n): add switch username translations to all locales

Added translation keys for username switching functionality:
- notifications.noUsername
- notifications.switchUsernameSuccess
- notifications.switchUsernameFailed
- notifications.playerNameTooLong
- confirm.switchUsernameTitle
- confirm.switchUsernameMessage
- confirm.switchUsernameButton

Languages updated: de-DE, es-ES, fr-FR, id-ID, pl-PL, pt-BR, ru-RU, sv-SE, tr-TR

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: move UUID_BUGS_FIX_PLAN.md to docs folder

* docs: update UUID_BUGS_FIX_PLAN with complete fix details

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>

* chore: rearrange, fix, and improve README.md

* chore: link downloads, platform, and version to release page in README.md

* chore: update discord link

* chore: insert contact link in CODE_OF_CONDUCT.md

* fix: missing version text on launcher

* chore: update quickstart button link to header

* chore: update discord link and give warning quickstart

* chore revise online play hosting instructions in README

Updated instructions for hosting an online game and clarified troubleshooting steps.

* Fix Turkish translations in tr-TR.json

* fix: EPERM error in Repair Game Button [windows testing needed]

* fix: invalid generated token that caused hangs on exit [windows testing needed]

* fix: major bug - hytale won't launch with laptop machine and ghost processes

* fix: discord RPC destroy error if not connected

* fix: major bug - detach game process to avoid launcher-held handles causing zombie process

* docs: add analysis on ghost process and launcher cleanup

* revert generateLocalTokens, wrong analysis on game launching issue

* revert add deps for generateLocalTokens

* Add proxy client and route downloads through it

* fix: Prevent JAR file corruption during proxy downloads

Fixed binary file corruption when downloading through proxy by using PassThrough stream to preserve data integrity while tracking download progress.

* Improve featured servers layout with Discord integration

- Add Discord button to server cards when discord link is present in API data
- Remove HF2P Servers section to use full width for featured servers
- Increase server card size (300x180px banner, larger fonts and spacing)
- Simplify layout from 2-column grid to single full-width container
- Discord button opens external browser with server invite link

* package version to 2.2.1

Update package.json version from 2.2.0 to 2.2.1 to publish a patch release.

* fix: add game_running_marker to prevent duplicate launches

* Add smart proxy with direct-fallback and logging

* fix: remove duplicate check

* fix: cache invalidation from .env prevents multiple launch attempts

for all env related, it is necessary to clear cache first, otherwise on few launch attempts the game wouldn't run

* fix: redact proxy_url and remove timed out emoji

* Prepare Release v2.2.1

* docs: enhance bug report template with placeholders and options

Updated the bug report template to include placeholders and additional Linux distributions.

* chore revise windows prerequisites and changelog

Updated prerequisites and changelog for version 2.2.1.

* chore: improvise badges, relocate star history, fix discord links

* chore: fix release notes for v2.2.1

* feat(macos): add code signing and notarization support

Add macOS code signing and notarization for Gatekeeper compatibility:

- Add hardened runtime configuration in package.json
- Add entitlements.mac.plist for required app permissions
- Enable built-in electron-builder notarization
- Add code signing and notarization secrets to workflow

Required GitHub Secrets:
- CSC_LINK: Base64-encoded .p12 certificate file
- CSC_KEY_PASSWORD: Password for the .p12 certificate
- APPLE_ID: Apple Developer account email
- APPLE_APP_SPECIFIC_PASSWORD: App-specific password from appleid.apple.com
- APPLE_TEAM_ID: 10-character Apple Developer Team ID

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Revise and enhance Hytale F2P Server Guide

Updated the Hytale F2P Server Guide with new sections and improved formatting.

* Update SERVER.md official accounts info

Added CloudNord hosting information and new section for playing online with official accounts.

* Update SERVER.md

* refactor: replace pre-patched JAR download with ByteBuddy agent

Migrate from downloading pre-patched server JARs from CDN to downloading
the DualAuth ByteBuddy Agent from GitHub releases. The server JAR stays
pristine - auth patching happens at runtime via -javaagent: flag.

clientPatcher.js:
- Replace patchServer() with ensureAgentAvailable()
- Download dualauth-agent.jar to Server/ directory
- Remove serverJarContainsDualAuth() and validateServerJarSize()

gameLauncher.js:
- Set JAVA_TOOL_OPTIONS env var with -javaagent: for runtime patching
- Update logging to show agent status instead of server patch count

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Bump package version to 2.2.2

Update package.json version from 2.2.1 to 2.2.2 to mark a patch release.

* Use new version API and default to v8 PWR

---------

Co-authored-by: Fazri Gading <fazrigading@gmail.com>
Co-authored-by: TalesAmaral <57869141+TalesAmaral@users.noreply.github.com>
Co-authored-by: walti0 <95646872+walti0@users.noreply.github.com>
Co-authored-by: Fazri Gading <super.fai700@gmail.com>
Co-authored-by: sanasol <mail@sanasol.ws>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Terromur <79866197+Terromur@users.noreply.github.com>
Co-authored-by: Zakhar Smokotov <zaharb840@gmail.com>
Co-authored-by: xSamiVS <samtaiebc@gmail.com>
Co-authored-by: MetricsLite <66024355+MetricsLite@users.noreply.github.com>
2026-02-11 11:13:14 +01:00

887 lines
32 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const { execFile, exec } = require('child_process');
const { promisify } = require('util');
const { getResolvedAppDir, findClientPath, findUserDataPath, findUserDataRecursive, GAME_DIR, CACHE_DIR, TOOLS_DIR } = require('../core/paths');
const { getOS, getArch } = require('../utils/platformUtils');
const { downloadFile, retryDownload, retryStalledDownload, MAX_AUTOMATIC_STALL_RETRIES } = require('../utils/fileManager');
const { getLatestClientVersion, getInstalledClientVersion } = require('../services/versionManager');
const { FORCE_CLEAN_INSTALL_VERSION, CLEAN_INSTALL_TEST_VERSION } = require('../core/testConfig');
const { installButler } = require('./butlerManager');
const { downloadAndReplaceHomePageUI, downloadAndReplaceLogo } = require('./uiFileManager');
const { saveUsername, saveInstallPath, loadJavaPath, CONFIG_FILE, loadConfig, loadVersionBranch, saveVersionClient, loadVersionClient } = require('../core/config');
const { resolveJavaPath, detectSystemJava, downloadJRE, getJavaExec, getBundledJavaPath } = require('./javaManager');
const { getUserDataPath, migrateUserDataToCentralized } = require('../utils/userDataMigration');
const userDataBackup = require('../utils/userDataBackup');
const execAsync = promisify(exec);
// Helper function to check if game processes are running
async function isGameRunning() {
try {
let command;
if (process.platform === 'win32') {
// On Windows, check for HytaleClient.exe processes
command = 'tasklist /FI "IMAGENAME eq HytaleClient.exe" /NH';
} else if (process.platform === 'darwin') {
// On macOS, check for HytaleClient processes
command = 'pgrep -f HytaleClient';
} else {
// On Linux, check for HytaleClient processes
command = 'pgrep -f HytaleClient';
}
const { stdout } = await execAsync(command);
return stdout.trim().length > 0;
} catch (error) {
// If command fails, assume no processes are running
return false;
}
}
// Helper function to safely remove directory with retry logic
async function safeRemoveDirectory(dirPath, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
if (fs.existsSync(dirPath)) {
fs.rmSync(dirPath, { recursive: true, force: true });
console.log(`Successfully removed directory: ${dirPath}`);
}
return; // Success, exit the loop
} catch (error) {
console.warn(`Attempt ${attempt}/${maxRetries} failed to remove ${dirPath}: ${error.message}`);
if (attempt < maxRetries) {
// Wait before retrying (exponential backoff)
const delay = Math.min(1000 * Math.pow(2, attempt - 1), 5000);
console.log(`Waiting ${delay}ms before retry...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
// Last attempt failed, throw the error
throw new Error(`Failed to remove directory ${dirPath} after ${maxRetries} attempts: ${error.message}`);
}
}
}
}
async function downloadPWR(branch = 'release', fileName = 'v8', progressCallback, cacheDir = CACHE_DIR, manualRetry = false) {
const osName = getOS();
const arch = getArch();
if (osName === 'darwin' && arch === 'amd64') {
throw new Error('Hytale x86_64 Intel Mac Support has not been released yet. Please check back later.');
}
const { getPWRUrlFromNewAPI } = require('../services/versionManager');
let url;
let isUsingNewAPI = false;
try {
console.log(`[DownloadPWR] Fetching URL from new API for branch: ${branch}, version: ${fileName}`);
url = await getPWRUrlFromNewAPI(branch, fileName);
isUsingNewAPI = true;
console.log(`[DownloadPWR] Using new API URL: ${url}`);
} catch (error) {
console.error(`[DownloadPWR] Failed to get URL from new API: ${error.message}`);
console.log(`[DownloadPWR] Falling back to old URL format`);
url = `https://game-patches.hytale.com/patches/${osName}/${arch}/${branch}/0/${fileName}.pwr`;
}
const dest = path.join(cacheDir, `${branch}_${fileName}.pwr`);
// Check if file exists and validate it
if (fs.existsSync(dest) && !manualRetry) {
console.log('PWR file found in cache:', dest);
// Validate file size (PWR files should be > 1MB and >= 1.5GB for complete downloads)
const stats = fs.statSync(dest);
if (stats.size < 1024 * 1024) {
return false;
}
// Check if file is under 1.5 GB (incomplete download)
const sizeInMB = stats.size / 1024 / 1024;
if (sizeInMB < 1500) {
console.log(`[PWR Validation] File appears incomplete: ${sizeInMB.toFixed(2)} MB < 1.5 GB`);
return false;
}
}
console.log(`Fetching PWR patch file from ${isUsingNewAPI ? 'NEW API' : 'old API'}:`, url);
try {
if (manualRetry) {
await retryDownload(url, dest, progressCallback);
} else {
await downloadFile(url, dest, progressCallback);
}
} catch (error) {
// Check for automatic stall retry conditions (only for stall errors, not manual retries)
if (!manualRetry &&
error.message &&
error.message.includes('stalled') &&
error.canRetry !== false && // Explicitly check it's not false
(!error.retryState || error.retryState.automaticStallRetries < MAX_AUTOMATIC_STALL_RETRIES)) {
console.log(`[PWR] Automatic stall retry triggered (${(error.retryState && error.retryState.automaticStallRetries || 0) + 1}/${MAX_AUTOMATIC_STALL_RETRIES})`);
try {
await retryStalledDownload(url, dest, progressCallback, error);
console.log('[PWR] Automatic stall retry successful');
// After successful automatic retry, continue with normal flow - the file should be valid now
const retryStats = fs.statSync(dest);
console.log(`PWR file downloaded (auto-retry), size: ${(retryStats.size / 1024 / 1024).toFixed(2)} MB`);
if (!validatePWRFile(dest)) {
console.log(`[PWR Validation] PWR file validation failed after auto-retry, deleting corrupted file: ${dest}`);
fs.unlinkSync(dest);
throw new Error('Downloaded PWR file is corrupted or invalid after automatic retry. Please retry manually');
}
} catch (retryError) {
console.error('[PWR] Automatic stall retry failed:', retryError.message);
// Create enhanced error with updated retry state
const enhancedError = new Error(`PWR download failed after automatic retries: ${retryError.message}`);
enhancedError.originalError = retryError;
enhancedError.retryState = retryError.retryState || error.retryState || null;
enhancedError.canRetry = true; // Still allow manual retry
enhancedError.pwrUrl = url;
enhancedError.pwrDest = dest;
enhancedError.branch = branch;
enhancedError.fileName = fileName;
enhancedError.cacheDir = cacheDir;
enhancedError.automaticRetriesExhausted = true;
throw enhancedError;
}
}
// Enhanced error handling for retry UI (non-stall errors or exhausted automatic retries)
const enhancedError = new Error(`PWR download failed: ${error.message}`);
enhancedError.originalError = error;
enhancedError.retryState = error.retryState || null;
enhancedError.canRetry = error.isConnectionLost ? false : (error.canRetry !== false); // Don't allow retry for connection lost
enhancedError.pwrUrl = url;
enhancedError.pwrDest = dest;
enhancedError.branch = branch;
enhancedError.fileName = fileName;
enhancedError.cacheDir = cacheDir;
enhancedError.isConnectionLost = error.isConnectionLost || false;
console.log(`[PWR] Error handling:`, {
message: enhancedError.message,
isConnectionLost: enhancedError.isConnectionLost,
canRetry: enhancedError.canRetry,
retryState: enhancedError.retryState
});
throw enhancedError;
}
// Enhanced PWR file validation
const stats = fs.statSync(dest);
console.log(`PWR file downloaded, size: ${(stats.size / 1024 / 1024).toFixed(2)} MB`);
if (!validatePWRFile(dest)) {
console.log(`[PWR Validation] PWR file validation failed, deleting corrupted file: ${dest}`);
fs.unlinkSync(dest);
throw new Error('Downloaded PWR file is corrupted or invalid. Please retry');
}
console.log('PWR saved to:', dest);
console.log(`[PWR Validation] PWR file validation passed: ${dest}`);
return dest;
}
// Manual retry function for PWR downloads
async function retryPWRDownload(branch, fileName, progressCallback, cacheDir = CACHE_DIR) {
console.log('Initiating manual PWR retry...');
return await downloadPWR(branch, fileName, progressCallback, cacheDir, true);
}
async function applyPWR(pwrFile, progressCallback, gameDir = GAME_DIR, toolsDir = TOOLS_DIR, branch = 'release', cacheDir = CACHE_DIR) {
console.log(`[Butler] Starting PWR application with:`);
console.log(`[Butler] - PWR file: ${pwrFile}`);
console.log(`[Butler] - Staging dir: ${path.join(gameDir, 'staging-temp')}`);
console.log(`[Butler] - Game dir: ${gameDir}`);
console.log(`[Butler] - Branch: ${branch}`);
console.log(`[Butler] - Cache dir: ${cacheDir}`);
// Validate PWR file exists and get diagnostic info
if (!pwrFile || typeof pwrFile !== 'string' || !fs.existsSync(pwrFile)) {
throw new Error(`PWR file not found: ${pwrFile || 'undefined'}. Please retry download.`);
}
const pwrStats = fs.statSync(pwrFile);
console.log(`[Butler] PWR file size: ${(pwrStats.size / 1024 / 1024).toFixed(2)} MB`);
console.log(`[Butler] PWR file exists: ${fs.existsSync(pwrFile)}`);
const butlerPath = await installButler(toolsDir);
console.log(`[Butler] Butler path: ${butlerPath}`);
console.log(`[Butler] Butler executable: ${fs.existsSync(butlerPath)}`);
const gameLatest = gameDir;
const stagingDir = path.join(gameLatest, 'staging-temp');
const clientPath = findClientPath(gameLatest);
if (clientPath) {
console.log('Game files detected, skipping patch installation.');
return;
}
// Validate and prepare directories
validateGameDirectory(gameLatest, stagingDir);
console.log(`[Butler] Game directory validated: ${gameLatest}`);
console.log(`[Butler] Staging directory validated: ${stagingDir}`);
if (progressCallback) {
progressCallback('Installing game patch...', null, null, null, null);
}
console.log('Installing game patch...');
if (!fs.existsSync(butlerPath)) {
throw new Error(`Butler tool not found at: ${butlerPath}`);
}
if (!fs.existsSync(pwrFile)) {
throw new Error(`PWR file not found at: ${pwrFile}`);
}
const args = [
'apply',
'--staging-dir',
stagingDir,
pwrFile,
gameLatest
];
console.log(`[Butler] Executing command: ${butlerPath} ${args.join(' ')}`);
try {
await new Promise((resolve, reject) => {
const child = execFile(butlerPath, args, {
maxBuffer: 1024 * 1024 * 10,
timeout: 600000
}, (error, stdout, stderr) => {
if (error) {
console.error('[Butler] stderr:', stderr);
console.error('[Butler] stdout:', stdout);
console.error('[Butler] error code:', error.code);
console.error('[Butler] error signal:', error.signal);
// Enhanced error pattern detection
const errorPatterns = {
'unexpected EOF': {
message: 'Corrupted PWR file detected and deleted. Please try launching the game again.',
shouldDeletePWR: true
},
'permission denied': {
message: 'Permission denied. Check file permissions and try again.',
shouldDeletePWR: false
},
'no space left': {
message: 'Insufficient disk space. Free up space and try again.',
shouldDeletePWR: false
},
'device full': {
message: 'Insufficient disk space. Free up space and try again.',
shouldDeletePWR: false
},
'already exists': {
message: 'Installation directory conflict. Clean directories and retry.',
shouldDeletePWR: false
},
'network error': {
message: 'Network error during patch installation. Please retry.',
shouldDeletePWR: false
},
'connection refused': {
message: 'Connection refused. Check network and retry.',
shouldDeletePWR: false
}
};
let enhancedMessage = `Patch installation failed: ${error.message}${stderr ? '\n' + stderr : ''}`;
let shouldDeletePWR = false;
// Check error patterns
const errorText = (stderr + ' ' + error.message).toLowerCase();
for (const [pattern, config] of Object.entries(errorPatterns)) {
if (errorText.includes(pattern)) {
enhancedMessage = config.message;
shouldDeletePWR = config.shouldDeletePWR;
console.log(`[Butler] Pattern matched: ${pattern}`);
break;
}
}
// Delete corrupted PWR file if needed
if (shouldDeletePWR) {
try {
if (fs.existsSync(pwrFile)) {
fs.unlinkSync(pwrFile);
console.log('[Butler] Corrupted PWR file deleted:', pwrFile);
}
} catch (delErr) {
console.error('[Butler] Failed to delete corrupted PWR file:', delErr);
}
}
// Enhanced error with retry context
const enhancedError = new Error(enhancedMessage);
enhancedError.canRetry = true;
enhancedError.branch = branch;
enhancedError.fileName = path.basename(pwrFile);
enhancedError.cacheDir = cacheDir;
enhancedError.butlerError = true;
enhancedError.errorCode = error.code;
enhancedError.stderr = stderr;
enhancedError.stdout = stdout;
console.log('[Butler] Enhanced error created with retry context');
reject(enhancedError);
} else {
console.log('[Butler] Patch installation completed successfully');
resolve();
}
});
});
} catch (error) {
console.error('[Butler] Exception during Butler execution:', error);
const enhancedError = new Error(`Butler execution failed: ${error.message}`);
enhancedError.canRetry = true;
enhancedError.branch = branch;
enhancedError.fileName = path.basename(pwrFile);
enhancedError.cacheDir = cacheDir;
enhancedError.butlerError = true;
throw enhancedError;
}
if (fs.existsSync(stagingDir)) {
fs.rmSync(stagingDir, { recursive: true, force: true });
}
// Delete PWR file from cache after successful installation
try {
if (fs.existsSync(pwrFile)) {
fs.unlinkSync(pwrFile);
console.log('[Butler] PWR file deleted from cache after successful installation:', pwrFile);
}
} catch (delErr) {
console.warn('[Butler] Failed to delete PWR file from cache:', delErr.message);
}
if (progressCallback) {
progressCallback('Installation complete', null, null, null, null);
}
console.log('Installation complete');
}
async function updateGameFiles(newVersion, progressCallback, gameDir = GAME_DIR, toolsDir = TOOLS_DIR, cacheDir = CACHE_DIR, branchOverride = null) {
let tempUpdateDir;
const branch = branchOverride || loadVersionBranch();
const installPath = path.dirname(path.dirname(path.dirname(path.dirname(gameDir))));
const config = loadConfig();
const oldBranch = config.version_branch || 'release';
console.log(`[UpdateGameFiles] Switching from ${oldBranch} to ${branch}`);
try {
// NEW 2.2.0: Ensure UserData migration to centralized location
try {
console.log('[UpdateGameFiles] Ensuring UserData migration...');
const migrationResult = await migrateUserDataToCentralized();
if (migrationResult.migrated) {
console.log('[UpdateGameFiles] ✓ UserData migrated to centralized location');
} else if (migrationResult.alreadyMigrated) {
console.log('[UpdateGameFiles] ✓ UserData already in centralized location');
}
} catch (migrationError) {
console.warn('[UpdateGameFiles] UserData migration warning:', migrationError.message);
}
if (progressCallback) {
progressCallback('Updating game files...', 10, null, null, null);
}
console.log(`Updating game files to version: ${newVersion} (branch: ${branch})`);
tempUpdateDir = path.join(gameDir, '..', 'temp_update');
if (fs.existsSync(tempUpdateDir)) {
fs.rmSync(tempUpdateDir, { recursive: true, force: true });
}
fs.mkdirSync(tempUpdateDir, { recursive: true });
if (progressCallback) {
progressCallback('Downloading new game version...', 20, null, null, null);
}
const pwrFile = await downloadPWR(branch, newVersion, progressCallback, cacheDir);
if (progressCallback) {
progressCallback('Extracting new files...', 60, null, null, null);
}
await applyPWR(pwrFile, progressCallback, tempUpdateDir, toolsDir, branch, cacheDir);
// Delete PWR file from cache after successful update
try {
if (fs.existsSync(pwrFile)) {
fs.unlinkSync(pwrFile);
console.log('[UpdateGameFiles] PWR file deleted from cache after successful update:', pwrFile);
}
} catch (delErr) {
console.warn('[UpdateGameFiles] Failed to delete PWR file from cache:', delErr.message);
}
if (progressCallback) {
progressCallback('Replacing game files...', 80, null, null, null);
}
if (fs.existsSync(gameDir)) {
console.log('Removing old game files...');
let retries = 3;
while (retries > 0) {
try {
fs.rmSync(gameDir, { recursive: true, force: true });
break;
} catch (err) {
if ((err.code === 'EPERM' || err.code === 'EBUSY') && retries > 0) {
retries--;
console.log(`[UpdateGameFiles] Removal failed with ${err.code}, retrying in 1s... (${retries} retries left)`);
await new Promise(resolve => setTimeout(resolve, 1000));
} else {
throw err;
}
}
}
}
fs.renameSync(tempUpdateDir, gameDir);
const homeUIResult = await downloadAndReplaceHomePageUI(gameDir, progressCallback);
console.log('HomePage.ui update result after update:', homeUIResult);
const logoResult = await downloadAndReplaceLogo(gameDir, progressCallback);
console.log('Logo@2x.png update result after update:', logoResult);
// NEW 2.2.0: No longer create UserData in game installation
// UserData is now in centralized location (getUserDataPath())
console.log('[UpdateGameFiles] UserData is managed in centralized location');
console.log(`Game files updated successfully to version: ${newVersion}`);
// Save the updated version and branch to config
saveVersionClient(newVersion);
const { saveVersionBranch } = require('../core/config');
saveVersionBranch(branch);
console.log('Waiting for file system sync...');
await new Promise(resolve => setTimeout(resolve, 2000));
if (progressCallback) {
progressCallback('Game update completed', 100, null, null, null);
}
return { success: true, updated: true, version: newVersion };
} catch (error) {
console.error('Error updating game files:', error);
if (tempUpdateDir && fs.existsSync(tempUpdateDir)) {
fs.rmSync(tempUpdateDir, { recursive: true, force: true });
}
throw new Error(`Failed to update game files: ${error.message}`);
}
}
function isGameInstalled(branchOverride = null) {
const branch = branchOverride || loadVersionBranch();
const appDir = getResolvedAppDir();
const gameDir = path.join(appDir, branch, 'package', 'game', 'latest');
const clientPath = findClientPath(gameDir);
return clientPath !== null;
}
async function installGame(playerName = 'Player', progressCallback, javaPathOverride, installPathOverride, branchOverride = null) {
console.log(`[InstallGame] branchOverride parameter received: ${branchOverride}`);
const loadedBranch = loadVersionBranch();
console.log(`[InstallGame] loadVersionBranch() returned: ${loadedBranch}`);
const branch = branchOverride || loadedBranch;
console.log(`[InstallGame] Final branch selected: ${branch}`);
const customAppDir = getResolvedAppDir(installPathOverride);
const customCacheDir = path.join(customAppDir, 'cache');
const customToolsDir = path.join(customAppDir, 'butler');
const customGameDir = path.join(customAppDir, branch, 'package', 'game', 'latest');
const customJreDir = path.join(customAppDir, branch, 'package', 'jre', 'latest');
// NEW 2.2.0: Ensure UserData migration to centralized location
try {
console.log('[InstallGame] Ensuring UserData migration...');
const migrationResult = await migrateUserDataToCentralized();
if (migrationResult.migrated) {
console.log('[InstallGame] ✓ UserData migrated to centralized location');
} else if (migrationResult.alreadyMigrated) {
console.log('[InstallGame] ✓ UserData already in centralized location');
}
} catch (migrationError) {
console.warn('[InstallGame] UserData migration warning:', migrationError.message);
}
[customAppDir, customCacheDir, customToolsDir].forEach(dir => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
});
// NOTE: Do NOT save username here - username should only be saved when user explicitly
// changes it in Settings. Saving here could overwrite a good username with 'Player' default.
// The username is only needed for launching, not for installing.
if (installPathOverride) {
saveInstallPath(installPathOverride);
}
const gameLatest = customGameDir;
let clientPath = findClientPath(gameLatest);
if (clientPath) {
if (progressCallback) {
progressCallback('Game already installed', 100, null, null, null);
}
console.log('Game is already installed');
return { success: true, alreadyInstalled: true };
}
const configuredJava = (javaPathOverride !== undefined && javaPathOverride !== null
? javaPathOverride
: loadJavaPath() || '').trim();
let javaBin = null;
if (configuredJava) {
javaBin = await resolveJavaPath(configuredJava);
if (!javaBin) {
throw new Error(`Configured Java path not found: ${configuredJava}`);
}
} else {
try {
await downloadJRE(progressCallback, customCacheDir, customJreDir);
} catch (error) {
// Don't immediately fall back to system Java for JRE download errors - let user retry
if (error.isJREError) {
console.error('[Install] JRE download failed, allowing user retry:', error.message);
throw error; // Re-throw JRE errors to trigger retry UI
}
// For non-download JRE errors, fall back to system Java
const fallback = await detectSystemJava();
if (fallback) {
javaBin = fallback;
console.log('[Install] Using system Java as fallback');
} else {
throw error;
}
}
if (!javaBin) {
javaBin = getJavaExec(customJreDir);
}
}
if (progressCallback) {
progressCallback('Fetching game files...', null, null, null, null);
}
console.log(`Installing game files for branch: ${branch}...`);
const latestVersion = await getLatestClientVersion(branch);
const targetVersion = FORCE_CLEAN_INSTALL_VERSION ? CLEAN_INSTALL_TEST_VERSION : latestVersion;
if (FORCE_CLEAN_INSTALL_VERSION) {
console.log(`TESTING MODE: Forcing installation of ${targetVersion} instead of ${latestVersion}`);
}
let pwrFile;
try {
pwrFile = await downloadPWR(branch, targetVersion, progressCallback, customCacheDir);
if (!pwrFile) {
console.log('[Install] PWR file not found or invalid, attempting retry...');
pwrFile = await retryPWRDownload(branch, targetVersion, progressCallback, customCacheDir);
}
if (!pwrFile || typeof pwrFile !== 'string') {
throw new Error(`PWR file download failed: received invalid path ${pwrFile}. Please retry download.`);
}
} catch (downloadError) {
console.error('[Install] PWR download failed:', downloadError.message);
throw downloadError;
}
await applyPWR(pwrFile, progressCallback, customGameDir, customToolsDir, branch, customCacheDir);
saveVersionClient(targetVersion);
const { saveVersionBranch } = require('../core/config');
saveVersionBranch(branch);
const homeUIResult = await downloadAndReplaceHomePageUI(customGameDir, progressCallback);
console.log('HomePage.ui update result after installation:', homeUIResult);
const logoResult = await downloadAndReplaceLogo(customGameDir, progressCallback);
console.log('Logo@2x.png update result after installation:', logoResult);
// NEW 2.2.0: No longer create UserData in game installation
// UserData is managed in centralized location (getUserDataPath())
console.log('[InstallGame] UserData is managed in centralized location');
if (progressCallback) {
progressCallback('Installation complete', 100, null, null, null);
}
console.log('Game installation completed successfully');
return {
success: true,
installed: true
};
}
async function uninstallGame() {
const appDir = getResolvedAppDir();
if (!fs.existsSync(appDir)) {
throw new Error('Game is not installed');
}
// Check if game is running before attempting to delete files
const gameRunning = await isGameRunning();
if (gameRunning) {
throw new Error('Cannot uninstall game while it is running. Please close the game first.');
}
try {
await safeRemoveDirectory(appDir);
console.log('Game uninstalled successfully - removed entire HytaleF2P folder');
if (fs.existsSync(CONFIG_FILE)) {
const config = loadConfig();
delete config.installPath;
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
}
} catch (error) {
throw new Error(`Failed to uninstall game: ${error.message}`);
}
}
function checkExistingGameInstallation(branchOverride = null) {
try {
const branch = branchOverride || loadVersionBranch();
const config = loadConfig();
if (!config.installPath || !config.installPath.trim()) {
return null;
}
const installPath = config.installPath.trim();
const gameDir = path.join(installPath, 'HytaleF2P', branch, 'package', 'game', 'latest');
if (!fs.existsSync(gameDir)) {
return null;
}
const clientPath = findClientPath(gameDir);
if (!clientPath) {
return null;
}
const userDataPath = findUserDataRecursive(gameDir);
return {
gameDir: gameDir,
clientPath: clientPath,
userDataPath: userDataPath,
installPath: installPath,
hasUserData: userDataPath && fs.existsSync(userDataPath),
branch: branch
};
} catch (error) {
console.error('Error checking existing game installation:', error);
return null;
}
}
async function repairGame(progressCallback, branchOverride = null) {
const branch = branchOverride || loadVersionBranch();
const appDir = getResolvedAppDir();
const gameDir = path.join(appDir, branch, 'package', 'game', 'latest');
const installPath = appDir;
let backupPath = null;
// Vérifier si on a version_client et version_branch dans config.json
const config = loadConfig();
const hasVersionConfig = !!(config.version_client && config.version_branch);
console.log(`[RepairGame] hasVersionConfig: ${hasVersionConfig}`);
// Check if game exists
if (!fs.existsSync(gameDir)) {
throw new Error('Game directory not found. Cannot repair.');
}
if (progressCallback) {
progressCallback('Backing up user data...', 10, null, null, null);
}
// Backup UserData using new system
try {
backupPath = await userDataBackup.backupUserData(installPath, branch, hasVersionConfig);
} catch (backupError) {
console.warn('UserData backup failed during repair:', backupError.message);
}
if (progressCallback) {
progressCallback('Removing old game files...', 30, null, null, null);
}
// Check if game is running before attempting to delete files
const gameRunning = await isGameRunning();
if (gameRunning) {
console.warn('[RepairGame] Game appears to be running. This may cause permission errors during repair.');
console.log('[RepairGame] Please close the game before repairing, or wait for the repair to complete.');
}
// Delete Game and Cache Directory with retry logic
console.log('Removing corrupted game files...');
try {
await safeRemoveDirectory(gameDir);
} catch (error) {
console.error(`[RepairGame] Failed to remove game directory: ${error.message}`);
throw new Error(`Cannot repair game: ${error.message}. Please ensure the game is not running and try again.`);
}
const cacheDir = path.join(appDir, 'cache');
if (fs.existsSync(cacheDir)) {
console.log('Clearing cache directory...');
try {
await safeRemoveDirectory(cacheDir);
} catch (error) {
console.warn(`[RepairGame] Failed to clear cache directory: ${error.message}`);
// Don't throw here, cache cleanup is not critical
}
}
console.log('Reinstalling game files...');
// Passing null/undefined for overrides to use defaults/saved configs
// installGame calls progressCallback internally
await installGame('Player', progressCallback, null, null, branch);
// Restore UserData using new system
if (backupPath) {
if (progressCallback) {
progressCallback('Restoring user data...', 90, null, null, null);
}
try {
await userDataBackup.restoreUserData(backupPath, installPath, branch);
await userDataBackup.cleanupBackup(backupPath);
console.log('UserData restored successfully after repair');
} catch (restoreError) {
console.warn('UserData restore failed after repair:', restoreError.message);
}
}
if (progressCallback) {
progressCallback('Repair completed successfully!', 100, null, null, null);
}
return { success: true, repaired: true };
}
// Directory validation and cleanup function
function validateGameDirectory(gameDir, stagingDir) {
try {
// Ensure game directory exists and is writable
if (!fs.existsSync(gameDir)) {
fs.mkdirSync(gameDir, { recursive: true });
console.log(`[Butler] Created game directory: ${gameDir}`);
}
// Test write permissions
const testFile = path.join(gameDir, '.permission_test');
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
console.log(`[Butler] Game directory is writable: ${gameDir}`);
// Clean and ensure staging directory
if (fs.existsSync(stagingDir)) {
console.log(`[Butler] Cleaning existing staging directory: ${stagingDir}`);
fs.rmSync(stagingDir, { recursive: true, force: true });
}
fs.mkdirSync(stagingDir, { recursive: true });
console.log(`[Butler] Created clean staging directory: ${stagingDir}`);
// Check disk space (basic check)
const freeSpace = fs.statSync(gameDir);
console.log(`[Butler] Directory validation completed successfully`);
} catch (error) {
throw new Error(`Directory validation failed: ${error.message}. Please check permissions and disk space.`);
}
}
// Enhanced PWR file validation
function validatePWRFile(filePath) {
try {
if (!fs.existsSync(filePath)) {
return false;
}
const stats = fs.statSync(filePath);
const sizeInMB = stats.size / 1024 / 1024;
if (stats.size < 1024 * 1024) {
return false;
}
// Check if file is under 1.5 GB (incomplete download)
if (sizeInMB < 1500) {
console.log(`[PWR Validation] File appears incomplete: ${sizeInMB.toFixed(2)} MB < 1.5 GB`);
return false;
}
// Basic file header validation (PWR files should have specific headers)
const buffer = fs.readFileSync(filePath, { start: 0, end: 20 });
if (buffer.length < 10) {
return false;
}
// Check for common PWR magic bytes or patterns
// This is a basic check - could be enhanced with actual PWR format specification
const header = buffer.toString('hex', 0, 10);
console.log(`[PWR Validation] File header: ${header}`);
return true;
} catch (error) {
console.error(`[PWR Validation] Error:`, error.message);
return false;
}
}
module.exports = {
downloadPWR,
retryPWRDownload,
applyPWR,
updateGameFiles,
isGameInstalled,
installGame,
uninstallGame,
isGameInstalled,
installGame,
uninstallGame,
checkExistingGameInstallation,
repairGame
};