forked from muaz-khan/RTCMultiConnection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·307 lines (249 loc) · 10.9 KB
/
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
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
// Muaz Khan - www.MuazKhan.com
// MIT License - www.WebRTC-Experiment.com/licence
// Documentation - github.com/muaz-khan/RTCMultiConnection
function resolveURL(url) {
var isWin = !!process.platform.match(/^win/);
if (!isWin) return url;
return url.replace(/\//g, '\\');
}
// Please use HTTPs on non-localhost domains.
var isUseHTTPs = false;
// var port = 443;
var port = process.env.PORT || 9001;
var fs = require('fs');
var path = require('path');
// see how to use a valid certificate:
// https://github.com/muaz-khan/WebRTC-Experiment/issues/62
var options = {
key: fs.readFileSync(path.join(__dirname, resolveURL('fake-keys/privatekey.pem'))),
cert: fs.readFileSync(path.join(__dirname, resolveURL('fake-keys/certificate.pem')))
};
// force auto reboot on failures
var autoRebootServerOnFailure = false;
// skip/remove this try-catch block if you're NOT using "config.json"
try {
var config = require(resolveURL('./config.json'));
if ((config.port || '').toString() !== '9001') {
port = parseInt(config.port);
}
if ((config.autoRebootServerOnFailure || '').toString() !== true) {
autoRebootServerOnFailure = true;
}
} catch (e) {}
// You don't need to change anything below
var server = require(isUseHTTPs ? 'https' : 'http');
var url = require('url');
function serverHandler(request, response) {
try {
var uri = url.parse(request.url).pathname,
filename = path.join(process.cwd(), uri);
if (filename && filename.search(/server.js|Scalable-Broadcast.js|Signaling-Server.js/g) !== -1) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.write('404 Not Found: ' + path.join('/', uri) + '\n');
response.end();
return;
}
var stats;
try {
stats = fs.lstatSync(filename);
if (filename && filename.search(/demos/g) === -1 && stats.isDirectory()) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.write('<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0;url=/demos/"></head><body></body></html>');
response.end();
return;
}
} catch (e) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.write('404 Not Found: ' + path.join('/', uri) + '\n');
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) {
response.writeHead(404, {
'Content-Type': 'text/html'
});
if (filename.indexOf(resolveURL('/demos/MultiRTC/')) !== -1) {
filename = filename.replace(resolveURL('/demos/MultiRTC/'), '');
filename += resolveURL('/demos/MultiRTC/index.html');
} else if (filename.indexOf(resolveURL('/demos/')) !== -1) {
filename = filename.replace(resolveURL('/demos/'), '');
filename += resolveURL('/demos/index.html');
} else {
filename += resolveURL('/demos/index.html');
}
}
var contentType = 'text/plain';
if (filename.toLowerCase().indexOf('.html') !== -1) {
contentType = 'text/html';
}
if (filename.toLowerCase().indexOf('.css') !== -1) {
contentType = 'text/css';
}
if (filename.toLowerCase().indexOf('.png') !== -1) {
contentType = 'image/png';
}
fs.readFile(filename, 'binary', function(err, file) {
if (err) {
response.writeHead(500, {
'Content-Type': 'text/plain'
});
response.write('404 Not Found: ' + path.join('/', uri) + '\n');
response.end();
return;
}
try {
var demos = (fs.readdirSync('demos') || []);
if (demos.length) {
var h2 = '<h2 style="text-align:center;display:block;"><a href="https://www.npmjs.com/package/rtcmulticonnection-v3"><img src="https://img.shields.io/npm/v/rtcmulticonnection-v3.svg"></a><a href="https://www.npmjs.com/package/rtcmulticonnection-v3"><img src="https://img.shields.io/npm/dm/rtcmulticonnection-v3.svg"></a><a href="https://travis-ci.org/muaz-khan/RTCMultiConnection"><img src="https://travis-ci.org/muaz-khan/RTCMultiConnection.png?branch=master"></a></h2>';
var otherDemos = '<section class="experiment" id="demos"><details><summary style="text-align:center;">Check ' + (demos.length - 1) + ' other RTCMultiConnection-v3 demos</summary>' + h2 + '<ol>';
demos.forEach(function(f) {
if (f && f !== 'index.html' && f.indexOf('.html') !== -1) {
otherDemos += '<li><a href="/demos/' + f + '">' + f + '</a> (<a href="https://github.com/muaz-khan/RTCMultiConnection/tree/master/demos/' + f + '">Source</a>)</li>';
}
});
otherDemos += '<ol></details></section><section class="experiment own-widgets latest-commits">';
file = file.replace('<section class="experiment own-widgets latest-commits">', otherDemos);
}
} catch (e) {}
try {
var docs = (fs.readdirSync('docs') || []);
if (docs.length) {
var html = '<section class="experiment" id="docs">';
html += '<details><summary style="text-align:center;">RTCMultiConnection Docs</summary>';
html += '<h2 style="text-align:center;display:block;"><a href="http://www.rtcmulticonnection.org/docs/">http://www.rtcmulticonnection.org/docs/</a></h2>';
html += '<ol>';
docs.forEach(function(f) {
if (f.indexOf('DS_Store') == -1) {
html += '<li><a href="https://github.com/muaz-khan/RTCMultiConnection/tree/master/docs/' + f + '">' + f + '</a></li>';
}
});
html += '</ol></details></section><section class="experiment own-widgets latest-commits">';
file = file.replace('<section class="experiment own-widgets latest-commits">', html);
}
} catch (e) {}
response.writeHead(200, {
'Content-Type': contentType
});
response.write(file, 'binary');
response.end();
});
} catch (e) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.write('<h1>Unexpected error:</h1><br><br>' + e.stack || e.message || JSON.stringify(e));
response.end();
}
}
var app;
if (isUseHTTPs) {
app = server.createServer(options, serverHandler);
} else {
app = server.createServer(serverHandler);
}
function cmd_exec(cmd, args, cb_stdout, cb_end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
me.exit = 0;
me.stdout = "";
child.stdout.on('data', function(data) {
cb_stdout(me, data)
});
child.stdout.on('end', function() {
cb_end(me)
});
}
function log_console() {
console.log(foo.stdout);
try {
var pidToBeKilled = foo.stdout.split('\nnode ')[1].split(' ')[0];
console.log('------------------------------');
console.log('Please execute below command:');
console.log('\x1b[31m%s\x1b[0m ', 'kill ' + pidToBeKilled);
console.log('Then try to run "server.js" again.');
console.log('------------------------------');
} catch (e) {}
}
function runServer() {
app.on('error', function(e) {
if (e.code == 'EADDRINUSE') {
if (e.address === '0.0.0.0') {
e.address = 'localhost';
}
var socketURL = (isUseHTTPs ? 'https' : 'http') + '://' + e.address + ':' + e.port + '/';
console.log('------------------------------');
console.log('\x1b[31m%s\x1b[0m ', 'Unable to listen on port: ' + e.port);
console.log('\x1b[31m%s\x1b[0m ', socketURL + ' is already in use. Please kill below processes using "kill PID".');
console.log('------------------------------');
foo = new cmd_exec('lsof', ['-n', '-i4TCP:9001'],
function(me, data) {
me.stdout += data.toString();
},
function(me) {
me.exit = 1;
}
);
setTimeout(log_console, 250);
}
});
app = app.listen(port, process.env.IP || '0.0.0.0', function(error) {
var addr = app.address();
if (addr.address === '0.0.0.0') {
addr.address = 'localhost';
}
var domainURL = (isUseHTTPs ? 'https' : 'http') + '://' + addr.address + ':' + addr.port + '/';
console.log('------------------------------');
console.log('socket.io is listening at:');
console.log('\x1b[31m%s\x1b[0m ', '\t' + domainURL);
console.log('\n');
console.log('Your web-browser (HTML file) MUST set this line:');
console.log('\x1b[31m%s\x1b[0m ', 'connection.socketURL = "' + domainURL + '";');
if (addr.address != 'localhost' && !isUseHTTPs) {
console.log('Warning:');
console.log('\x1b[31m%s\x1b[0m ', 'Please set isUseHTTPs=true to make sure audio,video and screen demos can work on Google Chrome as well.');
}
console.log('------------------------------');
console.log('Need help? http://bit.ly/2ff7QGk');
});
require('./Signaling-Server.js')(app, function(socket) {
try {
var params = socket.handshake.query;
// "socket" object is totally in your own hands!
// do whatever you want!
// in your HTML page, you can access socket as following:
// connection.socketCustomEvent = 'custom-message';
// var socket = connection.getSocket();
// socket.emit(connection.socketCustomEvent, { test: true });
if (!params.socketCustomEvent) {
params.socketCustomEvent = 'custom-message';
}
socket.on(params.socketCustomEvent, function(message) {
try {
socket.broadcast.emit(params.socketCustomEvent, message);
} catch (e) {}
});
} catch (e) {}
});
}
if (autoRebootServerOnFailure) {
// auto restart app on failure
var cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
cluster.on('exit', function(worker, code, signal) {
cluster.fork();
});
}
if (cluster.isWorker) {
runServer();
}
} else {
runServer();
}