-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhytale-server-installer.cjs
More file actions
343 lines (274 loc) · 8.87 KB
/
hytale-server-installer.cjs
File metadata and controls
343 lines (274 loc) · 8.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
const { exec, spawn } = require("child_process");
const fs = require("fs");
const path = require("path");
const https = require("https");
const unzipper = require("unzipper");
const { pipeline } = require("stream");
const { promisify } = require("util");
const os = require("os");
const { exit } = require("process");
/* -------------------------------------------------
RUNTIME PATHS
------------------------------------------------- */
const RUNTIME_DIR = process.pkg
? path.dirname(process.execPath)
: process.cwd();
const LOG_FILE = path.join(RUNTIME_DIR, "installer.log");
const CONFIG_FILE = path.join(RUNTIME_DIR, "installer-config.json");
// Reset log file
try {
fs.writeFileSync(LOG_FILE, "");
} catch (err) {
console.error("Failed to reset log file:", err);
}
const DOWNLOAD_URL = "https://downloader.hytale.com/hytale-downloader.zip";
const DOWNLOADER_ZIP = path.join(RUNTIME_DIR, "hytale-downloader.zip");
const EXTRACT_DIR = path.join(RUNTIME_DIR, "hytale-downloader");
const platform = os.platform();
const pipelineAsync = promisify(pipeline);
let DOWNLOADER_EXE =
platform === "win32"
? "hytale-downloader-windows-amd64.exe"
: platform === "linux"
? "hytale-downloader-linux-amd64"
: null;
if (!DOWNLOADER_EXE) {
throw new Error(`Unsupported OS: ${platform}`);
}
/* -------------------------------------------------
LOGGING SYSTEM
------------------------------------------------- */
function writeLog(level, msg) {
const line = `[${new Date().toISOString()}] [${level}] ${msg}\n`;
try {
fs.appendFileSync(LOG_FILE, line);
} catch (err) {
console.error("Failed to write log:", err);
}
console[level === "ERROR" ? "error" : "log"](msg);
}
const log = msg => writeLog("INFO", msg);
const warn = msg => writeLog("WARN", msg);
const error = msg => writeLog("ERROR", msg);
/* -------------------------------------------------
CONFIG SYSTEM
------------------------------------------------- */
const DEFAULT_CONFIG = {
startServer: true,
cleanUp: true,
downloaderArgs: "",
javaArgs: "-Xms2G -Xmx4G -XX:AOTCache=HytaleServer.aot",
hytaleArgs: "--assets Assets.zip --bind 5520"
};
function loadConfig() {
try {
if (!fs.existsSync(CONFIG_FILE)) {
fs.writeFileSync(CONFIG_FILE, JSON.stringify(DEFAULT_CONFIG, null, 2));
log("Created default installer-config.json");
return DEFAULT_CONFIG;
}
const raw = fs.readFileSync(CONFIG_FILE, "utf8");
const parsed = JSON.parse(raw);
return { ...DEFAULT_CONFIG, ...parsed };
} catch (err) {
error("Failed to load config.json: " + err.message);
return DEFAULT_CONFIG;
}
}
const config = loadConfig();
/* -------------------------------------------------
ERROR HANDLERS
------------------------------------------------- */
process.on("uncaughtException", err => {
error("UNCAUGHT EXCEPTION: " + (err?.stack || err));
process.exit(1);
});
process.on("unhandledRejection", err => {
error("UNHANDLED PROMISE REJECTION: " + (err?.stack || err));
process.exit(1);
});
/* -------------------------------------------------
HELPERS
------------------------------------------------- */
function execAsync(cmd) {
return new Promise((resolve, reject) => {
exec(cmd, (err, stdout, stderr) => {
if (err && !stderr) reject(err);
else resolve((stdout + stderr).trim());
});
});
}
function downloadFile(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest);
https
.get(url, res => {
if (res.statusCode !== 200) {
reject(new Error(`Download failed: ${res.statusCode}`));
return;
}
res.pipe(file);
file.on("finish", () => file.close(resolve));
})
.on("error", reject);
});
}
async function unzipAll(zipPath, targetDir) {
await fs.promises.mkdir(targetDir, { recursive: true });
const directory = await unzipper.Open.file(zipPath);
for (const file of directory.files) {
const fullPath = path.join(targetDir, file.path);
if (file.type === "Directory") {
await fs.promises.mkdir(fullPath, { recursive: true });
} else {
await fs.promises.mkdir(path.dirname(fullPath), { recursive: true });
await pipelineAsync(file.stream(), fs.createWriteStream(fullPath));
}
}
}
async function checkJava() {
let out;
try {
out = await execAsync("java -version");
} catch {
throw new Error("Java not installed or not accessible");
}
const match = out.match(/version\s+"(\d+)/i);
if (!match) throw new Error("Cannot parse Java version");
const version = Number(match[1]);
if (version < 25) throw new Error(`Java ${version} was detected but 25+ is required`);
log(`Java ${version} - OK`);
}
async function runDownloader() {
const exePath = path.resolve(EXTRACT_DIR, DOWNLOADER_EXE);
return new Promise((resolve, reject) => {
const args = config.downloaderArgs.split(" ");
const downloaderArgs = [
...args
];
const proc = spawn(exePath, downloaderArgs, { stdio: "inherit", cwd: RUNTIME_DIR });
proc.on("error", reject);
proc.on("exit", (code, signal) => {
if (signal) reject(new Error(`Downloader terminated by signal ${signal}`));
else if (code !== 0) reject(new Error(`Downloader exited with code ${code}`));
else resolve();
});
});
}
function findNewestZip(dir) {
log("Searching for newest ZIP...");
const zips = fs
.readdirSync(dir)
.filter(f => f.endsWith(".zip"))
.map(f => ({
name: f,
time: fs.statSync(path.join(dir, f)).mtimeMs
}))
.sort((a, b) => b.time - a.time);
if (!zips.length) throw new Error("No downloaded ZIP found");
const newest = path.join(dir, zips[0].name);
log(`Newest ZIP: ${newest}`);
return newest;
}
async function moveAll(srcDir, destDir) {
const items = await fs.promises.readdir(srcDir, { withFileTypes: true });
for (const item of items) {
const srcPath = path.join(srcDir, item.name);
const destPath = path.join(destDir, item.name);
if (item.isDirectory()) {
await fs.promises.mkdir(destPath, { recursive: true });
await moveAll(srcPath, destPath);
await fs.promises.rmdir(srcPath).catch(() => {});
} else {
await fs.promises.copyFile(srcPath, destPath);
await fs.promises.unlink(srcPath).catch(() => {});
}
}
}
async function deleteFiles(files) {
for (const file of files) {
try {
await fs.promises.unlink(file);
} catch {}
}
}
async function deleteDirs(dirs) {
for (const dir of dirs) {
if (!dir || dir === "/" || dir === process.cwd()) continue;
try {
await fs.promises.rm(dir, {
recursive: true,
force: true,
maxRetries: 5,
retryDelay: 200
});
} catch (err) {
warn(`Failed to delete ${dir}: ${err.message}`);
}
}
}
/* -------------------------------------------------
FINAL SERVER START
------------------------------------------------- */
async function startServer() {
if (!config.startServer) {
log("Server start skipped. Exiting...");
exit(0);
}
const args = config.javaArgs.split(" ");
const hytaleArgs = config.hytaleArgs.split(" ");
const finalArgs = [
...args,
"-jar",
"HytaleServer.jar",
...hytaleArgs
];
log("Starting server with:");
log("java " + finalArgs.join(" "));
const proc = spawn("java", finalArgs, { stdio: "inherit", cwd: RUNTIME_DIR });
proc.on("exit", code => {
log(`Server exited with code ${code}`);
});
proc.on("error", err => {
error("Failed to start server: " + err.message);
});
}
/* -------------------------------------------------
MAIN
------------------------------------------------- */
(async () => {
try {
log("=== HYTALE SERVER INSTALLER | by SkyKing_PX | Version 1.0.0 ===");
await checkJava();
log("Downloading Hytale downloader...");
await downloadFile(DOWNLOAD_URL, DOWNLOADER_ZIP);
log("Extracting Hytale downloader...");
await unzipAll(DOWNLOADER_ZIP, EXTRACT_DIR);
if (platform === "linux") {
const exePath = path.join(EXTRACT_DIR, DOWNLOADER_EXE);
await fs.promises.chmod(exePath, 0o755);
log("Set Linux executable permissions");
}
log("Running Hytale downloader...");
await runDownloader();
log("Detecting downloaded version...");
const downloadedZip = findNewestZip(RUNTIME_DIR);
log("Extracting Hytale server assets...");
await unzipAll(downloadedZip, RUNTIME_DIR);
log("Preparing assets...")
await moveAll(path.join(RUNTIME_DIR, "Server"), RUNTIME_DIR);
if (config.cleanUp) {
log("Cleaning up...");
await deleteFiles([DOWNLOADER_ZIP, downloadedZip, "QUICKSTART.md"]);
await deleteDirs([EXTRACT_DIR, path.join(RUNTIME_DIR, "Server")]);
} else {
log("Cleanup skipped");
}
log("Done.");
await startServer();
process.on("exit", () => log("Exiting Installer..."));
} catch (err) {
error("FATAL ERROR: " + err.stack);
exit(1);
}
})();