-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
327 lines (279 loc) · 10.7 KB
/
Copy pathmain.js
File metadata and controls
327 lines (279 loc) · 10.7 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
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron');
const path = require('path');
const fs = require('fs-extra');
const { spawn } = require('child_process');
const crypto = require('crypto');
const https = require('https');
const http = require('http');
let mainWindow;
let settings;
const VALID_EXE_NAME = 'SWGEmu.exe';
const VALID_EXE_MD5 = '47436739d9adf27a7aca283f0f1b3e86'; // Replace with actual MD5
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
icon: path.join(__dirname, 'build', 'icon.ico'),
frame: false,
transparent: true,
resizable: false, // Disable window resizing
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
backgroundColor: '#00000000', // Fully transparent
hasShadow: false, // Disable default window shadow
roundedCorners: true
});
mainWindow.loadFile('index.html');
}
// File system operations
ipcMain.handle('check-files', async (event, requiredFiles) => {
const missingFiles = [];
for (const file of requiredFiles) {
const exists = await fs.pathExists(file.path); // Assuming the file object has a 'path' property
if (!exists) {
missingFiles.push(file);
}
}
return missingFiles;
});
// Load the required files list from a remote server
ipcMain.handle('load-required-files', async () => {
const url = 'http://62.146.229.237/tre/required-files.json'; // Updated URL
return new Promise((resolve, reject) => {
http.get(url, (response) => { // Changed to http.get since the URL uses HTTP
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
try {
const jsonData = JSON.parse(data);
resolve(jsonData);
} catch (error) {
reject(new Error('Failed to parse JSON data'));
}
});
}).on('error', (error) => {
reject(new Error(`Failed to fetch required files list: ${error.message}`));
});
});
});
// Check MD5 of a file
ipcMain.handle('check-md5', async (event, filePath) => {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('md5');
const stream = fs.createReadStream(filePath);
stream.on('data', data => hash.update(data));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
});
// Add this function to preserve player profiles
async function preservePlayerProfiles(directory) {
const profilesPath = path.join(directory, 'profiles');
const backupPath = path.join(directory, 'profiles_backup');
try {
if (await fs.pathExists(profilesPath)) {
// If backup exists, restore it first
if (await fs.pathExists(backupPath)) {
await fs.remove(profilesPath);
await fs.move(backupPath, profilesPath);
}
}
} catch (error) {
console.error('Error preserving player profiles:', error);
}
}
// Modify the download-file handler to preserve profiles
ipcMain.handle('download-file', async (event, { url, destination, expectedMd5, skipChecks }) => {
return new Promise(async (resolve, reject) => {
// Check if this is a tre file download
const isTreFile = destination.toLowerCase().endsWith('.tre');
const gameDir = path.dirname(destination);
if (isTreFile) {
await preservePlayerProfiles(gameDir);
}
fs.mkdirSync(path.dirname(destination), { recursive: true });
function downloadWithRedirects(url) {
const protocol = url.startsWith('https') ? https : http;
protocol.get(url, (response) => {
// Handle redirects
if (response.statusCode === 301 || response.statusCode === 302) {
console.log(`Following redirect to: ${response.headers.location}`);
downloadWithRedirects(response.headers.location);
return;
}
if (response.statusCode !== 200) {
reject(new Error(`Server returned status code: ${response.statusCode}`));
return;
}
const file = fs.createWriteStream(destination);
let downloadedBytes = 0;
let startTime = Date.now();
const totalBytes = parseInt(response.headers['content-length'], 10);
response.on('data', (chunk) => {
downloadedBytes += chunk.length;
const percent = (downloadedBytes / totalBytes) * 100;
const elapsedSeconds = (Date.now() - startTime) / 1000;
const speed = downloadedBytes / elapsedSeconds;
mainWindow.webContents.send('download-progress', {
percent: percent,
speed: speed
});
});
response.pipe(file);
file.on('finish', () => {
file.close();
if (skipChecks) {
resolve('success');
return;
}
const hash = crypto.createHash('md5');
const readStream = fs.createReadStream(destination);
readStream.on('data', data => hash.update(data));
readStream.on('end', async () => {
const downloadedMd5 = hash.digest('hex');
if (downloadedMd5 !== expectedMd5) {
const response = await dialog.showMessageBox({
type: 'warning',
title: 'MD5 Mismatch',
message: `MD5 mismatch detected for ${path.basename(destination)}`,
detail: `Expected: ${expectedMd5}\nReceived: ${downloadedMd5}\n\nDo you want to keep this file anyway?`,
buttons: ['Keep File', 'Delete and Retry'],
defaultId: 1,
cancelId: 1
});
if (response.response === 0) {
resolve('kept-with-mismatch');
} else {
fs.unlinkSync(destination);
reject(new Error(`MD5_MISMATCH:${path.basename(destination)}`));
}
} else {
resolve('success');
}
});
readStream.on('error', reject);
});
}).on('error', (err) => {
fs.unlink(destination, () => {});
reject(err);
});
}
downloadWithRedirects(url);
});
});
// Launch executable
ipcMain.handle('select-directory', async () => {
const result = await dialog.showOpenDialog({
properties: ['openDirectory']
});
if (!result.canceled) {
return result.filePaths[0];
}
return null;
});
// Regular launch for SWGEmu.exe
ipcMain.handle('launch-game', async (event, exePath) => {
return new Promise(async (resolve, reject) => {
try {
// Verify filename
const basename = path.basename(exePath);
if (basename !== VALID_EXE_NAME) {
throw new Error('Invalid executable name detected');
}
// Verify MD5 one final time
const fileHash = await new Promise((resolve, reject) => {
const hash = crypto.createHash('md5');
const stream = fs.createReadStream(exePath);
stream.on('data', data => hash.update(data));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
if (fileHash !== VALID_EXE_MD5) {
throw new Error('Executable file hash verification failed');
}
// If verification passes, launch the game
const workingDir = path.dirname(exePath);
const process = spawn(exePath, [], {
cwd: workingDir,
detached: true,
stdio: 'ignore'
});
process.unref();
resolve();
} catch (error) {
reject(`Security check failed: ${error.message}`);
}
});
});
// Admin launch for SWGEmu_Setup.exe
ipcMain.handle('launch-admin', async (event, exePath) => {
try {
await shell.openPath(exePath);
return true;
} catch (error) {
throw error;
}
});
// Handle config file updates
ipcMain.handle('update-config', async (event, { directory, content }) => {
const configPath = path.join(directory, 'swgemu_login.cfg');
try {
await fs.writeFile(configPath, content, 'utf8');
return true;
} catch (error) {
throw error;
}
});
// Add this function to handle settings
function loadSettings() {
const userDataPath = app.getPath('userData');
const settingsPath = path.join(userDataPath, 'settings.json');
try {
if (fs.existsSync(settingsPath)) {
settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
} else {
settings = { installDir: null };
fs.writeFileSync(settingsPath, JSON.stringify(settings));
}
} catch (error) {
console.error('Error loading settings:', error);
settings = { installDir: null };
}
}
function saveSettings() {
const userDataPath = app.getPath('userData');
const settingsPath = path.join(userDataPath, 'settings.json');
try {
fs.writeFileSync(settingsPath, JSON.stringify(settings));
} catch (error) {
console.error('Error saving settings:', error);
}
}
// Load settings when app starts
app.whenReady().then(() => {
loadSettings();
createWindow();
});
// Add these IPC handlers
ipcMain.handle('get-install-dir', () => {
return settings.installDir;
});
ipcMain.handle('save-install-dir', (event, dir) => {
settings.installDir = dir;
saveSettings();
return true;
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});