forked from HadoukenIO/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
669 lines (533 loc) · 21 KB
/
index.js
File metadata and controls
669 lines (533 loc) · 21 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
/*
Copyright 2017 OpenFin Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
index.js
*/
// built\-in modules
let fs = require('fs');
let path = require('path');
let electron = require('electron');
let app = electron.app; // Module to control application life.
let BrowserWindow = electron.BrowserWindow;
let crashReporter = electron.crashReporter;
let dialog = electron.dialog;
let globalShortcut = electron.globalShortcut;
let ipc = electron.ipcMain;
// npm modules
let _ = require('underscore');
let minimist = require('minimist');
// local modules
let Application = require('./src/browser/api/application.js').Application;
let System = require('./src/browser/api/system.js').System;
let Window = require('./src/browser/api/window.js').Window;
let apiProtocol = require('./src/browser/api_protocol');
let socketServer = require('./src/browser/transports/socket_server').server;
let authenticationDelegate = require('./src/browser/authentication_delegate.js');
let convertOptions = require('./src/browser/convert_options.js');
let coreState = require('./src/browser/core_state.js');
let webRequestHandlers = require('./src/browser/web_request_handler.js');
let errors = require('./src/common/errors.js');
import ofEvents from './src/browser/of_events';
import {
portDiscovery
} from './src/browser/port_discovery';
import {
default as connectionManager,
meshEnabled,
getMeshUuid,
isMeshEnabledRuntime
} from './src/browser/connection_manager';
import * as log from './src/browser/log';
import {
applyAllRemoteSubscriptions
} from './src/browser/remote_subscriptions';
import route from './src/common/route';
// locals
let firstApp = null;
let rvmBus;
let otherInstanceRunning = false;
let appIsReady = false;
const deferredLaunches = [];
const USER_DATA = app.getPath('userData');
app.on('child-window-created', function(parentId, childId, childOptions) {
if (!coreState.addChildToWin(parentId, childId)) {
console.warn('failed to add');
}
Window.create(childId, childOptions);
});
app.on('select-client-certificate', function(event, webContents, url, list, callback) {
// No need to choose if there are
// fewer than two certificates
if (list.length < 2) {
return;
}
event.preventDefault();
let clientCertDialog = new BrowserWindow({
width: 450,
height: 280,
show: false,
frame: false,
skipTaskbar: true,
resizable: false,
alwaysOnTop: true,
webPreferences: {
nodeIntegration: true,
openfinIntegration: false
}
});
let ipcUuid = app.generateGUID();
let ipcTopic = 'client-certificate-selection/' + ipcUuid;
function resolve(cert) {
cleanup();
callback(cert);
}
function cleanup() {
ipc.removeListener(ipcTopic, onClientCertificateSelection);
clientCertDialog.removeListener('closed', onClosed);
}
function onClientCertificateSelection(event, index) {
if (index >= 0 && index < list.length) {
resolve(list[index]);
clientCertDialog.close();
}
}
function onClosed() {
resolve({}); // NOTE: Will cause a page load failure
}
ipc.on(ipcTopic, onClientCertificateSelection);
clientCertDialog.on('closed', onClosed);
let params = '?url=' + encodeURIComponent(url) + '&uuid=' + encodeURIComponent(ipcUuid) + '&certs=' + encodeURIComponent(_.pluck(list, 'issuerName'));
clientCertDialog.loadURL(path.resolve(__dirname, 'src', 'certificate', 'index.html') + params);
});
portDiscovery.on('runtime/launched', (portInfo) => {
//check if the ports match:
const myPortInfo = coreState.getSocketServerState();
const myUuid = getMeshUuid();
log.writeToLog('info', `Port discovery message received ${JSON.stringify(portInfo)}`);
//TODO include old runtimes in the determination.
if (meshEnabled && portInfo.port !== myPortInfo.port && isMeshEnabledRuntime(portInfo)) {
connectionManager.connectToRuntime(myUuid, portInfo).then((runtimePeer) => {
//one connected we broadcast our port discovery message.
staggerPortBroadcast(myPortInfo);
log.writeToLog('info', `Connected to runtime ${JSON.stringify(runtimePeer.portInfo)}`);
applyAllRemoteSubscriptions(runtimePeer);
}).catch(err => {
log.writeToLog('info', `Failed to connect to runtime ${JSON.stringify(portInfo)}, ${JSON.stringify(errors.errorToPOJO(err))}`);
});
}
});
includeFlashPlugin();
// Opt in to launch crash reporter
initializeCrashReporter(coreState.argo);
// Has a local copy of an app config
if (coreState.argo['local-startup-url']) {
try {
let localConfig = JSON.parse(fs.readFileSync(coreState.argo['local-startup-url']));
if (typeof localConfig['devtools_port'] === 'number') {
console.log('remote-debugging-port:', localConfig['devtools_port']);
app.commandLine.appendSwitch('remote-debugging-port', localConfig['devtools_port'].toString());
}
} catch (err) {
console.error(err);
}
}
const handleDelegatedLaunch = function(commandLine) {
let otherInstanceArgo = minimist(commandLine);
const socketServerState = coreState.getSocketServerState();
const portInfo = portDiscovery.getPortInfoByArgs(otherInstanceArgo, socketServerState.port);
initializeCrashReporter(otherInstanceArgo);
// delegated args from a second instance
launchApp(otherInstanceArgo, false);
// Will queue if server is not ready.
portDiscovery.broadcast(portInfo);
// command line flag --delete-cache-on-exit
rvmCleanup(otherInstanceArgo);
return true;
};
app.on('chrome-browser-process-created', function() {
otherInstanceRunning = app.makeSingleInstance((commandLine) => {
if (appIsReady) {
return handleDelegatedLaunch(commandLine);
} else {
deferredLaunches.push(commandLine);
return true;
}
});
if (otherInstanceRunning) {
if (appIsReady) {
deleteProcessLogfile(true);
}
app.commandLine.appendArgument('noerrdialogs');
process.argv.push('--noerrdialogs');
app.quit();
return;
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
appIsReady = true;
if (otherInstanceRunning) {
deleteProcessLogfile(true);
app.quit();
return;
}
app.registerNamedCallback('convertToElectron', convertOptions.convertToElectron);
app.registerNamedCallback('getWindowOptionsById', coreState.getWindowOptionsById);
app.vlog(1, 'process.versions: ' + JSON.stringify(process.versions, null, 2));
rvmBus = require('./src/browser/rvm/rvm_message_bus').rvmMessageBus;
app.allowNTLMCredentialsForAllDomains(true);
if (process.platform === 'win32') {
let integrityLevel = app.getIntegrityLevel();
System.log('info', `Runtime integrity level of the app: ${integrityLevel}`);
}
rotateLogs(coreState.argo);
//Once we determine we are the first instance running we setup the API's
//Create the new Application.
initServer();
webRequestHandlers.initHandlers();
launchApp(coreState.argo, true);
registerShortcuts();
//subscribe to auth requests:
app.on('login', (event, webContents, request, authInfo, callback) => {
let browserWindow = webContents.getOwnerBrowserWindow();
let ofWindow = coreState.getWinById(browserWindow.id).openfinWindow;
let identity = {
name: ofWindow._options.name,
uuid: ofWindow._options.uuid
};
const windowEvtName = route.window('auth-requested', identity.uuid, identity.name);
const appEvtName = route.application('window-auth-requested', identity.uuid);
authenticationDelegate.addPendingAuthRequests(identity, authInfo, callback);
if (ofEvents.listeners(windowEvtName).length < 1 && ofEvents.listeners(appEvtName).length < 1) {
authenticationDelegate.createAuthUI(identity);
} else {
ofEvents.emit(windowEvtName, {
topic: 'window',
type: 'auth-requested',
uuid: identity.uuid,
name: identity.name,
authInfo: authInfo
});
ofEvents.emit(appEvtName, {
topic: 'application',
type: 'window-auth-requested',
uuid: identity.uuid,
name: identity.name,
authInfo: authInfo
});
}
event.preventDefault();
});
// native code in AtomRendererClient::ShouldFork
app.on('enable-chromium-renderer-fork', event => {
// @TODO it should be an option for app, not runtime->arguments
if (coreState.argo['enable-chromium-renderer-fork']) {
app.vlog(1, 'applying Chromium renderer fork');
event.preventDefault();
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'download-asset', 'progress'), payload => {
if (payload) {
ofEvents.emit(route.system(`asset-download-progress-${payload.downloadId}`), {
totalBytes: payload.totalBytes,
downloadedBytes: payload.downloadedBytes
});
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'download-asset', 'error'), payload => {
if (payload) {
ofEvents.emit(route.system(`asset-download-error-${payload.downloadId}`), {
reason: payload.error,
err: errors.errorToPOJO(new Error(payload.error))
});
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'download-asset', 'complete'), payload => {
if (payload) {
ofEvents.emit(route.system(`asset-download-complete-${payload.downloadId}`), {
path: payload.path
});
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'application', 'runtime-download-progress'), payload => {
if (payload) {
ofEvents.emit(route.system(`runtime-download-progress-${ payload.downloadId }`), payload);
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'application', 'runtime-download-error'), payload => {
if (payload) {
ofEvents.emit(route.system(`runtime-download-error-${ payload.downloadId }`), {
reason: payload.error,
err: errors.errorToPOJO(new Error(payload.error))
});
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'application', 'runtime-download-complete'), payload => {
if (payload) {
ofEvents.emit(route.system(`runtime-download-complete-${ payload.downloadId }`), {
path: payload.path
});
}
});
// handle deferred launches
deferredLaunches.forEach((commandLine) => {
handleDelegatedLaunch(commandLine);
});
deferredLaunches.length = 0;
}); // end app.ready
function staggerPortBroadcast(myPortInfo) {
setTimeout(() => {
try {
portDiscovery.broadcast(myPortInfo);
} catch (e) {
log.writeToLog('info', e);
}
}, Math.floor(Math.random() * 50));
}
function includeFlashPlugin() {
let pluginName;
switch (process.platform) {
case 'win32':
pluginName = 'pepflashplayer.dll';
break;
case 'darwin':
pluginName = 'PepperFlashPlayer.plugin';
break;
case 'linux':
pluginName = 'libpepflashplayer.so';
break;
default:
pluginName = '';
break;
}
if (pluginName) {
app.commandLine.appendSwitch('ppapi-flash-path', path.join(process.resourcesPath, 'plugins', 'flash', pluginName));
}
}
function initializeCrashReporter(argo) {
if (!isInDiagnosticsMode(argo)) {
return;
}
const configUrl = argo['startup-url'] || argo['config'];
const diagnosticMode = argo['diagnostics'] || false;
crashReporter.startOFCrashReporter({ diagnosticMode, configUrl });
}
function rotateLogs(argo) {
// only keep the 7 most recent logfiles
System.getLogList((err, files) => {
if (err) {
System.log('error', `logfile error: ${err}`);
} else {
files.filter(file => {
return !(file.name === 'debug.log' || file.name.indexOf('debugp') === 0);
}).sort((a, b) => {
return (b.date - a.date);
}).slice(6).forEach(file => {
let filepath = path.join(USER_DATA, file.name);
fs.unlink(filepath, err => {
if (err) {
System.log('error', `cannot delete logfile: ${filepath}`);
} else {
System.log('info', `deleting logfile: ${filepath}`);
}
});
});
}
});
app.reopenLogfile();
// delete debugp????.log file
deleteProcessLogfile(false);
rvmCleanup(argo);
}
function deleteProcessLogfile(closeLogfile) {
let filename = app.getProcessLogfileName();
if (!filename) {
System.log('info', 'process logfile name is undefined');
System.log('info', coreState.argo);
return;
}
let filepath = path.join(USER_DATA, filename);
if (closeLogfile) {
app.closeLogfile();
}
try {
fs.unlinkSync(filepath);
System.log('info', `deleting process logfile: ${filepath}`);
} catch (e) {
System.log('error', `cannot delete process logfile: ${filepath}`);
}
}
function rvmCleanup(argo) {
let deleteCacheOnExitFlag = 'delete-cache-on-exit';
// notify RVM with necessary information to clean up cache folders on exit when we're called with --delete-cache-on-exit
let deleteCacheOnExit = argo[deleteCacheOnExitFlag];
if (deleteCacheOnExit) {
System.deleteCacheOnExit(() => {
console.log('Successfully sent a delete-cache-on-exit message to the RVM.');
}, (err) => {
console.log(err);
});
}
}
function initServer() {
let attemptedHardcodedPort = false;
apiProtocol.initApiHandlers();
socketServer.on('server/error', function(err) {
// Guard against non listen errors and infinite retries.
if (err && err.syscall === 'listen' && !attemptedHardcodedPort) {
// Assuming connection issue. Bind on any available port
console.log('Assuming connection issue. Bind on any available port');
attemptedHardcodedPort = true;
socketServer.start(0);
}
});
socketServer.on('server/open', function(port) {
console.log('Opened on', port);
portDiscovery.broadcast(portDiscovery.getPortInfoByArgs(coreState.argo, port));
});
socketServer.on('connection/message', function(id, message) {
console.log('Receieved message', message);
});
return socketServer;
}
//TODO: this function actually does more than just launch apps, it will initiate the web socket server and
//is essential for proper runtime startup and adapter connectivity. we want to split into smaller independent parts.
//please see the discussion on https://github.com/openfin/runtime-core/pull/194
function launchApp(argo, startExternalAdapterServer) {
if (isInDiagnosticsMode(argo)) {
log.setToVerbose();
}
convertOptions.fetchOptions(argo, configuration => {
const {
configUrl,
configObject,
configObject: { licenseKey }
} = configuration;
coreState.setManifest(configUrl, configObject);
if (argo['user-app-config-args']) {
const tempUrl = configObject['startup_app'].url;
const delimiter = tempUrl.indexOf('?') < 0 ? '?' : '&';
configObject['startup_app'].url = `${tempUrl}${delimiter}${argo['user-app-config-args']}`;
}
const startupAppOptions = convertOptions.getStartupAppOptions(configObject);
const uuid = startupAppOptions && startupAppOptions.uuid;
const ofApp = Application.wrap(uuid);
const ofManifestUrl = ofApp && ofApp._configUrl;
const isRunning = Application.isRunning(ofApp);
// this ensures that external connections that start the runtime can do so without a main window
let successfulInitialLaunch = true;
if (startupAppOptions && (!isRunning || ofManifestUrl !== configUrl)) {
//making sure that if a window is present we set the window name === to the uuid as per 5.0
startupAppOptions.name = uuid;
successfulInitialLaunch = initFirstApp(configObject, configUrl, licenseKey);
} else if (uuid) {
Application.run({
uuid,
name: uuid
},
'',
argo['user-app-config-args']
);
}
if (startExternalAdapterServer && successfulInitialLaunch) {
coreState.setStartManifest(configUrl, configObject);
socketServer.start(configObject['websocket_port'] || 9696);
}
app.emit('synth-desktop-icon-clicked', {
mouse: System.getMousePosition(),
tickCount: app.getTickCount(),
uuid
});
}, error => {
log.writeToLog(1, error, true);
if (!coreState.argo['noerrdialogs']) {
dialog.showErrorBox('Fatal Error', `${error}`);
}
app.quit();
});
}
function initFirstApp(configObject, configUrl, licenseKey) {
let startupAppOptions;
let successfulLaunch = false;
try {
startupAppOptions = convertOptions.getStartupAppOptions(configObject);
// Needs proper configs
firstApp = Application.create(startupAppOptions, configUrl);
coreState.setLicenseKey({ uuid: startupAppOptions.uuid }, licenseKey);
Application.run({
uuid: firstApp.uuid
});
firstApp.mainWindow.on('closed', function() {
firstApp = null;
});
successfulLaunch = true;
} catch (error) {
log.writeToLog(1, error, true);
if (rvmBus) {
rvmBus.publish({
topic: 'application',
action: 'hide-splashscreen',
sourceUrl: configUrl
});
}
if (!coreState.argo['noerrdialogs']) {
const srcMsg = error ? error.message : '';
const errorMessage = startupAppOptions.loadErrorMessage || `There was an error loading the application: ${ srcMsg }`;
dialog.showErrorBox('Fatal Error', errorMessage);
}
if (coreState.shouldCloseRuntime()) {
_.defer(() => {
app.quit();
});
}
}
return successfulLaunch;
}
function registerShortcuts() {
app.on('browser-window-focus', (event, browserWindow) => {
const windowOptions = coreState.getWindowOptionsById(browserWindow.id);
const accelerator = windowOptions && windowOptions.accelerator || {};
const webContents = browserWindow.webContents;
if (accelerator.zoom) {
const zoom = increment => { return () => { webContents.send('zoom', { increment }); }; };
globalShortcut.register('CommandOrControl+0', zoom(0));
globalShortcut.register('CommandOrControl+=', zoom(+1));
globalShortcut.register('CommandOrControl+Plus', zoom(+1));
globalShortcut.register('CommandOrControl+-', zoom(-1));
globalShortcut.register('CommandOrControl+_', zoom(-1));
}
if (accelerator.devtools) {
const devtools = () => { webContents.openDevTools(); };
globalShortcut.register('CommandOrControl+Shift+I', devtools);
}
if (accelerator.reload) {
const reload = () => { webContents.reload(); };
globalShortcut.register('F5', reload);
globalShortcut.register('CommandOrControl+R', reload);
}
if (accelerator.reloadIgnoringCache) {
const reloadIgnoringCache = () => { webContents.reloadIgnoringCache(); };
globalShortcut.register('Shift+F5', reloadIgnoringCache);
globalShortcut.register('CommandOrControl+Shift+R', reloadIgnoringCache);
}
});
const unhookShortcuts = (event, browserWindow) => {
globalShortcut.unregisterAll();
};
app.on('browser-window-closed', unhookShortcuts);
app.on('browser-window-blur', unhookShortcuts);
}
function isInDiagnosticsMode(argo) {
return !!(argo['diagnostics'] || argo['enable-crash-reporting']);
}