-
-
Notifications
You must be signed in to change notification settings - Fork 713
/
main.js
349 lines (300 loc) · 10.9 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
const { app } = require('electron');
const { BrowserWindow } = require('electron');
const { protocol } = require('electron');
const path = require('path');
const cProcess = require('child_process').spawn;
const portscanner = require('portscanner');
const { imageSize } = require('image-size');
let io, server, browserWindows, ipc, apiProcess, loadURL;
let appApi, menu, dialogApi, notification, tray, webContents;
let globalShortcut, shellApi, screen, clipboard, autoUpdater;
let commandLine, browserView;
let powerMonitor;
let splashScreen, hostHook;
let mainWindowId, nativeTheme;
let dock;
let launchFile;
let launchUrl;
let manifestJsonFileName = 'electron.manifest.json';
let watchable = false;
if (app.commandLine.hasSwitch('manifest')) {
manifestJsonFileName = app.commandLine.getSwitchValue('manifest');
}
if (app.commandLine.hasSwitch('watch')) {
watchable = true;
}
let currentBinPath = path.join(__dirname.replace('app.asar', ''), 'bin');
let manifestJsonFilePath = path.join(currentBinPath, manifestJsonFileName);
// if watch is enabled lets change the path
if (watchable) {
currentBinPath = path.join(__dirname, '../../'); // go to project directory
manifestJsonFilePath = path.join(currentBinPath, manifestJsonFileName);
}
// handle macOS events for opening the app with a file, etc
app.on('will-finish-launching', () => {
app.on('open-file', (evt, file) => {
evt.preventDefault();
launchFile = file;
});
app.on('open-url', (evt, url) => {
evt.preventDefault();
launchUrl = url;
});
});
const manifestJsonFile = require(manifestJsonFilePath);
if (manifestJsonFile.singleInstance || manifestJsonFile.aspCoreBackendPort) {
const mainInstance = app.requestSingleInstanceLock();
app.on('second-instance', (events, args = []) => {
args.forEach((parameter) => {
const words = parameter.split('=');
if (words.length > 1) {
app.commandLine.appendSwitch(words[0].replace('--', ''), words[1]);
} else {
app.commandLine.appendSwitch(words[0].replace('--', ''));
}
});
const windows = BrowserWindow.getAllWindows();
if (windows.length) {
if (windows[0].isMinimized()) {
windows[0].restore();
}
windows[0].focus();
}
});
if (!mainInstance) {
app.quit();
}
}
app.on('ready', () => {
// Fix ERR_UNKNOWN_URL_SCHEME using file protocol
// https://github.com/electron/electron/issues/23757
protocol.registerFileProtocol('file', (request, callback) => {
const pathname = request.url.replace('file:///', '');
callback(pathname);
});
if (isSplashScreenEnabled()) {
startSplashScreen();
}
// Added default port as configurable for port restricted environments.
let defaultElectronPort = 8000;
if (manifestJsonFile.electronPort) {
defaultElectronPort = manifestJsonFile.electronPort;
}
// hostname needs to be localhost, otherwise Windows Firewall will be triggered.
portscanner.findAPortNotInUse(defaultElectronPort, 65535, 'localhost', function (error, port) {
console.log('Electron Socket IO Port: ' + port);
startSocketApiBridge(port);
});
});
app.on('quit', async (event, exitCode) => {
await server.close();
apiProcess.kill();
});
function isSplashScreenEnabled() {
if (manifestJsonFile.hasOwnProperty('splashscreen')) {
if (manifestJsonFile.splashscreen.hasOwnProperty('imageFile')) {
return Boolean(manifestJsonFile.splashscreen.imageFile);
}
}
return false;
}
function startSplashScreen() {
let imageFile = path.join(currentBinPath, manifestJsonFile.splashscreen.imageFile);
imageSize(imageFile, (error, dimensions) => {
if (error) {
console.log(`load splashscreen error:`);
console.error(error);
throw new Error(error.message);
}
splashScreen = new BrowserWindow({
width: dimensions.width,
height: dimensions.height,
transparent: true,
center: true,
frame: false,
closable: false,
resizable: false,
skipTaskbar: true,
alwaysOnTop: true,
show: true,
});
splashScreen.setIgnoreMouseEvents(true);
app.once('browser-window-created', () => {
splashScreen.destroy();
});
const loadSplashscreenUrl = path.join(__dirname, 'splashscreen', 'index.html') + '?imgPath=' + imageFile;
splashScreen.loadURL('file://' + loadSplashscreenUrl);
splashScreen.once('closed', () => {
splashScreen = null;
});
});
}
function startSocketApiBridge(port) {
// instead of 'require('socket.io')(port);' we need to use this workaround
// otherwise the Windows Firewall will be triggered
server = require('http').createServer();
const { Server } = require('socket.io');
io = new Server({
pingTimeout: 60000, // in ms, default is 5000
pingInterval: 10000, // in ms, default is 25000
});
io.attach(server);
server.listen(port, 'localhost');
server.on('listening', function () {
console.log('Electron Socket started on port %s at %s', server.address().port, server.address().address);
// Now that socket connection is established, we can guarantee port will not be open for portscanner
if (watchable) {
startAspCoreBackendWithWatch(port);
} else {
startAspCoreBackend(port);
}
});
// prototype
app['mainWindowURL'] = '';
app['mainWindow'] = null;
// @ts-ignore
io.on('connection', (socket) => {
socket.on('disconnect', function (reason) {
console.log('Got disconnect! Reason: ' + reason);
try {
if (hostHook) {
const hostHookScriptFilePath = path.join(__dirname, 'ElectronHostHook', 'index.js');
delete require.cache[require.resolve(hostHookScriptFilePath)];
hostHook = undefined;
}
} catch (error) {
console.error(error.message);
}
});
if (global['electronsocket'] === undefined) {
global['electronsocket'] = socket;
global['electronsocket'].setMaxListeners(0);
}
console.log(
'ASP.NET Core Application connected...',
'global.electronsocket',
global['electronsocket'].id,
new Date()
);
if (appApi === undefined) appApi = require('./api/app')(socket, app);
if (browserWindows === undefined) browserWindows = require('./api/browserWindows')(socket, app);
if (commandLine === undefined) commandLine = require('./api/commandLine')(socket, app);
if (autoUpdater === undefined) autoUpdater = require('./api/autoUpdater')(socket);
if (ipc === undefined) ipc = require('./api/ipc')(socket);
if (menu === undefined) menu = require('./api/menu')(socket);
if (dialogApi === undefined) dialogApi = require('./api/dialog')(socket);
if (notification === undefined) notification = require('./api/notification')(socket);
if (tray === undefined) tray = require('./api/tray')(socket);
if (webContents === undefined) webContents = require('./api/webContents')(socket);
if (globalShortcut === undefined) globalShortcut = require('./api/globalShortcut')(socket);
if (shellApi === undefined) shellApi = require('./api/shell')(socket);
if (screen === undefined) screen = require('./api/screen')(socket);
if (clipboard === undefined) clipboard = require('./api/clipboard')(socket);
if (browserView === undefined) browserView = require('./api/browserView').browserViewApi(socket);
if (powerMonitor === undefined) powerMonitor = require('./api/powerMonitor')(socket);
if (nativeTheme === undefined) nativeTheme = require('./api/nativeTheme')(socket);
if (dock === undefined) dock = require('./api/dock')(socket);
socket.on('register-app-open-file-event', (id) => {
global['electronsocket'] = socket;
app.on('open-file', (event, file) => {
event.preventDefault();
global['electronsocket'].emit('app-open-file' + id, file);
});
if (launchFile) {
global['electronsocket'].emit('app-open-file' + id, launchFile);
}
});
socket.on('register-app-open-url-event', (id) => {
global['electronsocket'] = socket;
app.on('open-url', (event, url) => {
event.preventDefault();
global['electronsocket'].emit('app-open-url' + id, url);
});
if (launchUrl) {
global['electronsocket'].emit('app-open-url' + id, launchUrl);
}
});
try {
const hostHookScriptFilePath = path.join(__dirname, 'ElectronHostHook', 'index.js');
if (isModuleAvailable(hostHookScriptFilePath) && hostHook === undefined) {
const { HookService } = require(hostHookScriptFilePath);
hostHook = new HookService(socket, app);
hostHook.onHostReady();
}
} catch (error) {
console.error(error.message);
}
});
}
function isModuleAvailable(name) {
try {
require.resolve(name);
return true;
} catch (e) {}
return false;
}
function startAspCoreBackend(electronPort) {
if (manifestJsonFile.aspCoreBackendPort) {
startBackend(manifestJsonFile.aspCoreBackendPort);
} else {
// hostname needs to be localhost, otherwise Windows Firewall will be triggered.
portscanner.findAPortNotInUse(electronPort + 1, 65535, 'localhost', function (error, electronWebPort) {
startBackend(electronWebPort);
});
}
function startBackend(aspCoreBackendPort) {
console.log('ASP.NET Core Port: ' + aspCoreBackendPort);
loadURL = `http://localhost:${aspCoreBackendPort}`;
const parameters = [
getEnvironmentParameter(),
`/electronPort=${electronPort}`,
`/electronWebPort=${aspCoreBackendPort}`,
];
let binaryFile = manifestJsonFile.executable;
const os = require('os');
if (os.platform() === 'win32') {
binaryFile = binaryFile + '.exe';
}
let binFilePath = path.join(currentBinPath, binaryFile);
var options = { cwd: currentBinPath };
apiProcess = cProcess(binFilePath, parameters, options);
apiProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data.toString()}`);
});
}
}
function startAspCoreBackendWithWatch(electronPort) {
if (manifestJsonFile.aspCoreBackendPort) {
startBackend(manifestJsonFile.aspCoreBackendPort);
} else {
// hostname needs to be localhost, otherwise Windows Firewall will be triggered.
portscanner.findAPortNotInUse(electronPort + 1, 65535, 'localhost', function (error, electronWebPort) {
startBackend(electronWebPort);
});
}
function startBackend(aspCoreBackendPort) {
console.log('ASP.NET Core Watch Port: ' + aspCoreBackendPort);
loadURL = `http://localhost:${aspCoreBackendPort}`;
const parameters = [
'watch',
'run',
getEnvironmentParameter(),
`/electronPort=${electronPort}`,
`/electronWebPort=${aspCoreBackendPort}`,
];
var options = {
cwd: currentBinPath,
env: process.env,
};
apiProcess = cProcess('dotnet', parameters, options);
apiProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data.toString()}`);
});
}
}
function getEnvironmentParameter() {
if (manifestJsonFile.environment) {
return '--environment=' + manifestJsonFile.environment;
}
return '';
}