-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
205 lines (169 loc) · 6.55 KB
/
index.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
const config = require('./config.json');
var express = require('express');
const path = require('path');
var fs = require('fs');
var https = require('https');
var http = require('http');
var ws = require('ws');
var geoip = require('geoip-lite');
const options = {
key: fs.readFileSync(config.sslKey),
cert: fs.readFileSync(config.sslCert)
};
var decision;
var usersArray = [];
var users = express();
users.get("/", function (req, res) {
res.json({ users: usersArray })
});
var page = express();
page.get("/", function (req, res) {
if (decision == 'lowlatency') {
res.sendFile(path.join(__dirname, "/public/lowlatency.html"));
} else if (decision == 'quality') {
res.sendFile(path.join(__dirname, "/public/quality.html"));
} else {
res.sendFile(path.join(__dirname, "/public/default.html"));
}
});
//Redirects from http to https to stop accidental wrong URLs
var redirect = express();
var server = http.createServer(redirect);
redirect.get('*', function (req, res) {
res.redirect('https://' + req.headers.host + req.url);
})
server.listen(80);
var app = express();
app.use(express.static('public'));
app.use("/users", users);
app.use("/", page);
var httpsServer = https.createServer(options, app);
var httpsServerForUsers = https.createServer(options);
var socketServer = new ws.Server({ server: httpsServer, perMessageDeflate: false });
var socketServerUsers = new ws.Server({ server: httpsServerForUsers, perMessageDeflate: false });
socketServer.connectionCount = 0;
socketServer.on('connection', function (socket, upgradeReq) {
let cookies;
let location;
try {
location = geoip.lookup((upgradeReq || socket.upgradeReq).socket.remoteAddress.replace('::ffff:', ''));
} catch (err) {
console.log("GeoIP not loaded correctly or key not given.")
}
try {
cookies = Object.fromEntries((upgradeReq || socket.upgradeReq).headers.cookie.split('; ').map(x => x.split(/=(.*)$/, 2).map(decodeURIComponent)))
if (cookies.streamkey != config.streamKey || !cookies.username) { //Failed authentication
console.log(`Failed authentication from: ${(upgradeReq || socket.upgradeReq).socket.remoteAddress.replace('::ffff:', '')} : ${(location) ? (`${location.city}, ${location.region} ${location.country}`) : "(Unknown Location)"}`);
socket.close();
return;
} else {
usersArray.push(cookies.username);
updateUsers();
}
} catch (err) {
socket.close();
return;
}
socketServer.connectionCount++;
console.log(`New user connected to stream: ${cookies.username} - ${(upgradeReq || socket.upgradeReq).socket.remoteAddress.replace('::ffff:', '')} : ${(location) ? (`${location.city}, ${location.region} ${location.country}`) : "(Unknown Location)"}.(${socketServer.connectionCount} total).`);
socket.on('close', function (code, message) {
try {
usersArray.find((user, i) => {
if (user == cookies.username) {
usersArray.splice(i, 1); // Find and remove first matching username
updateUsers();
}
});
} catch (err) {
}
socketServer.connectionCount--;
console.log(`${cookies.username} disconnected (${socketServer.connectionCount} total).`);
});
});
socketServer.broadcast = function (data) {
socketServer.clients.forEach(function each(client) {
if (client.readyState === ws.OPEN) {
client.send(data);
}
});
};
socketServerUsers.connectionCount = 0;
socketServerUsers.on('connection', function (socket, upgradeReq) {
let cookies;
let location;
try {
location = geoip.lookup((upgradeReq || socket.upgradeReq).socket.remoteAddress.replace('::ffff:', ''));
} catch (err) {
console.log("GeoIP not loaded correctly or key not given.")
}
try {
cookies = Object.fromEntries((upgradeReq || socket.upgradeReq).headers.cookie.split('; ').map(x => x.split(/=(.*)$/, 2).map(decodeURIComponent)))
if (cookies.streamkey != config.streamKey || !cookies.username) { //Failed authentication
console.log(`Failed authentication from: ${(upgradeReq || socket.upgradeReq).socket.remoteAddress.replace('::ffff:', '')} : ${(location) ? (`${location.city}, ${location.region} ${location.country}`) : "(Unknown Location)"}`);
// console.log(`Failed authentication from: ${(upgradeReq || socket.upgradeReq).socket.remoteAddress.replace('::ffff:', '')} `);
socket.close();
return;
}
} catch (err) {
socket.close();
return;
}
socketServerUsers.connectionCount++;
updateUsers();
socket.on('close', function (code, message) {
socketServerUsers.connectionCount--;
});
});
function updateUsers() {
socketServerUsers.clients.forEach(function each(client) {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify(usersArray));
}
});
}
httpsServer.listen(config.wsPort);
httpsServerForUsers.listen(config.wsUsersPort);
var streamServer = https.createServer(options, function (request, response) {
var params = request.url.substr(1).split('/');
let location;
try {
location = geoip.lookup(request.socket.remoteAddress.replace('::ffff:', ''));
} catch (err) {
console.log("GeoIP not loaded correctly or key not given.")
}
if (params[0] !== config.streamSecret) {
console.log(`Failed Stream Connection: ${request.socket.remoteAddress.replace('::ffff:', '')}:${request.socket.remotePort} ${(location) ? (`${location.city}, ${location.region} ${location.country}`) : "(Unknown Location)"} - wrong secret.`);
response.end();
return false;
}
if (params[1] == 'lowlatency') {
decision = 'lowlatency';
console.log(`Switched to low latency mode.`);
} else if (params[1] == 'quality') {
decision = 'quality';
console.log(`Switched to quality mode.`);
} else {
console.log("No stream type given. Use either lowlatency or quality.");
response.end();
return false;
}
response.connection.setTimeout(0);
// console.log(`Successful Stream Connection: ${request.socket.remoteAddress.replace('::ffff:', '')}:${request.socket.remotePort} `);
console.log(`Successful Stream Connection: ${request.socket.remoteAddress.replace('::ffff:', '')}:${request.socket.remotePort} ${(location) ? (`${location.city}, ${location.region} ${location.country}`) : "(Unknown Location)"}`);
request.on('data', function (data) {
socketServer.broadcast(data);
if (request.socket.recording) {
request.socket.recording.write(data);
}
});
request.on('end', function () {
console.log('Stream Connection closed.');
if (request.socket.recording) {
request.socket.recording.close();
}
});
})
streamServer.headersTimeout = 0;
streamServer.listen(config.streamPort);
console.log(`Listening for incoming Video Stream on https://127.0.0.1:${config.streamPort}/${config.streamSecret}`);
console.log(`Awaiting WebSocket connections on wss://127.0.0.1:${config.wsPort}/`);