-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathhttp-server.js
94 lines (83 loc) · 2.44 KB
/
http-server.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
const fs = require('fs');
const path = require('path');
const express = require('express');
const pull = require('pull-stream');
const debug = require('debug')('ssb:room:http');
const {parseAddress, parseMultiServerInvite} = require('ssb-ref');
const qr = require('qr-image');
function fileExistsSync(filename) {
try {
fs.accessSync(filename);
} catch (err) {
return false;
}
return true;
}
function startHTTPServer(ssb) {
const app = express();
app.use(express.static(__dirname + '/assets'));
app.use(require('body-parser').urlencoded({extended: true}));
app.set('port', 8007);
app.set('views', __dirname + '/pages');
app.set('view engine', 'ejs');
const roomCfgFilePath = path.join(ssb.config.path, 'roomcfg');
app.get('/', (req, res) => {
if (!fileExistsSync(roomCfgFilePath)) {
debug('There is no roomcfg file, ask for setup');
res.redirect('setup');
return;
}
fs.readFile(roomCfgFilePath, {encoding: 'utf-8'}, (err1, rawCfg) => {
if (err1) debug('ERROR loading roomcfg file');
const roomConfig = JSON.parse(rawCfg);
let invite = ssb.invite.get();
let host = parseAddress(parseMultiServerInvite(invite).remote).host;
if (req.headers && req.headers.host) {
const requestedHost = req.headers.host.split(':')[0];
invite = invite.replace(host, requestedHost);
host = requestedHost;
}
const qrCode = qr.svgObject(invite);
pull(
ssb.tunnel.endpoints(),
pull.take(1),
pull.drain(endpoints => {
res.render('index', {
host: host,
name: roomConfig.name,
description: roomConfig.description,
onlineCount: (endpoints || {length: 0}).length,
invite: invite,
qrSize: qrCode.size,
qrPath: qrCode.path,
});
}),
);
});
});
app.get('/setup', (req, res) => {
if (fileExistsSync(roomCfgFilePath)) {
res.redirect('/');
return;
}
if (req.query && req.query.name) {
fs.writeFileSync(roomCfgFilePath, JSON.stringify(req.query), {
encoding: 'utf-8',
});
res.redirect('/');
} else {
res.render('setup');
}
});
app.listen(app.get('port'), () => {
debug('Express app is running on port %s', app.get('port'));
});
return {};
}
module.exports = {
name: 'roomhttpserver',
version: '1.0.0',
manifest: {},
permissions: {},
init: startHTTPServer,
};