-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
423 lines (348 loc) · 11.5 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
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
/**
* Moodlefreak Chat Server v.0.3
*
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*
* @package moodlefreak-chat
* @copyright 2015 MoodleFreak.com
* @author Luuk Verhoeven
**/
// Includes
var fs = require('fs');
var config = require('./config');
var express = require('express');
var app = express();
var options = {
key: fs.readFileSync(config.ssl_key),
cert: fs.readFileSync(config.ssl_cert),
requestCert: false,
rejectUnauthorized: false
};
var server = require('https').createServer(options, app);
var io = require("socket.io")(server);
// Rigorous implementation of RFC4122 (v1 and v4) UUIDs.
var uuid = require('node-uuid');
// JavaScript's functional programming helper library.
var _ = require('underscore')._;
// Caja's stand-alone HTML sanitizer for node
var Util = require('./util.js')();
var Room = require('./room.js');
// Start server
server.listen(config.port, function () {
console.log('Server listening at port %d', config.port);
});
// Data Holders
var rooms = {};
var sockets = [];
var buffersendonexit = false;
io.on('connection', function (client) {
var address = client.handshake.address;
// console.log("New connection from " + address);
});
function join(socket, chatobject, fn) {
console.log("join");
// console.log(chatobject);
// Validate key/host.
var valid = Util.validToken(chatobject.shared_secret, chatobject.hostname);
if (!valid.status) {
console.log(valid.error);
fn(valid);
return;
}
// We can continue.
chatobject.id = socket.id;
socket.has_access = true;
socket.namespace = valid.namespace;
// Check if the roomnamespace is set.
if (rooms[socket.namespace] === undefined) {
rooms[socket.namespace] = [];
}
// Use namespace to allow more environment to connect.
var roomname = Util.getRoomNameFromChatobject(chatobject);
if (rooms[socket.namespace][roomname] === undefined) {
rooms[socket.namespace][roomname] = new Room(roomname, socket.namespace, valid.callback, chatobject.shared_secret);
}
// Reference.
var room = rooms[socket.namespace][roomname];
room.addUser(chatobject);
// Join the room.
socket.join(roomname).in(socket.namespace);
// Only send userlist update to correct room.
if(roomname.indexOf("_pm_") === -1){
io.sockets.in(roomname).emit("update-user-list", {
users : room.getAllUsers(),
count : room.getUserCount(),
status: true
});
}
// Add the socket to a container.
sockets.push(socket);
fn({'status': true});
}
/**
* Validate the call and return a room object
*
* @param {object} socket
* @param {object} chatobject
* @param {function} fn
* @returns {Room|boolean}
*/
function validAccessAndReturnRoom(socket, chatobject, fn) {
if (!socket.has_access || socket.namespace === "") {
// Maybe got disconnected???
join(socket, chatobject, fn);
// Stop invalid calls
if (!socket.has_access) {
return false;
}
}
var roomname = Util.getRoomNameFromChatobject(chatobject);
if (rooms[socket.namespace][roomname] !== undefined) {
console.log('Found Room()');
return rooms[socket.namespace][roomname];
}
return false;
}
/**
* Send the chat message buffers to the server
* Note: this also executed on error / termination
*/
function sendBuffersAndCleaning(bufferSend) {
console.log('Send Buffers');
// loop
for (var namespace in rooms) {
if (rooms.hasOwnProperty(namespace)) {
for (var roomname in rooms[namespace]) {
console.log('Roomname: ' + roomname);
var room = rooms[namespace][roomname];
var count = room.getMessagesCount();
console.log('Messages: ' + count);
if (count > 0) {
// send to a server
room.forwardMessagesToDBServer(bufferSend);
}
if (room.getUserCount() == 0) {
console.log('Delete room');
delete rooms[namespace][roomname];
}
}
}
}
console.log('Buffers loop end');
}
function bufferSend() {
console.log('buffersendonexit = true');
buffersendonexit = true;
}
io.sockets.on("connection", function (socket) {
// Set some defaults
socket.has_access = false;
socket.namespace = "";
/**
* Join the chatroom
*/
socket.on("join", function (chatobject, fn) {
join(socket, chatobject, fn);
});
/**
* End the openwebinar & unload/remove the room from chat server
*/
socket.on("ending", function (chatobject, fn) {
var room = validAccessAndReturnRoom(socket, chatobject, fn);
if (typeof room === 'object') {
if (chatobject.usertype === 'broadcaster' && room.validateBroadcasterIdentifier(chatobject)) {
console.log('OK');
// only the broadcaster can do this
io.sockets.in(room.name).emit("openwebinar-ended", {
status: true
});
var count = room.getMessagesCount();
console.log('Messages: ' + count);
if (count > 0) {
// send to a server
room.forwardMessagesToDBServer();
}
fn({status: true});
return;
}
}
fn({status: false});
});
/**
* Get the latest userlist in from the room
*/
socket.on("get-userlist", function (chatobject, fn) {
var room = validAccessAndReturnRoom(socket, chatobject, fn);
if (typeof room === 'object') {
fn({
status: true,
users : room.getAllUsers(),
count : room.getUserCount()
});
return;
}
fn({status: false});
});
/**
* Mute a usertype
*/
socket.on("mute", function (chatobject, mute_usertype, value, fn) {
console.log('mute');
var room = validAccessAndReturnRoom(socket, chatobject, fn);
if (typeof room === 'object') {
if (chatobject.usertype === 'broadcaster' && room.validateBroadcasterIdentifier(chatobject)) {
console.log('OK');
fn({
status: true,
mute : room.setMute(mute_usertype, value)
});
return;
} else {
console.log('error: your_not_a_broadcaster ' + chatobject.broadcaster_identifier + ' usertype:' + chatobject.usertype);
fn({
status : false,
'error': 'your_not_a_broadcaster'
});
return;
}
}
fn({status: false});
});
/**
* Notice a user in the main room
*/
socket.on("send-notice-user", function (chatobject, to_user_id, fn) {
console.log('send-notice-user');
var room = validAccessAndReturnRoom(socket, chatobject, fn);
if (typeof room === 'object') {
// Send to clients
console.log(to_user_id);
var socketidclient = room.getSocketByUserId(chatobject, to_user_id);
if (socketidclient) {
console.log('send:' + socketidclient);
chatobject.timestamp = Math.round(new Date().getTime() / 1000);
io.to(socketidclient).emit("new-incoming-private-message", chatobject);
fn({'status': true});
} else {
console.log('user not connected anymore');
fn({
'status' : false,
'message': 'user not connected anymore'
});
}
} else {
console.log('unknown_room');
fn({
'status': false,
'error' : 'unknown_room'
});
}
});
/**
* Send a chat message to the room clients
*/
socket.on("send", function (chatobject, fn) {
var room = validAccessAndReturnRoom(socket, chatobject, fn);
console.log(typeof room);
if (typeof room === 'object') {
console.log('valid room');
if (!room.canType(chatobject)) {
fn({
'status': false,
'error' : 'muted'
});
return;
}
// Send to clients
io.sockets.in(room.name).emit("update-chat", room.addMessage(chatobject));
fn({'status': true});
} else {
console.log('unknown_room');
fn({
'status': false,
'error' : 'unknown_room'
});
}
});
/**
* Client disconnect
*/
socket.on("disconnect", function () {
// console.log("disconnect");
// Remove this user from all possible rooms
for (var roomname in rooms[socket.namespace]) {
var room = rooms[socket.namespace][roomname];
if (room.removeUser(socket.id)) {
if (room.getUserCount() == 0) {
console.log('Nobody in the room anymore.. we should delete the room');
// cleanup prevent empty rooms
var count = room.getMessagesCount();
console.log('Messages: ' + count);
if (count > 0) {
// send to a server
room.forwardMessagesToDBServer();
}
console.log('Delete room');
delete rooms[socket.namespace][roomname];
}
console.log('update-user-list');
io.sockets.in(roomname).emit("update-user-list", {
users : room.getAllUsers(),
count : room.getUserCount(),
status: true
});
} else {
console.log('You are not in this room!');
}
}
// Remove from the sockets
// @todo check if we can do without it
var o = _.findWhere(sockets, {'id': socket.id});
sockets = _.without(sockets, o);
});
});
// Send the room buffers to DB servers
var intervalCron = setInterval(function () {
console.log('Cron check buffers');
sendBuffersAndCleaning(false);
}, 60000); // 1 minute
// so the program will not close instantly
process.stdin.resume();
/**
* Execute on error or termination
*
* @param options
* @param err
*/
function exitHandler(options, err) {
var i = 0;
try {
// stop the cron
clearInterval(intervalCron);
} catch (e) {
}
if (err) {
// log real errors to console
console.log(err.stack);
}
if (options.exit && buffersendonexit === false) {
buffersendonexit = 0;
// Send chat logs DB servers before we exit
sendBuffersAndCleaning(bufferSend);
// delay exit for posting to the DB servers
setInterval(function () {
console.log('.' + i);
if (buffersendonexit === true || i == 20) {
// the real exit
process.exit();
}
i++;
}, 500);
}
}
//do something when app is closing
process.on('exit', exitHandler.bind(null, {exit: true}));
//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit: true}));
//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit: true}));