This repository has been archived by the owner on Apr 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
428 lines (373 loc) · 15.3 KB
/
main.js
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
const { app, BrowserWindow, dialog, ipcMain } = require('electron');
const fs = require('fs');
const path = require('path');
const md5 = require('md5');
const childProcess = require('child_process');
const net = require('net');
// Prevent Chromium from lowering the priority of the renderer process
app.commandLine.appendSwitch('disable-renderer-backgrounding');
// File handler used for the log file, may be opened in a couple locations
let logFile = null;
const createLogFile = () => {
// Create log file and open it for writing
const appDataDir = app.getPath('appData');
if (!fs.existsSync(path.join(appDataDir, 'z5client-logs'))) {
fs.mkdirSync(path.join(appDataDir, 'z5client-logs'));
}
if (logFile) { return logFile; }
return fs.openSync(path.join(appDataDir, 'z5client-logs', `${new Date().getTime()}.txt`), 'w');
};
process.on('uncaughtException', (error) => {
const logFile = createLogFile();
const errorMessage = error.hasOwnProperty('message') ? error.message : JSON.stringify(error);
fs.writeFileSync(logFile, `\n[${new Date().toLocaleString()}] ${errorMessage}`);
const errorStack = error.hasOwnProperty('stack') ? error.stack : 'No stack trace available.';
fs.writeFileSync(logFile, `\n[${new Date().toLocaleString()}] ${errorStack}`);
// If there is another client bound to the address, close this client
if (error.code === 'EADDRINUSE') {
process.kill(process.pid);
}
});
// Create the log file for this run
logFile = createLogFile();
// Array to hold socket clients
const socketClients = {};
// Main UI window the user will interact with, used for IPC
let uiWindow = null;
// Perform certain actions during the install process
if (require('electron-squirrel-startup')) {
if (process.platform === 'win32') {
// Prepare to add registry entries for .apz5 files
const Registry = require('winreg');
const exePath = path.join(process.env.LOCALAPPDATA, 'Z5Client', 'Z5Client.exe');
// Set file type description for .apz5 files
const descriptionKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\archipelago.Z5client.v1',
});
descriptionKey.set(Registry.DEFAULT_VALUE, Registry.REG_SZ, 'Archipelago Binary Patch',
(error) => {
console.error(error);
const errorMessage = error.hasOwnProperty('message') ? error.message : JSON.stringify(error);
fs.writeFileSync(logFile, `\n[${new Date().toLocaleString()}] Error while writing registry ` +
`values: ${errorMessage}`);
const errorStack = error.hasOwnProperty('stack') ? error.stack : 'No stack trace available.';
fs.writeFileSync(logFile, `\n[${new Date().toLocaleString()}] ${errorStack}`);
});
// Set icon for .apz5 files
const iconKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\archipelago.Z5client.v1\\DefaultIcon',
});
iconKey.set(Registry.DEFAULT_VALUE, Registry.REG_SZ, `${exePath},0`, (error) => console.error(error));
// Set set default program for launching .apz5 files (Z5Client)
const commandKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\archipelago.Z5client.v1\\shell\\open\\command'
});
commandKey.set(Registry.DEFAULT_VALUE, Registry.REG_SZ, `"${exePath}" "%1"`, (error) => console.error(error));
// Set .apz5 files to launch with Z5Client
const extensionKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\.apz5',
});
extensionKey.set(Registry.DEFAULT_VALUE, Registry.REG_SZ, 'archipelago.Z5client.v1',
(error) => console.error(error));
}
// Do not launch the client during the install process
return app.quit();
}
const createWindow = () => {
const win = new BrowserWindow({
width: 1280,
minWidth: 400,
height: 720,
minHeight: 100,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
preload: path.join(__dirname, 'preload.js'),
backgroundThrottling: false,
},
});
win.loadFile('index.html');
return win;
};
const createPatchingWindow = () => {
const win = new BrowserWindow({
width: 400,
height: 75,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
backgroundThrottling: false,
},
});
win.loadFile('patching.html');
return win;
};
app.whenReady().then(async () => {
// Create the local config file if it does not exist
const configPath = path.join(app.getPath('appData'), 'z5client.config.json');
if (!fs.existsSync(configPath)) {
fs.writeFileSync(configPath,JSON.stringify({}));
}
// Load the config into memory
const configData = fs.readFileSync(configPath).toString();
// If the config file is empty, it must be regenerated later
const config = configData ? JSON.parse(configData) : {};
const validRomHashes = [
'5BD1FE107BF8106B2AB6650ABECD54D6'.toLowerCase(), // Compressed little-endian
'6697768A7A7DF2DD27A692A2638EA90B'.toLowerCase(), // Compressed big-endian
'05f0f3ebacbc8df9243b6148ffe4792f'.toLowerCase(), // Decompressed
];
// Prompt for base rom file if not present in config, missing from disk, or it fails the hash check
if (
!config.hasOwnProperty('baseRomPath') || // Base ROM not present in config file
!fs.existsSync(config.baseRomPath) || // Base ROM not present on file system
!['n64', 'z64'].includes(config.baseRomPath.slice(-3)) || // Base ROM has invalid extension
!validRomHashes.includes(md5(fs.readFileSync(config.baseRomPath))) // Base ROM fails hash check
) {
let baseRomPath = dialog.showOpenDialogSync(null, {
title: 'Select base ROM',
buttonLabel: 'Choose ROM',
message: 'Choose a base ROM to be used when patching.',
});
// Save base rom filepath back to config file
if (baseRomPath) {
config.baseRomPath = baseRomPath[0];
fs.writeFileSync(configPath, JSON.stringify(Object.assign({}, config, {
baseRomPath: config.baseRomPath,
})));
}
}
let patchingWindow = null;
// Create a new ROM from the patch file if the patch file is provided and the base rom is known
for (const arg of process.argv) {
if (arg.substr(-5).toLowerCase() === '.apz5') {
if (config.hasOwnProperty('baseRomPath') && fs.existsSync(config.baseRomPath)) {
if (!fs.existsSync(arg)) { break; }
if (!validRomHashes.includes(md5(fs.readFileSync(config.baseRomPath)))) {
dialog.showMessageBoxSync({
type: 'info',
title: 'Invalid Base ROM',
message: 'The ROM file for your game could not be created because the base ROM is invalid.',
});
break;
}
// Patch the .apz5
patchingWindow = createPatchingWindow();
await new Promise((r) => setTimeout(r, 250)); // Wait 250 milliseconds for the patching window to render
const outPath = path.join(path.dirname(arg),
`${path.basename(arg).substr(0, path.basename(arg).length - 5)}.n64`);
if (process.platform === 'win32') {
childProcess.execFileSync(path.join(__dirname, 'oot-patcher', 'Patch.exe'), // Path
[config.baseRomPath, arg, outPath],
{ timeout: 60000 }); // Timeout the process after one minute
// If a custom launcher is specified, attempt to launch the ROM file using the specified loader
if (config.hasOwnProperty('launcherPath') && fs.existsSync(config.launcherPath)) {
childProcess.spawn(config.launcherPath, [outPath], { detached: true });
break;
}
childProcess.spawn('explorer', [outPath], { detached: true });
}
if (process.platform === 'linux') {
// Check if wine is installed
if (!fs.existsSync(path.sep + path.join('usr', 'bin', 'wine')) &&
!fs.existsSync(path.sep + path.join('usr', 'sbin', 'wine'))
) {
dialog.showMessageBoxSync(null, {
type: 'info',
title: 'Unable to Patch ROM',
message: 'wine could not be found on your system. Your ROM file will not be patched.',
buttons: ['Okay'],
});
break;
}
// Launch patcher with wine and await completion
childProcess.execFileSync('wine',
[path.join(__dirname, 'oot-patcher', 'Patch.exe'), config.baseRomPath, arg, outPath],
{ timeout: 60000 }
);
// Execute patched ROM, let OS decide what to do with it
childProcess.execFile(outPath);
}
}
// This was the patch file argument. Do not keep searching for it
break;
}
}
uiWindow = createWindow();
if (patchingWindow) { patchingWindow.close(); }
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
uiWindow = createWindow();
if (patchingWindow) { patchingWindow.close(); }
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
}).catch((error) => {
const errorMessage = error.hasOwnProperty('message') ? error.message : JSON.stringify(error);
fs.writeFileSync(logFile, `\n[${new Date().toLocaleString()}] ${errorMessage}`);
const errorStack = error.hasOwnProperty('stack') ? error.stack : 'No stack trace available.';
fs.writeFileSync(logFile, `\n[${new Date().toLocaleString()}] ${errorStack}`);
});
// IPC listener for client config
ipcMain.on('setLauncher', (event, args) => {
// Allow the user to specify a program to launch the ROM
const configPath = path.join(app.getPath('appData'), 'z5client.config.json');
const config = JSON.parse(fs.readFileSync(configPath).toString());
const launcherPath = dialog.showOpenDialogSync({
title: 'Locate ROM Launcher',
buttonLabel: 'Select Launcher',
message: 'Choose an executable to be used when launching the ROM',
});
if (launcherPath) {
fs.writeFileSync(configPath, JSON.stringify(Object.assign({}, config, {
launcherPath: launcherPath[0],
})));
}
});
// IPC listener for logging
ipcMain.handle('writeToLog', (event, data) => fs.writeFileSync(logFile, `[${new Date().toLocaleString()}] ${data}`));
// Host a socket server used for communicating with the N64
const hostname = '127.0.0.1';
const port = 28920;
const socketMessage = (msg) => `${msg}\r\n`;
net.createServer((socket) => {
// If there is already a client connected, reject the connection
if (Object.keys(socketClients).length > 0) {
socket.destroy();
return;
}
const socketId = Math.random() * 1000000000;
// Buffer incoming socket messages. They may come in as incomplete, or multiple at once
let incomingMessageBuffer = '';
socket.on('data', (data) => {
// Add the new data to the buffer
incomingMessageBuffer += data.toString();
// So long as the buffer contains a newline character, it contains a completed message
while (incomingMessageBuffer.includes('\n')) {
// Find the first newline and handle the message before it
const newlineIndex = incomingMessageBuffer.indexOf('\n');
handleSocketMessage(incomingMessageBuffer.slice(0, newlineIndex));
// Remove the handled message from the buffer
incomingMessageBuffer = incomingMessageBuffer.slice(newlineIndex + 1);
}
});
// On close, remove socket from list of active clients
socket.on('close', (data) =>{
delete socketClients[socketId];
if (Object.keys(socketClients).length === 0) {
uiWindow.webContents.send('deviceConnected', false);
}
});
// On error, remove socket from list of active clients
socket.on('error', (err) => {
delete socketClients[socketId];
if (Object.keys(socketClients).length === 0) {
uiWindow.webContents.send('deviceConnected', false);
}
console.log(err)
});
// Store the client in the list of active clients
socketClients[socketId] = socket;
uiWindow.webContents.send('deviceConnected', true);
}).listen(port, hostname);
const handleSocketMessage = (message) => {
const messageParts = message.split('|');
const messageType = messageParts.splice(0,1)[0];
switch (messageType) {
case 'requestComplete':
uiWindow.webContents.send('requestComplete', messageParts);
break;
default:
console.warn(`Unknown message type received: ${messageType} with data:\n${JSON.stringify(messageParts)}`);
break;
}
};
// Interprocess communication with the renderer process, used for communication with OoT LUA Script
ipcMain.on('receiveItem', (event, requestId, itemOffset) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`receiveItem|${requestId}|${itemOffset}`));
});
});
ipcMain.on('isItemReceivable', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`isItemReceivable|${requestId}`));
});
});
ipcMain.on('getReceivedItemCount', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`getReceivedItemCount|${requestId}`));
});
});
ipcMain.on('getRomName', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`getRomName|${requestId}`));
});
});
ipcMain.on('setNames', (event, requestId, namesObj) => {
Object.values(socketClients).forEach((socket) => {
let commandStr = `setNames|${requestId}`;
Object.keys(namesObj).forEach((key) => commandStr += `|${key}|${namesObj[key]}`);
socket.write(socketMessage(commandStr));
});
});
ipcMain.on('getLocationChecks', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`getLocationChecks|${requestId}`));
});
});
ipcMain.on('getCurrentGameMode', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`getCurrentGameMode|${requestId}`));
});
});
ipcMain.on('isGameComplete', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`isGameComplete|${requestId}`));
});
});
ipcMain.on('isDeathLinkEnabled', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`isDeathLinkEnabled|${requestId}`));
});
});
ipcMain.on('isLinkAlive', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`isLinkAlive|${requestId}`));
});
});
ipcMain.on('killLink', (event, requestId) => {
Object.values(socketClients).forEach((socket) => {
socket.write(socketMessage(`killLink|${requestId}`));
});
});
ipcMain.on('disconnectAllClients', (event) => {
Object.values(socketClients).forEach((socket) => {
socket.destroy();
});
});
// Version checking
ipcMain.handle('clientUpdatePrompt', async (event, tag) => {
const versionUpdate = await dialog.showMessageBox(null, {
type: 'info',
title: 'A Client Update is Available',
message: 'A version of the Z5Client is available. It is recommended to upgrade, as outdated ' +
'versions may contain bugs or be incompatible with new Archipelago features.',
buttons: ['Do not update', 'Open downloads page'],
});
// If the user clicked on "Skip Patching", don't prompt them anymore
if (!versionUpdate.response) { return; }
const open = require('open');
open(`https://github.com/ArchipelagoMW/Z5Client/releases/tag/${tag}`);
});