1
/* global module, require, console, __dirname */
2
/**
3
* Event listeners used by EasyRTC. Many of these can be overridden using server options.
4
*
5
* @module easyrtc_default_event_listeners
6
* @author Priologic Software, info@easyrtc.com
7
* @copyright Copyright 2016 Priologic Software. All rights reserved.
8
* @license BSD v2, see LICENSE file in module root folder.
9
*/
10
11
var util = require("util"); // General utility functions core module
12
var _ = require("underscore"); // General utility functions external module
13
var g = require("./general_util"); // General utility functions local module
14
15
var async = require("async"); // Asynchronous calls external module
16
17
var pub = require("./easyrtc_public_obj"); // EasyRTC public object
18
19
/**
20
* Event listeners used by EasyRTC. Many of these can be overridden using server options. The interfaces should be used as a guide for creating new listeners.
21
*
22
* @class
23
*/
24
var eventListener = module.exports;
25
26
/**
27
* Default listener for event "authenticate". This event is called as part of the authentication process. To deny authentication, call the next() with an Error. By default everyone gets in!
28
*
29
* @param {Object} socket Socket.io socket object. References the individual connection socket.
30
* @param {String} easyrtcid Unique identifier for an EasyRTC connection.
31
* @param {string} appName Application name which uniquely identifies it on the server.
32
* @param {?String} username Username to assign to the connection.
33
* @param {?*} credential Credential for the connection. Can be any JSONable object.
34
* @param {Object} easyrtcAuthMessage Message object containing the complete authentication message sent by the connection.
35
* @param {nextCallback} next A success callback of form next(err).
36
*/
37
eventListener.onAuthenticate = function(socket, easyrtcid, appName, username, credential, easyrtcAuthMessage, next) {
38
next(null);
39
};
40
41
42
/**
43
* Default listener for event "authenticated". This event is called after a connection is authenticated and the connection object is generated and requested rooms are joined. Call next(err) to continue the connection procedure.
44
*
45
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
46
* @param {nextCallback} next A success callback of form next(err).
47
*/
48
eventListener.onAuthenticated = function(connectionObj, next) {
49
next(null);
50
};
51
52
53
/**
54
* Default listener for event "connection". This event is called when socket.io accepts a new connection.
55
*
56
* @param {Object} socket Socket.io socket object. References the individual connection socket.
57
* @param {String} easyrtcid Unique identifier for an EasyRTC connection.
58
* @param {nextCallback} next A success callback of form next(err).
59
*/
60
eventListener.onConnection = function(socket, easyrtcid, next){
61
var connectionObj = {}; // prepare variables to house the connection object
62
63
// Initially upon a connection, we are only concerned with receiving an easyrtcAuth message
64
socket.on("easyrtcAuth", function(msg, socketCallback) {
65
66
if (pub.getOption("logMessagesEnable")) {
67
try {
68
pub.util.logDebug("["+easyrtcid+"] Incoming socket.io message: ["+JSON.stringify(msg)+"]");
69
}
70
catch(err) {
71
pub.util.logDebug("["+easyrtcid+"] Incoming socket.io message");
72
}
73
}
74
75
pub.events.emit("easyrtcAuth", socket, easyrtcid, msg, socketCallback, function(err, newConnectionObj){
76
if(err){
77
pub.util.logError("["+easyrtcid+"] Unhandled easyrtcCmd listener error.", err);
78
return;
79
}
80
81
connectionObj = newConnectionObj;
82
});
83
});
84
85
pub.util.logDebug("Running func 'onConnection'");
86
next(null);
87
};
88
89
90
/**
91
* Default listener for event "disconnect". This event is called when socket.io detects a disconnection. Disconnections can occur due to either side purposefully dropping a connection, network disconnection, or time out.
92
*
93
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
94
* @param {nextCallback} next A success callback of form next(err).
95
*/
96
eventListener.onDisconnect = function(connectionObj, next){
97
pub.util.logDebug("Running func 'onDisconnect'");
98
99
async.waterfall([
100
function(asyncCallback) {
101
// Get array of rooms
102
connectionObj.getRoomNames(asyncCallback);
103
},
104
function(roomNames, asyncCallback) {
105
// leave all rooms
106
async.each(roomNames,
107
function(currentRoomName, asyncEachCallback) {
108
pub.events.emit("roomLeave", connectionObj, currentRoomName, function(err){asyncEachCallback(null);});
109
},
110
function(err){
111
asyncCallback(null);
112
}
113
);
114
},
115
function(asyncCallback) {
116
// log all connections as ended
117
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Disconnected");
118
connectionObj.removeConnection(asyncCallback);
119
}
120
], function(err) {
121
next(null);
122
});
123
124
next(null);
125
};
126
127
128
/**
129
* Default listener for event "easyrtcAuth". This event is fired when an incoming 'easyrtcAuth' message is received from a client.
130
*
131
* @param {Object} socket Socket.io socket object. References the individual connection socket.
132
* @param {String} easyrtcid Unique identifier for an EasyRTC connection.
133
* @param {Object} msg Message object which contains the full message from a client; this can include the standard msgType and msgData fields.
134
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
135
* @param {Function} callback Callback to call upon completion. Delivers parameter (err, connectionObj).
136
*/
137
eventListener.onEasyrtcAuth = function(socket, easyrtcid, msg, socketCallback, callback){
138
pub.util.logDebug("["+easyrtcid+"] Running func 'onEasyrtcAuth'");
139
140
var appObj, connectionObj, sessionObj; // prepare variables to house the application, connection, and session objects
141
142
var tokenMsg = {
143
msgType: "token",
144
msgData:{}
145
};
146
147
var appName;
148
var newAppName = (_.isObject(msg.msgData) &&_.isString(msg.msgData.applicationName)) ? msg.msgData.applicationName : pub.getOption("appDefaultName");
149
150
// Ensure socketCallback is present
151
if(!_.isFunction(socketCallback)) {
152
pub.util.logWarning("["+easyrtcid+"] EasyRTC Auth message received with no callback. Disconnecting socket.", msg);
153
try{socket.disconnect();}catch(e){}
154
return;
155
}
156
157
// Only accept authenticate message
158
if(!_.isObject(msg) || !_.isString(msg.msgType) || msg.msgType != "authenticate") {
159
pub.util.logWarning("["+easyrtcid+"] EasyRTC Auth message received without msgType of 'authenticate'. Disconnecting socket.", msg);
160
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_BAD_AUTH"), appObj);
161
try{socket.disconnect();}catch(e){}
162
return;
163
}
164
165
// Check msg structure.
166
if(!_.isObject(msg.msgData)
167
|| !_.isString(msg.msgData.apiVersion)
168
|| (msg.msgData.roomJoin !== undefined && !_.isObject(msg.msgData.roomJoin))
169
) {
170
pub.util.logWarning("["+easyrtcid+"] EasyRTC Auth message received with improper msgData. Disconnecting socket.", msg);
171
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_BAD_STRUCTURE"), appObj);
172
try{socket.disconnect();}catch(e){}
173
return;
174
}
175
176
async.waterfall([
177
function(asyncCallback) {
178
// Check message structure
179
pub.util.isValidIncomingMessage("easyrtcAuth", msg, null, asyncCallback);
180
},
181
182
function(isMsgValid, msgErrorCode, asyncCallback) {
183
// If message structure is invalid, send error, disconnect socket, and write to log
184
if (!isMsgValid) {
185
try{
186
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg(msgErrorCode), appObj);
187
socket.disconnect();
188
}catch(e){}
189
pub.util.logWarning("["+easyrtcid+"] EasyRTC Auth message received with invalid message format [" + msgErrorCode + "]. Disconnecting socket.", msg);
190
callback(new pub.util.ConnectionError("["+easyrtcid+"] EasyRTC Auth message received with invalid message format [" + msgErrorCode + "]. Disconnecting socket."));
191
return;
192
}
193
194
// Remove any old listeners
195
socket.removeAllListeners("easyrtcCmd");
196
socket.removeAllListeners("easyrtcMsg");
197
socket.removeAllListeners("disconnect"); // TODO: Come up with alternative to removing all disconnect listeners
198
199
pub.util.logDebug("Emitting Authenticate");
200
201
var username = (msg.msgData.username ? msg.msgData.username : null);
202
var credential = (msg.msgData.credential ? msg.msgData.credential: null);
203
204
// Authenticate is responsible for authenticating the connection
205
pub.events.emit("authenticate", socket, easyrtcid, newAppName, username, credential, msg, function(err){
206
if (err) {
207
try{
208
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_BAD_AUTH"), appObj);
209
socket.disconnect();
210
pub.util.logInfo("["+newAppName+"]["+easyrtcid+"] Authentication denied. Socket disconnected.", err);
211
}catch(e){}
212
} else {
213
asyncCallback(null);
214
}
215
});
216
},
217
218
function(asyncCallback) {
219
// Check to see if the requested app currently exists.
220
pub.isApp(newAppName, asyncCallback);
221
222
},
223
224
function(isApp, asyncCallback) {
225
// If requested app exists, then call it, otherwise create it.
226
if (isApp) {
227
pub.app(newAppName, asyncCallback);
228
} else {
229
// if appAutoCreateEnable is true, then a new app will be created using the default options
230
if(pub.getOption("appAutoCreateEnable")) {
231
pub.createApp(newAppName, null, asyncCallback);
232
} else {
233
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_APP_AUTH_FAIL"), appObj);
234
socket.disconnect();
235
pub.util.logWarning("[" + easyrtcid + "] Authentication failed. Requested application not found [" + newAppName + "]. Socket disconnected.");
236
}
237
}
238
},
239
240
function(newAppObj, asyncCallback) {
241
// Now that we have an app, we can use it
242
appObj = newAppObj;
243
appName = appObj.getAppName();
244
245
appObj.isConnected(easyrtcid, asyncCallback);
246
},
247
248
function(isConnected, asyncCallback) {
249
// If socket has previously connected, disconnect them.
250
if (isConnected){
251
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_APP_AUTH_FAIL"), appObj);
252
socket.disconnect();
253
pub.util.logWarning("[" + easyrtcid + "] Authentication failed. Already connected. Socket disconnected.");
254
return;
255
}
256
257
// if roomJoin is present in message, check the room names
258
if (msg.msgData.roomJoin) {
259
for (var currentRoomName in msg.msgData.roomJoin) {
260
if (!_.isString(currentRoomName) || !appObj.getOption("roomNameRegExp").test(currentRoomName)) {
261
pub.events.emit("emitReturnError", socketCallback, "MSG_REJECT_TARGET_ROOM", pub.util.nextToNowhere);
262
pub.util.logInfo("[" + easyrtcid + "] Authentication failed. Requested room name not allowed [" + currentRoomName + "].");
263
return;
264
}
265
}
266
}
267
asyncCallback(null);
268
},
269
270
function(asyncCallback) {
271
// Create the connection object
272
appObj.createConnection(easyrtcid, socket.id, asyncCallback);
273
},
274
275
276
function(newConnectionObj, asyncCallback) {
277
connectionObj = newConnectionObj;
278
279
// Check if there is an easyrtcsid
280
if (_.isString(msg.msgData.easyrtcsid)) {
281
appObj.isSession(msg.msgData.easyrtcsid, function(err, isSession){
282
if (err) {
283
asyncCallback(err);
284
return;
285
}
286
if (isSession) {
287
appObj.session(msg.msgData.easyrtcsid, asyncCallback);
288
} else {
289
appObj.createSession(msg.msgData.easyrtcsid, asyncCallback);
290
}
291
});
292
}
293
else {
294
asyncCallback(null, null);
295
}
296
},
297
298
function(newSessionObj, asyncCallback) {
299
if (!newSessionObj) {
300
asyncCallback(null);
301
return;
302
}
303
sessionObj = newSessionObj;
304
connectionObj.joinSession(sessionObj.getEasyrtcsid(), asyncCallback);
305
},
306
307
function(asyncCallback) {
308
// Set connection as being authenticated (we pre-authenticated)
309
connectionObj.setAuthenticated(true, asyncCallback);
310
},
311
312
function(asyncCallback) {
313
// Set username (if defined)
314
if (msg.msgData.username !== undefined) {
315
connectionObj.setUsername(msg.msgData.username, asyncCallback);
316
} else {
317
asyncCallback(null);
318
}
319
},
320
321
function(asyncCallback) {
322
// Set credential (if defined)
323
if (msg.msgData.username !== undefined) {
324
connectionObj.setCredential(msg.msgData.credential, asyncCallback);
325
} else {
326
asyncCallback(null);
327
}
328
},
329
330
function(asyncCallback) {
331
// Set presence (if defined)
332
if (_.isObject(msg.msgData.setPresence)) {
333
connectionObj.setPresence(msg.msgData.setPresence,asyncCallback);
334
} else {
335
asyncCallback(null);
336
}
337
},
338
339
function(asyncCallback) {
340
// Join a room. If no rooms are defined than join the default room
341
if (_.isObject(msg.msgData.roomJoin) && !_.isEmpty(msg.msgData.roomJoin)) {
342
async.each(Object.keys(msg.msgData.roomJoin), function(currentRoomName, roomCallback) {
343
344
appObj.isRoom(currentRoomName, function(err, isRoom){
345
if(err) {
346
roomCallback(err);
347
return;
348
}
349
350
// Set roomParameter map. This may be used by custom listeners.
351
var currentRoomParameter;
352
if (msg.msgData.roomJoin[currentRoomName] && _.isObject(msg.msgData.roomJoin[currentRoomName].roomParameter)){
353
currentRoomParameter = msg.msgData.roomJoin[currentRoomName].roomParameter;
354
}
355
356
if (isRoom) {
357
// Join existing room
358
pub.events.emit("roomJoin", connectionObj, currentRoomName, currentRoomParameter, roomCallback);
359
}
360
else if (appObj.getOption("roomAutoCreateEnable")) {
361
// Room doesn't yet exist, however we are allowed to create it.
362
pub.events.emit("roomCreate", appObj, connectionObj, currentRoomName, null, function(err, roomObj){
363
if (err) {
364
roomCallback(err);
365
return;
366
}
367
pub.events.emit("roomJoin", connectionObj, currentRoomName, currentRoomParameter, roomCallback);
368
});
369
}
370
else {
371
// Can't join room and we are not allowed to create it. Error Out.
372
try{
373
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_BAD_ROOM"), appObj);
374
socket.disconnect();
375
}catch(e){}
376
pub.util.logInfo("[" + easyrtcid + "] Authentication failed. Requested room name does not exist [" + currentRoomName + "].");
377
}
378
});
379
}, function(err, newRoomObj) {
380
asyncCallback(err);
381
});
382
}
383
384
// If no room is initially provided, have them join the default room (if enabled)
385
else if (connectionObj.getApp().getOption("roomDefaultEnable")) {
386
pub.events.emit("roomJoin", connectionObj, connectionObj.getApp().getOption("roomDefaultName"), null, function(err, roomObj){
387
asyncCallback(err);
388
});
389
}
390
391
// No room provided, and can't join default room
392
else {
393
asyncCallback(null);
394
}
395
},
396
397
function(asyncCallback) {
398
// Add new listeners
399
socket.on("easyrtcCmd", function(msg, socketCallback){
400
if (pub.getOption("logMessagesEnable")) {
401
try {
402
pub.util.logDebug("["+appName+"]["+easyrtcid+"] Incoming socket.io message: ["+JSON.stringify(msg)+"]");
403
}
404
catch(err) {
405
pub.util.logDebug("["+appName+"]["+easyrtcid+"] Incoming socket.io message");
406
}
407
}
408
409
pub.events.emit("easyrtcCmd", connectionObj, msg, socketCallback, function(err){
410
if(err){pub.util.logError("["+appName+"]["+easyrtcid+"] Unhandled easyrtcCmd listener error.", err);}
411
});
412
413
});
414
socket.on("easyrtcMsg", function(msg, socketCallback){
415
if (pub.getOption("logMessagesEnable")) {
416
try {
417
pub.util.logDebug("["+appName+"]["+easyrtcid+"] Incoming socket.io message: ["+JSON.stringify(msg)+"]");
418
}
419
catch(err) {
420
pub.util.logDebug("["+appName+"]["+easyrtcid+"] Incoming socket.io message");
421
}
422
}
423
424
pub.events.emit("easyrtcMsg", connectionObj, msg, socketCallback, function(err){
425
if(err){pub.util.logError("["+appName+"]["+easyrtcid+"] Unhandled easyrtcMsg listener error.", err);}
426
});
427
});
428
socket.on("disconnect", function(){
429
pub.events.emit("disconnect", connectionObj, function(err){
430
if(err){pub.util.logError("["+appName+"]["+easyrtcid+"] Unhandled disconnect listener error.", err);}
431
});
432
});
433
asyncCallback(null);
434
},
435
436
function(asyncCallback){
437
pub.events.emit("authenticated", connectionObj, asyncCallback);
438
},
439
440
function(asyncCallback){
441
pub.events.emit("emitReturnToken", connectionObj, socketCallback, asyncCallback);
442
},
443
444
function(asyncCallback){
445
446
// TODO: Reinstate this emit function by setting flag for roomJoin event so it doesn't automatically emit delta's
447
// Emit clientList delta to other clients in room
448
// connectionObj.emitRoomDataDelta(false, function(err, roomDataObj){asyncCallback(err);});
449
asyncCallback(null);
450
}
451
452
],
453
// This function is called upon completion of the async waterfall, or upon an error being thrown.
454
function (err) {
455
if (err){
456
try{
457
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_GEN_FAIL"), appObj);
458
socket.disconnect();
459
pub.util.logError("["+easyrtcid+"] General authentication error. Socket disconnected.", err);
460
}catch(e){}
461
} else {
462
callback(null, connectionObj);
463
}
464
});
465
};
466
467
468
/**
469
* Default listener for event "easyrtcCmd". This event is fired when an incoming 'easyrtcCmd' message is received from a client.
470
*
471
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
472
* @param {Object} msg Message object which contains the full message from a client; this can include the standard msgType and msgData fields.
473
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
474
* @param {nextCallback} next A success callback of form next(err).
475
*/
476
eventListener.onEasyrtcCmd = function(connectionObj, msg, socketCallback, next){
477
var appName = connectionObj.getAppName();
478
var appObj = connectionObj.getApp();
479
var easyrtcid = connectionObj.getEasyrtcid();
480
481
482
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC command received with msgType [" + msg.msgType + "]");
483
if (!_.isFunction(next)) {
484
next = pub.util.nextToNowhere;
485
}
486
487
if(!_.isFunction(socketCallback)) {
488
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC command message received with no callback. Ignoring.", msg);
489
return;
490
}
491
492
async.waterfall([
493
function(asyncCallback) {
494
// Check message structure
495
pub.util.isValidIncomingMessage("easyrtcCmd", msg, connectionObj.getApp(), asyncCallback);
496
},
497
498
function(isMsgValid, msgErrorCode, asyncCallback) {
499
// If message structure is invalid, send error, and write to log
500
if (!isMsgValid) {
501
try{
502
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg(msgErrorCode), appObj);
503
}catch(e){}
504
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC Auth message received with invalid message format [" + msgErrorCode + "]. Disconnecting socket.", msg);
505
return;
506
}
507
asyncCallback(null);
508
},
509
function(asyncCallback) {
510
// The msgType controls how each message is handled
511
switch(msg.msgType) {
512
case "setUserCfg":
513
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] WebRTC setUserCfg command received. This feature is not yet complete.");
514
pub.util.sendSocketCallbackAck(easyrtcid, socketCallback, appObj);
515
next(null);
516
break;
517
518
case "setPresence":
519
pub.events.emit("msgTypeSetPresence", connectionObj, msg.msgData.setPresence, socketCallback, next);
520
break;
521
522
case "setRoomApiField":
523
pub.events.emit("msgTypeSetRoomApiField", connectionObj, msg.msgData.setRoomApiField, socketCallback, next);
524
break;
525
526
case "roomJoin":
527
pub.events.emit("msgTypeRoomJoin", connectionObj, msg.msgData.roomJoin, socketCallback, next);
528
break;
529
530
case "roomLeave":
531
pub.events.emit("msgTypeRoomLeave", connectionObj, msg.msgData.roomLeave, socketCallback, next);
532
break;
533
534
case "getIceConfig":
535
pub.events.emit("msgTypeGetIceConfig", connectionObj, socketCallback, next);
536
break;
537
538
case "getRoomList":
539
pub.events.emit("msgTypeGetRoomList", connectionObj, socketCallback, next);
540
break;
541
542
case "candidate":
543
case "offer":
544
case "answer":
545
case "reject":
546
case "hangup":
547
// Relay message to targetEasyrtcid
548
var outgoingMsg = {senderEasyrtcid: connectionObj.getEasyrtcid(), msgData:msg.msgData};
549
550
connectionObj.getApp().connection(msg.targetEasyrtcid, function(err,targetConnectionObj){
551
if (err){
552
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_TARGET_EASYRTCID"), appObj);
553
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Could not send WebRTC signal to client [" + msg.targetEasyrtcid + "]. They may no longer be online.");
554
return;
555
}
556
pub.events.emit("emitEasyrtcCmd", targetConnectionObj, msg.msgType, outgoingMsg, null, next);
557
pub.util.sendSocketCallbackAck(easyrtcid, socketCallback, appObj);
558
next(null);
559
});
560
break;
561
562
default:
563
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_BAD_TYPE"), appObj);
564
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Received easyrtcCmd message with unhandled msgType.", msg);
565
next(null);
566
}
567
}
568
],
569
function(err) {
570
if (err) {
571
try {
572
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_GEN_FAIL"), appObj);
573
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Received easyrtcCmd message with general error.", msg);
574
} catch(e){}
575
}
576
});
577
};
578
579
580
/**
581
* Default listener for event "easyrtcMsg". This event is fired when an incoming 'easyrtcMsg' message is received from a client.
582
*
583
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
584
* @param {Object} msg Message object which contains the full message from a client; this can include the standard msgType and msgData fields.
585
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
586
* @param {nextCallback} next A success callback of form next(err).
587
*/
588
eventListener.onEasyrtcMsg = function(connectionObj, msg, socketCallback, next){
589
var easyrtcid = connectionObj.getEasyrtcid();
590
var appObj = connectionObj.getApp();
591
592
593
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message received of type [" + msg.msgType + "]");
594
595
if (!_.isFunction(next)) {
596
next = pub.util.nextToNowhere;
597
}
598
599
if(!_.isFunction(socketCallback)) {
600
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message received with no callback. Ignoring message.", msg);
601
return;
602
}
603
604
async.waterfall([
605
function(asyncCallback) {
606
// Check message structure
607
pub.util.isValidIncomingMessage("easyrtcMsg", msg, connectionObj.getApp(), asyncCallback);
608
},
609
610
function(isMsgValid, msgErrorCode, asyncCallback) {
611
// If message structure is invalid, send error, and write to log
612
if (!isMsgValid) {
613
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg(msgErrorCode), appObj);
614
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message received with invalid message format [" + msgErrorCode + "].", msg);
615
return;
616
}
617
asyncCallback(null);
618
},
619
function(asyncCallback) {
620
621
// test targetEasyrtcid (if defined). Will prevent client from sending to themselves
622
if (msg.targetEasyrtcid !== undefined && msg.targetEasyrtcid == connectionObj.getEasyrtcid()) {
623
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_TARGET_EASYRTCID"), appObj);
624
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message received with improper targetEasyrtcid", msg);
625
return;
626
}
627
628
// Determine if sending message to single client, an entire room, or an entire group
629
if (msg.targetEasyrtcid !== undefined) {
630
// Relay a message to a single client
631
var outgoingMsg = {
632
senderEasyrtcid: connectionObj.getEasyrtcid(),
633
targetEasyrtcid: msg.targetEasyrtcid,
634
msgType: msg.msgType,
635
msgData: msg.msgData
636
};
637
var targetConnectionObj = {};
638
639
async.waterfall([
640
function(asyncCallback) {
641
// getting connection object for targetEasyrtcid
642
connectionObj.getApp().connection(msg.targetEasyrtcid, asyncCallback);
643
},
644
function(newTargetConnectionObj, asyncCallback) {
645
targetConnectionObj = newTargetConnectionObj;
646
647
// TODO: Add option to restrict users not in same room from sending messages to users in room
648
649
// Handle targetRoom (if present)
650
if (msg.targetRoom) {
651
targetConnectionObj.isInRoom(msg.targetRoom, function(err, isAllowed){
652
if (err || !isAllowed) {
653
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_TARGET_ROOM"), appObj);
654
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message received with improper target room", msg);
655
return;
656
}
657
outgoingMsg.targetRoom = msg.targetRoom;
658
asyncCallback(null);
659
});
660
}
661
else {
662
asyncCallback(null);
663
}
664
},
665
666
function(asyncCallback) {
667
// Handle targetGroup (if present)
668
if (msg.targetGroup) {
669
targetConnectionObj.isInGroup(msg.targetGroup, function(err, isAllowed){
670
if (err || !isAllowed) {
671
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_TARGET_GROUP"), appObj);
672
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message received with improper target group", msg);
673
return;
674
}
675
outgoingMsg.targetGroup = msg.targetGroup;
676
asyncCallback(null);
677
});
678
}
679
else {
680
asyncCallback(null);
681
}
682
},
683
684
function(asyncCallback) {
685
pub.events.emit("emitEasyrtcMsg", targetConnectionObj, msg.msgType, outgoingMsg, null, asyncCallback);
686
}
687
688
],
689
function (err) {
690
if (err) {
691
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_GEN_FAIL"), appObj);
692
pub.util.logError("["+connectionObj.getEasyrtcid()+"] General message error. Message ignored.", err);
693
} else {
694
pub.util.sendSocketCallbackAck(easyrtcid, socketCallback, appObj); }
695
});
696
}
697
698
else if (msg.targetRoom) {
699
// Relay a message to one or more clients in a room
700
701
var outgoingMsg = {
702
senderEasyrtcid: connectionObj.getEasyrtcid(),
703
targetRoom: msg.targetRoom,
704
msgType: msg.msgType,
705
msgData: msg.msgData
706
};
707
708
var targetRoomObj = null;
709
710
async.waterfall([
711
function(asyncCallback){
712
// get room object
713
connectionObj.getApp().room(msg.targetRoom, asyncCallback);
714
},
715
716
function(newTargetRoomObj, asyncCallback) {
717
targetRoomObj = newTargetRoomObj;
718
719
// get list of connections in the room
720
targetRoomObj.getConnections(asyncCallback);
721
},
722
723
function(connectedEasyrtcidArray, asyncCallback) {
724
for (var i = 0; i < connectedEasyrtcidArray.length; i++) {
725
// Stop client from sending message to themselves
726
if (connectedEasyrtcidArray[i] == connectionObj.getEasyrtcid()) {
727
continue;
728
}
729
730
connectionObj.getApp().connection(connectedEasyrtcidArray[i], function(err, targetConnectionObj){
731
if (err) {
732
return;
733
}
734
735
// Do we limit by group? If not the message goes out to all in room
736
if(msg.targetGroup) {
737
targetConnectionObj.isInGroup(msg.targetGroup, function(err, isAllowed){
738
if (isAllowed) {
739
pub.events.emit("emitEasyrtcMsg", targetConnectionObj, msg.msgType, outgoingMsg, null, pub.util.nextToNowhere);
740
}
741
});
742
}
743
else {
744
pub.events.emit("emitEasyrtcMsg", targetConnectionObj, msg.msgType, outgoingMsg, null, pub.util.nextToNowhere);
745
}
746
});
747
}
748
asyncCallback(null);
749
}
750
],
751
function(err) {
752
if (err) {
753
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_TARGET_ROOM"), appObj);
754
}
755
else {
756
pub.util.sendSocketCallbackAck(easyrtcid, socketCallback, appObj); }
757
});
758
759
}
760
761
else if (msg.targetGroup) {
762
// Relay a message to one or more clients in a group
763
var targetGroupObj = null;
764
765
var outgoingMsg = {
766
senderEasyrtcid: connectionObj.getEasyrtcid(),
767
targetGroup: msg.targetGroup,
768
msgType: msg.msgType,
769
msgData: msg.msgData
770
};
771
772
async.waterfall([
773
function(asyncCallback){
774
// get group object
775
connectionObj.getApp().group(msg.targetGroup, asyncCallback);
776
},
777
778
function(newTargetGroupObj, asyncCallback) {
779
targetGroupObj = newTargetGroupObj;
780
781
// get list of connections in the group
782
targetGroupObj.getConnections(asyncCallback);
783
},
784
785
function(connectedEasyrtcidArray, asyncCallback) {
786
for (var i = 0; i < connectedEasyrtcidArray.length; i++) {
787
// Stop client from sending message to themselves
788
if (connectedEasyrtcidArray[i] == connectionObj.getEasyrtcid()) {
789
continue;
790
}
791
792
connectionObj.getApp().connection(connectedEasyrtcidArray[i], function(err, targetConnectionObj){
793
if (err) {
794
return;
795
}
796
pub.events.emit("emitEasyrtcMsg", targetConnectionObj, msg.msgType, outgoingMsg, null, pub.util.nextToNowhere);
797
});
798
}
799
asyncCallback(null);
800
}
801
],
802
function(err) {
803
if (err) {
804
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_TARGET_GROUP"), appObj);
805
}
806
else {
807
pub.util.sendSocketCallbackAck(easyrtcid, socketCallback, appObj);
808
}
809
});
810
811
}
812
else {
813
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message received without targetEasyrtcid or targetRoom", msg);
814
next(null);
815
}
816
}
817
],
818
function(err) {
819
if (err) {
820
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_GEN_FAIL"), appObj);
821
pub.util.logError("["+connectionObj.getEasyrtcid()+"] General message error. Message ignored.", err);
822
}
823
});
824
};
825
826
827
/**
828
* Default listener for event "emitEasyrtcCmd". This event is fired when the server should emit an EasyRTC command to a client.
829
*
830
* The easyrtcid and serverTime fields will be added to the msg automatically.
831
*
832
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
833
* @param {String} msgType Message type of the message.
834
* @param {Object} msg Message object which contains the full message to a client; this can include the standard msgData field.
835
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
836
* @param {nextCallback} next A success callback of form next(err).
837
*/
838
eventListener.onEmitEasyrtcCmd = function(connectionObj, msgType, msg, socketCallback, next){
839
if (!_.isObject(connectionObj)){
840
next(new pub.util.ConnectionError("Connection object invalid. Client may have disconnected."));
841
return;
842
}
843
844
var easyrtcid = connectionObj.getEasyrtcid();
845
var appName = connectionObj.getAppName();
846
847
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onEmitEasyrtcCmd' with msgType ["+msgType+"]");
848
if (!msg) {
849
msg = {};
850
}
851
if(!_.isFunction(socketCallback)) {
852
socketCallback = function(returnMsg) {
853
if (_.isObject(returnMsg) && _.isString(returnMsg.msgType) && returnMsg.msgType == "ack"){
854
// pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message: unhandled Ack return message.");
855
}
856
else {
857
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message: unhandled return message.", returnMsg);
858
}
859
};
860
}
861
862
msg.easyrtcid = connectionObj.getEasyrtcid();
863
msg.msgType = msgType;
864
msg.serverTime = Date.now();
865
866
connectionObj.socket.emit( "easyrtcCmd", msg, socketCallback);
867
868
if (pub.getOption("logMessagesEnable")) {
869
try {
870
pub.util.logDebug("["+appName+"]["+easyrtcid+"] Sending socket.io message: ["+JSON.stringify(msg)+"]");
871
}
872
catch(err) {
873
pub.util.logDebug("["+appName+"]["+easyrtcid+"] Sending socket.io message");
874
}
875
}
876
877
next(null);
878
};
879
880
881
/**
882
* Default listener for event "emitEasyrtcMsg". This event is fired when the server should emit an EasyRTC message to a client.
883
*
884
* The easyrtcid and serverTime fields will be added to the msg automatically.
885
*
886
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
887
* @param {String} msgType Message type of the message.
888
* @param {Object} msg Message object which contains the full message to a client; this can include the standard msgData field.
889
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
890
* @param {nextCallback} next A success callback of form next(err).
891
*/
892
eventListener.onEmitEasyrtcMsg = function(connectionObj, msgType, msg, socketCallback, next){
893
if (!_.isObject(connectionObj)){
894
next(new pub.util.ConnectionError("Connection object invalid. Client may have disconnected."));
895
return;
896
}
897
898
var easyrtcid = connectionObj.getEasyrtcid();
899
var appName = connectionObj.getAppName();
900
901
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onEmitEasyrtcMsg' with msgType ["+msgType+"]");
902
903
904
if (!msg) {
905
msg = {};
906
}
907
if(!_.isFunction(socketCallback)) {
908
socketCallback = function(returnMsg) {
909
if (_.isObject(returnMsg) && _.isString(returnMsg.msgType) && returnMsg.msgType == "ack"){
910
// pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message: unhandled Ack return message.");
911
}
912
else {
913
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC message: unhandled return message.", returnMsg);
914
}
915
};
916
}
917
msg.easyrtcid = connectionObj.getEasyrtcid();
918
msg.msgType = msgType;
919
msg.serverTime = Date.now();
920
921
connectionObj.socket.emit( "easyrtcMsg", msg, socketCallback);
922
923
if (pub.getOption("logMessagesEnable")) {
924
try {
925
pub.util.logDebug("["+appName+"]["+easyrtcid+"] Sending socket.io message: ["+JSON.stringify(msg)+"]");
926
}
927
catch(err) {
928
pub.util.logDebug("["+appName+"]["+easyrtcid+"] Sending socket.io message");
929
}
930
}
931
932
next(null);
933
};
934
935
936
/**
937
* Default listener for event "emitError". This event is fired when the server should emit an EasyRTC error to a client.
938
*
939
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
940
* @param {String} errorCode EasyRTC error code associated with an error.
941
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
942
* @param {nextCallback} next A success callback of form next(err).
943
*/
944
eventListener.onEmitError = function(connectionObj, errorCode, socketCallback, next){
945
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onEmitError'");
946
if(!_.isFunction(socketCallback)) {
947
socketCallback = function(returnMsg) {
948
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC info: unhandled ACK return message.", returnMsg);
949
};
950
}
951
if(!_.isFunction(next)) {
952
next = pub.util.nextToNowhere;
953
}
954
955
pub.events.emit("emitEasyrtcCmd", connectionObj, "error", pub.util.getErrorMsg(errorCode), socketCallback, next);
956
};
957
958
959
/**
960
* Default listener for event "emitReturnAck". This event is fired when the server should return an Ack to a client via an acknowledgment message.
961
*
962
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
963
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
964
* @param {nextCallback} next A success callback of form next(err).
965
*/
966
eventListener.onEmitReturnAck = function(connectionObj, socketCallback, next){
967
var easyrtcid = connectionObj.getEasyrtcid();
968
var appObj = connectionObj.getApp();
969
970
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onEmitReturnAck'");
971
if(!_.isFunction(socketCallback)) {
972
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC: unable to return ack to socket.");
973
return;
974
}
975
if(!_.isFunction(next)) {
976
next = pub.util.nextToNowhere;
977
}
978
979
var msg = {
980
msgType: "ack",
981
msgData:{}
982
};
983
984
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, msg, appObj);
985
986
next(null);
987
};
988
989
990
/**
991
* Default listener for event "emitReturnError". This event is fired when the server should return an Error to a client via an acknowledgment message.
992
*
993
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
994
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
995
* @param {String} errorCode EasyRTC error code associated with an error.
996
* @param {nextCallback} next A success callback of form next(err).
997
*/
998
eventListener.onEmitReturnError = function(connectionObj, socketCallback, errorCode, next){
999
var easyrtcid = connectionObj.getEasyrtcid();
1000
var appObj = connectionObj.getApp();
1001
1002
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onEmitReturnError'");
1003
if(!_.isFunction(socketCallback)) {
1004
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC: unable to return error to socket. Error code was [" + errorCode + "]");
1005
1006
next(new pub.util.ConnectionError("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Unable to return error to socket. Error code was [" + errorCode + "]"));
1007
return;
1008
}
1009
if(!_.isFunction(next)) {
1010
next = pub.util.nextToNowhere;
1011
}
1012
1013
var msg = pub.util.getErrorMsg(errorCode);
1014
1015
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, msg, appObj);
1016
1017
next(null);
1018
};
1019
1020
1021
/**
1022
* Default listener for event "emitReturnToken". This event is fired when the server should return a token to a client via an acknowledgment message.
1023
*
1024
* This is done after a client has been authenticated and the connection has been established.
1025
*
1026
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1027
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
1028
* @param {nextCallback} next A success callback of form next(err).
1029
*/
1030
eventListener.onEmitReturnToken = function(connectionObj, socketCallback, next){
1031
var easyrtcid = connectionObj.getEasyrtcid();
1032
var appObj = connectionObj.getApp();
1033
1034
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onSendToken'");
1035
1036
var tokenMsg = {
1037
msgType: "token",
1038
msgData:{}
1039
};
1040
1041
// Ensure socketCallback is present
1042
if(!_.isFunction(socketCallback)) {
1043
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC onSendToken called with no socketCallback.");
1044
try{connectionObj.socket.disconnect();}catch(e){}
1045
return;
1046
}
1047
1048
async.waterfall([
1049
function(asyncCallback){
1050
// Get rooms user is in along with list
1051
connectionObj.generateRoomClientList("join", null, asyncCallback);
1052
},
1053
function(roomData, asyncCallback) {
1054
// Set roomData
1055
tokenMsg.msgData.roomData = roomData;
1056
1057
// Retrieve ice config
1058
connectionObj.events.emit("getIceConfig", connectionObj, asyncCallback);
1059
},
1060
1061
function(iceServers, asyncCallback) {
1062
tokenMsg.msgData.application = {applicationName:connectionObj.getAppName()};
1063
tokenMsg.msgData.easyrtcid = connectionObj.getEasyrtcid();
1064
tokenMsg.msgData.iceConfig = {iceServers: iceServers};
1065
tokenMsg.msgData.serverTime = Date.now();
1066
1067
easyrtcid = tokenMsg.msgData.easyrtcid;
1068
1069
// Get Application fields
1070
appObj.getFields(true, asyncCallback);
1071
},
1072
1073
function(fieldObj, asyncCallback) {
1074
if (!_.isEmpty(fieldObj)){
1075
tokenMsg.msgData.application.field = fieldObj;
1076
}
1077
1078
// Get Connection fields
1079
connectionObj.getFields(true, asyncCallback);
1080
},
1081
1082
function(fieldObj, asyncCallback) {
1083
if (!_.isEmpty(fieldObj)){
1084
tokenMsg.msgData.field = fieldObj;
1085
}
1086
1087
// get session object
1088
connectionObj.getSessionObj(asyncCallback);
1089
},
1090
1091
function(sessionObj, asyncCallback) {
1092
if (sessionObj) {
1093
tokenMsg.msgData.sessionData = {"easyrtcsid":sessionObj.getEasyrtcsid()};
1094
1095
// Get session fields
1096
sessionObj.getFields(true, asyncCallback);
1097
}
1098
else {
1099
asyncCallback(null, null);
1100
}
1101
},
1102
1103
function(fieldObj, asyncCallback) {
1104
// Set session field (if present)
1105
if (fieldObj && !_.isEmpty(fieldObj)){
1106
tokenMsg.msgData.sessionData.field = fieldObj;
1107
}
1108
1109
// Emit token back to socket (SUCCESS!)
1110
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, tokenMsg, appObj);
1111
1112
asyncCallback(null);
1113
}
1114
1115
],
1116
// This function is called upon completion of the async waterfall, or upon an error being thrown.
1117
function (err) {
1118
if (err){
1119
next(err);
1120
} else {
1121
next(null);
1122
}
1123
});
1124
};
1125
1126
1127
/**
1128
* Default listener for event "log". This event is fired when ever a loggable item is observed.
1129
*
1130
* @param {string} level Log severity level. Can be ("debug"|"info"|"warning"|"error")
1131
* @param {string} logText Text for log.
1132
* @param {?*} [logFields] Simple JSON object which contains extra fields to be logged.
1133
* @param {?nextCallback} next A success callback of form next(err).
1134
*/
1135
eventListener.onLog = function(level, logText, logFields, next) {
1136
if(!_.isFunction(next)) {
1137
next = pub.util.nextToNowhere;
1138
}
1139
1140
var consoleText = "";
1141
1142
var currentDate = new Date();
1143
if (pub.getOption("logColorEnable")) {
1144
var colors = require("colors");
1145
if(pub.getOption("logDateEnable")) {
1146
consoleText += currentDate.toISOString().grey + " - ";
1147
}
1148
switch (level) {
1149
case "debug":
1150
consoleText += "debug ".bold.blue;
1151
break;
1152
case "info":
1153
consoleText += "info ".bold.green;
1154
break;
1155
case "warning":
1156
consoleText += "warning".bold.yellow;
1157
break;
1158
case "error":
1159
consoleText += "error ".bold.red;
1160
break;
1161
default:
1162
consoleText += level.bold;
1163
}
1164
consoleText += " - " + "EasyRTC: ".bold + logText;
1165
}
1166
else {
1167
if(pub.getOption("logDateEnable")) {
1168
consoleText += currentDate.toISOString() + " - ";
1169
}
1170
consoleText += level;
1171
consoleText += " - " + "EasyRTC: " + logText;
1172
}
1173
1174
if (logFields != undefined && logFields != null) {
1175
if (pub.getOption("logErrorStackEnable") && pub.util.isError(logFields)) {
1176
console.log(consoleText, ((pub.getOption("logColorEnable"))? "\nStack Trace:\n------------\n".bold + logFields.stack.magenta + "\n------------".bold : "\nStack Trace:\n------------\n" + logFields.stack + "\n------------"));
1177
}
1178
else if (pub.getOption("logWarningStackEnable") && pub.util.isWarning(logFields)) {
1179
console.log(consoleText, ((pub.getOption("logColorEnable"))? "\nStack Trace:\n------------\n".bold + logFields.stack.cyan + "\n------------".bold : "\nStack Trace:\n------------\n" + logFields.stack + "\n------------"));
1180
}
1181
else {
1182
console.log(consoleText, util.inspect(logFields, {colors:pub.getOption("logColorEnable"), showHidden:false, depth:pub.getOption("logObjectDepth")}));
1183
}
1184
} else {
1185
console.log(consoleText);
1186
}
1187
next(null);
1188
};
1189
1190
1191
/**
1192
* Default listener for event "msgTypeRoomJoin". This event is fired when an easyrtcCmd message with msgType of "roomJoin" is received from a client.
1193
*
1194
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1195
* @param {Object} rooms A room object containing a map of room names and room parameters.
1196
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
1197
* @param {nextCallback} next A success callback of form next(err).
1198
*/
1199
eventListener.onMsgTypeRoomJoin = function(connectionObj, rooms, socketCallback, next){
1200
var easyrtcid = connectionObj.getEasyrtcid();
1201
var appObj = connectionObj.getApp();
1202
1203
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onMsgTypeRoomJoin'");
1204
if(!_.isFunction(socketCallback)) {
1205
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC info: unhandled socket message callback.");
1206
return;
1207
}
1208
1209
if(!_.isFunction(next)) {
1210
next = pub.util.nextToNowhere;
1211
}
1212
1213
if(!_.isObject(rooms) || _.isEmpty(rooms)) {
1214
pub.events.emit("emitReturnError", socketCallback, "MSG_REJECT_BAD_STRUCTURE", pub.util.nextToNowhere);
1215
return;
1216
}
1217
1218
for (var currentRoomName in rooms) {
1219
if (!_.isString(currentRoomName) || !connectionObj.getApp().getOption("roomNameRegExp").test(currentRoomName)) {
1220
pub.events.emit("emitReturnError", socketCallback, "MSG_REJECT_TARGET_ROOM", pub.util.nextToNowhere);
1221
return;
1222
}
1223
}
1224
1225
async.each(Object.keys(rooms), function(currentRoomName, roomCallback) {
1226
appObj.isRoom(currentRoomName, function(err, isRoom){
1227
1228
// Set roomParameter map. This may be used by custom listeners.
1229
var currentRoomParameter;
1230
if (rooms[currentRoomName] && _.isObject(rooms[currentRoomName].roomParameter)){
1231
currentRoomParameter = rooms[currentRoomName].roomParameter;
1232
}
1233
1234
if (isRoom) {
1235
pub.events.emit("roomJoin", connectionObj, currentRoomName, currentRoomParameter, roomCallback);
1236
}
1237
else if (appObj.getOption("roomAutoCreateEnable")) {
1238
pub.events.emit("roomCreate", appObj, connectionObj, currentRoomName, null, function(err, roomObj){
1239
if (err) {
1240
roomCallback(err);
1241
return;
1242
}
1243
pub.events.emit("roomJoin", connectionObj, currentRoomName, currentRoomParameter, roomCallback);
1244
});
1245
}
1246
else {
1247
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"]["+currentRoomName+"] Unable to join non-existent room.");
1248
roomCallback(new pub.util.ConnectionError("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"]["+currentRoomName+"] Unable to join room."));
1249
}
1250
});
1251
}, function(err, newRoomObj) {
1252
if (err) {
1253
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_BAD_ROOM"), appObj);
1254
next(null); // Error has been handled
1255
return;
1256
}
1257
1258
connectionObj.generateRoomClientList("join", rooms, function(err, roomData){
1259
if (err) {
1260
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_BAD_ROOM"), appObj);
1261
next(null); // Error has been handled
1262
}
1263
else {
1264
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, {"msgType":"roomData", "msgData":{"roomData":roomData}}, appObj);
1265
}
1266
});
1267
});
1268
};
1269
1270
1271
/**
1272
* Default listener for event "msgTypeRoomLeave". This event is fired when an easyrtcCmd message with msgType of "roomLeave" is received from a client.
1273
*
1274
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1275
* @param {Object} rooms A room object containing a map of room names.
1276
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
1277
* @param {nextCallback} next A success callback of form next(err).
1278
*/
1279
eventListener.onMsgTypeRoomLeave = function(connectionObj, rooms, socketCallback, next){
1280
var easyrtcid = connectionObj.getEasyrtcid();
1281
var appObj = connectionObj.getApp();
1282
1283
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onMsgTypeRoomLeave' with rooms: ",rooms);
1284
if(!_.isFunction(socketCallback)) {
1285
socketCallback = function(returnMsg) {
1286
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC info: unhandled ACK return message.", returnMsg);
1287
};
1288
}
1289
1290
if(!_.isFunction(next)) {
1291
next = pub.util.nextToNowhere;
1292
}
1293
1294
// Loop through each room in the rooms object. Emit the leaveRoom event for each one.
1295
async.each(Object.keys(rooms), function(currentRoomName, asyncCallback) {
1296
connectionObj.events.emit("roomLeave", connectionObj, currentRoomName, function(err){
1297
if (err) {
1298
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Error leaving room ["+currentRoomName+"].", err);
1299
}
1300
asyncCallback(null);
1301
});
1302
}, function(err, newRoomObj) {
1303
var roomData = {};
1304
for (var currentRoomName in rooms) {
1305
roomData[currentRoomName]={
1306
"roomName": currentRoomName,
1307
"roomStatus": "leave"
1308
};
1309
}
1310
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, {"msgType":"roomData", "msgData":{"roomData":roomData}}, appObj);
1311
next(null);
1312
});
1313
};
1314
1315
1316
/**
1317
* Default listener for event "msgTypeGetIceConfig". This event is fired when an easyrtcCmd message with msgType of "getIceConfig" is received from a client.
1318
*
1319
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1320
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
1321
* @param {nextCallback} next A success callback of form next(err).
1322
*/
1323
eventListener.onMsgTypeGetIceConfig = function(connectionObj, socketCallback, next){
1324
var easyrtcid = connectionObj.getEasyrtcid();
1325
var appObj = connectionObj.getApp();
1326
1327
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onMsgTypeGetIceConfig'");
1328
1329
if(!_.isFunction(socketCallback)) {
1330
socketCallback = function(returnMsg) {
1331
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC info: unhandled ACK return message.", returnMsg);
1332
};
1333
}
1334
1335
if(!_.isFunction(next)) {
1336
next = pub.util.nextToNowhere;
1337
}
1338
1339
connectionObj.events.emit("getIceConfig", connectionObj, function(err, iceConfigObj){
1340
if (err) {
1341
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_GEN_FAIL"), appObj);
1342
}
1343
else {
1344
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, {"msgType":"iceConfig", "msgData":{"iceConfig":{"iceServers":iceConfigObj}}}, appObj);
1345
}
1346
next(null);
1347
});
1348
};
1349
1350
1351
/**
1352
* Default listener for event "msgTypeGetRoomList". This event is fired when an easyrtcCmd message with msgType of "getRoomList" is received from a client.
1353
*
1354
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1355
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
1356
* @param {nextCallback} next A success callback of form next(err).
1357
*/
1358
eventListener.onMsgTypeGetRoomList = function(connectionObj, socketCallback, next){
1359
var easyrtcid = connectionObj.getEasyrtcid();
1360
var appObj = connectionObj.getApp();
1361
1362
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onMsgTypeGetRoomList'");
1363
1364
if(!_.isFunction(socketCallback)) {
1365
socketCallback = function(returnMsg) {
1366
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC info: unhandled ACK return message.", returnMsg);
1367
};
1368
}
1369
1370
if(!_.isFunction(next)) {
1371
next = pub.util.nextToNowhere;
1372
}
1373
1374
connectionObj.generateRoomList(
1375
function(err, roomList) {
1376
if(err) {
1377
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_NO_ROOM_LIST"), appObj);
1378
}
1379
else {
1380
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, {"msgType":"roomList", "msgData":{"roomList":roomList}}, appObj);
1381
}
1382
next(null);
1383
}
1384
);
1385
};
1386
1387
1388
/**
1389
* Default listener for event "msgTypeSetPresence". This event is fired when an easyrtcCmd message with msgType of "setPresence" is received from a client.
1390
*
1391
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1392
* @param {Object} presenceObj Presence object which contains all the fields for setting a presence for a connection.
1393
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
1394
* @param {nextCallback} next A success callback of form next(err).
1395
*/
1396
eventListener.onMsgTypeSetPresence = function(connectionObj, presenceObj, socketCallback, next){
1397
var easyrtcid = connectionObj.getEasyrtcid();
1398
var appObj = connectionObj.getApp();
1399
1400
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onMsgTypeSetPresence' with setPresence: ",presenceObj);
1401
if(!_.isFunction(socketCallback)) {
1402
socketCallback = function(returnMsg) {
1403
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC info: unhandled ACK return message.", returnMsg);
1404
};
1405
}
1406
1407
if(!_.isFunction(next)) {
1408
next = pub.util.nextToNowhere;
1409
}
1410
1411
connectionObj.setPresence(
1412
presenceObj,
1413
function(err){
1414
if (err) {
1415
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_PRESENCE"), appObj);
1416
}
1417
else {
1418
connectionObj.emitRoomDataDelta(false, function(err, roomDataObj){
1419
if (err) {
1420
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_PRESENCE"), appObj);
1421
}
1422
else {
1423
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, {"msgType":"roomData", "msgData":{"roomData":roomDataObj}}, appObj);
1424
}
1425
});
1426
}
1427
next(null);
1428
}
1429
);
1430
};
1431
1432
1433
/**
1434
* Default listener for event "msgTypeSetRoomApiField". This event is fired when an easyrtcCmd message with msgType of "setRoomApiField" is received from a client.
1435
*
1436
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1437
* @param {Object} roomApiFieldObj Api Field object which contains all the fields for setting a presence for a connection.
1438
* @param {Function} socketCallback Socket.io callback function which delivers a response to a socket. Expects a single parameter (msg).
1439
* @param {nextCallback} next A success callback of form next(err).
1440
*/
1441
eventListener.onMsgTypeSetRoomApiField = function(connectionObj, roomApiFieldObj, socketCallback, next){
1442
var easyrtcid = connectionObj.getEasyrtcid();
1443
var appObj = connectionObj.getApp();
1444
1445
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onMsgTypeSetRoomApiField' with apiFieldObj: ",roomApiFieldObj);
1446
if(!_.isFunction(socketCallback)) {
1447
socketCallback = function(returnMsg) {
1448
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] EasyRTC info: unhandled ACK return message.", returnMsg);
1449
};
1450
}
1451
1452
if(!_.isFunction(next)) {
1453
next = pub.util.nextToNowhere;
1454
}
1455
1456
connectionObj.room(roomApiFieldObj.roomName, function(err, connectionRoomObj){
1457
if (err) {
1458
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_BAD_ROOM"), appObj);
1459
next(null);
1460
return;
1461
}
1462
connectionRoomObj.setApiField(roomApiFieldObj.field, function(err){
1463
if (err) {
1464
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_BAD_FIELD"), appObj);
1465
next(null);
1466
return;
1467
}
1468
connectionRoomObj.emitRoomDataDelta(false, function(err, roomDataDelta){
1469
if (err) {
1470
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("MSG_REJECT_GEN_FAIL"), appObj);
1471
next(null);
1472
return;
1473
}
1474
1475
var msg = {"msgType":"roomData", "msgData": {"roomData": {}}};
1476
msg.msgData.roomData[roomApiFieldObj.roomName] = roomDataDelta;
1477
pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, msg, appObj);
1478
});
1479
});
1480
});
1481
};
1482
1483
1484
/**
1485
* Default listener for event "getIceConfig". Returns an ICE configuration object to the callback.
1486
*
1487
* The ICE configuration object will hold the array of STUN and TURN servers the connection should use when forming a peer connection. This default listener uses the "appIceServers" configuration option at the application level.
1488
*
1489
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1490
* @param {Function} callback Callback of form (err, iceConfigArray)
1491
*/
1492
eventListener.onGetIceConfig = function(connectionObj, callback){
1493
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onGetIceConfig'");
1494
callback(null, connectionObj.getApp().getOption("appIceServers"));
1495
};
1496
1497
1498
/**
1499
* Default listener for event "roomCreate". Creates a room attached to an application with a specified room name. The optional creatorConnectionObj is provided to provide context; joining the room is done separately. If successful, the callback returns a roomObj.
1500
*
1501
* @param {Object} appObj EasyRTC application object. Contains methods used for identifying and managing an application.
1502
* @param {?Object} creatorConnectionObj EasyRTC connection object belonging to the creator of the room. Contains methods used for identifying and managing a connection.
1503
* @param {string} roomName Room name which uniquely identifies a room within an EasyRTC application.
1504
* @param {?Object} roomOptions Sets room level options. May be null or map of key/value pairs.
1505
* @param {Function} callback Callback of form (err, roomObj)
1506
*/
1507
eventListener.onRoomCreate = function(appObj, creatorConnectionObj, roomName, roomOptions, callback){
1508
pub.util.logDebug("["+appObj.getAppName()+"]" + (creatorConnectionObj?"["+creatorConnectionObj.getEasyrtcid()+"]":"") + " Room ["+ roomName +"] Running func 'onRoomCreate'");
1509
appObj.createRoom(roomName, roomOptions, callback);
1510
};
1511
1512
1513
/**
1514
* Default listener for event "roomJoin". Joins a connection to a a specified room. If successful, the callback will return a connectionRoomObj.
1515
*
1516
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1517
* @param {string} roomName Room name which uniquely identifies a room within an EasyRTC application.
1518
* @param {?Object} roomParameter A map(dictionary) object with key/value pairs. The values can be any JSONable object. This field is not currently looked at by EasyRTC, however it is available for custom server applications. May be used for room options or authentication needs.
1519
* @param {Function} callback Callback of form (err, connectionRoomObj)
1520
*/
1521
eventListener.onRoomJoin = function(connectionObj, roomName, roomParameter, callback){
1522
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onRoomJoin'");
1523
1524
// roomParameter is a new field. To ease upgrading we'll just show a warning to server applications which haven't updated
1525
if (_.isFunction(roomParameter)){
1526
pub.util.logWarning("Upgrade notice: EasyRTC roomJoin event called without roomParameter object.");
1527
callback = roomParameter;
1528
roomParameter = null;
1529
}
1530
1531
connectionObj.joinRoom(roomName, function(err, connectionRoomObj){
1532
if (err) {
1533
callback(err);
1534
return;
1535
}
1536
connectionRoomObj.emitRoomDataDelta(false, function(err, roomDataDelta){
1537
// Return connectionRoomObj regardless of if there was a problem sending out the deltas
1538
callback(null, connectionRoomObj);
1539
});
1540
});
1541
};
1542
1543
1544
/**
1545
* Default listener for event "roomLeave". Run upon a connection leaving a room.
1546
*
1547
* @param {Object} connectionObj EasyRTC connection object. Contains methods used for identifying and managing a connection.
1548
* @param {string} roomName Room name which uniquely identifies a room within an EasyRTC application.
1549
* @param {nextCallback} next A success callback of form next(err).
1550
*/
1551
eventListener.onRoomLeave = function(connectionObj, roomName, next){
1552
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Running func 'onRoomLeave' with rooms ["+roomName+"]");
1553
1554
if(!_.isFunction(next)) {
1555
next = pub.util.nextToNowhere;
1556
}
1557
1558
connectionObj.room(roomName, function(err, connectionRoomObj){
1559
if (err) {
1560
pub.util.logWarning("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Couldn't leave room [" + roomName + "]");
1561
next(err);
1562
return;
1563
}
1564
1565
pub.util.logDebug("["+connectionObj.getAppName()+"]["+connectionObj.getEasyrtcid()+"] Leave room [" + roomName + "]");
1566
connectionRoomObj.leaveRoom(next);
1567
});
1568
};
1569
1570
1571
/**
1572
* Default listener for event "shutdown". This event is fired when the server is being shutdown.
1573
*
1574
* @param {nextCallback} next A success callback of form next(err).
1575
*/
1576
eventListener.onShutdown = function(next){
1577
pub.util.logDebug("Running func 'onShutdown'");
1578
next(null);
1579
};
1580
1581
1582
/**
1583
* Default listener for event "startup". This event initializes EasyRTC server so it is ready for connections.
1584
*
1585
* @param {nextCallback} next A success callback of form next(err).
1586
*/
1587
eventListener.onStartup = function(next){
1588
if (!_.isFunction(next)) {
1589
next = pub.util.nextToNowhere;
1590
}
1591
1592
pub.util.logDebug("Running func 'onStartup'");
1593
async.waterfall([
1594
function(callback) {
1595
pub.util.logDebug("Configuring Http server");
1596
1597
// Set the EasyRTC demos
1598
if (pub.getOption("demosEnable")) {
1599
pub.util.logDebug("Setting up demos to be accessed from '" + pub.getOption("demosPublicFolder") + "/'");
1600
pub.httpApp.get(pub.getOption("demosPublicFolder") + "/*", function(req, res) {
1601
(res.sendFile||res.sendfile).call(res,
1602
"./demos/" + (req.params[0] ? req.params[0] : "index.html"),
1603
// TODO security check
1604
{root:__dirname + "/../"},
1605
function(err) {
1606
try{if (err && err.status && res && !res._headerSent) {
1607
res.status(404);
1608
var body = "<html><head><title>File Not Found</title></head><body><h1>File Not Found</h1></body></html>";
1609
res.setHeader("Content-Type", "text/html");
1610
res.setHeader("Content-Length", body.length);
1611
res.end(body);
1612
}}catch(e){}
1613
}
1614
);
1615
});
1616
// Forward people who forget the trailing slash to the folder.
1617
pub.httpApp.get(pub.getOption("demosPublicFolder"), function(req, res) {res.redirect(pub.getOption("demosPublicFolder") + "/");});
1618
}
1619
1620
if (pub.getOption("apiEnable")) {
1621
// Set the EasyRTC API files
1622
pub.util.logDebug("Setting up API files to be accessed from '" + pub.getOption("apiPublicFolder") + "/'");
1623
pub.httpApp.get(pub.getOption("apiPublicFolder") + "/easyrtc.js", function(req, res) {pub.util.sendSessionCookie(req, res); (res.sendFile||res.sendfile).call(res,"api/easyrtc.js", {root:__dirname + "/../"});});
1624
pub.httpApp.get(pub.getOption("apiPublicFolder") + "/easyrtc_ft.js", function(req, res) {pub.util.sendSessionCookie(req, res); (res.sendFile||res.sendfile).call(res,"api/easyrtc_ft.js", {root:__dirname + "/../"});});
1625
pub.httpApp.get(pub.getOption("apiPublicFolder") + "/easyrtc.css", function(req, res) {pub.util.sendSessionCookie(req, res); (res.sendFile||res.sendfile).call(res,"api/easyrtc.css", {root:__dirname + "/../"});});
1626
pub.httpApp.get(pub.getOption("apiPublicFolder") + "/easyrtc.min.js", function(req, res) {pub.util.sendSessionCookie(req, res); (res.sendFile||res.sendfile).call(res,"open_source/api/easyrtc.min.js", {root:__dirname + "/../"});});
1627
pub.httpApp.get(pub.getOption("apiPublicFolder") + "/easyrtc_ft.min.js", function(req, res) {pub.util.sendSessionCookie(req, res); (res.sendFile||res.sendfile).call(res,"api/easyrtc_ft.min.js", {root:__dirname + "/../"});});
1628
pub.httpApp.get(pub.getOption("apiPublicFolder") + "/easyrtc.min.css", function(req, res) {pub.util.sendSessionCookie(req, res); (res.sendFile||res.sendfile).call(res,"open_source/api/easyrtc.min.css", {root:__dirname + "/../"});});
1629
pub.httpApp.get(pub.getOption("apiPublicFolder") + "/img/*", function(req, res) {
1630
pub.util.sendSessionCookie(req, res);
1631
(res.sendFile||res.sendfile).call(res,
1632
"./api/img/" + (req.params[0] ? req.params[0] : "index.html"),
1633
{root:__dirname + "/../"},
1634
function(err) {
1635
try{if (err && err.status && res && !res._headerSent) {
1636
res.status(404);
1637
var body = "<html><head><title>File Not Found</title></head><body><h1>File Not Found</h1></body></html>";
1638
res.setHeader("Content-Type", "text/html");
1639
res.setHeader("Content-Length", body.length);
1640
res.end(body);
1641
}}catch(e){}
1642
}
1643
);
1644
});
1645
if(pub.getOption("apiLabsEnable")){
1646
pub.httpApp.get(pub.getOption("apiPublicFolder") + "/labs/*", function(req, res) {
1647
pub.util.sendSessionCookie(req, res);
1648
(res.sendFile||res.sendfile).call(res,
1649
"./api/labs/" + (req.params[0] ? req.params[0] : "index.html"),
1650
{root:__dirname + "/../"},
1651
function(err) {
1652
try{if (err && err.status && res && !res._headerSent) {
1653
res.status(404);
1654
var body = "<html><head><title>File Not Found</title></head><body><h1>File Not Found</h1></body></html>";
1655
res.setHeader("Content-Type", "text/html");
1656
res.setHeader("Content-Length", body.length);
1657
res.end(body);
1658
}}catch(e){}
1659
}
1660
);
1661
});
1662
}
1663
}
1664
1665
if (pub.getOption("apiEnable") && pub.getOption("apiOldLocationEnable")) {
1666
pub.util.logWarning("Enabling listening for API files in older depreciated location.");
1667
// Transition - Old locations of EasyRTC API files
1668
pub.httpApp.get("/js/easyrtc.js", function(req, res) {(res.sendFile||res.sendfile).call(res,"api/easyrtc.js", {root:__dirname + "/../"});});
1669
pub.httpApp.get("/css/easyrtc.css", function(req, res) {(res.sendFile||res.sendfile).call(res,"api/easyrtc.css", {root:__dirname + "/../"});});
1670
}
1671
callback(null);
1672
},
1673
1674
function(callback) {
1675
pub.util.logDebug("Configuring Socket server");
1676
1677
pub.socketServer.sockets.on("connection", function (socket) {
1678
var easyrtcid = pub.util.getAvailableEasyrtcid();
1679
1680
pub.util.logDebug("["+easyrtcid+"]["+socket.id+"] Socket connected");
1681
pub.util.logDebug("Emitting event 'connection'");
1682
pub.events.emit("connection", socket, easyrtcid, function(err){
1683
if(err){
1684
socket.disconnect();
1685
pub.util.logError("["+easyrtcid+"] Connect error", err);
1686
}
1687
});
1688
});
1689
callback(null);
1690
},
1691
1692
// Setup default application
1693
function(callback) {
1694
pub.createApp(pub.getOption("appDefaultName"), null, callback);
1695
},
1696
1697
function(appObj, callback) {
1698
// Checks to see if there is a newer version of EasyRTC available
1699
if (pub.getOption("updateCheckEnable")) {
1700
pub.util.updateCheck();
1701
}
1702
callback(null);
1703
}
1704
],
1705
// This function is called upon completion of the async waterfall, or upon an error being thrown.
1706
function (err) {
1707
next(err);
1708
});
1709
};