-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.js
1143 lines (1076 loc) · 36 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Provides Node.js - Drupal integration.
*/
var request = require('request'),
url = require('url'),
fs = require('fs'),
express = require('express'),
socket_io = require('socket.io'),
util = require('util'),
querystring = require('querystring'),
vm = require('vm');
var channels = {},
authenticatedClients = {},
onlineUsers = {},
presenceTimeoutIds = {},
contentChannelTimeoutIds = {},
tokenChannels = {},
settingsDefaults = {
scheme: 'http',
port: 8080,
host: 'localhost',
resource: '/socket.io',
serviceKey: '',
debug: false,
baseAuthPath: '/nodejs/',
publishUrl: 'publish',
kickUserUrl: 'user/kick/:uid',
logoutUserUrl: 'user/logout/:authtoken',
addUserToChannelUrl: 'user/channel/add/:channel/:uid',
removeUserFromChannelUrl: 'user/channel/remove/:channel/:uid',
addChannelUrl: 'channel/add/:channel',
removeChannelUrl: 'channel/remove/:channel',
setUserPresenceListUrl: 'user/presence-list/:uid/:uidList',
addAuthTokenToChannelUrl: 'authtoken/channel/add/:channel/:uid',
removeAuthTokenFromChannelUrl: 'authtoken/channel/remove/:channel/:uid',
toggleDebugUrl: 'debug/toggle',
contentTokenUrl: 'content/token',
publishMessageToContentChannelUrl: 'content/token/message',
getContentTokenUsersUrl: 'content/token/users',
extensions: [],
clientsCanWriteToChannels: false,
clientsCanWriteToClients: false,
transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'],
jsMinification: true,
jsEtag: true,
backend: {
host: 'localhost',
scheme: 'http',
port: 80,
basePath: '/',
messagePath: 'nodejs/message'
},
logLevel: 1
},
extensions = [];
try {
var settings = vm.runInThisContext(fs.readFileSync(process.cwd() + '/nodejs.config.js'));
}
catch (exception) {
console.log("Failed to read config file, exiting: " + exception);
process.exit(1);
}
for (var key in settingsDefaults) {
if (key != 'backend' && !settings.hasOwnProperty(key)) {
settings[key] = settingsDefaults[key];
}
}
if (!settings.hasOwnProperty('backend')) {
settings.backend = settingsDefaults.backend;
}
else {
for (var key2 in settingsDefaults.backend) {
if (!settings.backend.hasOwnProperty(key2)) {
settings.backend[key2] = settingsDefaults.backend[key2];
}
}
}
// Load server extensions
for (var i in settings.extensions) {
try {
// Load JS files for extensions as modules, and collect the returned
// object for each extension.
extensions.push(require(__dirname + '/' + settings.extensions[i]));
console.log("Extension loaded: " + settings.extensions[i]);
}
catch (exception) {
console.log("Failed to load extension " + settings.extensions[i] + " [" + exception + "]");
process.exit(1);
}
}
/**
* Check if the given channel is client-writable.
*/
var channelIsClientWritable = function (channel) {
if (channels.hasOwnProperty(channel)) {
return channels[channel].isClientWritable;
}
return false;
}
/**
* Returns the backend url.
*/
var getBackendUrl = function () {
return settings.backend.scheme + '://' + settings.backend.host + ':' +
settings.backend.port + settings.backend.basePath + settings.backend.messagePath;
}
/**
* Send a message to the backend.
*/
var sendMessageToBackend = function (message, callback) {
var requestBody = querystring.stringify({
messageJson: JSON.stringify(message),
serviceKey: settings.serviceKey
});
var options = {
uri: getBackendUrl(),
body: requestBody,
headers: {
'Content-Length': Buffer.byteLength(requestBody),
'Content-Type': 'application/x-www-form-urlencoded'
}
}
if (settings.debug) {
console.log("Sending message to backend", message, options);
}
request.post(options, callback);
}
/**
* Authenticate a client connection based on the message it sent.
*/
var authenticateClient = function (client, message) {
// If the authToken is verified, initiate a connection with the client.
if (authenticatedClients[message.authToken]) {
if (settings.debug) {
console.log('Reusing existing authentication data for key:', message.authToken, ', client id:', client.id);
}
setupClientConnection(client.id, authenticatedClients[message.authToken], message.contentTokens);
}
else {
message.messageType = 'authenticate';
message.clientId = client.id;
sendMessageToBackend(message, authenticateClientCallback);
}
}
/**
* Handle authentication call response.
*/
var authenticateClientCallback = function (error, response, body) {
if (error) {
console.log("Error with authenticate client request:", error);
return;
}
if (response.statusCode == 404) {
if (settings.debug) {
console.log('Backend authentication url not found, full response info:', response);
}
else {
console.log('Backend authentication url not found.');
}
return;
}
var authData = false;
try {
authData = JSON.parse(body);
}
catch (exception) {
console.log('Failed to parse authentication message:', exception);
if (settings.debug) {
console.log('Failed message string: ' + body);
}
return;
}
if (!checkServiceKey(authData.serviceKey)) {
console.log('Invalid service key "', authData.serviceKey, '"');
return;
}
if (authData.nodejsValidAuthToken) {
if (settings.debug) {
console.log('Valid login for uid "', authData.uid, '"');
}
setupClientConnection(authData.clientId, authData, authData.contentTokens);
authenticatedClients[authData.authToken] = authData;
}
else {
console.log('Invalid login for uid "', authData.uid, '"');
delete authenticatedClients[authData.authToken];
}
}
/**
* Send a presence notifcation for uid.
*/
var sendPresenceChangeNotification = function (uid, presenceEvent) {
if (onlineUsers[uid]) {
for (var i in onlineUsers[uid]) {
var sessionIds = getNodejsSessionIdsFromUid(onlineUsers[uid][i]);
if (sessionIds.length > 0 && settings.debug) {
console.log('Sending presence notification for', uid, 'to', onlineUsers[uid][i]);
}
for (var j in sessionIds) {
io.sockets.socket(sessionIds[j]).json.send({'presenceNotification': {'uid': uid, 'event': presenceEvent}});
}
}
}
if (settings.debug) {
console.log('sendPresenceChangeNotification', uid, presenceEvent, onlineUsers);
}
}
/**
* Callback that wraps all requests and checks for a valid service key.
*/
var checkServiceKeyCallback = function (request, response, next) {
if (checkServiceKey(request.header('NodejsServiceKey', ''))) {
next();
}
else {
response.send({'error': 'Invalid service key.'});
}
}
/**
* Check a service key against the configured service key.
*/
var checkServiceKey = function (serviceKey) {
if (settings.serviceKey && serviceKey != settings.serviceKey) {
console.log('Invalid service key "' + serviceKey + '", expecting "' + settings.serviceKey + '"');
return false;
}
return true;
}
/**
* Http callback - return the list of content channel users.
*/
var getContentTokenUsers = function (request, response) {
var requestBody = '';
request.setEncoding('utf8');
request.on('data', function (chunk) {
requestBody += chunk;
});
request.on('end', function () {
try {
var channel = JSON.parse(requestBody);
}
catch (exception) {
console.log('getContentTokensUsers: Invalid JSON "' + requestBody + '"', exception);
response.send({error: 'Invalid JSON, error: ' + exception.toString()});
}
try {
response.send({users: getContentTokenChannelUsers(channel.channel)});
}
catch (exception) {
console.log('getContentTokensUsers:', exception);
response.send({error: 'Error calling getContentTokenChannelUsers() for channel "' + channel.channel + '", error: ' + exception.toString()});
}
});
}
/**
* Http callback - set the debug flag.
*/
var toggleDebug = function (request, response) {
var requestBody = '';
request.setEncoding('utf8');
request.on('data', function (chunk) {
requestBody += chunk;
});
request.on('end', function () {
try {
var toggle = JSON.parse(requestBody);
settings.debug = toggle.debug;
response.send({debug: toggle.debug});
}
catch (exception) {
console.log('toggleDebug: Invalid JSON "' + requestBody + '"', exception);
response.send({error: 'Invalid JSON, error: ' + e.toString()});
}
});
}
/**
* Http callback - read in a JSON message and publish it to interested clients.
*/
var publishMessage = function (request, response) {
var sentCount = 0, requestBody = '';
request.setEncoding('utf8');
request.on('data', function (chunk) {
requestBody += chunk;
});
request.on('end', function () {
try {
var message = JSON.parse(requestBody);
if (settings.debug) {
console.log('publishMessage: message', message);
}
}
catch (exception) {
console.log('publishMessage: Invalid JSON "' + requestBody + '"', exception);
response.send({error: 'Invalid JSON, error: ' + exception.toString()});
return;
}
if (message.broadcast) {
if (settings.debug) {
console.log('Broadcasting message');
}
io.sockets.json.send(message);
sentCount = io.sockets.sockets.length;
}
else {
sentCount = publishMessageToChannel(message);
}
process.emit('message-published', message, sentCount);
response.send({sent: sentCount});
});
}
/**
* Publish a message to clients subscribed to a channel.
*/
var publishMessageToChannel = function (message) {
if (!message.hasOwnProperty('channel')) {
console.log('publishMessageToChannel: An invalid message object was provided.');
return 0;
}
if (!channels.hasOwnProperty(message.channel)) {
console.log('publishMessageToChannel: The channel "' + message.channel + '" doesn\'t exist.');
return 0;
}
var clientCount = 0;
for (var sessionId in channels[message.channel].sessionIds) {
if (publishMessageToClient(sessionId, message)) {
clientCount++;
}
}
if (settings.debug) {
console.log('Sent message to ' + clientCount + ' clients in channel "' + message.channel + '"');
}
return clientCount;
}
/**
* Publish a message to clients subscribed to a channel.
*/
var publishMessageToContentChannel = function (request, response) {
var sentCount = 0, requestBody = '';
request.setEncoding('utf8');
request.on('data', function (chunk) {
requestBody += chunk;
});
request.on('end', function () {
try {
var message = JSON.parse(requestBody);
if (settings.debug) {
console.log('publishMessageToContentChannel: message', message);
}
}
catch (exception) {
console.log('publishMessageToContentChannel: Invalid JSON "' + requestBody + '"', exception);
response.send({error: 'Invalid JSON, error: ' + exception.toString()});
return;
}
if (!message.hasOwnProperty('channel')) {
console.log('publishMessageToContentChannel: An invalid message object was provided.');
response.send({error: 'Invalid message'});
return;
}
if (!tokenChannels.hasOwnProperty(message.channel)) {
console.log('publishMessageToContentChannel: The channel "' + message.channel + '" doesn\'t exist.');
response.send({error: 'Invalid message'});
return;
}
for (var socketId in tokenChannels[message.channel].sockets) {
publishMessageToClient(socketId, message);
}
response.send({sent: 'sent'});
});
}
/**
* Publish a message to a specific client.
*/
var publishMessageToClient = function (sessionId, message) {
if (io.sockets.sockets[sessionId]) {
io.sockets.socket(sessionId).json.send(message);
if (settings.debug) {
console.log('Sent message to client ' + sessionId);
}
return true;
}
else {
console.log('publishMessageToClient: Failed to find client ' + sessionId);
}
};
/**
* Sends a 404 message.
*/
var send404 = function (request, response) {
response.send('Not Found.', 404);
};
/**
* Kicks the given logged in user from the server.
*/
var kickUser = function (request, response) {
if (request.params.uid) {
// Delete the user from the authenticatedClients hash.
for (var authToken in authenticatedClients) {
if (authenticatedClients[authToken].uid == request.params.uid) {
delete authenticatedClients[authToken];
}
}
// Destroy any socket connections associated with this uid.
for (var clientId in io.sockets.sockets) {
if (io.sockets.sockets[clientId].uid == request.params.uid) {
delete io.sockets.sockets[clientId];
if (settings.debug) {
console.log('kickUser: deleted socket "' + clientId + '" for uid "' + request.params.uid + '"');
}
// Delete any channel entries for this clientId.
for (var channel in channels) {
delete channels[channel].sessionIds[clientId];
}
}
}
response.send({'status': 'success'});
return;
}
console.log('Failed to kick user, no uid supplied');
response.send({'status': 'failed', 'error': 'missing uid'});
};
/**
* Logout the given user from the server.
*/
var logoutUser = function (request, response) {
var authToken = request.params.authtoken || '';
if (authToken) {
console.log('Logging out http session', authToken);
// Delete the user from the authenticatedClients hash.
delete authenticatedClients[authToken];
// Destroy any socket connections associated with this authToken.
for (var clientId in io.sockets.sockets) {
if (io.sockets.sockets[clientId].authToken == authToken) {
delete io.sockets.sockets[clientId];
// Delete any channel entries for this clientId.
for (var channel in channels) {
delete channels[channel].sessionIds[clientId];
}
}
}
response.send({'status': 'success'});
return;
}
console.log('Failed to logout user, no authToken supplied');
response.send({'status': 'failed', 'error': 'missing authToken'});
};
/**
* Get the list of backend uids and authTokens connected to a content token channel.
*/
var getContentTokenChannelUsers = function (channel) {
var users = {uids: [], authTokens: []};
for (var sessionId in tokenChannels[channel].sockets) {
if (io.sockets.sockets[sessionId].uid) {
users.uids.push(io.sockets.sockets[sessionId].uid);
}
else {
users.authTokens.push(io.sockets.sockets[sessionId].authToken);
}
}
return users;
}
/**
* Get the list of Node.js sessionIds for a given uid.
*/
var getNodejsSessionIdsFromUid = function (uid) {
var sessionIds = [];
for (var sessionId in io.sockets.sockets) {
if (io.sockets.sockets[sessionId].uid == uid) {
sessionIds.push(sessionId);
}
}
if (settings.debug) {
console.log('getNodejsSessionIdsFromUid', {uid: uid, sessionIds: sessionIds});
}
return sessionIds;
}
/**
* Get the list of Node.js sessionIds for a given authToken.
*/
var getNodejsSessionIdsFromAuthToken = function (authToken) {
var sessionIds = [];
for (var sessionId in io.sockets.sockets) {
if (io.sockets.sockets[sessionId].authToken == authToken) {
sessionIds.push(sessionId);
}
}
if (settings.debug) {
console.log('getNodejsSessionIdsFromAuthToken', {authToken: authToken, sessionIds: sessionIds});
}
return sessionIds;
}
/**
* Add a user to a channel.
*/
var addUserToChannel = function (request, response) {
var uid = request.params.uid || '';
var channel = request.params.channel || '';
if (uid && channel) {
if (!/^\d+$/.test(uid)) {
console.log("Invalid uid: " + uid);
response.send({'status': 'failed', 'error': 'Invalid uid.'});
return;
}
if (!/^[a-z0-9_]+$/i.test(channel)) {
console.log("Invalid channel: " + channel);
response.send({'status': 'failed', 'error': 'Invalid channel name.'});
return;
}
channels[channel] = channels[channel] || {'sessionIds': {}};
var sessionIds = getNodejsSessionIdsFromUid(uid);
if (sessionIds.length > 0) {
for (var i in sessionIds) {
channels[channel].sessionIds[sessionIds[i]] = sessionIds[i];
}
if (settings.debug) {
console.log("Added channel '" + channel + "' to sessionIds " + sessionIds.join());
}
response.send({'status': 'success'});
}
else {
console.log("No active sessions for uid: " + uid);
response.send({'status': 'failed', 'error': 'No active sessions for uid.'});
}
for (var authToken in authenticatedClients) {
if (authenticatedClients[authToken].uid == uid) {
if (authenticatedClients[authToken].channels.indexOf(channel) == -1) {
authenticatedClients[authToken].channels.push(channel);
if (settings.debug) {
console.log("Added channel '" + channel + "' authenticatedClients");
}
}
}
}
}
else {
console.log("Missing uid or channel");
response.send({'status': 'failed', 'error': 'Missing uid or channel'});
}
};
/**
* Add an authToken to a channel.
*/
var addAuthTokenToChannel = function (request, response) {
var authToken = request.params.authToken || '';
var channel = request.params.channel || '';
if (!authToken || !channel) {
console.log("Missing authToken or channel");
response.send({'status': 'failed', 'error': 'Missing authToken or channel'});
return;
}
if (!/^[a-z0-9_]+$/i.test(channel)) {
console.log("Invalid channel: " + channel);
response.send({'status': 'failed', 'error': 'Invalid channel name.'});
return;
}
if (!authenticatedClients[authToken]) {
console.log("Unknown authToken : " + authToken);
response.send({'status': 'failed', 'error': 'Invalid authToken.'});
return;
}
channels[channel] = channels[channel] || {'sessionIds': {}};
var sessionIds = getNodejsSessionIdsFromAuthtoken(authToken);
if (sessionIds.length > 0) {
for (var i in sessionIds) {
channels[channel].sessionIds[sessionIds[i]] = sessionIds[i];
}
if (settings.debug) {
console.log("Added sessionIds '" + sessionIds.join() + "' to channel '" + channel + "'");
}
response.send({'status': 'success'});
}
else {
console.log("No active sessions for authToken: " + authToken);
response.send({'status': 'failed', 'error': 'No active sessions for uid.'});
}
if (authenticatedClients[authToken].channels.indexOf(channel) == -1) {
authenticatedClients[authToken].channels.push(channel);
if (settings.debug) {
console.log("Added channel '" + channel + "' to authenticatedClients");
}
}
};
/**
* Add a client (specified by session ID) to a channel.
*/
var addClientToChannel = function (sessionId, channel) {
if (sessionId && channel) {
if (!/^[0-9]+$/.test(sessionId) || !io.sockets.sockets.hasOwnProperty(sessionId)) {
console.log("addClientToChannel: Invalid sessionId: " + sessionId);
}
else if (!/^[a-z0-9_]+$/i.test(channel)) {
console.log("addClientToChannel: Invalid channel: " + channel);
}
else {
channels[channel] = channels[channel] || {'sessionIds': {}};
channels[channel].sessionIds[sessionId] = sessionId;
if (settings.debug) {
console.log("Added channel '" + channel + "' to sessionId " + sessionId);
}
return true;
}
}
else {
console.log("addClientToChannel: Missing sessionId or channel name");
}
return false;
};
/**
* Remove a channel.
*/
var removeChannel = function (request, response) {
var channel = request.params.channel || '';
if (channel) {
if (!/^[a-z0-9_]+$/i.test(channel)) {
console.log('Invalid channel: ' + channel);
response.send({'status': 'failed', 'error': 'Invalid channel name.'});
return;
}
if (channels[channel]) {
delete channels[channel];
if (settings.debug) {
console.log("Successfully removed channel '" + channel + "'");
}
response.send({'status': 'success'});
}
else {
console.log("Non-existent channel name '" + channel + "'");
response.send({'status': 'failed', 'error': 'Non-existent channel name.'});
return;
}
}
else {
console.log("Missing channel");
response.send({'status': 'failed', 'error': 'Invalid data: missing channel'});
}
}
/**
* Add a channel.
*/
var addChannel = function (request, response) {
var channel = request.params.channel || '';
if (channel) {
if (!/^[a-z0-9_]+$/i.test(channel)) {
console.log('Invalid channel: ' + channel);
response.send({'status': 'failed', 'error': 'Invalid channel name.'});
return;
}
if (channels[channel]) {
console.log("Channel name '" + channel + "' already exists.");
response.send({'status': 'failed', 'error': "Channel name '" + channel + "' already exists."});
return;
}
channels[channel] = {'sessionIds': {}};
if (settings.debug) {
console.log("Successfully added channel '" + channel + "'");
}
response.send({'status': 'success'});
}
else {
console.log("Missing channel");
response.send({'status': 'failed', 'error': 'Invalid data: missing channel'});
}
}
/**
* Remove a user from a channel.
*/
var removeUserFromChannel = function (request, response) {
var uid = request.params.uid || '';
var channel = request.params.channel || '';
if (uid && channel) {
if (!/^\d+$/.test(uid)) {
console.log('Invalid uid: ' + uid);
response.send({'status': 'failed', 'error': 'Invalid uid.'});
return;
}
if (!/^[a-z0-9_]+$/i.test(channel)) {
console.log('Invalid channel: ' + channel);
response.send({'status': 'failed', 'error': 'Invalid channel name.'});
return;
}
if (channels[channel]) {
var sessionIds = getNodejsSessionIdsFromUid(uid);
for (var i in sessionIds) {
if (channels[channel].sessionIds[sessionIds[i]]) {
delete channels[channel].sessionIds[sessionIds[i]];
}
}
for (var authToken in authenticatedClients) {
if (authenticatedClients[authToken].uid == uid) {
var index = authenticatedClients[authToken].channels.indexOf(channel);
if (index != -1) {
delete authenticatedClients[authToken].channels[index];
}
}
}
if (settings.debug) {
console.log("Successfully removed uid '" + uid + "' from channel '" + channel + "'");
}
response.send({'status': 'success'});
}
else {
console.log("Non-existent channel name '" + channel + "'");
response.send({'status': 'failed', 'error': 'Non-existent channel name.'});
return;
}
}
else {
console.log("Missing uid or channel");
response.send({'status': 'failed', 'error': 'Invalid data'});
}
}
/**
* Remove an authToken from a channel.
*/
var removeAuthTokenFromChannel = function (request, response) {
var authToken = request.params.authToken || '';
var channel = request.params.channel || '';
if (authToken && channel) {
if (!authenticatedClients[authToken]) {
console.log('Invalid authToken: ' + uid);
response.send({'status': 'failed', 'error': 'Invalid authToken.'});
return;
}
if (!/^[a-z0-9_]+$/i.test(channel)) {
console.log('Invalid channel: ' + channel);
response.send({'status': 'failed', 'error': 'Invalid channel name.'});
return;
}
if (channels[channel]) {
var sessionIds = getNodejsSessionIdsFromAuthToken(authToken);
for (var i in sessionIds) {
if (channels[channel].sessionIds[sessionIds[i]]) {
delete channels[channel].sessionIds[sessionIds[i]];
}
}
if (authenticatedClients[authToken]) {
var index = authenticatedClients[authToken].channels.indexOf(channel);
if (index != -1) {
delete authenticatedClients[authToken].channels[index];
}
}
if (settings.debug) {
console.log("Successfully removed authToken '" + authToken + "' from channel '" + channel + "'.");
}
response.send({'status': 'success'});
}
else {
console.log("Non-existent channel name '" + channel + "'");
response.send({'status': 'failed', 'error': 'Non-existent channel name.'});
return;
}
}
else {
console.log("Missing authToken or channel");
response.send({'status': 'failed', 'error': 'Invalid data'});
}
}
/**
* Remove a client (specified by session ID) from a channel.
*/
var removeClientFromChannel = function (sessionId, channel) {
if (sessionId && channel) {
if (!/^[0-9]+$/.test(sessionId) || !io.sockets.sockets.hasOwnProperty(sessionId)) {
console.log("removeClientFromChannel: Invalid sessionId: " + sessionId);
}
else if (!/^[a-z0-9_]+$/i.test(channel) || !channels.hasOwnProperty(channel)) {
console.log("removeClientFromChannel: Invalid channel: " + channel);
}
else if (channels[channel].sessionIds[sessionId]) {
delete channels[channels].sessionIds[sessionId];
if (settings.debug) {
console.log("Removed sessionId '" + sessionId + "' from channel '" + channel + "'");
}
return true;
}
}
else {
console.log("removeClientFromChannel: Missing sessionId or channel name");
}
return false;
};
/**
* Set the list of users a uid can see presence info about.
*/
var setUserPresenceList = function (uid, uids) {
var uid = request.params.uid || '';
var uidlist = request.params.uidlist.split(',') || [];
if (uid && uidlist) {
if (!/^\d+$/.test(uid)) {
console.log("Invalid uid: " + uid);
response.send({'status': 'failed', 'error': 'Invalid uid.'});
return;
}
if (uidlist.length == 0) {
console.log("Empty uidlist");
response.send({'status': 'failed', 'error': 'Empty uid list.'});
return;
}
for (var i in uidlist) {
if (!/^\d+$/.test(uidlist[i])) {
console.log("Invalid uid: " + uid);
response.send({'status': 'failed', 'error': 'Invalid uid.'});
return;
}
}
onlineUsers[uid] = uidlist;
response.send({'status': 'success'});
}
else {
response.send({'status': 'failed', 'error': 'Invalid parameters.'});
}
}
/**
* Cleanup after a socket has disconnected.
*/
var cleanupSocket = function (socket) {
if (settings.debug) {
console.log("Cleaning up after socket id", socket.id, 'uid', socket.uid);
}
for (var channel in channels) {
delete channels[channel].sessionIds[socket.id];
}
var uid = socket.uid;
if (uid != 0) {
if (presenceTimeoutIds[uid]) {
clearTimeout(presenceTimeoutIds[uid]);
}
presenceTimeoutIds[uid] = setTimeout(checkOnlineStatus, 2000, uid);
}
for (var tokenChannel in tokenChannels) {
console.log("cleanupSocket: checking tokenChannel", tokenChannel, socket.id);
if (tokenChannels[tokenChannel].sockets[socket.id]) {
console.log("cleanupSocket: found socket.id for tokenChannel", tokenChannel, tokenChannels[tokenChannel].sockets[socket.id]);
if (tokenChannels[tokenChannel].sockets[socket.id].notifyOnDisconnect) {
if (contentChannelTimeoutIds[tokenChannel + '_' + uid]) {
clearTimeout(contentChannelTimeoutIds[tokenChannel + '_' + uid]);
}
contentChannelTimeoutIds[tokenChannel + '_' + uid] = setTimeout(checkTokenChannelStatus, 2000, tokenChannel, socket);
}
delete tokenChannels[tokenChannel].sockets[socket.id];
}
}
delete io.sockets.sockets[socket.id];
}
/**
* Check for any open sockets associated with the channel and socket pair.
*/
var checkTokenChannelStatus = function (tokenChannel, socket) {
// If the tokenChannel no longer exists, just bail.
if (!tokenChannels[tokenChannel]) {
console.log("checkTokenChannelStatus: no tokenChannel", tokenChannel, socket.uid);
return;
}
// If we find a socket for this user in the given tokenChannel, we can just
// return, as there's nothing we need to do.
var sessionIds = getNodejsSessionIdsFromUid(socket.uid);
for (var i = 0; i < sessionIds.length; i++) {
if (tokenChannels[tokenChannel].sockets[sessionIds[i]]) {
console.log("checkTokenChannelStatus: found socket for tokenChannel", tokenChannel, socket.uid);
return;
}
}
// We didn't find a socket for this uid, and we have other sockets in this,
// channel, so send disconnect notification message.
var message = {
'channel': tokenChannel,
'contentChannelNotification': true,
'data': {
'uid': socket.uid,
'type': 'disconnect',
}
};
for (var socketId in tokenChannels[tokenChannel].sockets) {
publishMessageToClient(socketId, message);
}
}
/**
* Check for any open sockets for uid.
*/
var checkOnlineStatus = function (uid) {
if (getNodejsSessionIdsFromUid(uid).length == 0) {
if (settings.debug) {
console.log("Sending offline notification for", uid);
}
setUserOffline(uid);
}
}
/**
* Sends offline notification to sockets, the backend and cleans up our list.
*/
var setUserOffline = function (uid) {
sendPresenceChangeNotification(uid, 'offline');
delete onlineUsers[uid];
sendMessageToBackend({uid: uid, messageType: 'userOffline'}, function (response) { });
}
/**
* Set a content token.
*/
var setContentToken = function (request, response) {
var requestBody = '';
request.setEncoding('utf8');
request.on('data', function (chunk) {
requestBody += chunk;
});
request.on('end', function () {
try {
var message = JSON.parse(requestBody);
if (settings.debug) {
console.log('setContentToken: message', message);
}
}
catch (exception) {
console.log('setContentToken: Invalid JSON "' + requestBody + '"', exception);
response.send({error: 'Invalid JSON, error: ' + exception.toString()});
return;
}
tokenChannels[message.channel] = tokenChannels[message.channel] || {'tokens': {}, 'sockets': {}};
tokenChannels[message.channel].tokens[message.token] = message;
if (settings.debug) {
console.log('setContentToken', message.token, 'for channel', message.channel);
}
response.send({status: 'ok'});
});
}
/**
* Setup a io.sockets.sockets{}.connection with uid, channels etc.
*/
var setupClientConnection = function (sessionId, authData, contentTokens) {
if (!io.sockets.sockets[sessionId]) {
console.log("Client socket '" + sessionId + "' went away.");
console.log(authData);
return;
}
io.sockets.sockets[sessionId].authToken = authData.authToken;
io.sockets.sockets[sessionId].uid = authData.uid;
for (var i in authData.channels) {
channels[authData.channels[i]] = channels[authData.channels[i]] || {'sessionIds': {}};
channels[authData.channels[i]].sessionIds[sessionId] = sessionId;
}
if (authData.uid != 0) {
var sendPresenceChange = !onlineUsers[authData.uid];
onlineUsers[authData.uid] = authData.presenceUids || [];
if (sendPresenceChange) {
sendPresenceChangeNotification(authData.uid, 'online');
}
}
var clientToken = '';
for (var tokenChannel in contentTokens) {