This repository has been archived by the owner on Sep 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
570 lines (470 loc) · 15.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
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
'use strict';
// imports
const nomnom = require('nomnom');
const http = require('http');
const path = require('path');
const url = require('url');
const fs = require('fs');
const os = require('os');
const mime = require('mime');
const yaml = require('js-yaml');
const io = require('socket.io');
const ChalkAnimation = require('chalk-animation');
// keep a global reference of certain objects to stop them getting garbage collected
let win, powersave;
// load package and config
const pkg = require('./package.json');
const ultimirror = {};
// make ultimirror framework available globally
global.ultimirror = ultimirror;
// initialise framework variables
ultimirror.sys = {
rootDir: __dirname,
name: pkg.name,
version: pkg.version
};
// define function to get full file path
ultimirror.path = function (pathItems) {
pathItems.unshift(
ultimirror.sys.rootDir, 'app'
);
return path.join.apply(this, pathItems);
};
// load utility functions
ultimirror.fn = require(
ultimirror.path(
[
'js', 'ultimirror', 'fn.js'
]
)
);
ultimirror.moduleInstances = {};
// define command line arguments
const staticConfigOptions = {
configFile: {
abbr: 'c',
default: 'default',
help: 'Load a specified config file'
},
layout: {
abbr: 'l',
help: 'Show a specified layout'
},
settings: {
abbr: 's',
flag: true,
default: false,
help: 'Show settings page instead of mirror UI'
},
webInspector: {
abbr: 'wi',
flag: true,
default: false,
help: 'Show web inspector'
},
edgePadding: {
abbr: 'e',
choices: [
'none',
'small',
'medium',
'large'
],
default: 'medium',
help: 'Amount of padding between mirror UI and edge of screen'
},
noAutoChange: {
abbr: 'na',
flag: true,
default: false,
help: 'No auto changing of layouts'
},
mute: {
abbr: 'm',
flag: true,
default: false,
help: 'No audio'
},
notOnTop: {
abbr: 'n',
flag: true,
default: false,
help: 'Do not force the window to be on top of other windows'
},
version: {
abbr: 'v',
flag: true,
help: 'Print version and exit',
callback: function () {
return `${ultimirror.sys.name} ${ultimirror.sys.version}`;
}
},
windowed: {
abbr: 'w',
flag: true,
default: false,
help: 'Open windowed instead of fullscreen'
},
showWindow: {
abbr: 's',
default: true,
help: 'Show the app GUI in a window (if disabled, this will only be accessible via a web browser)'
},
zoom: {
abbr: 'z',
default: 1,
help: 'Zoom factor'
},
port: {
abbr: 'p',
default: 8080,
help: 'Local port number that interface is served from'
}
};
// parse command line options
var configCommandLine = nomnom
.options(
staticConfigOptions
)
.parse(
process.argv.slice(1)
);
// load base config
var baseConfigFile = path.join(
ultimirror.sys.rootDir, 'base.config'
);
try {
ultimirror.base = yaml.safeLoad(
fs.readFileSync(
baseConfigFile,
'utf8'
)
);
} catch (e) {
ultimirror.fn.log.error(
`Could not load ${baseConfigFile}`
);
process.exit(1);
}
// load specified (or default) config file
var configFile = ultimirror.path(
[
'config', `${configCommandLine['configFile']}.config`
]
);
try {
if (configCommandLine['configFile'] !== 'default') {
ultimirror.fn.log.info(
`Loading ${configFile}...`
);
}
let configData = yaml.safeLoad(
fs.readFileSync(
configFile,
'utf8'
)
);
ultimirror.config = configData.config;
ultimirror.moduleConfig = configData.moduleConfig;
} catch (e) {
ultimirror.fn.log.error(
`Could not load ${configFile}`
);
process.exit(1);
}
// merge static and command line config values
for (var key in configCommandLine) {
if (['0', '_'].indexOf(key) === -1) {
if (typeof staticConfigOptions[key] === 'undefined') {
// command line value doesn't exist in static config, insert it
ultimirror.config[key] = configCommandLine[key];
} else if (configCommandLine[key] !== staticConfigOptions[key].default) {
// overwrite static value
ultimirror.config[key] = configCommandLine[key];
}
}
}
// start serving interface via URL's
var server = http
.createServer(
function (request, response) {
// get the file
var filepath = decodeURI(
url.parse(request.url).pathname
);
if ((filepath === '/') || filepath.match(/^\/admin/)) {
filepath = '/admin.html';
} else if (filepath.match(/^\/mirror/)) {
filepath = '/mirror.html';
}
filepath = `./app${filepath}`;
var extname = path.extname(filepath),
contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.svg':
contentType = 'image/svg+xml';
break;
case '.png':
contentType = 'image/png';
break;
case '.ico':
contentType = 'image/x-icon';
break;
}
fs.readFile(filepath, function (error, content) {
if (error) {
ultimirror.fn.log.error(
error
);
}
if (error) {
if (error.code == 'ENOENT') {
response.writeHead(404, { 'Content-Type': contentType });
response.end('404', 'utf-8');
} else {
response.writeHead(500);
response.end(`Sorry, check with the site admin for error: ${error.code}\n`);
response.end();
}
} else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
)
.listen(
ultimirror.config.port
);
// make web contents available globally (for IPC)
global.ipc = io(
server,
{
transports: ['websocket', 'polling']
}
);
// set up IPC connection with the browser...
ipc.on(
'connection',
function (socket) {
// on initialise signal from browser, initialise backend elements
socket.on(
'initialise',
function (context) {
// tell mandatory modules we are ready
for (var i in ultimirror.base.mandatoryModules) {
var moduleId = 'default',
moduleKey = `${ultimirror.base.mandatoryModules[i]}_${moduleId}`;
ultimirror.moduleInstances[moduleKey]
.load()
.then(
function () {
socket.emit(
'moduleInitialised',
{
moduleType: ultimirror.base.mandatoryModules[i],
moduleId: moduleId
}
);
}
);
}
// show intro screen?
if (!ultimirror.config.layout &&
(typeof ultimirror.moduleInstances['system_default'].config.showIntro === 'number') &&
(ultimirror.moduleInstances['system_default'].config.showIntro > 0)) {
// temporarily store original value, then set to intro layout
ultimirror.base.layout._mirror = ultimirror.base.layout.mirror;
ultimirror.base.layout.mirror = 'intro';
// set layout to change to the initial layout after the specified number of seconds
setTimeout(
function () {
// restore temporary value and clean up storage
ultimirror.base.layout.mirror = ultimirror.base.layout._mirror;
delete ultimirror.base.layout._mirror;
// update value to force layout view to change
ultimirror.fn.update(
['layout', 'mirror'],
ultimirror.base.layout.mirror
);
// set up auto layout switching
ultimirror.fn.layout.autoChangeDisplay();
},
(ultimirror.moduleInstances['system_default'].config.showIntro * 1000)
);
} else {
// no intro screen, set up auto layout switching immediately
ultimirror.fn.layout.autoChangeDisplay();
}
// add context ultimirror into object
ultimirror.context = context;
// send data to the web page context
socket.emit(
'setData',
{
keyPath: ['ultimirror'],
data: ultimirror
}
);
}
);
// on initialiseModuleInstance signal from browser, initialise the module on the backend
socket.on(
'initialiseModuleInstance',
function (module) {
var moduleKey = `${module.moduleType}_${module.moduleId}`;
// initialise module instance if not already initialised
if (ultimirror.moduleInstances[moduleKey] === undefined) {
ultimirror.fn.module
.load(
module
)
.then(
function (moduleInstance) {
// set module instance into the backend datastore
ultimirror.moduleInstances[moduleKey] = moduleInstance;
// send the module instance back to the browser
socket.emit(
'setData',
{
keyPath: ['ultimirror', 'moduleInstances'],
data: ultimirror.moduleInstances
}
);
// now load the module data
ultimirror.fn.module.moduleReady(socket, moduleKey);
}
);
} else {
// load the module data
ultimirror.fn.module.moduleReady(socket, moduleKey);
}
}
);
// set up actions forwarder
socket.on(
'action',
function (data) {
if ((typeof data.fn === 'object') && (data.fn.length > 0)) {
// attempt to call function in base environment
var fn = ultimirror;
for (var f in data.fn) {
fn = fn[data.fn[f]];
}
if (typeof fn === 'function') {
fn.apply(
ultimirror,
data.params
);
}
} else if (data.moduleType && data.moduleId) {
// attempt to call action on module
var moduleKey = `${data.moduleType}_${data.moduleId}`;
// call function on module if it exists
if (ultimirror.moduleInstances[moduleKey] && (typeof ultimirror.moduleInstances[moduleKey][data.fn] === 'function')) {
ultimirror.moduleInstances[moduleKey][data.fn].apply(
ultimirror.moduleInstances[moduleKey],
data.params
);
}
}
}
);
}
);
// show welcome message
ChalkAnimation.rainbow(
'\n' +
`${ultimirror.sys.name} (v${ultimirror.sys.version})` +
(
ultimirror.config.debug ?
' (debug enabled)':
''
) +
'\n'
).start();
// warn if no window will be opened
if (!ultimirror.config.showWindow) {
ultimirror.fn.log.info(
'!! Note: Ultimirror window is disabled in the config, visit the URL below to operate !!'
);
}
// initialise mandatory modules
for (var i in ultimirror.base.mandatoryModules) {
var moduleId = 'default',
moduleKey = `${ultimirror.base.mandatoryModules[i]}_${moduleId}`;
// initialise module instance if not already initialised
if (ultimirror.moduleInstances[moduleKey] === undefined) {
ultimirror.fn.module
.load(
{
moduleType: ultimirror.base.mandatoryModules[i],
moduleId: moduleId
}
)
.then(
function (moduleInstance) {
// store module instance in backend datastore
ultimirror.moduleInstances[moduleKey] = moduleInstance;
// tell module to load its data
ultimirror.moduleInstances[moduleKey]
.load()
.then(
function () {
// TODO: do something here?
}
);
}
);
}
}
// create and show app window?
if (ultimirror.config.showWindow) {
const electron = require('electron');
const app = electron.app;
if (!app) {
ultimirror.fn.log.error(
'Electron environment not found'
);
process.exit(1);
}
// observe app ready event
app.on(
'ready',
function () {
var obj = ultimirror.fn.createWindow();
// set created objects into global scope
win = obj.win;
powersave = obj.powersave;
}
);
// observe app all windows closed event
app.on(
'window-all-closed',
function () {
// on OS X, keep application active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
}
);
// observe app activate event
app.on(
'activate',
function () {
// recreate a window in the app when the dock icon is clicked and there are no other windows open
if (win === null) {
createWindow();
}
}
);
}