forked from NeurodataWithoutBorders/nwb-guide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
executable file
·506 lines (432 loc) · 14.5 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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
const { app, BrowserWindow, dialog, shell } = require("electron");
require("@electron/remote/main").initialize();
app.showExitPrompt = true;
const path = require("path");
const glob = require("glob");
const fp = require("find-free-port");
const os = require("os");
const contextMenu = require("electron-context-menu");
const log = require("electron-log");
require("v8-compile-cache");
const { ipcMain } = require("electron");
const { autoUpdater } = require("electron-updater");
const { JSONStorage } = require("node-localstorage");
const { trackEvent } = require("./scripts/others/analytics/analytics");
const { fstat } = require("fs");
const { resolve } = require("path");
const axios = require("axios");
const { info } = require("console");
const { node } = require("prop-types");
log.transports.console.level = false;
log.transports.file.level = "debug";
autoUpdater.channel = "latest";
autoUpdater.logger = log;
global.trackEvent = trackEvent;
const nodeStorage = new JSONStorage(app.getPath("userData"));
/*************************************************************
* Python Process
*************************************************************/
// flask setup environment variables
const PY_FLASK_DIST_FOLDER = "pyflaskdist";
const PY_FLASK_FOLDER = "pyflask";
const PY_FLASK_MODULE = "app";
let pyflaskProcess = null;
let PORT = 4242;
let selectedPort = null;
const portRange = 100;
/**
* Determine if the application is running from a packaged version or from a dev version.
* The resources path is used for Linux and Mac builds and the app.getAppPath() is used for Windows builds.
* @returns {boolean} True if the app is packaged, false if it is running from a dev version.
*/
const guessPackaged = () => {
log.info("Guessing if packaged");
const windowsPath = path.join(__dirname, PY_FLASK_DIST_FOLDER);
const unixPath = path.join(process.resourcesPath, PY_FLASK_MODULE);
log.info(unixPath);
if (process.platform === "darwin" || process.platform === "linux") {
if (require("fs").existsSync(unixPath)) {
log.info("Unix path exists");
return true;
} else {
log.info("Unix path does not exist");
return false;
}
}
if (process.platform === "win32") {
if (require("fs").existsSync(windowsPath)) {
return true;
} else {
return false;
}
}
};
/**
* Get the system path to the api server script.
* The script is located in the resources folder for packaged Linux and Mac builds and in the app.getAppPath() for Windows builds.
* It is relative to the main.js file directory when in dev mode.
* @returns {string} The path to the api server script that needs to be executed to start the Python server
*/
const getScriptPath = () => {
if (!guessPackaged()) {
log.info("App is not packaged returning path: ");
log.info(path.join(__dirname, PY_FLASK_FOLDER, PY_FLASK_MODULE + ".py"));
return path.join(__dirname, PY_FLASK_FOLDER, PY_FLASK_MODULE + ".py");
}
if (process.platform === "win32") {
return path.join(__dirname, PY_FLASK_DIST_FOLDER, PY_FLASK_MODULE + ".exe");
} else {
log.info("Since app is packaged returning path: ");
return path.join(process.resourcesPath, PY_FLASK_MODULE);
}
};
const selectPort = () => {
return PORT;
};
const createPyProc = async () => {
let script = getScriptPath();
log.info(script);
let port = "" + selectPort();
await killAllPreviousProcesses();
if (require("fs").existsSync(script)) {
log.info("server exists at specified location");
} else {
log.info("server does not exist at specified location");
}
fp(PORT, PORT + portRange)
.then(([freePort]) => {
let port = freePort;
if (guessPackaged()) {
log.info("Application is packaged");
pyflaskProcess = require("child_process").execFile(script, [port], {
// stdio: "ignore",
});
} else {
log.info("Application is not packaged");
pyflaskProcess = require("child_process").spawn("python", [script, port], {
// stdio: "ignore",
});
}
if (pyflaskProcess != null) {
console.log("child process success on port " + port);
log.info("child process success on port " + port);
// Listen for errors from Python process
pyflaskProcess.stderr.on("data", function (data) {
console.log("[python]:", data.toString());
});
} else console.error("child process failed to start on port" + port);
selectedPort = port;
})
.catch((err) => {
console.log(err);
});
};
/**
* Kill the python server process. Needs to be called before SODA closes.
*/
const exitPyProc = async () => {
log.info("Killing python server process");
// Windows does not properly shut off the python server process. This ensures it is killed.
const killPythonProcess = () => {
// kill pyproc with command line
const cmd = require("child_process").spawnSync("taskkill", [
"/pid",
pyflaskProcess.pid,
"/f",
"/t",
]);
};
await killAllPreviousProcesses();
// check if the platform is Windows
if (process.platform === "win32") {
killPythonProcess();
pyflaskProcess = null;
PORT = null;
return;
}
// kill signal to pyProc
pyflaskProcess.kill();
pyflaskProcess = null;
PORT = null;
};
const killAllPreviousProcesses = async () => {
console.log("Killing all previous processes");
// kill all previous python processes that could be running.
let promisesArray = [];
let endRange = PORT + portRange;
// create a loop of 100
for (let currentPort = PORT; currentPort <= endRange; currentPort++) {
promisesArray.push(
axios.get(`http://127.0.0.1:${currentPort}/server_shutdown`, {})
);
}
// wait for all the promises to resolve
await Promise.allSettled(promisesArray);
};
// 5.4.1 change: We call createPyProc in a spearate ready event
// app.on("ready", createPyProc);
// 5.4.1 change: We call exitPyreProc when all windows are killed so it has time to kill the process before closing
/*************************************************************
* Main app window
*************************************************************/
let mainWindow = null;
let user_restart_confirmed = false;
let updatechecked = false;
let window_reloaded = false;
function initialize() {
const checkForAnnouncements = () => {
mainWindow.webContents.send("checkForAnnouncements");
};
makeSingleInstance();
loadDemos();
function createWindow() {
// mainWindow.webContents.openDevTools();
mainWindow.webContents.on("new-window", (event, url) => {
event.preventDefault();
shell.openExternal(url);
});
mainWindow.webContents.once("dom-ready", () => {
if (updatechecked == false) {
autoUpdater.checkForUpdatesAndNotify();
}
});
mainWindow.on("close", async (e) => {
if (!user_restart_confirmed) {
if (app.showExitPrompt) {
e.preventDefault(); // Prevents the window from closing
dialog
.showMessageBox(BrowserWindow.getFocusedWindow(), {
type: "question",
buttons: ["Yes", "No"],
title: "Confirm",
message: "Any running process will be stopped. Are you sure you want to quit?",
})
.then((responseObject) => {
let { response } = responseObject;
if (response === 0) {
// Runs the following if 'Yes' is clicked
var announcementsLaunch = nodeStorage.getItem("announcements");
nodeStorage.setItem("announcements", false);
quit_app();
}
});
}
} else {
var first_launch = nodeStorage.getItem("firstlaunch");
nodeStorage.setItem("firstlaunch", true);
nodeStorage.setItem("announcements", true);
await exitPyProc();
app.exit();
}
});
}
const quit_app = () => {
console.log("Quit app called");
app.showExitPrompt = false;
mainWindow.close();
/// feedback form iframe prevents closing gracefully
/// so force close
if (!mainWindow.closed) {
mainWindow.destroy();
}
};
app.on("ready", () => {
createPyProc();
const windowOptions = {
minWidth: 1121,
minHeight: 735,
width: 1121,
height: 735,
center: true,
show: false,
icon: __dirname + "/assets/img/logo-neuroconv.png",
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
sandbox: false,
// preload: path.join(__dirname, "preload.js"),
},
};
mainWindow = new BrowserWindow(windowOptions);
require("@electron/remote/main").enable(mainWindow.webContents);
mainWindow.loadURL(path.join("file://", __dirname, "/index.html"));
const splash = new BrowserWindow({
width: 340,
height: 340,
frame: false,
icon: __dirname + "/assets/img/logo-neuroconv.png",
alwaysOnTop: true,
transparent: true,
});
splash.loadURL(path.join("file://", __dirname, "/splash-screen.html"));
// if main window is ready to show, then destroy the splash window and show up the main window
mainWindow.once("ready-to-show", () => {
setTimeout(function () {
splash.close();
//mainWindow.maximize();
mainWindow.show();
createWindow();
var first_launch = nodeStorage.getItem("firstlaunch");
var announcementsLaunch = nodeStorage.getItem("announcements");
if (first_launch == true || first_launch == undefined) {
mainWindow.reload();
mainWindow.focus();
nodeStorage.setItem("firstlaunch", false);
run_pre_flight_checks();
}
if (announcementsLaunch == true || announcementsLaunch == undefined) {
checkForAnnouncements();
}
run_pre_flight_checks();
autoUpdater.checkForUpdatesAndNotify();
updatechecked = true;
}, 6000);
});
mainWindow.on("show", () => {
var first_launch = nodeStorage.getItem("firstlaunch");
if ((first_launch == true || first_launch == undefined) && window_reloaded == false) {
}
// run_pre_flight_checks();
});
});
app.on("ready", () => {
trackEvent("Success", "App Launched - OS", os.platform() + "-" + os.release());
trackEvent("Success", "App Launched - SODA", app.getVersion());
});
app.on("window-all-closed", async () => {
await exitPyProc();
app.quit();
});
app.on("will-quit", () => {
app.quit();
});
}
function run_pre_flight_checks() {
console.log("Running pre-checks");
mainWindow.webContents.send("run_pre_flight_checks");
}
// Make this app a single instance app.
const gotTheLock = app.requestSingleInstanceLock();
function makeSingleInstance() {
if (process.mas) return;
if (!gotTheLock) {
app.quit();
} else {
app.on("second-instance", () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
}
/*
the saveImage context Menu-Item works; however, it does not notify users that a download occurs.
If you check your download folder, you'll see it there.
See: https://github.com/nteract/nteract/issues/1655
showSaveImageAs prompts the users where they want to save the image.
*/
contextMenu();
// Require each JS file in the main-process dir
function loadDemos() {
const files = glob.sync(path.join(__dirname, "main-process/**/*.js"));
files.forEach((file) => {
require(file);
});
}
initialize();
ipcMain.on("resize-window", (event, dir) => {
var x = mainWindow.getSize()[0];
var y = mainWindow.getSize()[1];
if (dir === "up") {
x = x + 1;
y = y + 1;
} else {
x = x - 1;
y = y - 1;
}
mainWindow.setSize(x, y);
});
// Google analytics tracking function
// To use, category and action is required. Label and value can be left out
// if not needed. Sample requests from renderer.js is shown below:
//ipcRenderer.send('track-event', "App Backend", "Python Connection Established");
//ipcRenderer.send('track-event', "App Backend", "Errors", "server", error);
ipcMain.on("track-event", (event, category, action, label, value) => {
if (label == undefined && value == undefined) {
trackEvent(category, action);
} else if (label != undefined && value == undefined) {
trackEvent(category, action, label);
} else {
trackEvent(category, action, label, value);
}
});
ipcMain.on("app_version", (event) => {
event.sender.send("app_version", { version: app.getVersion() });
});
autoUpdater.on("update-available", () => {
log.info("update_available");
mainWindow.webContents.send("update_available");
});
autoUpdater.on("update-downloaded", () => {
log.info("update_downloaded");
mainWindow.webContents.send("update_downloaded");
});
ipcMain.on("restart_app", async () => {
user_restart_confirmed = true;
nodeStorage.setItem("announcements", true);
log.info("quitAndInstall");
autoUpdater.quitAndInstall();
});
const wait = async (delay) => {
return new Promise((resolve) => setTimeout(resolve, delay));
};
ipcMain.on("orcid", (event, url) => {
const windowOptions = {
minWidth: 500,
minHeight: 300,
width: 900,
height: 800,
center: true,
show: true,
icon: __dirname + "/assets/menu-icon/soda_icon.png",
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
},
// modal: true,
parent: mainWindow,
closable: true,
};
let pennsieveModal = new BrowserWindow(windowOptions);
// send to client so they can use this for the Pennsieve endpoint for integrating an ORCID
let accessCode;
pennsieveModal.on("close", function () {
// send event back to the renderer to re-run the prepublishing checks
// this will detect if the user added their ORCID iD
event.reply("orcid-reply", accessCode);
pennsieveModal = null;
});
pennsieveModal.loadURL(url);
pennsieveModal.once("ready-to-show", async () => {
pennsieveModal.show();
});
// track when the page navigates
pennsieveModal.webContents.on("did-navigate", () => {
// get the URL
url = pennsieveModal.webContents.getURL();
// check if the url includes the access code
if (url.includes("code=")) {
// get the access code from the url
let params = new URLSearchParams(url.slice(url.search(/\?/)));
accessCode = params.get("code");
// if so close the window
pennsieveModal.close();
}
});
});
ipcMain.on("get-port", (event) => {
log.info("Renderer requested port: " + selectedPort);
event.returnValue = selectedPort;
});