-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathelectron.js
More file actions
484 lines (450 loc) · 15.4 KB
/
electron.js
File metadata and controls
484 lines (450 loc) · 15.4 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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/* jshint node: true */
'use strict';
if (require('electron-squirrel-startup')) {
return;
}
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const emberAppLocation = `file://${__dirname}/dist/index.html`;
const ipc = require('electron').ipcMain;
const dialog = require('electron').dialog;
const fs = require('fs');
const crypto = require('crypto');
const bonjour = require('bonjour');
const sudo = require('electron-sudo');
const path = require('path');
const yauzl = require('yauzl');
const Transform = require("stream").Transform;
const drivelist = require('drivelist');
const request = require('request');
const readline = require('readline');
const child_process = require('child_process');
const requestProgress = require('request-progress');
let mainWindow = null;
let isDownloading = false;
let processAbortFlag = false;
let zipPath;
electron.crashReporter.start();
app.on('window-all-closed', function onWindowAllClosed() {
app.quit();
});
app.on('ready', function onReady() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
icon: __dirname + 'includes/icon.png'
});
if (process.platform === "linux" && process.env.PATH.indexOf(":/sbin") === -1) {
process.env.PATH = process.env.PATH += ":/sbin";
}
delete mainWindow.module;
// If you want to open up dev tools programmatically, call
// mainWindow.openDevTools();
// By default, we'll open the Ember App by directly going to the
// file system.
//
// Please ensure that you have set the locationType option in the
// config/environment.js file to 'hash'. For more information,
// please consult the ember-electron readme.
mainWindow.loadURL(emberAppLocation);
// If a loading operation goes wrong, we'll send Electron back to
// Ember App entry point
mainWindow.webContents.on('did-fail-load', () => {
mainWindow.loadURL(emberAppLocation);
});
mainWindow.on('closed', () => {
mainWindow = null;
});
});
ipc.on('sendAbort', function() {
processAbortFlag = true;
});
ipc.on('exitApp', function() {
app.quit();
});
ipc.on('openGenesis', function(event, addr) {
electron.shell.openExternal(addr);
});
ipc.on('scanNetwork', function(event) {
event.sender.send('setSearchingStatus', true);
var b = bonjour();
var browser = b.find({type: 'http'}, function (service) {
if (service.name === 'arkOS') {
event.sender.send('scannedServer', service);
}
});
setTimeout(function() {
event.sender.send('setSearchingStatus', false);
browser.stop();
}, 5000);
});
ipc.on('getDevices', function(event) {
var devices = [];
drivelist.list(function(err, drives) {
devices = drives.filter(function(drive) {
return process.platform === 'win32' ? drive.name !== "C:" : !drive.system;
});
event.sender.send('gotDevices', devices);
});
});
ipc.on('startDownload', function(event, downloadUrl) {
if (isDownloading) {
return;
}
zipPath = path.join(app.getPath('downloads'), 'arkos-' + path.basename(downloadUrl));
fs.stat(zipPath, function(err, stats) {
if (stats && stats.isFile()) {
console.log('Archive found in download directory. Sending for integrity check');
event.sender.send('updateDownloadProgress', {percentage: 1.0, size: {}});
event.sender.send('downloadComplete');
} else {
downloadArchive(event, downloadUrl);
}
});
});
var downloadArchive = function(event, downloadUrl) {
isDownloading = true;
console.log('Starting download');
var r = request(downloadUrl);
requestProgress(r)
.on('response', function(resp) {
if (resp.statusCode !== 200) {
console.log('Download error: HTTP ' + resp.statusCode);
mainWindow.loadURL(emberAppLocation);
dialog.showErrorBox('Download Error', 'HTTP ' + resp.statusCode);
}
})
.on('progress', function(state) {
/* console.log('Download progress: ' + (Math.round(state.percentage * 10000) / 100) + '%'); */
if (processAbortFlag) {
r.abort();
}
mainWindow.setProgressBar(state.percentage);
event.sender.send('updateDownloadProgress', state);
})
.on('error', function(err) {
console.log('Download error: ' + err);
mainWindow.setProgressBar(-1);
mainWindow.loadURL(emberAppLocation);
dialog.showErrorBox('Download Error', err.message);
})
.on('end', function() {
isDownloading = false;
mainWindow.setProgressBar(-1);
if (processAbortFlag) {
processAbortFlag = false;
fs.unlink(zipPath);
console.log('Download cancelled');
} else {
console.log('Download complete');
event.sender.send('updateDownloadProgress', {percentage: 1.0, size: {}});
event.sender.send('downloadComplete');
}
})
.pipe(fs.createWriteStream(zipPath));
};
ipc.on('startIntegrityCheck', function(event, hashUrl) {
console.log('Starting integrity check');
mainWindow.setProgressBar(0);
event.sender.send('updateWriteProgress', {percent: 0});
var checkProgress = {byteCount: 0, totalBytes: fs.statSync(zipPath).size};
var sha256sum = crypto.createHash('sha256');
var f = fs.ReadStream(zipPath);
var pct;
f.on('data', function(data) {
if (processAbortFlag) {
f.destroy();
}
checkProgress.byteCount += data.length;
pct = Math.round(checkProgress.byteCount / checkProgress.totalBytes);
mainWindow.setProgressBar(pct);
event.sender.send('updateWriteProgress', {percent: pct * 100});
sha256sum.update(data);
});
f.on('close', function() {
if (processAbortFlag) {
console.log('Integrity check aborted');
processAbortFlag = false;
}
});
f.on('end', function() {
var digest = sha256sum.digest('hex');
request(hashUrl, function(err, resp, body) {
if (processAbortFlag) {
console.log('Integrity check aborted');
processAbortFlag = false;
} else if (err) {
console.log('Integrity check error: ' + err);
dialog.showErrorBox('Integrity Check Error', err.message);
mainWindow.loadURL(emberAppLocation);
} else if (resp.statusCode !== 200) {
console.log('Integrity check error: HTTP ' + resp.statusCode);
dialog.showErrorBox('Integrity Check Error', 'HTTP ' + resp.statusCode);
mainWindow.loadURL(emberAppLocation);
} else if (body.split(' ')[0] !== digest) {
fs.unlink(zipPath);
console.log('Integrity check FAILED');
event.sender.send('integrityCheckComplete', 'fail');
dialog.showErrorBox('Integrity Check Error', 'The integrity check for this file failed. It may have been corrupted during the download, or an updated version may be available from arkOS. It will now be removed. Please try your install again.');
mainWindow.loadURL(emberAppLocation);
} else {
console.log('Integrity check PASSED');
event.sender.send('integrityCheckComplete', 'pass');
}
mainWindow.setProgressBar(-1);
});
});
});
ipc.on('startExtraction', function(event) {
var images = {};
console.log('Starting archive extraction');
event.sender.send('extractionStarted');
yauzl.open(zipPath, {lazyEntries: true}, function(err, zipfile) {
if (err) {
throw err;
}
zipfile.readEntry();
zipfile.on("close", function() {
extractImage(images.boot, event, function() {
if (processAbortFlag) {
return;
} else if (images.data) {
extractImage(images.data, event, function() {
console.log('Archive extraction complete');
event.sender.send('extractionComplete', 'pass', images.boot.name, images.data.name);
});
} else {
console.log('Archive extraction complete');
event.sender.send('extractionComplete', 'pass', images.boot.name, null);
}
});
});
zipfile.on("entry", function(entry) {
if (entry.fileName.indexOf('-boot-') >= 0 || entry.fileName.indexOf('-data-') === -1) {
images.boot = {name: entry.fileName, size: entry.uncompressedSize};
} else {
images.data = {name: entry.fileName, size: entry.uncompressedSize};
}
zipfile.readEntry();
});
zipfile.on("error", function(err) {
console.log(err);
console.log('Archive check failed');
processAbortFlag = true;
dialog.showErrorBox('Archive check failed', err);
mainWindow.loadURL(emberAppLocation);
});
});
processAbortFlag = false;
});
var extractImage = function(img, event, callback) {
var progress = {byteCount: 0, totalBytes: img.size, percent: 0};
var outPath = path.join(app.getPath('downloads'), img.name);
console.log('Extracting image: ' + JSON.stringify(img));
yauzl.open(zipPath, {lazyEntries: true}, function(err, zipfile) {
if (err) {
throw err;
}
zipfile.readEntry();
zipfile.on("close", function() {
mainWindow.setProgressBar(-1);
event.sender.send('updateWriteProgress', null);
if (processAbortFlag) {
console.log('Archive extraction aborted');
processAbortFlag = false;
} else {
callback();
}
});
zipfile.on("entry", function(entry) {
if (entry.fileName !== img.name) {
zipfile.readEntry();
} else {
zipfile.openReadStream(entry, function(err, readStream) {
if (err) {
throw err;
}
event.sender.send('updateWriteProgress', progress);
var reportProgress = setInterval(function() {
event.sender.send('updateWriteProgress', progress);
mainWindow.setProgressBar((progress.byteCount / progress.totalBytes));
}, 1000);
var filter = new Transform();
filter._transform = function(chunk, encoding, cb) {
if (processAbortFlag) {
clearInterval(reportProgress);
readStream.unpipe();
readStream.destroy();
zipfile.close();
}
progress.byteCount += chunk.length;
progress.percent = Math.round(progress.byteCount / progress.totalBytes * 10000) / 100;
cb(null, chunk);
};
filter._flush = function(cb) {
clearInterval(reportProgress);
cb();
zipfile.readEntry();
};
var writeStream = fs.createWriteStream(outPath);
var filterPipe = readStream.pipe(filter);
filterPipe.pipe(writeStream);
});
}
});
zipfile.on("error", function(err) {
event.sender.send('updateWriteProgress', null);
mainWindow.setProgressBar(-1);
console.log(err);
console.log('Archive extraction failed');
processAbortFlag = true;
dialog.showErrorBox('Archive extraction failed', err);
mainWindow.loadURL(emberAppLocation);
});
});
};
ipc.on('writeDisks', function(event, image1, device1, image2, device2) {
var stderr = '';
var cmd = '';
var nodePath = process.execPath;
image1 = path.join(app.getPath('downloads'), image1);
image2 = image2 ? path.join(app.getPath('downloads'), image2) : null;
switch (process.platform) {
case 'darwin':
var appName = app.getName();
device1.device = '/dev/rdisk' + device1.device.slice(-1)[0];
if (device2) {
device2.device = '/dev/rdisk' + device2.device.slice(-1)[0];
}
if (nodePath.indexOf("/Electron.app/") >= 0) {
appName = 'Electron';
}
nodePath = path.resolve(process.resourcesPath, '..', 'Frameworks',
appName + ' Helper.app', 'Contents', 'MacOS', appName + ' Helper');
cmd = `"\\\"${nodePath}\\\" \\\"${__dirname}/includes/disk-write.js\\\" ${process.platform} ${device1.device} ${image1} ${device1.mountpoint}`;
if (device2 && image2) {
cmd += ` ${device2.device} \\\"${image2}\\\" ${device2.mountpoint}`;
}
cmd += '"';
break;
case 'win32':
cmd = `"${nodePath}" "${__dirname}/includes/disk-write.js" ${process.platform} ${device1.device} ${image1} ${device1.mountpoint}`;
if (device2 && image2) {
cmd += ` ${device2.device} "${image2}" ${device2.mountpoint}`;
}
break;
default:
// linux
cmd = ["env", "ELECTRON_RUN_AS_NODE=1", "ELECTRON_NO_ATTACH_CONSOLE=1", nodePath,
`${__dirname}/includes/disk-write.js`, process.platform, device1.device, image1,
device1.mountpoint];
if (device2 && image2) {
cmd.concat([device2.device, image2, device2.mountpoint]);
}
break;
}
console.log('Command will be: ' + cmd);
var onWriteError = function(err) {
err = typeof err === "string" ? err : err.toString();
if (err && err !== 'sudo: a password is required\n' && err !== 'null') {
console.log('Disk write failed: ' + err);
dialog.showErrorBox('Disk Write Error', err);
mainWindow.loadURL(emberAppLocation);
}
};
var handleStreams = function(proc) {
readline.createInterface({
input : proc.stdout,
terminal : false
}).on('line', function(line) {
if (processAbortFlag) {
proc.stdout.unpipe();
proc.kill();
} else {
if (line.startsWith('{') && line.endsWith('}')) {
var progress = JSON.parse(line);
if (progress) {
mainWindow.setProgressBar(progress.percent / 100);
}
event.sender.send('updateWriteProgress', progress);
}
}
});
proc.stderr.on('data', function(data) {
if (data) {
stderr += data;
}
});
proc.on('close', function(code) {
if (code === 0) {
mainWindow.setProgressBar(-1);
event.sender.send('updateWriteProgress', null);
console.log('Disk write complete');
event.sender.send('diskWriteDone', 'pass');
} else if (processAbortFlag) {
console.log('Disk write aborted');
processAbortFlag = false;
} else {
onWriteError(stderr);
}
});
};
var options = {
name: 'arkOS Assistant',
icns: `${__dirname}/includes/icon.icns`,
process: {
options: {
env: {
'ELECTRON_RUN_AS_NODE': 1,
'ELECTRON_NO_ATTACH_CONSOLE': 1
}
},
on: function(ps) {
handleStreams(ps);
}
}
};
// launch write commands
console.log('Beginning disk write');
mainWindow.setProgressBar(2);
event.sender.send('updateWriteProgress', {percent: 100});
switch (process.platform) {
case 'darwin':
case 'win32':
sudo.exec(cmd, options, function(err) {
mainWindow.setProgressBar(-1);
event.sender.send('updateWriteProgress', null);
if (err) {
onWriteError(err);
}
});
break;
default:
// linux
var ps = child_process.spawn("/usr/bin/pkexec", ['--disable-internal-agent'].concat(cmd));
handleStreams(ps);
break;
}
});
ipc.on('removeDownloadedFiles', function() {
fs.stat(zipPath, function(err, stats) {
if (stats && stats.isFile()) {
yauzl.open(zipPath, {lazyEntries: true}, function(err, zipfile) {
zipfile.readEntry();
zipfile.on("close", function() {
fs.unlink(zipPath);
});
zipfile.on("entry", function(entry) {
var imgPath = path.join(app.getPath('downloads'), entry.fileName);
fs.stat(imgPath, function(err, stats) {
if (stats && stats.isFile()) {
fs.unlink(imgPath);
}
});
zipfile.readEntry();
});
});
}
});
});