-
Notifications
You must be signed in to change notification settings - Fork 3
/
ortc.umd.js
4257 lines (3663 loc) · 129 KB
/
ortc.umd.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
//=====================IbtRealTimeSJ.js============================
/**********************************************************
* API IbtRealTimeSJ.js
***********************************************************/
/*
* Initializes a new instance of the IbtRealTimeSJ class.
*/
function IbtRealTimeSJ() {
/***********************************************************
* @attributes
***********************************************************/
var appKey; // application key
var authToken; // authentication token
var clusterUrl; // cluster URL to connect
var waitingClusterResponse; // indicates whether is waiting for a cluster response
var connectionTimeout; // connection timeout in milliseconds
var messageMaxSize; // message maximum size in bytes
var channelMaxSize; // channel maximum size in bytes
var channelsMaxSize; // maximum of channels for batchSend
var messagesBuffer; // buffer to hold the message parts
var id; // object identifier
var isConnected; // indicates whether the client object is connected
var isConnecting; // indicates whether the client object is connecting
var alreadyConnectedFirstTime; // indicates whether the client already connected for the first time
var stopReconnecting; // indicates whether the user disconnected (stop the reconnecting proccess)
var ortc; // represents the object itself
var sockjs; // socket connected to
var url; // URL to connect
var userPerms; // user permissions
var connectionMetadata; // connection metadata used to identify the client
var announcementSubChannel; // announcement subchannel
var subscribedChannels; // subscribed/subscribing channels
var lastKeepAlive; // holds the time of the last keep alive received
var invalidConnection; // indicates whether the connection is valid
var reconnectIntervalId; // id used for the reconnect interval
var reconnectStartedAt; // the time which the reconnect started
var validatedTimeoutId; // id used for the validated timeout
var validatedArrived; // indicates whether the validated message arrived
var retryingWithSsl; // indicates whether the connection is being retried with SSL
var protocol; // protocol to use
var sslSessionCookieName; // the SSL session cookie name
var sessionCookieName; // the session cookie name
var sessionId; // the session ID
var registrationId; // browser device token for push notifications
var pushPlatform; // push notifications platform
var pendingPublishMessages; // hash with the messages pending publish acknowledge from server
var publishTimeout; // Publish method timeout in miliseconds
/***********************************************************
* @attributes initialization
***********************************************************/
sslSessionCookieName = "ortcssl";
sessionCookieName = "ortcsession-";
connectionTimeout = 5000;
messageMaxSize = 800;
channelMaxSize = 100;
connectionMetadataMaxSize = 256;
channelsMaxSize=50;
// Time in seconds
var heartbeatDefaultTime = 15; // Heartbeat default interval time
var heartbeatDefaultFails = 3; // Heartbeat default max fails
var heartbeatMaxTime = 60;
var heartbeatMinTime = 10;
var heartbeatMaxFails = 6;
var heartbeatMinFails = 1;
var heartbeatTime = heartbeatDefaultTime; // Heartbeat interval time
var heartbeatFails = heartbeatDefaultFails; // Heartbeat max fails
var heartbeatInterval = null; // Heartbeat interval
var heartbeatActive = false;
messagesBuffer = {};
subscribedChannels = {};
pendingPublishMessages = {};
isConnected = false;
isConnecting = false;
alreadyConnectedFirstTime = false;
invalidConnection = false;
waitingClusterResponse = false;
validatedArrived = false;
retryingWithSsl = false;
ortc = this;
lastKeepAlive = null;
userPerms = null;
reconnectStartedAt = null;
protocol = undefined;
pushPlatform = "GCM";
publishTimeout = 5000;
var delegateExceptionCallback = function (ortcArg, event) {
if (ortcArg !== null && ortcArg.onException !== null) {
ortcArg.onException(ortcArg, event);
}
};
/***********************************************************
* @properties
***********************************************************/
this.getId = function () {
return id;
};
this.setId = function (newId) {
id = newId;
};
this.getUrl = function () {
return url;
};
this.setUrl = function (newUrl) {
url = newUrl; clusterUrl = null;
};
this.getClusterUrl = function () {
return clusterUrl;
};
this.setClusterUrl = function (newUrl) {
clusterUrl = newUrl;
url = null;
};
this.getConnectionTimeout = function () {
return connectionTimeout;
};
this.setConnectionTimeout = function (newTimeout) {
connectionTimeout = newTimeout;
};
this.getIsConnected = function () {
return isConnected && ortc.sockjs !== null;
};
this.getConnectionMetadata = function () {
return connectionMetadata;
};
this.setConnectionMetadata = function (newConnectionMetadata) {
connectionMetadata = newConnectionMetadata;
};
this.getAnnouncementSubChannel = function () {
return announcementSubChannel;
};
this.setAnnouncementSubChannel = function (newAnnouncementSubChannel) {
announcementSubChannel = newAnnouncementSubChannel;
};
this.getProtocol = function () {
return protocol;
};
this.setProtocol = function (newProtocol) {
protocol = newProtocol;
};
this.getSessionId = function () {
return sessionId;
};
/*
* Get heartbeat interval.
*/
this.getHeartbeatTime = function () {
return heartbeatTime;
};
/*
* Set heartbeat interval.
*/
this.setHeartbeatTime = function (newHeartbeatTime) {
if (newHeartbeatTime && !isNaN(newHeartbeatTime)){
if (newHeartbeatTime > heartbeatMaxTime || newHeartbeatTime < heartbeatMinTime){
delegateExceptionCallback(ortc, 'Heartbeat time is out of limits - Min: ' + heartbeatMinTime + '| Max: ' + heartbeatMaxTime);
} else {
heartbeatTime = newHeartbeatTime;
}
} else {
delegateExceptionCallback(ortc, 'Invalid heartbeat time ' + newHeartbeatTime);
}
};
/*
* Get how many times can the client fail the heartbeat.
*/
this.getHeartbeatFails = function () {
return heartbeatFails;
};
/*
* Set heartbeat fails. Defines how many times can the client fail the heartbeat.
*/
this.setHeartbeatFails = function (newHeartbeatFails) {
if (newHeartbeatFails && !isNaN(newHeartbeatFails)) {
if (newHeartbeatFails > heartbeatMaxFails || newHeartbeatFails < heartbeatMinFails){
delegateExceptionCallback(ortc, 'Heartbeat fails is out of limits - Min: ' + heartbeatMinFails + ' | Max: ' + heartbeatMaxFails);
} else {
heartbeatFails = newHeartbeatFails;
}
} else {
delegateExceptionCallback(ortc, 'Invalid heartbeat fails ' + newHeartbeatFails);
}
};
/*
* Get heart beat active.
*/
this.getHeartbeatActive = function(){
return heartbeatActive;
}
/*
* Set heart beat active. Heart beat provides better accuracy for presence data.
*/
this.setHeartbeatActive = function(active){
heartbeatActive = active;
}
this.getPublishTimeout = function () { return publishTimeout; };
this.setPublishTimeout = function (newTimeout) { publishTimeout = newTimeout; };
/***********************************************************
* @events
***********************************************************/
this.onConnected = null;
this.onDisconnected = null;
this.onSubscribed = null;
this.onUnsubscribed = null;
this.onException = null;
this.onReconnecting = null;
this.onReconnected = null;
/***********************************************************
* @public methods
***********************************************************/
/*
* Connects to the gateway with the application key and authentication token.
*/
this.connect = function (appKey, authToken) {
/*
Sanity Checks
*/
if (isConnected) {
delegateExceptionCallback(ortc, "Already connected");
}
else if (!url && !clusterUrl) {
delegateExceptionCallback(ortc, "URL and Cluster URL are null or empty");
}
else if (!appKey) {
delegateExceptionCallback(ortc, "Application Key is null or empty");
}
else if (!authToken) {
delegateExceptionCallback(ortc, "Authentication Token is null or empty");
}
else if (url && !ortcIsValidUrl(url)) {
delegateExceptionCallback(ortc, "Invalid URL");
}
else if (clusterUrl && !ortcIsValidUrl(clusterUrl)) {
delegateExceptionCallback(ortc, "Invalid Cluster URL");
}
else if (!ortcIsValidInput(appKey)) {
delegateExceptionCallback(ortc, "Application Key has invalid characters");
}
else if (!ortcIsValidInput(authToken)) {
delegateExceptionCallback(ortc, "Authentication Token has invalid characters");
}
else if (!ortcIsValidInput(announcementSubChannel)) {
delegateExceptionCallback(ortc, "Announcement Subchannel has invalid characters");
}
else if (connectionMetadata && connectionMetadata.length > connectionMetadataMaxSize) {
delegateExceptionCallback(ortc, "Connection metadata size exceeds the limit of " + connectionMetadataMaxSize + " characters");
}
else {
ortc.appKey = appKey;
ortc.authToken = authToken;
isConnecting = true;
stopReconnecting = false;
validatedArrived = false;
clearValidatedTimeout(self);
// Read SSL session cookie
//var sslConn = readCookie(sslSessionCookieName);
var sslConn = false;
if (sslConn) {
changeUrlSsl();
}
if (clusterUrl && clusterUrl != null) {
clusterUrl = clusterUrl.ortcTreatUrl();
clusterConnection();
}
else {
url = url.ortcTreatUrl();
ortc.sockjs = createSocketConnection(url);
}
//If ssl connection increase connection timeout
if ((clusterUrl && clusterUrl != null && (clusterUrl.indexOf("/ssl") >= 0)) || (url && (url.indexOf("https") >= 0))) {
if(!retryingWithSsl){
ortc.setConnectionTimeout(30 * 1000);
}else{
if(ortc.getConnectionTimeout() < 300 * 1000){
if(ortc.getConnectionTimeout() < 30 * 1000){
ortc.setConnectionTimeout(30 * 1000);
}else{
ortc.setConnectionTimeout((ortc.getConnectionTimeout() + 10) * 1000);
}
}else{
stopReconnecting = true;
clearReconnectInterval();
}
}
}
if (!ortc.reconnectIntervalId && !stopReconnecting) {
// Interval to reconnect
ortc.reconnectIntervalId = setInterval(function () {
if (stopReconnecting) {
clearReconnectInterval();
}
else {
var currentDateTime = new Date();
if (ortc.sockjs == null && !waitingClusterResponse) {
reconnectSocket();
}
// 35 seconds
if (lastKeepAlive != null && (lastKeepAlive + 35000 < new Date().getTime())) {
lastKeepAlive = null;
// Server went down
if (isConnected) {
disconnectSocket();
}
}
}
}, ortc.getConnectionTimeout());
}
}
};
this.setNotificationConfig = function(config){
config.cmd = "config";
this.sendMessageToServiceWorker(config);
};
this.showNotification = function(notification){
notification.cmd = "notification";
this.sendMessageToServiceWorker(notification);
};
this.sendMessageToServiceWorker = function(message) {
return new Promise(function(resolve, reject) {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event) {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
});
}
/*
* Subscribes to the channel so the client object can receive all messages sent to it by other clients with Notifications.
*/
this.subscribeWithNotifications = function(channel, subscribeOnReconnected, regId, onMessageCallback){
ortc.registrationId = regId;
this._subscribe(channel, subscribeOnReconnected, regId, null, onMessageCallback);
}
/*
* Subscribes to the channel so the client object can receive all messages sent that are valid according to the given filter
*/
this.subscribeWithFilter = function(channel, subscribeOnReconnected, filter, onMessageCallback){
this._subscribe(channel, subscribeOnReconnected, null, filter, onMessageCallback);
}
/*
* Subscribes to the channel so the client object can receive all messages sent to it by other clients.
*/
this.subscribe = function (channel, subscribeOnReconnected, onMessageCallback){
this._subscribe(channel, subscribeOnReconnected, null, null, onMessageCallback);
};
/*
* Subscribes to the channel using at-least-once delivery mode (buffered messages)
*/
this.subscribeWithBuffer = function(channel, subscriberId, onMessageWithBufferCallback){
if(subscriberId) {
var options = {
channel: channel,
subscribeOnReconnected: true,
subscriberId: subscriberId
}
this.subscribeWithOptions(options, function(ortc, msgOptions) {
onMessageWithBufferCallback(ortc, msgOptions.channel, msgOptions.seqId, msgOptions.message);
});
} else {
delegateExceptionCallback(ortc, 'subscribeWithBuffer called with no subscriberId');
}
}
/*
* Subscribes to the channel with multiple options
*/
this.subscribeWithOptions = function (options, onMessageWithOptionsCallback){
if(options) {
this._subscribeOptions(options.channel, options.subscribeOnReconnected, options.regId, options.filter, options.subscriberId, onMessageWithOptionsCallback);
} else {
delegateExceptionCallback(ortc, 'subscribeWithOptions called with no options');
}
};
this._subscribe = function(channel, subscribeOnReconnected, regId, filter, onMessageCallback) {
/*
Sanity Checks
*/
if (!isConnected) {
delegateExceptionCallback(ortc, "Not connected");
}
else if (!channel) {
delegateExceptionCallback(ortc, "Channel is null or empty");
}
else if (!ortcIsValidInput(channel)) {
delegateExceptionCallback(ortc, "Channel has invalid characters");
}
else if (subscribedChannels[channel] && subscribedChannels[channel].isSubscribing) {
delegateExceptionCallback(ortc, "Already subscribing to the channel \"" + channel + "\"");
}
else if (subscribedChannels[channel] && subscribedChannels[channel].isSubscribed) {
delegateExceptionCallback(ortc, "Already subscribed to the channel \"" + channel + "\"");
}
else if (channel.length > channelMaxSize) {
delegateExceptionCallback(ortc, "Channel size exceeds the limit of " + channelMaxSize + " characters");
}
else if (!ortcIsValidBoolean(subscribeOnReconnected)) {
delegateExceptionCallback(ortc, "The argument \"subscribeOnReconnected\" must be a boolean");
}
else if (!ortcIsFunction(onMessageCallback)) {
delegateExceptionCallback(ortc, "The argument \"onMessageCallback\" must be a function");
}
else {
if (ortc.sockjs != null) {
var domainChannelCharacterIndex = channel.indexOf(":");
var channelToValidate = channel;
var hashPerm = null;
if (domainChannelCharacterIndex > 0) {
channelToValidate = channel.substring(0, domainChannelCharacterIndex + 1) + "*";
}
if (userPerms && userPerms != null) {
hashPerm = userPerms[channelToValidate] ? userPerms[channelToValidate] : userPerms[channel];
}
if (userPerms && userPerms != null && !hashPerm) {
delegateExceptionCallback(ortc, "No permission found to subscribe to the channel \"" + channel + "\"");
}
else {
if (subscribedChannels[channel]) {
subscribedChannels[channel].isSubscribing = true;
subscribedChannels[channel].isSubscribed = false;
subscribedChannels[channel].subscribeOnReconnected = subscribeOnReconnected;
subscribedChannels[channel].onMessageCallback = onMessageCallback;
subscribedChannels[channel].filter = filter;
}
else {
subscribedChannels[channel] = { "isSubscribing": true, "isSubscribed": false, "subscribeOnReconnected": subscribeOnReconnected, "onMessageCallback": onMessageCallback, "filter": filter };
}
if (regId) {
subscribedChannels[channel].withNotifications = true;
ortc.sockjs.send("subscribe;" + ortc.appKey + ";" + ortc.authToken + ";" + channel + ";" + hashPerm + ";" + regId + ";" + pushPlatform);
}else{
subscribedChannels[channel].withNotifications = false;
if(filter) {
ortc.sockjs.send("subscribefilter;" + ortc.appKey + ";" + ortc.authToken + ";" + channel + ";" + hashPerm + ";" + filter);
} else {
ortc.sockjs.send("subscribe;" + ortc.appKey + ";" + ortc.authToken + ";" + channel + ";" + hashPerm);
}
}
}
}
}
};
this._subscribeOptions = function(channel, subscribeOnReconnected, regId, filter, subscriberId, onMessageCallback) {
/*
Sanity Checks
*/
if (!isConnected) {
delegateExceptionCallback(ortc, 'Not connected');
}
else if (!channel) {
delegateExceptionCallback(ortc, 'Channel is null or empty');
}
else if (!ortcIsValidInput(channel)) {
delegateExceptionCallback(ortc, 'Channel has invalid characters');
}
else if (!ortcIsValidInput(subscriberId)) {
delegateExceptionCallback(ortc, 'subscriberId has invalid characters');
}
else if (subscribedChannels[channel] && subscribedChannels[channel].isSubscribing) {
delegateExceptionCallback(ortc, 'Already subscribing to the channel \'' + channel + '\'');
}
else if (subscribedChannels[channel] && subscribedChannels[channel].isSubscribed) {
delegateExceptionCallback(ortc, 'Already subscribed to the channel \'' + channel + '\'');
}
else if (channel.length > channelMaxSize) {
delegateExceptionCallback(ortc, 'Channel size exceeds the limit of ' + channelMaxSize + ' characters');
}
else if (!ortcIsFunction(onMessageCallback)) {
delegateExceptionCallback(ortc, 'The argument \'onMessageCallback\' must be a function');
}
else {
if (!subscribeOnReconnected) {
subscribeOnReconnected = true;
}
if(!regId) {
regId = '';
}
if(!filter) {
filter = '';
}
if(!subscriberId) {
subscriberId = '';
}
if (ortc.sockjs != null) {
var domainChannelCharacterIndex = channel.indexOf(':');
var channelToValidate = channel;
var hashPerm = null;
if (domainChannelCharacterIndex > 0) {
channelToValidate = channel.substring(0, domainChannelCharacterIndex + 1) + '*';
}
if (userPerms && userPerms != null) {
hashPerm = userPerms[channelToValidate] ? userPerms[channelToValidate] : userPerms[channel];
}
if (userPerms && userPerms != null && !hashPerm) {
delegateExceptionCallback(ortc, 'No permission found to subscribe to the channel \'' + channel + '\'');
}
else {
if (subscribedChannels[channel]) {
subscribedChannels[channel].isSubscribing = true;
subscribedChannels[channel].isSubscribed = false;
subscribedChannels[channel].subscribeOnReconnected = subscribeOnReconnected;
subscribedChannels[channel].onMessageCallback = onMessageCallback;
subscribedChannels[channel].filter = filter;
subscribedChannels[channel].withOptions = true;
subscribedChannels[channel].subscriberId = subscriberId;
}
else {
subscribedChannels[channel] = {
'isSubscribing': true,
'isSubscribed': false,
'subscribeOnReconnected': subscribeOnReconnected,
'onMessageCallback': onMessageCallback,
'filter': filter,
'withOptions': true,
'subscriberId': subscriberId
};
}
if (regId) {
subscribedChannels[channel].withNotifications = true;
}else{
subscribedChannels[channel].withNotifications = false;
}
ortc.sockjs.send('subscribeoptions;' + ortc.appKey + ';' + ortc.authToken + ';' + channel + ';' + subscriberId + ';' + regId + ';' + pushPlatform + ';' + hashPerm + ';' + filter);
}
}
}
};
/*
* Unsubscribes from the channel so the client object stops receiving messages sent to it.
*/
this.unsubscribe = function (channel) {
/*
Sanity Checks
*/
if (!isConnected) {
delegateExceptionCallback(ortc, "Not connected");
}
else if (!channel) {
delegateExceptionCallback(ortc, "Channel is null or empty");
}
else if (!ortcIsValidInput(channel)) {
delegateExceptionCallback(ortc, "Channel has invalid characters");
}
else if (!subscribedChannels[channel] || (subscribedChannels[channel] && !subscribedChannels[channel].isSubscribed)) {
delegateExceptionCallback(ortc, "Not subscribed to the channel " + channel);
}
else if (channel.length > channelMaxSize) {
delegateExceptionCallback(ortc, "Channel size exceeds the limit of " + channelMaxSize + " characters");
}
else {
if (ortc.sockjs != null) {
if (subscribedChannels[channel].withNotifications == true) {
ortc.sockjs.send("unsubscribe;" + ortc.appKey + ";" + channel + ";" + ortc.registrationId + ";" + pushPlatform);
}else{
ortc.sockjs.send("unsubscribe;" + ortc.appKey + ";" + channel);
}
subscribedChannels[channel].isSubscribed = false;
}
}
};
this._sendWithMethod = function(channel, message, method, ttl, callback) {
/*
Sanity Checks
*/
var err;
if (!isConnected || ortc.sockjs == null) {
err = 'Not connected';
}
else if (!method) {
err = 'Send Method is null or empty';
}
else if (!channel) {
err = 'Channel is null or empty';
}
else if (!ortcIsValidInput(channel)) {
err = 'Channel has invalid characters';
}
else if (!message) {
err = 'Message is null or empty';
}
else if (!ortcIsString(message)) {
err = 'Message must be a string';
}
else if (channel.length > channelMaxSize) {
err = 'Channel size exceeds the limit of ' + channelMaxSize + ' characters';
} else {
var domainChannelCharacterIndex = channel.indexOf(':');
var channelToValidate = channel;
var hashPerm = null;
if (domainChannelCharacterIndex > 0) {
channelToValidate = channel.substring(0, domainChannelCharacterIndex + 1) + '*';
}
if (userPerms && userPerms != null) {
hashPerm = userPerms[channelToValidate] ? userPerms[channelToValidate] : userPerms[channel];
}
if (userPerms && userPerms != null && !hashPerm) {
err = 'No permission found to send to the channel \'' + channel + '\'';
}
else {
// Multi part
var messageParts = [];
var messageId = generateId(8);
var i;
var allowedMaxSize = messageMaxSize - channel.length;
for (i = 0; i < message.length; i = i + allowedMaxSize) {
// Just one part
if (message.length <= allowedMaxSize) {
messageParts.push(message);
break;
}
if (message.substring(i, i + allowedMaxSize)) {
messageParts.push(message.substring(i, i + allowedMaxSize));
}
}
if(method === "publish") {
if(pendingPublishMessages[messageId]) {
err = "Message id conflict. Please retry publishing the message"
} else {
if(!ttl) {
ttl = 0;
}
// check for acknowledge timeout
var ackTimeout = setTimeout(function() {
if(pendingPublishMessages[messageId]) {
var err = "Message publish timeout after " + publishTimeout / 1000 + " seconds";
if(pendingPublishMessages[messageId].callback) {
pendingPublishMessages[messageId].callback(err);
}
delete pendingPublishMessages[messageId];
}
}, publishTimeout);
var pendingMsg = {
totalNumOfParts: messageParts.length,
callback: callback,
timeout: ackTimeout
};
pendingPublishMessages[messageId] = pendingMsg;
}
}
if(!err) {
if(method === 'publish') {
if (messageParts.length < 20) {
for (var j = 1; j <= messageParts.length; j++) {
ortc.sockjs.send('publish;' + ortc.appKey + ';' + ortc.authToken + ';' + channel + ';' + ttl + ';' + hashPerm + ';' + messageId + '_' + j + '-' + messageParts.length + '_' + messageParts[j - 1]);
}
} else {
// throttle send to 10 parts/sec to avoid server rate limiting
var partsSent = 0;
var partSendInterval = setInterval(function() {
if(isConnected && ortc.sockjs) {
var currentPart = partsSent + 1;
var totalParts = messageParts.length;
ortc.sockjs.send('publish;' + ortc.appKey + ';' + ortc.authToken + ';' + channel + ';' + ttl + ';' + hashPerm + ';' + messageId + '_' + currentPart + '-' + totalParts + '_' + messageParts[currentPart - 1]);
partsSent++;
if(partsSent === messageParts.length) {
clearInterval(partSendInterval);
}
} else {
// socket was disconnected, stop sending
clearInterval(partSendInterval);
}
}, 100);
}
} else {
// send
for (var j = 1; j <= messageParts.length; j++) {
ortc.sockjs.send(method + ';' + ortc.appKey + ';' + ortc.authToken + ';' + channel + ';' + hashPerm + ';' + messageId + '_' + j + '-' + messageParts.length + '_' + messageParts[j - 1]);
}
}
}
}
}
if (err) {
delegateExceptionCallback(ortc, err);
if(callback) {
callback(err);
}
}
}
/*
* Sends the message to the channel using send method (at-most-once delivery semantics)
*/
this.send = function (channel, message) {
this._sendWithMethod(channel, message, "send");
};
/*
* Sends the message to the channel using publish method (at-least-once delivery semantics)
*/
this.publish = function (channel, message, ttl, callback) {
this._sendWithMethod(channel, message, "publish", ttl, callback);
};
/*
* Sends the message to multiple channels.
*/
this.batchSend = function (channels, message) {
/*
Sanity Checks
*/
channels = ortcStrToArray(channels);
if (!isConnected || ortc.sockjs == null) {
delegateExceptionCallback(ortc, "Not connected");
}
else if (!ortcIsArray(channels)) {
delegateExceptionCallback(ortc, "Channels must be a array");
}
else if (!message) {
delegateExceptionCallback(ortc, "Message is null or empty");
}
else if (!ortcIsString(message)) {
delegateExceptionCallback(ortc, "Message must be a string");
}
else if(channels.length <= 0){
delegateExceptionCallback(ortc, "Channels must be an array at least with one channel");
}else if(channels.length > channelsMaxSize){
channels = [];
delegateExceptionCallback(ortc, "The channel maximum was reached (>"+ channelsMaxSize +")");
}
for(i=0;i<channels.length;i++){
var channel = channels[i];
if (channel.length > channelMaxSize) {
channels.splice(i,1);
delegateExceptionCallback(ortc, "Channel "+ channel +" size exceeds the limit of " + channelMaxSize + " characters");
}
}
if(channels.length > 0){
var arrayHashPerm = [];
for(i=0;i<channels.length;i++){
var channel = channels[i];
var domainChannelCharacterIndex = channel.indexOf(":");
var channelToValidate = channel;
var hashPerm = null;
if (domainChannelCharacterIndex > 0) {
channelToValidate = channel.substring(0, domainChannelCharacterIndex + 1) + "*";
}
if (userPerms && userPerms != null) {
hashPerm = userPerms[channelToValidate] ? userPerms[channelToValidate] : userPerms[channel];
}
if (userPerms && userPerms != null && !hashPerm) {
channels.splice(i,1);
delegateExceptionCallback(ortc, "No permission found to send to the channel \"" + channel + "\"");
}else{
arrayHashPerm.push(hashPerm);
}
}
if(channels.length > 0) {
var messageParts = [];
var messageId = generateId(8);
var allowedMaxSize = messageMaxSize - channels.toString().length;
for (i = 0; i < message.length; i = i + allowedMaxSize) {
// Just one part
if (message.length <= allowedMaxSize) {
messageParts.push(message);
break;
}
if (message.substring(i, i + allowedMaxSize)) {
messageParts.push(message.substring(i, i + allowedMaxSize));
}
}
for (j = 1; j <= messageParts.length; j++) {
ortc.sockjs.send("batchSend;" + ortc.appKey + ";" + ortc.authToken + ";" + JSON.stringify(channels) + ";" + JSON.stringify(arrayHashPerm) + ";" + messageId + "_" + j + "-" + messageParts.length + "_" + messageParts[j - 1]);
}
}
}
};
/*
* Disconnects from the gateway.
*/
this.disconnect = function () {
clearReconnectInterval();
stopReconnectProcess();
// Clear pending messages and their timeouts (if any)
for (var messageId in pendingPublishMessages) {
if (pendingPublishMessages.hasOwnProperty(messageId)) {
if(pendingPublishMessages[messageId].timeout) {
clearTimeout(pendingPublishMessages[messageId].timeout);
}
delete pendingPublishMessages[messageId];
}
}
// Clear subscribed channels
subscribedChannels = {};
/*
Sanity Checks
*/
if (!isConnected && !invalidConnection) {
delegateExceptionCallback(ortc, "Not connected");
}
else {
disconnectSocket();
}
};
/*
* Gets a value indicating whether this client object is subscribed to the channel.
*/
this.isSubscribed = function (channel) {
/*
Sanity Checks
*/
if (!isConnected) {
delegateExceptionCallback(ortc, "Not connected");
}
else if (!channel) {
delegateExceptionCallback(ortc, "Channel is null or empty");
}
else if (!ortcIsValidInput(channel)) {
delegateExceptionCallback(ortc, "Channel has invalid characters");
}
else {
if (subscribedChannels[channel] && subscribedChannels[channel].isSubscribed) {
return subscribedChannels[channel].isSubscribed;
}
else {
return false;
}
}
};
/*
* Gets a json indicating the subscriptions in a channel.
*/
this.presence = function (parameters,callback) {
try{
var requestUrl = null
, isCluster = false
, appKey = ortc.appKey
, authToken = ortc.authToken;
if(parameters.url){
requestUrl = parameters.url.ortcTreatUrl();
isCluster = parameters.isCluster;
appKey = parameters.applicationKey;
authToken = parameters.authenticationToken;
}else{
if (clusterUrl && clusterUrl != null) {
requestUrl = clusterUrl;
isCluster = true;
}
else {
requestUrl = url.ortcTreatUrl();;
}
}
getServerUrl({
requestUrl : requestUrl,
isCluster : isCluster,
appKey : appKey
},
function(error,serverUrl){
if(error){
callback(error,null);
}else{
jsonp(serverUrl + "/presence/" + appKey + "/" + authToken + "/" + parameters.channel,callback);
}
});
}catch(e){
callback("Unable to get presence data",null);
}
};
var getServerUrl = function(parameters,callback){
if (parameters.requestUrl && parameters.isCluster) {
var guid = generateGuid();
var queryString = "guid=" + generateGuid();
queryString = parameters.appKey ? queryString + "&appkey=" + parameters.appKey : queryString;
loadClusterServerScript(parameters.requestUrl + "/?" + queryString, guid, function (clusterServerResolved, scriptGuid) {
if (clusterServerResolved) {
var resultUrl = SOCKET_SERVER;
callback(null,resultUrl);
}else{
callback(null,"Unable to get server from cluster");