-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·479 lines (362 loc) · 12.4 KB
/
app.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
#!/usr/bin/env node
const dotenv = require('dotenv').config()
const envfile = require('envfile');
const child_process = require('child_process');
const { spawn } = require('child_process');
const fs = require('fs');
let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let debug = require('debug')('phantom-web:server');
let http = require('http');
let later = require('later');
let updateSchedule = later.parse.cron("0 3 * * *");
let updateTimer = later.setInterval(update, updateSchedule);
let os = require('os');
let ssdp = require("peer-ssdp");
let SERVER = os.type() + "/" + os.release() + " UPnP/1.1 famium/0.0.1";
let uuid = "6bd5eabd-b7c8-4f7b-ae6c-a30ccdeb5988";
let peer = ssdp.createPeer();
let ifaces = os.networkInterfaces();
const ssdpHeader = {
HOST: '239.255.255.250:1900',
EXT: '',
'CACHE-CONTROL': 'max-age=100',
LOCATION: "http://{{networkInterfaceAddress}}:3000/desc.xml",
SERVER: SERVER,
ST: "upnp:rootdevice",
USN: "uuid:" + uuid + "::upnp:rootdevice",
'BOOTID.UPNP.ORG': 1
};
/**
* handle peer ready event. This event will be emitted after `peer.start()` is called.
*/
let interval;
peer.on("ready",function(){
// hey were over here! echo echo echo echo
interval = setInterval(function(){
peer.alive(ssdpHeader);
}, 1000);
}).on("notify", function (headers, address) {
// do nothing we don't care
}).on("search", function (headers, address) {
// oh oh oh, yes we're hearing! we're over HERE!
peer.reply(ssdpHeader, address);
}).on("found", function (headers, address) {
// oh someone found us yay
}).on("close", function () {
console.log("ssdp connection closed");
}).start();
process.on('exit', function(){
clearInterval(interval);
// Close peer. Afer peer is closed the `close` event will be emitted.
peer.close();
});
let servers = [];
let config;
try {
config = require("./config.json");
} catch {
try {
config = require("./config.bak.json")
} catch {
config = { "servers": [] }
}
}
config = config.servers || [];
//config = require("./config.json").servers || [];
let currentVersion = JSON.parse( fs.readFileSync('./package.json', 'utf8') ).version;
let newVersion;
let updating = false;
console.log(`Current Version: ${currentVersion}`);
async function update() {
console.log("Updating phantom-web to latest version.");
currentVersion = JSON.parse( fs.readFileSync('./package.json', 'utf8') ).version;
child_process.execSync("git reset --hard");
child_process.exec("git pull", (error, stdout, stderr) => {
writeConfig()
newVersion = JSON.parse( fs.readFileSync('./package.json', 'utf8') ).version;
console.log(`New Version: ${newVersion}`);
if ( (currentVersion !== newVersion) ) {
updating = true;
console.log("Applying update.");
installUpdate().then(() => {
console.log("Update Applied.");
writeConfig().then( () => {
shutdown();
});
});
}
});
}
async function shutdown() {
// kill all running phantoms
if (servers.length) {
console.log("It's dawn the phantom's are ablaze.")
servers.forEach( (server, index) => {
server.kill('SIGHUP');
delete config[index].pid;
console.log(`Phantom ${index} died.`);
});
} else {
console.log("It's day time. No phantom's to slay.");
}
updateTimer.clear();
console.log("Update scheduler leashed.");
console.log("Stopping SSDP service.");
clearInterval(interval);
peer.close();
console.log("Goodbye.");
server.close();
//sometimes you just need to use a sledgehammer
setTimeout(()=> {
process.exit();
}, 1000);
}
async function installUpdate() {
console.log("Run npm install after update.");
child_process.execSync("npm install");
console.log("Fix file permissions after update.");
child_process.exec("sudo chown ubuntu:ubuntu ./ -R");
child_process.exec("sudo chmod 775 ./");
child_process.exec("sudo chmod +x app.js");
await sleep(500);
}
update().then(() => {
// downloads latest version of phantom
if (process.platform === "linux") {
// if a username and password for DWS have been provided in the env file the DWAgent will be installed.
if (process.env.DWS_USERNAME && process.env.DWS_PASSWORD) {
// just in case the dwagent install sh file exists, delete it so we get a fresh copy.
if (fs.existsSync(__dirname + '/dwagent_generic.sh')) {
child_process.execSync(`rm dwagent_generic.sh`);
}
// download the install sh file
child_process.execSync(`wget https://www.dwservice.net/download/dwagent_generic.sh`);
// if it hasn't already been installed
if (!fs.existsSync('/usr/share/dwagent/native/dwagent.desktop')) {
console.log("install attempted");
child_process.execSync(`sudo bash dwagent_generic.sh -silent user=${process.env.DWS_USERNAME} password=${process.env.DWS_PASSWORD} name=${process.env.DWS_NAME} logpath=xxxxx`);
}
// deletes the dws credentials after install as they won't be required again and we don't want them hanging around for someone to hoover up
let parsedFile = envfile.parse(fs.readFileSync('.env').toString());
console.log(parsedFile);
parsedFile.DWS_USERNAME = '';
parsedFile.DWS_PASSWORD = '';
fs.writeFileSync('./.env', envfile.stringify(parsedFile));
}
if (process.arch === "arm") {
child_process.execSync(`curl -u "azariah001:${process.env.GITHUB_KEY}" -s https://api.github.com/repos/jhead/phantom/releases | grep browser_download_url | grep 'arm${process.config.variables.arm_version}' | head -n 1 | cut -d '"' -f 4 | xargs wget -N`);
child_process.execSync(`cp phantom-linux-arm${process.config.variables.arm_version} phantom`);
} else {
// this github key has ZERO permissions. Exists only for accessing github public api to check what the latest release is for phantom.
child_process.execSync(`curl -u "azariah001:${process.env.GITHUB_KEY}" -s https://api.github.com/repos/jhead/phantom/releases | grep browser_download_url | grep 'linux' | head -n 1 | cut -d '"' -f 4 | xargs wget -N`);
child_process.execSync(`cp phantom-linux phantom`);
}
child_process.execSync("chmod u+x ./phantom");
}
console.log("Phantom Updated.")
}).then(() => {
if (!updating) {
config.forEach( (server, index) => {
if (!!server.auto && !server.pid) {
startServer(index);
}
});
}
});
let app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/**
* Get port from environment and store in Express.
*/
var port = 3000;
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
app.get('/', (req, res, next) => {
res.render('index', { title: 'Servers', servers: config, currentVersion: currentVersion, newVersion: newVersion || currentVersion });
});
app.get('/update', (req,res,next) => {
update();
res.redirect('/');
});
// provide SSDP service description file with servers current IP address.
app.get('/desc.xml', (req, res, next) => {
let ip;
Object.keys(ifaces).forEach(function (ifname) {
let alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
if (alias >= 1) {
// this single interface has multiple ipv4 addresses
//console.log(ifname + ':' + alias, iface.address);
} else {
// this interface has only one ipv4 adress
ip = iface.address;
}
++alias;
});
});
res.set('Content-Type', 'text/xml');
res.render('desc', { title: 'Servers', ip: ip });
});
app.get('/server/edit/:index', (req, res, next) => {
let phantomServer = config[req.params.index];
phantomServer.index = req.params.index;
res.render('edit', { title: 'Edit External Server', server: phantomServer, currentVersion: currentVersion, newVersion: newVersion || currentVersion })
});
app.post('/server/edit', (req, res, next) => {
config[req.body.server.index].name = req.body.server.name;
config[req.body.server.index].address = req.body.server.address;
config[req.body.server.index].port = req.body.server.port;
config[req.body.server.index].auto = req.body.server.auto;
writeConfig();
if (!!config[req.body.server.index].pid) {
stopServer(req.body.server.index);
startServer(req.body.server.index);
}
res.redirect('/');
});
app.get('/server/create', (req,res, next) => {
res.render('create', { title: 'Add External Server', currentVersion: currentVersion, newVersion: newVersion || currentVersion });
});
app.post('/server/create', createServer, (req, res, next) => {
res.redirect('/');
});
app.get('/server/delete/:index', (req, res, next) => {
if (!!config[req.params.index].pid) {
stopServer(req.params.index);
}
config.splice(req.params.index, 1);
writeConfig();
res.redirect('/');
});
app.get('/server/start/:index', (req, res, next) => {
if (!config[req.params.index].pid) {
startServer(req.params.index);
} else {
stopServer(req.params.index);
startServer(req.params.index);
}
res.redirect('/');
});
app.get('/server/stop/:index', (req, res, next) => {
stopServer(req.params.index);
res.redirect('/');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
function startServer(index) {
try {
servers.push( spawn("./phantom", ["-server", `${config[index].address}:${config[index].port}`, "-workers", `${process.env.THREADS || 4}`] ) );
config[index].pid = servers[servers.length - 1].pid;
console.log(`${config[index].name} launched`);
} catch (e) {
console.log(JSON.stringify(e, "", 4));
}
servers[servers.length - 1].on('close', (code, signal) => {
console.log(`Server terminated due to receipt of signal ${signal}`);
});
}
function stopServer(index) {
servers.forEach( (server, i) => {
if (server.pid === config[index].pid) {
console.log(`Stopping ${config[index].name} server.`);
server.kill('SIGHUP');
servers.slice(i, 1);
delete config[index].pid;
}
});
}
function createServer(req, res, next) {
console.log(`Create: ${JSON.stringify(req.body.server, "", 4)}`);
config.push(req.body.server);
writeConfig();
if (!!req.body.start) {
startServer(config.length - 1);
}
next();
}
async function writeConfig() {
let file = [];
config.forEach( (server, index) => {
file[index] = {};
file[index].name = config[index].name;
file[index].address = config[index].address;
file[index].port = config[index].port;
file[index].auto = config[index].auto;
});
fs.writeFileSync('./config.json', JSON.stringify({ "servers": file }));
fs.writeFileSync('./config.bak.json', JSON.stringify({ "servers": file }));
console.log("Configuration saved.");
}
function sleep(millis) {
return new Promise(resolve => setTimeout(resolve, millis));
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}
module.exports = app;