Release Build v2.2.0 (#236)

* 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

---------

Co-authored-by: TalesAmaral <57869141+TalesAmaral@users.noreply.github.com>
Co-authored-by: walti0 <95646872+walti0@users.noreply.github.com>
Co-authored-by: AMIAY <letudiantenrap.collab@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>
This commit is contained in:
Fazri Gading
2026-01-31 06:19:46 +08:00
committed by GitHub
parent da186333cb
commit d5cc0868e9
50 changed files with 5934 additions and 3631 deletions

View File

@@ -84,15 +84,6 @@ function loadUsername() {
return config.username || 'Player';
}
function saveChatUsername(chatUsername) {
saveConfig({ chatUsername: chatUsername || '' });
}
function loadChatUsername() {
const config = loadConfig();
return config.chatUsername || '';
}
function getUuidForUser(username) {
const { v4: uuidv4 } = require('uuid');
const config = loadConfig();
@@ -294,17 +285,6 @@ function resetCurrentUserUuid() {
return setUuidForUser(username, newUuid);
}
function saveChatColor(color) {
const config = loadConfig();
config.chatColor = color;
saveConfig(config);
}
function loadChatColor() {
const config = loadConfig();
return config.chatColor || '#3498db';
}
function saveGpuPreference(gpuPreference) {
saveConfig({ gpuPreference: gpuPreference || 'auto' });
}
@@ -343,10 +323,6 @@ module.exports = {
saveConfig,
saveUsername,
loadUsername,
saveChatUsername,
loadChatUsername,
saveChatColor,
loadChatColor,
getUuidForUser,
saveJavaPath,
loadJavaPath,

View File

@@ -14,6 +14,21 @@ function getAppDir() {
}
}
/**
* Get centralized UserData saves directory (NEW in 2.2.0)
* UserData is now stored separately from game installation
*/
function getHytaleSavesDir() {
const home = os.homedir();
if (process.platform === 'win32') {
return path.join(home, 'AppData', 'Local', 'HytaleSaves');
} else if (process.platform === 'darwin') {
return path.join(home, 'Library', 'Application Support', 'HytaleSaves');
} else {
return path.join(home, '.hytalesaves');
}
}
const DEFAULT_APP_DIR = getAppDir();
function getResolvedAppDir(customPath) {
@@ -218,20 +233,8 @@ async function getModsPath(customInstallPath = null) {
function getProfilesDir(customInstallPath = null) {
try {
// get UserData path
let installPath = customInstallPath;
if (!installPath) {
const configFile = path.join(DEFAULT_APP_DIR, 'config.json');
if (fs.existsSync(configFile)) {
const config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
installPath = config.installPath || '';
}
}
if (!installPath) installPath = getAppDir();
const branch = loadVersionBranch();
const gameLatest = path.join(installPath, branch, 'package', 'game', 'latest');
const userDataPath = findUserDataPath(gameLatest);
// NEW 2.2.0: Use centralized UserData location
const userDataPath = getHytaleSavesDir();
const profilesDir = path.join(userDataPath, 'Profiles');
if (!fs.existsSync(profilesDir)) {
@@ -247,6 +250,7 @@ function getProfilesDir(customInstallPath = null) {
module.exports = {
getAppDir,
getHytaleSavesDir,
getResolvedAppDir,
expandHome,
APP_DIR,

View File

@@ -0,0 +1,7 @@
const FORCE_CLEAN_INSTALL_VERSION = false;
const CLEAN_INSTALL_TEST_VERSION = '4.pwr';
module.exports = {
FORCE_CLEAN_INSTALL_VERSION,
CLEAN_INSTALL_TEST_VERSION
};

View File

@@ -5,10 +5,6 @@
const {
saveUsername,
loadUsername,
saveChatUsername,
loadChatUsername,
saveChatColor,
loadChatColor,
saveJavaPath,
loadJavaPath,
saveInstallPath,
@@ -20,10 +16,11 @@ const {
saveCloseLauncherOnStart,
loadCloseLauncherOnStart,
// Hardware Acceleration
saveLauncherHardwareAcceleration,
loadLauncherHardwareAcceleration,
loadConfig,
saveConfig,
saveModsToConfig,
loadModsFromConfig,
@@ -113,10 +110,6 @@ module.exports = {
// User configuration functions
saveUsername,
loadUsername,
saveChatUsername,
loadChatUsername,
saveChatColor,
loadChatColor,
getUuidForUser,
// Java configuration functions
@@ -144,6 +137,10 @@ module.exports = {
saveLauncherHardwareAcceleration,
loadLauncherHardwareAcceleration,
// Config functions
loadConfig,
saveConfig,
// GPU Preference functions
saveGpuPreference,
loadGpuPreference,

View File

@@ -0,0 +1,272 @@
const fs = require('fs');
const path = require('path');
const { execFile } = require('child_process');
const { downloadFile, retryDownload } = require('../utils/fileManager');
const { getOS, getArch } = require('../utils/platformUtils');
const { validateChecksum, extractVersionDetails, canUseDifferentialUpdate, needsIntermediatePatches, getInstalledClientVersion } = require('../services/versionManager');
const { installButler } = require('./butlerManager');
const { GAME_DIR, CACHE_DIR, TOOLS_DIR } = require('../core/paths');
const { saveVersionClient } = require('../core/config');
async function acquireGameArchive(downloadUrl, targetPath, checksum, progressCallback, allowRetry = true) {
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.');
}
if (fs.existsSync(targetPath)) {
const stats = fs.statSync(targetPath);
if (stats.size > 1024 * 1024) {
const isValid = await validateChecksum(targetPath, checksum);
if (isValid) {
console.log(`Valid archive found in cache: ${targetPath}`);
return targetPath;
}
console.log('Cached archive checksum mismatch, re-downloading');
fs.unlinkSync(targetPath);
}
}
console.log(`Downloading game archive from: ${downloadUrl}`);
try {
if (allowRetry) {
await retryDownload(downloadUrl, targetPath, progressCallback);
} else {
await downloadFile(downloadUrl, targetPath, progressCallback);
}
} catch (error) {
const enhancedError = new Error(`Archive download failed: ${error.message}`);
enhancedError.originalError = error;
enhancedError.downloadUrl = downloadUrl;
enhancedError.targetPath = targetPath;
throw enhancedError;
}
const stats = fs.statSync(targetPath);
console.log(`Archive downloaded, size: ${(stats.size / 1024 / 1024).toFixed(2)} MB`);
const isValid = await validateChecksum(targetPath, checksum);
if (!isValid) {
console.log('Downloaded archive checksum validation failed, removing corrupted file');
fs.unlinkSync(targetPath);
throw new Error('Downloaded archive is corrupted or invalid. Please retry');
}
console.log(`Archive validation passed: ${targetPath}`);
return targetPath;
}
async function deployGameArchive(archivePath, destinationDir, toolsDir, progressCallback, isDifferential = false) {
if (!archivePath || !fs.existsSync(archivePath)) {
throw new Error(`Archive not found: ${archivePath || 'undefined'}`);
}
const stats = fs.statSync(archivePath);
console.log(`Deploying archive: ${archivePath}`);
console.log(`Archive size: ${(stats.size / 1024 / 1024).toFixed(2)} MB`);
console.log(`Deployment mode: ${isDifferential ? 'differential' : 'full'}`);
const butlerPath = await installButler(toolsDir);
const stagingDir = path.join(destinationDir, 'staging-temp');
if (!fs.existsSync(destinationDir)) {
fs.mkdirSync(destinationDir, { recursive: true });
}
if (fs.existsSync(stagingDir)) {
fs.rmSync(stagingDir, { recursive: true, force: true });
}
fs.mkdirSync(stagingDir, { recursive: true });
if (progressCallback) {
progressCallback(isDifferential ? 'Applying differential update...' : 'Installing game files...', null, null, null, null);
}
const args = [
'apply',
'--staging-dir',
stagingDir,
archivePath,
destinationDir
];
console.log(`Executing deployment: ${butlerPath} ${args.join(' ')}`);
return new Promise((resolve, reject) => {
const child = execFile(butlerPath, args, {
maxBuffer: 1024 * 1024 * 10,
timeout: 600000
}, (error, stdout, stderr) => {
if (error) {
const cleanStderr = stderr.replace(/[\u2714\u2716\u2713\u2717\u26A0\uD83D[\uDC00-\uDFFF]]/g, '').trim();
const cleanStdout = stdout.replace(/[\u2714\u2716\u2713\u2717\u26A0\uD83D[\uDC00-\uDFFF]]/g, '').trim();
if (cleanStderr) console.error('Deployment stderr:', cleanStderr);
if (cleanStdout) console.error('Deployment stdout:', cleanStdout);
const errorText = (stderr + ' ' + error.message).toLowerCase();
let message = 'Game deployment failed';
if (errorText.includes('unexpected eof')) {
message = 'Corrupted archive detected. Please retry download.';
if (fs.existsSync(archivePath)) {
fs.unlinkSync(archivePath);
}
} else if (errorText.includes('permission denied')) {
message = 'Permission denied. Check file permissions and try again.';
} else if (errorText.includes('no space left') || errorText.includes('device full')) {
message = 'Insufficient disk space. Free up space and try again.';
}
const deployError = new Error(message);
deployError.originalError = error;
deployError.stderr = cleanStderr;
deployError.stdout = cleanStdout;
return reject(deployError);
}
console.log('Game deployment completed successfully');
const cleanOutput = stdout.replace(/[\u2714\u2716\u2713\u2717\u26A0\uD83D[\uDC00-\uDFFF]]/g, '').trim();
if (cleanOutput) {
console.log(cleanOutput);
}
if (fs.existsSync(stagingDir)) {
try {
fs.rmSync(stagingDir, { recursive: true, force: true });
} catch (cleanupErr) {
console.warn('Failed to cleanup staging directory:', cleanupErr.message);
}
}
resolve();
});
child.on('error', (err) => {
console.error('Deployment process error:', err);
reject(new Error(`Failed to execute deployment tool: ${err.message}`));
});
});
}
async function performIntelligentUpdate(targetVersion, branch = 'release', progressCallback, gameDir = GAME_DIR, cacheDir = CACHE_DIR, toolsDir = TOOLS_DIR) {
console.log(`Initiating intelligent update to version ${targetVersion}`);
const currentVersion = getInstalledClientVersion();
console.log(`Current version: ${currentVersion || 'none (clean install)'}`);
console.log(`Target version: ${targetVersion}`);
console.log(`Branch: ${branch}`);
if (branch !== 'release') {
console.log(`Pre-release branch detected - forcing full archive download`);
const versionDetails = await extractVersionDetails(targetVersion, branch);
const archiveName = path.basename(versionDetails.fullUrl);
const archivePath = path.join(cacheDir, `${branch}_${archiveName}`);
if (progressCallback) {
progressCallback('Downloading full game archive (pre-release)...', 0, null, null, null);
}
await acquireGameArchive(versionDetails.fullUrl, archivePath, null, progressCallback);
await deployGameArchive(archivePath, gameDir, toolsDir, progressCallback, false);
saveVersionClient(targetVersion);
console.log(`Pre-release installation completed. Version ${targetVersion} is now installed.`);
return;
}
if (!currentVersion) {
console.log('No existing installation detected - downloading full archive');
const versionDetails = await extractVersionDetails(targetVersion, branch);
const archiveName = path.basename(versionDetails.fullUrl);
const archivePath = path.join(cacheDir, `${branch}_${archiveName}`);
if (progressCallback) {
progressCallback(`Downloading full game archive (first install - v${targetVersion})...`, 0, null, null, null);
}
await acquireGameArchive(versionDetails.fullUrl, archivePath, null, progressCallback);
await deployGameArchive(archivePath, gameDir, toolsDir, progressCallback, false);
saveVersionClient(targetVersion);
console.log(`Initial installation completed. Version ${targetVersion} is now installed.`);
return;
}
const patchesToApply = needsIntermediatePatches(currentVersion, targetVersion);
if (patchesToApply.length === 0) {
console.log('Already at target version or invalid version sequence');
return;
}
console.log(`Applying ${patchesToApply.length} differential patch(es): ${patchesToApply.join(' -> ')}`);
for (let i = 0; i < patchesToApply.length; i++) {
const patchVersion = patchesToApply[i];
const versionDetails = await extractVersionDetails(patchVersion, branch);
const canDifferential = canUseDifferentialUpdate(getInstalledClientVersion(), versionDetails);
if (!canDifferential || !versionDetails.differentialUrl) {
console.log(`WARNING: Differential patch not available for ${patchVersion}, using full archive`);
const archiveName = path.basename(versionDetails.fullUrl);
const archivePath = path.join(cacheDir, `${branch}_${archiveName}`);
if (progressCallback) {
progressCallback(`Downloading full archive for ${patchVersion} (${i + 1}/${patchesToApply.length})...`, 0, null, null, null);
}
await acquireGameArchive(versionDetails.fullUrl, archivePath, null, progressCallback);
await deployGameArchive(archivePath, gameDir, toolsDir, progressCallback, false);
} else {
console.log(`Applying differential patch: ${versionDetails.sourceVersion} -> ${patchVersion}`);
const archiveName = path.basename(versionDetails.differentialUrl);
const archivePath = path.join(cacheDir, `${branch}_patch_${archiveName}`);
if (progressCallback) {
progressCallback(`Applying patch ${i + 1}/${patchesToApply.length}: ${patchVersion}...`, 0, null, null, null);
}
await acquireGameArchive(versionDetails.differentialUrl, archivePath, versionDetails.checksum, progressCallback);
await deployGameArchive(archivePath, gameDir, toolsDir, progressCallback, true);
if (fs.existsSync(archivePath)) {
try {
fs.unlinkSync(archivePath);
console.log(`Cleaned up patch file: ${archiveName}`);
} catch (cleanupErr) {
console.warn(`Failed to cleanup patch file: ${cleanupErr.message}`);
}
}
}
saveVersionClient(patchVersion);
console.log(`Patch ${patchVersion} applied successfully (${i + 1}/${patchesToApply.length})`);
}
console.log(`Update completed successfully. Version ${targetVersion} is now installed.`);
}
async function ensureGameInstalled(targetVersion, branch = 'release', progressCallback, gameDir = GAME_DIR, cacheDir = CACHE_DIR, toolsDir = TOOLS_DIR) {
const { findClientPath } = require('../core/paths');
const clientPath = findClientPath(gameDir);
if (clientPath) {
const currentVersion = getInstalledClientVersion();
if (currentVersion === targetVersion) {
console.log(`Game already installed at correct version: ${targetVersion}`);
return;
}
}
await performIntelligentUpdate(targetVersion, branch, progressCallback, gameDir, cacheDir, toolsDir);
}
module.exports = {
acquireGameArchive,
deployGameArchive,
performIntelligentUpdate,
ensureGameInstalled
};

View File

@@ -10,8 +10,11 @@ const { setupWaylandEnvironment, setupGpuEnvironment } = require('../utils/platf
const { saveUsername, saveInstallPath, loadJavaPath, getUuidForUser, getAuthServerUrl, getAuthDomain, loadVersionBranch, loadVersionClient, saveVersionClient } = require('../core/config');
const { resolveJavaPath, getJavaExec, getBundledJavaPath, detectSystemJava, JAVA_EXECUTABLE } = require('./javaManager');
const { getLatestClientVersion } = require('../services/versionManager');
const { updateGameFiles } = require('./gameManager');
const { FORCE_CLEAN_INSTALL_VERSION, CLEAN_INSTALL_TEST_VERSION } = require('../core/testConfig');
const { ensureGameInstalled } = require('./differentialUpdateManager');
const { syncModsForCurrentProfile } = require('./modManager');
const { getUserDataPath } = require('../utils/userDataMigration');
const { syncServerList } = require('../utils/serverListSync');
// Client patcher for custom auth server (sanasol.ws)
let clientPatcher = null;
@@ -102,11 +105,21 @@ function generateLocalTokens(uuid, name) {
}
async function launchGame(playerName = 'Player', progressCallback, javaPathOverride, installPathOverride, gpuPreference = 'auto', branchOverride = null) {
// Synchronize server list on every game launch
try {
console.log('[Launcher] Synchronizing server list...');
await syncServerList();
} catch (syncError) {
console.warn('[Launcher] Server list sync failed, continuing launch:', syncError.message);
}
const branch = branchOverride || loadVersionBranch();
const customAppDir = getResolvedAppDir(installPathOverride);
const customGameDir = path.join(customAppDir, branch, 'package', 'game', 'latest');
const customJreDir = path.join(customAppDir, branch, 'package', 'jre', 'latest');
const userDataDir = path.join(customGameDir, 'Client', 'UserData');
// NEW 2.2.0: Use centralized UserData location
const userDataDir = getUserDataPath();
const gameLatest = customGameDir;
let clientPath = findClientPath(gameLatest);
@@ -166,7 +179,7 @@ async function launchGame(playerName = 'Player', progressCallback, javaPathOverr
if (progressCallback && msg) {
progressCallback(msg, percent, null, null, null);
}
});
}, null, branch);
if (patchResult.success) {
console.log(`Game patched successfully (${patchResult.patchCount} total occurrences)`);
@@ -282,6 +295,55 @@ exec "$REAL_JAVA" "\${ARGS[@]}"
const gpuEnv = setupGpuEnvironment(gpuPreference);
Object.assign(env, gpuEnv);
// Linux: Replace bundled libzstd.so with system version to fix glibc 2.41+ crash
// The bundled libzstd causes "free(): invalid pointer" on Steam Deck / Ubuntu LTS
if (process.platform === 'linux' && process.env.HYTALE_NO_LIBZSTD_FIX !== '1') {
const clientDir = path.dirname(clientPath);
const bundledLibzstd = path.join(clientDir, 'libzstd.so');
const backupLibzstd = path.join(clientDir, 'libzstd.so.bundled');
// Common system libzstd paths
const systemLibzstdPaths = [
'/usr/lib/libzstd.so.1', // Arch Linux, Steam Deck
'/usr/lib/x86_64-linux-gnu/libzstd.so.1', // Debian/Ubuntu
'/usr/lib64/libzstd.so.1' // Fedora/RHEL
];
let systemLibzstd = null;
for (const p of systemLibzstdPaths) {
if (fs.existsSync(p)) {
systemLibzstd = p;
break;
}
}
if (systemLibzstd && fs.existsSync(bundledLibzstd)) {
try {
const stats = fs.lstatSync(bundledLibzstd);
// Only replace if it's not already a symlink to system version
if (!stats.isSymbolicLink()) {
// Backup bundled version
if (!fs.existsSync(backupLibzstd)) {
fs.renameSync(bundledLibzstd, backupLibzstd);
console.log(`Linux: Backed up bundled libzstd.so`);
} else {
fs.unlinkSync(bundledLibzstd);
}
// Create symlink to system version
fs.symlinkSync(systemLibzstd, bundledLibzstd);
console.log(`Linux: Linked libzstd.so to system version (${systemLibzstd}) for glibc 2.41+ compatibility`);
} else {
const linkTarget = fs.readlinkSync(bundledLibzstd);
console.log(`Linux: libzstd.so already linked to ${linkTarget}`);
}
} catch (libzstdError) {
console.warn(`Linux: Could not replace libzstd.so: ${libzstdError.message}`);
}
}
}
try {
let spawnOptions = {
stdio: ['ignore', 'pipe', 'pipe'],
@@ -385,7 +447,13 @@ async function launchGameWithVersionCheck(playerName = 'Player', progressCallbac
const customCacheDir = path.join(customAppDir, 'cache');
try {
await updateGameFiles(latestVersion, progressCallback, customGameDir, customToolsDir, customCacheDir, branch);
let versionToInstall = latestVersion;
if (FORCE_CLEAN_INSTALL_VERSION && !installedVersion) {
versionToInstall = CLEAN_INSTALL_TEST_VERSION;
console.log(`TESTING MODE: Clean install detected, forcing version ${versionToInstall} instead of ${latestVersion}`);
}
await ensureGameInstalled(versionToInstall, branch, progressCallback, customGameDir, customCacheDir, customToolsDir);
console.log('Game updated successfully, patching will be forced on launch...');
if (progressCallback) {

View File

@@ -5,13 +5,14 @@ const { getResolvedAppDir, findClientPath, findUserDataPath, findUserDataRecursi
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 userDataBackup = require('../utils/userDataBackup');
const { getUserDataPath, migrateUserDataToCentralized } = require('../utils/userDataMigration');
async function downloadPWR(branch = 'release', fileName = '4.pwr', progressCallback, cacheDir = CACHE_DIR, manualRetry = false) {
async function downloadPWR(branch = 'release', fileName = '7.pwr', progressCallback, cacheDir = CACHE_DIR, manualRetry = false) {
const osName = getOS();
const arch = getArch();
@@ -300,6 +301,16 @@ async function applyPWR(pwrFile, progressCallback, gameDir = GAME_DIR, toolsDir
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);
}
@@ -308,31 +319,25 @@ async function applyPWR(pwrFile, progressCallback, gameDir = GAME_DIR, toolsDir
async function updateGameFiles(newVersion, progressCallback, gameDir = GAME_DIR, toolsDir = TOOLS_DIR, cacheDir = CACHE_DIR, branchOverride = null) {
let tempUpdateDir;
let backupPath = null;
const branch = branchOverride || loadVersionBranch();
const installPath = path.dirname(path.dirname(path.dirname(path.dirname(gameDir))));
// Vérifier si on a version_client et version_branch dans config.json
const config = loadConfig();
const hasVersionConfig = !!(config.version_client && config.version_branch);
const oldBranch = config.version_branch || 'release'; // L'ancienne branche pour le backup
console.log(`[UpdateGameFiles] hasVersionConfig: ${hasVersionConfig}`);
const oldBranch = config.version_branch || 'release';
console.log(`[UpdateGameFiles] Switching from ${oldBranch} to ${branch}`);
try {
if (progressCallback) {
progressCallback('Backing up user data...', 5, null, null, null);
}
// Backup UserData AVANT de télécharger/installer (critical for same-branch updates)
// NEW 2.2.0: Ensure UserData migration to centralized location
try {
console.log(`[UpdateGameFiles] Attempting to backup UserData from old branch: ${oldBranch}`);
backupPath = await userDataBackup.backupUserData(installPath, oldBranch, hasVersionConfig);
if (backupPath) {
console.log(`[UpdateGameFiles] ✓ UserData backed up from ${oldBranch}: ${backupPath}`);
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 (backupError) {
console.warn('[UpdateGameFiles] UserData backup failed:', backupError.message);
} catch (migrationError) {
console.warn('[UpdateGameFiles] UserData migration warning:', migrationError.message);
}
if (progressCallback) {
@@ -358,7 +363,15 @@ async function updateGameFiles(newVersion, progressCallback, gameDir = GAME_DIR,
}
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);
}
@@ -390,31 +403,9 @@ async function updateGameFiles(newVersion, progressCallback, gameDir = GAME_DIR,
const logoResult = await downloadAndReplaceLogo(gameDir, progressCallback);
console.log('Logo@2x.png update result after update:', logoResult);
// Ensure UserData directory exists
const userDataDir = path.join(gameDir, 'Client', 'UserData');
if (!fs.existsSync(userDataDir)) {
console.log(`[UpdateGameFiles] Creating UserData directory at: ${userDataDir}`);
fs.mkdirSync(userDataDir, { recursive: true });
}
if (progressCallback) {
progressCallback('Restoring user data...', 90, null, null, null);
}
// Restore UserData using new system
if (backupPath) {
try {
console.log(`[UpdateGameFiles] Restoring UserData from ${oldBranch} to ${branch}`);
console.log(`[UpdateGameFiles] Source backup: ${backupPath}`);
await userDataBackup.restoreUserData(backupPath, installPath, branch);
await userDataBackup.cleanupBackup(backupPath);
console.log(`[UpdateGameFiles] ✓ UserData migrated successfully from ${oldBranch} to ${branch}`);
} catch (restoreError) {
console.warn('[UpdateGameFiles] ✗ UserData restore failed:', restoreError.message);
}
} else {
console.log('[UpdateGameFiles] No backup to restore, empty UserData folder created');
}
// 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}`);
@@ -434,15 +425,6 @@ async function updateGameFiles(newVersion, progressCallback, gameDir = GAME_DIR,
} catch (error) {
console.error('Error updating game files:', error);
if (backupPath) {
try {
await userDataBackup.cleanupBackup(backupPath);
console.log('UserData backup cleaned up after error');
} catch (cleanupError) {
console.warn('Could not clean up UserData backup:', cleanupError.message);
}
}
if (tempUpdateDir && fs.existsSync(tempUpdateDir)) {
fs.rmSync(tempUpdateDir, { recursive: true, force: true });
}
@@ -470,28 +452,18 @@ async function installGame(playerName = 'Player', progressCallback, javaPathOver
const customToolsDir = path.join(customAppDir, 'butler');
const customGameDir = path.join(customAppDir, branch, 'package', 'game', 'latest');
const customJreDir = path.join(customAppDir, branch, 'package', 'jre', 'latest');
const userDataDir = path.join(customGameDir, 'Client', 'UserData');
// 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(`[InstallGame] Configuration detected - version_client: ${config.version_client}, version_branch: ${config.version_branch}`);
console.log(`[InstallGame] hasVersionConfig: ${hasVersionConfig}`);
// Backup UserData AVANT l'installation si nécessaire
let backupPath = null;
if (progressCallback) {
progressCallback('Checking for existing UserData...', 5, null, null, null);
}
// NEW 2.2.0: Ensure UserData migration to centralized location
try {
console.log(`[InstallGame] Attempting UserData backup (hasVersionConfig: ${hasVersionConfig})...`);
backupPath = await userDataBackup.backupUserData(customAppDir, branch, hasVersionConfig);
if (backupPath) {
console.log(`[InstallGame] ✓ UserData backed up to: ${backupPath}`);
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 (backupError) {
console.warn('[InstallGame] UserData backup failed:', backupError.message);
} catch (migrationError) {
console.warn('[InstallGame] UserData migration warning:', migrationError.message);
}
[customAppDir, customCacheDir, customToolsDir].forEach(dir => {
@@ -500,10 +472,6 @@ async function installGame(playerName = 'Player', progressCallback, javaPathOver
}
});
if (!fs.existsSync(userDataDir)) {
fs.mkdirSync(userDataDir, { recursive: true });
}
saveUsername(playerName);
if (installPathOverride) {
saveInstallPath(installPathOverride);
@@ -561,31 +529,33 @@ async function installGame(playerName = 'Player', progressCallback, javaPathOver
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, latestVersion, progressCallback, customCacheDir);
pwrFile = await downloadPWR(branch, targetVersion, progressCallback, customCacheDir);
// If downloadPWR returns false, it means the file doesn't exist or is invalid
// We should retry the download with a manual retry flag
if (!pwrFile) {
console.log('[Install] PWR file not found or invalid, attempting retry...');
pwrFile = await retryPWRDownload(branch, latestVersion, progressCallback, customCacheDir);
pwrFile = await retryPWRDownload(branch, targetVersion, progressCallback, customCacheDir);
}
// Double-check we have a valid file path
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; // Re-throw to be handled by the main installGame error handler
throw downloadError;
}
await applyPWR(pwrFile, progressCallback, customGameDir, customToolsDir, branch, customCacheDir);
// Save the installed version and branch to config
saveVersionClient(latestVersion);
saveVersionClient(targetVersion);
const { saveVersionBranch } = require('../core/config');
saveVersionBranch(branch);
@@ -595,29 +565,9 @@ async function installGame(playerName = 'Player', progressCallback, javaPathOver
const logoResult = await downloadAndReplaceLogo(customGameDir, progressCallback);
console.log('Logo@2x.png update result after installation:', logoResult);
// Ensure UserData directory exists
if (!fs.existsSync(userDataDir)) {
console.log(`[InstallGame] Creating UserData directory at: ${userDataDir}`);
fs.mkdirSync(userDataDir, { recursive: true });
}
// Restore UserData from backup if exists
if (backupPath) {
if (progressCallback) {
progressCallback('Restoring UserData...', 95, null, null, null);
}
try {
console.log(`[InstallGame] Restoring UserData from: ${backupPath}`);
await userDataBackup.restoreUserData(backupPath, customAppDir, branch);
await userDataBackup.cleanupBackup(backupPath);
console.log('[InstallGame] ✓ UserData restored successfully');
} catch (restoreError) {
console.warn('[InstallGame] ✗ UserData restore failed:', restoreError.message);
}
} else {
console.log('[InstallGame] No backup to restore, empty UserData folder created');
}
// 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);

View File

@@ -3,7 +3,7 @@ const path = require('path');
const crypto = require('crypto');
const axios = require('axios');
const { getOS } = require('../utils/platformUtils');
const { getModsPath, getProfilesDir } = require('../core/paths');
const { getModsPath, getProfilesDir, getHytaleSavesDir } = require('../core/paths');
const { saveModsToConfig, loadModsFromConfig } = require('../core/config');
const profileManager = require('./profileManager');
@@ -296,8 +296,9 @@ async function syncModsForCurrentProfile() {
console.log(`[ModManager] Syncing mods for profile: ${activeProfile.name} (${activeProfile.id})`);
// 1. Resolve Paths
// globalModsPath is the one the game uses (symlink target)
const globalModsPath = await getModsPath();
// centralModsPath is HytaleSaves\Mods (centralized location for active mods)
const hytaleSavesDir = getHytaleSavesDir();
const centralModsPath = path.join(hytaleSavesDir, 'Mods');
// profileModsPath is the real storage for this profile
const profileModsPath = getProfileModsPath(activeProfile.id);
const profileDisabledModsPath = path.join(path.dirname(profileModsPath), 'DisabledMods');
@@ -306,96 +307,51 @@ async function syncModsForCurrentProfile() {
fs.mkdirSync(profileDisabledModsPath, { recursive: true });
}
// 2. Symlink / Migration Logic
let needsLink = false;
let globalStats = null;
// 2. Copy-based Mod Sync (No symlinks - avoids permission issues)
// Ensure HytaleSaves\Mods directory exists
if (!fs.existsSync(centralModsPath)) {
fs.mkdirSync(centralModsPath, { recursive: true });
console.log(`[ModManager] Created centralized mods directory: ${centralModsPath}`);
}
// Check for old symlink and convert to real directory if needed (one-time migration)
try {
globalStats = fs.lstatSync(globalModsPath);
const centralStats = fs.lstatSync(centralModsPath);
if (centralStats.isSymbolicLink()) {
console.log('[ModManager] Removing old symlink, converting to copy-based system...');
fs.unlinkSync(centralModsPath);
fs.mkdirSync(centralModsPath, { recursive: true });
}
} catch (e) {
// Path doesn't exist
// Path doesn't exist, will be created above
}
if (globalStats) {
if (globalStats.isSymbolicLink()) {
const linkTarget = fs.readlinkSync(globalModsPath);
// Normalize paths for comparison
if (path.resolve(linkTarget) !== path.resolve(profileModsPath)) {
console.log(`[ModManager] Updating symlink from ${linkTarget} to ${profileModsPath}`);
fs.unlinkSync(globalModsPath);
needsLink = true;
}
} else if (globalStats.isDirectory()) {
// MIGRATION: It's a real directory. Move contents to profile.
console.log('[ModManager] Migrating global mods folder to profile folder...');
const files = fs.readdirSync(globalModsPath);
for (const file of files) {
const src = path.join(globalModsPath, file);
const dest = path.join(profileModsPath, file);
// Only move if dest doesn't exist to avoid overwriting
if (!fs.existsSync(dest)) {
fs.renameSync(src, dest);
}
}
// Also migrate DisabledMods if it exists globally
const globalDisabledPath = path.join(path.dirname(globalModsPath), 'DisabledMods');
if (fs.existsSync(globalDisabledPath) && fs.lstatSync(globalDisabledPath).isDirectory()) {
const dFiles = fs.readdirSync(globalDisabledPath);
for (const file of dFiles) {
const src = path.join(globalDisabledPath, file);
const dest = path.join(profileDisabledModsPath, file);
if (!fs.existsSync(dest)) {
fs.renameSync(src, dest);
}
}
// We can remove global DisabledMods now, as it's not used by game
try { fs.rmSync(globalDisabledPath, { recursive: true, force: true }); } catch(e) {}
}
// Remove the directory so we can link it
try {
let retries = 3;
while (retries > 0) {
try {
fs.rmSync(globalModsPath, { recursive: true, force: true });
break;
} catch (err) {
if ((err.code === 'EPERM' || err.code === 'EBUSY') && retries > 0) {
retries--;
await new Promise(resolve => setTimeout(resolve, 500));
} else {
throw err;
}
}
}
needsLink = true;
} catch (e) {
console.error('Failed to remove global mods dir:', e);
// Throw error to stop.
throw new Error('Failed to migrate mods directory. Please clear ' + globalModsPath);
}
}
} else {
needsLink = true;
}
if (needsLink) {
console.log(`[ModManager] Creating symlink: ${globalModsPath} -> ${profileModsPath}`);
// Copy enabled mods from profile to HytaleSaves\Mods (for game to use)
console.log(`[ModManager] Copying enabled mods from ${profileModsPath} to ${centralModsPath}`);
// First, clear central mods folder
const existingCentralMods = fs.existsSync(centralModsPath) ? fs.readdirSync(centralModsPath) : [];
for (const file of existingCentralMods) {
const filePath = path.join(centralModsPath, file);
try {
const symlinkType = getOS() === 'windows' ? 'junction' : 'dir';
fs.symlinkSync(profileModsPath, globalModsPath, symlinkType);
} catch (err) {
// If we can't create the symlink, try creating the directory first
console.error('[ModManager] Failed to create symlink. Falling back to direct folder mode.');
console.error(err.message);
// Fallback: create a real directory so the game still works
if (!fs.existsSync(globalModsPath)) {
fs.mkdirSync(globalModsPath, { recursive: true });
fs.unlinkSync(filePath);
} catch (e) {
console.warn(`Failed to remove ${file} from central mods:`, e.message);
}
}
// Copy enabled mods to HytaleSaves\Mods
const enabledModFiles = fs.existsSync(profileModsPath) ? fs.readdirSync(profileModsPath).filter(f => f.endsWith('.jar') || f.endsWith('.zip')) : [];
for (const file of enabledModFiles) {
const src = path.join(profileModsPath, file);
const dest = path.join(centralModsPath, file);
try {
fs.copyFileSync(src, dest);
console.log(`[ModManager] Copied ${file} to HytaleSaves\\Mods`);
} catch (e) {
console.error(`Failed to copy ${file}:`, e.message);
}
}
}
// 3. Auto-Repair (Download missing mods)
const profileModsSnapshot = activeProfile.mods || [];
@@ -460,7 +416,7 @@ async function syncModsForCurrentProfile() {
}
// 5. Enforce Enabled/Disabled State (Move files between Profile/Mods and Profile/DisabledMods)
// Note: Since Global/Mods IS Profile/Mods (via symlink), moving out of Profile/Mods disables it for the game.
// Note: Enabled mods are copied to HytaleSaves\Mods, disabled mods stay in Profile/DisabledMods
const disabledFiles = fs.existsSync(profileDisabledModsPath) ? fs.readdirSync(profileDisabledModsPath).filter(f => f.endsWith('.jar') || f.endsWith('.zip')) : [];
const allFiles = new Set([...enabledFiles, ...disabledFiles]);

View File

@@ -1,11 +1,17 @@
const axios = require('axios');
const crypto = require('crypto');
const fs = require('fs');
const { getOS, getArch } = require('../utils/platformUtils');
const BASE_PATCH_URL = 'https://game-patches.hytale.com/patches';
const MANIFEST_API = 'https://files.hytalef2p.com/api/patch_manifest';
async function getLatestClientVersion(branch = 'release') {
try {
console.log(`Fetching latest client version from API (branch: ${branch})...`);
const response = await axios.get('https://files.hytalef2p.com/api/version_client', {
params: { branch },
timeout: 5000,
timeout: 40000,
headers: {
'User-Agent': 'Hytale-F2P-Launcher'
}
@@ -16,16 +22,144 @@ async function getLatestClientVersion(branch = 'release') {
console.log(`Latest client version for ${branch}: ${version}`);
return version;
} else {
console.log('Warning: Invalid API response, falling back to default version');
return '4.pwr';
console.log('Warning: Invalid API response, falling back to latest known version (7.pwr)');
return '7.pwr';
}
} catch (error) {
console.error('Error fetching client version:', error.message);
console.log('Warning: API unavailable, falling back to default version');
return '4.pwr';
console.log('Warning: API unavailable, falling back to latest known version (7.pwr)');
return '7.pwr';
}
}
function buildArchiveUrl(buildNumber, branch = 'release') {
const os = getOS();
const arch = getArch();
return `${BASE_PATCH_URL}/${os}/${arch}/${branch}/0/${buildNumber}.pwr`;
}
async function checkArchiveExists(buildNumber, branch = 'release') {
const url = buildArchiveUrl(buildNumber, branch);
try {
const response = await axios.head(url, { timeout: 10000 });
return response.status === 200;
} catch (error) {
return false;
}
}
async function discoverAvailableVersions(latestKnown, branch = 'release', maxProbe = 50) {
const available = [];
const latest = parseInt(latestKnown.replace('.pwr', ''));
for (let i = latest; i >= Math.max(1, latest - maxProbe); i--) {
const exists = await checkArchiveExists(i, branch);
if (exists) {
available.push(`${i}.pwr`);
}
}
return available;
}
async function fetchPatchManifest(branch = 'release') {
try {
const os = getOS();
const arch = getArch();
const response = await axios.get(MANIFEST_API, {
params: { branch, os, arch },
timeout: 10000
});
return response.data.patches || {};
} catch (error) {
console.error('Failed to fetch patch manifest:', error.message);
return {};
}
}
async function extractVersionDetails(targetVersion, branch = 'release') {
const buildNumber = parseInt(targetVersion.replace('.pwr', ''));
const previousBuild = buildNumber - 1;
const manifest = await fetchPatchManifest(branch);
const patchInfo = manifest[buildNumber];
return {
version: targetVersion,
buildNumber: buildNumber,
buildName: `HYTALE-Build-${buildNumber}`,
fullUrl: patchInfo?.original_url || buildArchiveUrl(buildNumber, branch),
differentialUrl: patchInfo?.patch_url || null,
checksum: patchInfo?.patch_hash || null,
sourceVersion: patchInfo?.from ? `${patchInfo.from}.pwr` : (previousBuild > 0 ? `${previousBuild}.pwr` : null),
isDifferential: !!patchInfo?.proper_patch,
releaseNotes: patchInfo?.patch_note || null
};
}
function canUseDifferentialUpdate(currentVersion, targetDetails) {
if (!targetDetails) return false;
if (!targetDetails.differentialUrl) return false;
if (!targetDetails.isDifferential) return false;
if (!currentVersion) return false;
const currentBuild = parseInt(currentVersion.replace('.pwr', ''));
const expectedSource = parseInt(targetDetails.sourceVersion?.replace('.pwr', '') || '0');
return currentBuild === expectedSource;
}
function needsIntermediatePatches(currentVersion, targetVersion) {
if (!currentVersion) return [];
const current = parseInt(currentVersion.replace('.pwr', ''));
const target = parseInt(targetVersion.replace('.pwr', ''));
const intermediates = [];
for (let i = current + 1; i <= target; i++) {
intermediates.push(`${i}.pwr`);
}
return intermediates;
}
async function computeFileChecksum(filePath) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(filePath);
stream.on('data', data => hash.update(data));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
async function validateChecksum(filePath, expectedChecksum) {
if (!expectedChecksum) return true;
const actualChecksum = await computeFileChecksum(filePath);
return actualChecksum === expectedChecksum;
}
function getInstalledClientVersion() {
try {
const { loadVersionClient } = require('../core/config');
return loadVersionClient();
} catch (err) {
return null;
}
}
module.exports = {
getLatestClientVersion
getLatestClientVersion,
buildArchiveUrl,
checkArchiveExists,
discoverAvailableVersions,
extractVersionDetails,
canUseDifferentialUpdate,
needsIntermediatePatches,
computeFileChecksum,
validateChecksum,
getInstalledClientVersion
};

File diff suppressed because it is too large Load Diff

View File

@@ -18,11 +18,16 @@ function isWaylandSession() {
}
const sessionType = process.env.XDG_SESSION_TYPE;
const waylandDisplay = process.env.WAYLAND_DISPLAY;
// Debug logging
console.log(`[PlatformUtils] Checking Wayland: XDG_SESSION_TYPE=${sessionType}, WAYLAND_DISPLAY=${waylandDisplay}`);
if (sessionType && sessionType.toLowerCase() === 'wayland') {
return true;
}
if (process.env.WAYLAND_DISPLAY) {
if (waylandDisplay) {
return true;
}
@@ -44,19 +49,48 @@ function setupWaylandEnvironment() {
if (process.platform !== 'linux') {
return {};
}
// If the user has manually set SDL_VIDEODRIVER (e.g. to 'x11'), strictly respect it.
if (process.env.SDL_VIDEODRIVER) {
console.log(`User manually set SDL_VIDEODRIVER=${process.env.SDL_VIDEODRIVER}, ignoring internal Wayland configuration.`);
return {};
}
if (!isWaylandSession()) {
console.log('Detected X11 session, using default environment');
return {};
}
console.log('Detected Wayland session, configuring environment...');
console.log('Detected Wayland session, checking for Gamescope/Steam Deck...');
const envVars = {
SDL_VIDEODRIVER: 'wayland'
};
const envVars = {};
// Only set Ozone hint if not already set by user
if (!process.env.ELECTRON_OZONE_PLATFORM_HINT) {
envVars.ELECTRON_OZONE_PLATFORM_HINT = 'wayland';
}
// 2. DETECT GAMESCOPE / STEAM DECK
// Native Wayland often fails for SDL games in Gaming Mode (gamescope), so we force X11 (XWayland).
// Checks:
// - XDG_CURRENT_DESKTOP == 'gamescope'
// - SteamDeck=1 (often set in SteamOS)
const currentDesktop = process.env.XDG_CURRENT_DESKTOP || '';
const isGamescope = currentDesktop.toLowerCase() === 'gamescope' || process.env.SteamDeck === '1';
envVars.ELECTRON_OZONE_PLATFORM_HINT = 'wayland';
if (isGamescope) {
console.log('Gamescope / Steam Deck detected, forcing SDL_VIDEODRIVER=x11 for compatibility');
envVars.SDL_VIDEODRIVER = 'x11';
} else {
// For standard desktop Wayland (GNOME, KDE), we leave SDL_VIDEODRIVER unset.
// This allows SDL3/SDL2 to use its internal preference (Wayland > X11).
// EXCEPT if it was somehow force-set to 'wayland' by the parent process (rare but possible),
// we strictly want to allow fallback, so we might unset it if it was 'wayland'.
// But since we checked process.env.SDL_VIDEODRIVER at the start, we know it's NOT set manually.
// So we effectively do nothing for standard Wayland, letting SDL decide.
console.log('Standard Wayland session detected, letting SDL decide backend (auto-fallback enabled).');
}
console.log('Wayland environment variables:', envVars);
return envVars;

View File

@@ -0,0 +1,120 @@
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');
const { getHytaleSavesDir } = require('../core/paths');
const SERVER_LIST_URL = 'https://assets.authbp.xyz/server.json';
function getLocalDateTime() {
return formatLocalDateTime(new Date());
}
function formatLocalDateTime(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
const offsetMinutes = -date.getTimezoneOffset();
const offsetHours = Math.floor(Math.abs(offsetMinutes) / 60);
const offsetMins = Math.abs(offsetMinutes) % 60;
const offsetSign = offsetMinutes >= 0 ? '+' : '-';
const offset = `${offsetSign}${String(offsetHours).padStart(2, '0')}:${String(offsetMins).padStart(2, '0')}`;
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}0000${offset}`;
}
async function syncServerList() {
try {
const hytaleSavesDir = getHytaleSavesDir();
const serverListPath = path.join(hytaleSavesDir, 'ServerList.json');
console.log('[ServerListSync] Fetching server list from', SERVER_LIST_URL);
let remoteData;
try {
const response = await axios.get(SERVER_LIST_URL, {
timeout: 40000,
headers: {
'User-Agent': 'Hytale-F2P-Launcher'
}
});
remoteData = response.data;
} catch (fetchError) {
console.warn('[ServerListSync] Failed to fetch remote server list:', fetchError.message);
remoteData = { SavedServers: [] };
}
let localData = { SavedServers: [] };
if (fs.existsSync(serverListPath)) {
try {
const localContent = fs.readFileSync(serverListPath, 'utf-8');
localData = JSON.parse(localContent);
console.log('[ServerListSync] Loaded existing local server list with', localData.SavedServers?.length || 0, 'servers');
} catch (parseError) {
console.warn('[ServerListSync] Failed to parse local server list, creating new one:', parseError.message);
localData = { SavedServers: [] };
}
} else {
console.log('[ServerListSync] Local server list does not exist, creating new one');
}
if (!localData.SavedServers) {
localData.SavedServers = [];
}
if (!remoteData.SavedServers) {
remoteData.SavedServers = [];
}
const existingServersByAddress = new Map();
const userServers = [];
for (const server of localData.SavedServers) {
existingServersByAddress.set(server.Address.toLowerCase(), server);
}
const remoteAddresses = new Set(remoteData.SavedServers.map(s => s.Address.toLowerCase()));
for (const server of localData.SavedServers) {
if (!remoteAddresses.has(server.Address.toLowerCase())) {
userServers.push(server);
}
}
const currentDate = getLocalDateTime();
const apiServers = [];
for (const remoteServer of remoteData.SavedServers) {
const serverToAdd = {
Id: uuidv4(),
Name: "@ " + remoteServer.Name,
Address: remoteServer.Address,
DateSaved: currentDate,
img_Banner: remoteServer.img_Banner || null // Copy banner if exists
};
apiServers.push(serverToAdd);
console.log('[ServerListSync] Added/Updated server with new ID:', remoteServer.Name);
}
localData.SavedServers = [...apiServers, ...userServers];
const addedCount = apiServers.length;
if (!fs.existsSync(hytaleSavesDir)) {
fs.mkdirSync(hytaleSavesDir, { recursive: true });
}
fs.writeFileSync(serverListPath, JSON.stringify(localData, null, 2), 'utf-8');
console.log('[ServerListSync] Server list synchronized:', addedCount, 'API servers added, total:', localData.SavedServers.length);
return { success: true, added: addedCount, total: localData.SavedServers.length };
} catch (error) {
console.error('[ServerListSync] Failed to synchronize server list:', error.message);
return { success: false, error: error.message };
}
}
module.exports = {
syncServerList
};

View File

@@ -46,7 +46,8 @@ class UserDataBackup {
console.log(`[UserDataBackup] Copying from ${userDataPath} to ${backupPath}...`);
await fs.copy(userDataPath, backupPath, {
overwrite: true,
errorOnExist: false
errorOnExist: false,
dereference: true // Follow symlinks to avoid EPERM errors on Windows
});
console.log('[UserDataBackup] ✓ Backup completed successfully');
return backupPath;
@@ -82,7 +83,8 @@ class UserDataBackup {
await fs.copy(backupPath, userDataPath, {
overwrite: true,
errorOnExist: false
errorOnExist: false,
dereference: true // Follow symlinks to avoid EPERM errors on Windows
});
console.log('UserData restore completed successfully');

View File

@@ -0,0 +1,172 @@
const fs = require('fs-extra');
const path = require('path');
const { getHytaleSavesDir, getResolvedAppDir } = require('../core/paths');
const { loadConfig, saveConfig } = require('../core/config');
/**
* NEW SYSTEM (2.2.0+): UserData Migration to Centralized Location
*
* UserData is now stored in a centralized location instead of inside game installation:
* - Windows: %LOCALAPPDATA%\HytaleSaves\
* - macOS: ~/Library/Application Support/HytaleSaves/
* - Linux: ~/.hytalesaves/
*
* This eliminates the need for backup/restore during updates.
*/
/**
* Check if migration to centralized UserData has been completed
*/
function isMigrationCompleted() {
const config = loadConfig();
return config.userDataMigrated === true;
}
/**
* Mark migration as completed
*/
function markMigrationCompleted() {
saveConfig({ userDataMigrated: true });
console.log('[UserDataMigration] Migration marked as completed in config');
}
/**
* Find old UserData location (pre-2.2.0)
* Searches in: installPath/branch/package/game/latest/Client/UserData
*/
function findOldUserDataPath() {
try {
const config = loadConfig();
const installPath = getResolvedAppDir();
const branch = config.version_branch || 'release';
console.log(`[UserDataMigration] Looking for old UserData...`);
console.log(`[UserDataMigration] Install path: ${installPath}`);
console.log(`[UserDataMigration] Branch: ${branch}`);
// Old location
const oldPath = path.join(installPath, branch, 'package', 'game', 'latest', 'Client', 'UserData');
console.log(`[UserDataMigration] Checking: ${oldPath}`);
console.log(`[UserDataMigration] Checking: ${oldPath}`);
if (fs.existsSync(oldPath)) {
console.log(`[UserDataMigration] ✓ Found old UserData at: ${oldPath}`);
return oldPath;
}
console.log(`[UserDataMigration] ✗ Not found at current branch location`);
// Try other branch if current doesn't exist
const otherBranch = branch === 'release' ? 'pre-release' : 'release';
const otherPath = path.join(installPath, otherBranch, 'package', 'game', 'latest', 'Client', 'UserData');
console.log(`[UserDataMigration] Checking other branch: ${otherPath}`);
console.log(`[UserDataMigration] Checking other branch: ${otherPath}`);
if (fs.existsSync(otherPath)) {
console.log(`[UserDataMigration] ✓ Found old UserData in other branch at: ${otherPath}`);
return otherPath;
}
console.log('[UserDataMigration] ✗ No old UserData found in any branch');
return null;
} catch (error) {
console.error('[UserDataMigration] Error finding old UserData:', error);
return null;
}
}
/**
* Migrate UserData from old location to new centralized location
* One-time operation when upgrading to 2.2.0
*/
async function migrateUserDataToCentralized() {
// Check if already migrated
if (isMigrationCompleted()) {
console.log('[UserDataMigration] Migration already completed, skipping');
return { success: true, alreadyMigrated: true };
}
console.log('[UserDataMigration] === Starting UserData Migration to Centralized Location ===');
const newUserDataPath = getHytaleSavesDir();
console.log(`[UserDataMigration] Target location: ${newUserDataPath}`);
// Ensure new directory exists
if (!fs.existsSync(newUserDataPath)) {
fs.mkdirSync(newUserDataPath, { recursive: true });
console.log('[UserDataMigration] Created new HytaleSaves directory');
}
// Find old UserData
const oldUserDataPath = findOldUserDataPath();
if (!oldUserDataPath) {
console.log('[UserDataMigration] No old UserData found - fresh install or already migrated');
// Don't mark as migrated - let it check again next time in case game gets installed later
return { success: true, freshInstall: true };
}
// Check if new location already has data (shouldn't happen, but safety check)
const existingFiles = fs.readdirSync(newUserDataPath);
if (existingFiles.length > 0) {
console.warn('[UserDataMigration] New location already contains files, marking as migrated to avoid re-attempts');
markMigrationCompleted();
return { success: true, skipped: true, reason: 'target_not_empty' };
}
try {
console.log(`[UserDataMigration] Copying from ${oldUserDataPath} to ${newUserDataPath}...`);
// Copy all UserData to new location
await fs.copy(oldUserDataPath, newUserDataPath, {
overwrite: false,
errorOnExist: false,
dereference: true // Follow symlinks to avoid EPERM errors on Windows
});
console.log('[UserDataMigration] ✓ UserData copied successfully');
// Mark migration as completed
markMigrationCompleted();
console.log('[UserDataMigration] === Migration Completed Successfully ===');
return {
success: true,
migrated: true,
from: oldUserDataPath,
to: newUserDataPath
};
} catch (error) {
console.error('[UserDataMigration] ✗ Migration failed:', error);
return {
success: false,
error: error.message,
from: oldUserDataPath,
to: newUserDataPath
};
}
}
/**
* Get the centralized UserData path (always use this in 2.2.0+)
* Ensures directory exists
*/
function getUserDataPath() {
const userDataPath = getHytaleSavesDir();
// Ensure directory exists
if (!fs.existsSync(userDataPath)) {
fs.mkdirSync(userDataPath, { recursive: true });
console.log(`[UserDataMigration] Created UserData directory: ${userDataPath}`);
}
return userDataPath;
}
module.exports = {
migrateUserDataToCentralized,
getUserDataPath,
isMigrationCompleted,
findOldUserDataPath
};