-
Notifications
You must be signed in to change notification settings - Fork 57
/
skylink.debug.js
13110 lines (11855 loc) · 498 KB
/
skylink.debug.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
/*! skylinkjs - v0.6.15 - Thu Sep 22 2016 18:47:20 GMT+0800 (SGT) */
(function() {
'use strict';
/**
* Polyfill for Object.keys() from Mozilla
* From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
*/
if (!Object.keys) {
Object.keys = (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({
toString: null
}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function(obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop);
}
if (hasDontEnumBug) {
for (var i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
}
}
return result;
}
})()
}
/**
* Polyfill for Date.getISOString() from Mozilla
* From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*/
(function() {
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
'Z';
};
})();
/**
* Polyfill for addEventListener() from Eirik Backer @eirikbacker (github.com).
* From https://gist.github.com/eirikbacker/2864711
* MIT Licensed
*/
(function(win, doc){
if(win.addEventListener) return; //No need to polyfill
function docHijack(p){var old = doc[p];doc[p] = function(v){ return addListen(old(v)) }}
function addEvent(on, fn, self){
return (self = this).attachEvent('on' + on, function(e){
var e = e || win.event;
e.preventDefault = e.preventDefault || function(){e.returnValue = false}
e.stopPropagation = e.stopPropagation || function(){e.cancelBubble = true}
fn.call(self, e);
});
}
function addListen(obj, i){
if(i = obj.length)while(i--)obj[i].addEventListener = addEvent;
else obj.addEventListener = addEvent;
return obj;
}
addListen([doc, win]);
if('Element' in win)win.Element.prototype.addEventListener = addEvent; //IE8
else{ //IE < 8
doc.attachEvent('onreadystatechange', function(){addListen(doc.all)}); //Make sure we also init at domReady
docHijack('getElementsByTagName');
docHijack('getElementById');
docHijack('createElement');
addListen(doc.all);
}
})(window, document);
/**
* Global function that clones an object.
*/
var clone = function (obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
var copy = function (data) {
var copy = data.constructor();
for (var attr in data) {
if (data.hasOwnProperty(attr)) {
copy[attr] = data[attr];
}
}
return copy;
};
if (typeof obj === 'object' && !Array.isArray(obj)) {
try {
return JSON.parse( JSON.stringify(obj) );
} catch (err) {
return copy(obj);
}
}
return copy(obj);
};
/**
* <h2>Prerequisites on using Skylink</h2>
* Before using any Skylink functionalities, you will need to authenticate your App Key using
* the <a href="#method_init">`init()` method</a>.
*
* To manage or create App Keys, you may access the [Skylink Developer Portal here](https://console.temasys.io).
*
* To view the list of supported browsers, visit [the list here](
* https://github.com/Temasys/SkylinkJS#supported-browsers).
*
* Here are some articles to help you get started:
* - [How to setup a simple video call](https://temasys.com.sg/getting-started-with-webrtc-and-skylinkjs/)
* - [How to setup screensharing](https://temasys.com.sg/screensharing-with-skylinkjs/)
* - [How to create a chatroom like feature](https://temasys.com.sg/building-a-simple-peer-to-peer-webrtc-chat/)
*
* Here are some demos you may use to aid your development:
* - Getaroom.io [[Demo](https://getaroom.io) / [Source code](https://github.com/Temasys/getaroom)]
* - Creating a component [[Link](https://github.com/Temasys/skylink-call-button)]
*
* You may see the example below in the <a href="#">Constructor tab</a> to have a general idea how event subscription
* and the ordering of <a href="#method_init"><code>init()</code></a> and
* <a href="#method_joinRoom"><code>joinRoom()</code></a> methods should be called.
*
* If you have any issues, you may find answers to your questions in the FAQ section on [our support portal](
* http://support.temasys.com.sg), asks questions, request features or raise bug tickets as well.
*
* If you would like to contribute to our SkylinkJS codebase, see [the contributing README](
* https://github.com/Temasys/SkylinkJS/blob/master/CONTRIBUTING.md).
*
* [See License (Apache 2.0)](https://github.com/Temasys/SkylinkJS/blob/master/LICENSE)
*
* @class Skylink
* @constructor
* @example
* // Here's a simple example on how you can start using Skylink.
* var skylinkDemo = new Skylink();
*
* // Subscribe all events first as a general guideline
* skylinkDemo.on("incomingStream", function (peerId, stream, peerInfo, isSelf) {
* if (isSelf) {
* attachMediaStream(document.getElementById("selfVideo"), stream);
* } else {
* var peerVideo = document.createElement("video");
* peerVideo.id = peerId;
* peerVideo.autoplay = "autoplay";
* document.getElementById("peersVideo").appendChild(peerVideo);
* attachMediaStream(peerVideo, stream);
* }
* });
*
* skylinkDemo.on("peerLeft", function (peerId, peerInfo, isSelf) {
* if (!isSelf) {
* var peerVideo = document.getElementById(peerId);
* // do a check if peerVideo exists first
* if (peerVideo) {
* document.getElementById("peersVideo").removeChild(peerVideo);
* } else {
* console.error("Peer video for " + peerId + " is not found.");
* }
* }
* });
*
* // init() should always be called first before other methods other than event methods like on() or off().
* skylinkDemo.init("YOUR_APP_KEY_HERE", function (error, success) {
* if (success) {
* skylinkDemo.joinRoom("my_room", {
* userData: "My Username",
* audio: true,
* video: true
* });
* }
* });
* @for Skylink
* @since 0.5.0
*/
function Skylink() {
if (!(this instanceof Skylink)) {
return new Skylink();
}
}
/**
* Contains the current version of Skylink Web SDK.
* @attribute VERSION
* @type String
* @readOnly
* @for Skylink
* @since 0.1.0
*/
Skylink.prototype.VERSION = '0.6.15';
/**
* Function that generates an <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> (Unique ID).
* @method generateUUID
* @return {String} Returns a generated UUID (Unique ID).
* @for Skylink
* @since 0.5.9
*/
Skylink.prototype.generateUUID = function() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
return uuid;
};
Skylink.prototype.DATA_CHANNEL_STATE = {
CONNECTING: 'connecting',
OPEN: 'open',
CLOSING: 'closing',
CLOSED: 'closed',
ERROR: 'error'
};
/**
* The list of Datachannel types.
* @attribute DATA_CHANNEL_TYPE
* @param {String} MESSAGING <small>Value <code>"messaging"</code></small>
* The value of the Datachannel type that is used only for messaging in
* <a href="#method_sendP2PMessage"><code>sendP2PMessage()</code> method</a>.
* <small>However for Peers that do not support simultaneous data transfers, this Datachannel
* type will be used to do data transfers (1 at a time).</small>
* <small>Each Peer connections will only have one of this Datachannel type and the
* connection will only close when the Peer connection is closed (happens when <a href="#event_peerConnectionState">
* <code>peerConnectionState</code> event</a> triggers parameter payload <code>state</code> as
* <code>CLOSED</code> for Peer).</small>
* @param {String} DATA <small>Value <code>"data"</code></small>
* The value of the Datachannel type that is used only for a data transfer in
* <a href="#method_sendURLData"><code>sendURLData()</code> method</a> and
* <a href="#method_sendBlobData"><code>sendBlobData()</code> method</a>.
* <small>The connection will close after the data transfer has been completed or terminated (happens when
* <a href="#event_dataTransferState"><code>dataTransferState</code> event</a> triggers parameter payload
* <code>state</code> as <code>DOWNLOAD_COMPLETED</code>, <code>UPLOAD_COMPLETED</code>,
* <code>REJECTED</code>, <code>CANCEL</code> or <code>ERROR</code> for Peer).</small>
* @type JSON
* @readOnly
* @for Skylink
* @since 0.6.1
*/
Skylink.prototype.DATA_CHANNEL_TYPE = {
MESSAGING: 'messaging',
DATA: 'data'
};
/**
* Stores the flag if Peers should have any Datachannel connections.
* @attribute _enableDataChannel
* @default true
* @type Boolean
* @private
* @for Skylink
* @since 0.3.0
*/
Skylink.prototype._enableDataChannel = true;
/**
* Stores the list of Peer Datachannel connections.
* @attribute _dataChannels
* @param {JSON} (#peerId) The list of Datachannels associated with Peer ID.
* @param {RTCDataChannel} (#peerId).<#channelLabel> The Datachannel connection.
* The property name <code>"main"</code> is reserved for messaging Datachannel type.
* @type JSON
* @private
* @for Skylink
* @since 0.2.0
*/
Skylink.prototype._dataChannels = {};
/**
* Function that starts a Datachannel connection with Peer.
* @method _createDataChannel
* @private
* @for Skylink
* @since 0.5.5
*/
Skylink.prototype._createDataChannel = function(peerId, channelType, dc, customChannelName) {
var self = this;
if (typeof dc === 'string') {
customChannelName = dc;
dc = null;
}
if (!customChannelName) {
log.error([peerId, 'RTCDataChannel', null, 'Aborting of creating Datachannel as no ' +
'channel name is provided for channel. Aborting of creating Datachannel'], {
channelType: channelType
});
return;
}
var channelName = (dc) ? dc.label : customChannelName;
var pc = self._peerConnections[peerId];
var SctpSupported =
!(window.webrtcDetectedBrowser === 'chrome' && window.webrtcDetectedVersion < 30 ||
window.webrtcDetectedBrowser === 'opera' && window.webrtcDetectedVersion < 20 );
if (!SctpSupported) {
log.warn([peerId, 'RTCDataChannel', channelName, 'SCTP not supported'], {
channelType: channelType
});
return;
}
var dcHasOpened = function () {
log.log([peerId, 'RTCDataChannel', channelName, 'Datachannel state ->'], {
readyState: 'open',
channelType: channelType
});
self._trigger('dataChannelState', self.DATA_CHANNEL_STATE.OPEN,
peerId, null, channelName, channelType);
};
if (!dc) {
try {
dc = pc.createDataChannel(channelName);
if (dc.readyState === self.DATA_CHANNEL_STATE.OPEN) {
// the datachannel was not defined in array before it was triggered
// set a timeout to allow the dc objec to be returned before triggering "open"
setTimeout(dcHasOpened, 500);
} else {
self._trigger('dataChannelState', dc.readyState, peerId, null,
channelName, channelType);
self._wait(function () {
log.log([peerId, 'RTCDataChannel', dc.label, 'Firing callback. ' +
'Datachannel state has opened ->'], dc.readyState);
dcHasOpened();
}, function () {
return dc.readyState === self.DATA_CHANNEL_STATE.OPEN;
});
}
log.debug([peerId, 'RTCDataChannel', channelName, 'Datachannel RTC object is created'], {
readyState: dc.readyState,
channelType: channelType
});
} catch (error) {
log.error([peerId, 'RTCDataChannel', channelName, 'Exception occurred in datachannel:'], {
channelType: channelType,
error: error
});
self._trigger('dataChannelState', self.DATA_CHANNEL_STATE.ERROR, peerId, error,
channelName, channelType);
return;
}
} else {
if (dc.readyState === self.DATA_CHANNEL_STATE.OPEN) {
// the datachannel was not defined in array before it was triggered
// set a timeout to allow the dc objec to be returned before triggering "open"
setTimeout(dcHasOpened, 500);
} else {
dc.onopen = dcHasOpened;
}
}
log.log([peerId, 'RTCDataChannel', channelName, 'Binary type support ->'], {
binaryType: dc.binaryType,
readyState: dc.readyState,
channelType: channelType
});
dc.dcType = channelType;
dc.onerror = function(error) {
log.error([peerId, 'RTCDataChannel', channelName, 'Exception occurred in datachannel:'], {
channelType: channelType,
readyState: dc.readyState,
error: error
});
self._trigger('dataChannelState', self.DATA_CHANNEL_STATE.ERROR, peerId, error,
channelName, channelType);
};
dc.onclose = function() {
log.debug([peerId, 'RTCDataChannel', channelName, 'Datachannel state ->'], {
readyState: 'closed',
channelType: channelType
});
dc.hasFiredClosed = true;
// give it some time to set the variable before actually closing and checking.
setTimeout(function () {
// redefine pc
pc = self._peerConnections[peerId];
// if closes because of firefox, reopen it again
// if it is closed because of a restart, ignore
var checkIfChannelClosedDuringConn = !!pc ? !pc.dataChannelClosed : false;
if (checkIfChannelClosedDuringConn && dc.dcType === self.DATA_CHANNEL_TYPE.MESSAGING) {
log.debug([peerId, 'RTCDataChannel', channelName, 'Re-opening closed datachannel in ' +
'on-going connection'], {
channelType: channelType,
readyState: dc.readyState,
isClosedDuringConnection: checkIfChannelClosedDuringConn
});
self._dataChannels[peerId].main =
self._createDataChannel(peerId, self.DATA_CHANNEL_TYPE.MESSAGING, null, peerId);
log.debug([peerId, 'RTCDataChannel', channelName, 'Re-opened closed datachannel'], {
channelType: channelType,
readyState: dc.readyState,
isClosedDuringConnection: checkIfChannelClosedDuringConn
});
} else {
self._closeDataChannel(peerId, channelName);
self._trigger('dataChannelState', self.DATA_CHANNEL_STATE.CLOSED, peerId, null,
channelName, channelType);
log.debug([peerId, 'RTCDataChannel', channelName, 'Datachannel has closed'], {
channelType: channelType,
readyState: dc.readyState,
isClosedDuringConnection: checkIfChannelClosedDuringConn
});
}
}, 100);
};
dc.onmessage = function(event) {
self._dataChannelProtocolHandler(event.data, peerId, channelName, channelType);
};
return dc;
};
/**
* Function that sends data over the Datachannel connection.
* @method _sendDataChannelMessage
* @private
* @for Skylink
* @since 0.5.2
*/
Skylink.prototype._sendDataChannelMessage = function(peerId, data, channelKey) {
var self = this;
var channelName;
if (!channelKey || channelKey === peerId) {
channelKey = 'main';
}
var dcList = self._dataChannels[peerId] || {};
var dc = dcList[channelKey];
if (!dc) {
log.error([peerId, 'RTCDataChannel', channelKey + '|' + channelName,
'Datachannel connection to peer does not exist'], {
enabledState: self._enableDataChannel,
dcList: dcList,
dc: dc,
type: (data.type || 'DATA'),
data: data,
channelKey: channelKey
});
return;
} else {
channelName = dc.label;
log.debug([peerId, 'RTCDataChannel', channelKey + '|' + channelName,
'Sending data using this channel key'], data);
if (dc.readyState === this.DATA_CHANNEL_STATE.OPEN) {
var dataString = (typeof data === 'object') ? JSON.stringify(data) : data;
log.debug([peerId, 'RTCDataChannel', channelKey + '|' + dc.label,
'Sending to peer ->'], {
readyState: dc.readyState,
type: (data.type || 'DATA'),
data: data
});
dc.send(dataString);
} else {
log.error([peerId, 'RTCDataChannel', channelKey + '|' + dc.label,
'Datachannel is not opened'], {
readyState: dc.readyState,
type: (data.type || 'DATA'),
data: data
});
this._trigger('dataChannelState', this.DATA_CHANNEL_STATE.ERROR,
peerId, 'Datachannel is not ready.\nState is: ' + dc.readyState);
}
}
};
/**
* Function that stops the Datachannel connection and removes object references.
* @method _closeDataChannel
* @private
* @for Skylink
* @since 0.1.0
*/
Skylink.prototype._closeDataChannel = function(peerId, channelName) {
var self = this;
var dcList = self._dataChannels[peerId] || {};
var dcKeysList = Object.keys(dcList);
if (channelName) {
dcKeysList = [channelName];
}
for (var i = 0; i < dcKeysList.length; i++) {
var channelKey = dcKeysList[i];
var dc = dcList[channelKey];
if (dc) {
if (dc.readyState !== self.DATA_CHANNEL_STATE.CLOSED) {
log.log([peerId, 'RTCDataChannel', channelKey + '|' + dc.label,
'Closing datachannel']);
dc.close();
} else {
if (!dc.hasFiredClosed && window.webrtcDetectedBrowser === 'firefox') {
log.log([peerId, 'RTCDataChannel', channelKey + '|' + dc.label,
'Closed Firefox datachannel']);
self._trigger('dataChannelState', self.DATA_CHANNEL_STATE.CLOSED, peerId,
null, channelName, channelKey === 'main' ? self.DATA_CHANNEL_TYPE.MESSAGING :
self.DATA_CHANNEL_TYPE.DATA);
}
}
delete self._dataChannels[peerId][channelKey];
log.log([peerId, 'RTCDataChannel', channelKey + '|' + dc.label,
'Sucessfully removed datachannel']);
} else {
log.log([peerId, 'RTCDataChannel', channelKey + '|' + channelName,
'Unable to close Datachannel as it does not exists'], {
dc: dc,
dcList: dcList
});
}
}
};
Skylink.prototype.DATA_TRANSFER_DATA_TYPE = {
BINARY_STRING: 'binaryString',
ARRAY_BUFFER: 'arrayBuffer',
BLOB: 'blob'
};
/**
* Stores the data chunk size for Blob transfers.
* @attribute _CHUNK_FILE_SIZE
* @type Number
* @private
* @readOnly
* @for Skylink
* @since 0.5.2
*/
Skylink.prototype._CHUNK_FILE_SIZE = 49152;
/**
* Stores the data chunk size for Blob transfers transferring from/to
* Firefox browsers due to limitation tested in the past in some PCs (linx predominatly).
* @attribute _MOZ_CHUNK_FILE_SIZE
* @type Number
* @private
* @readOnly
* @for Skylink
* @since 0.5.2
*/
Skylink.prototype._MOZ_CHUNK_FILE_SIZE = 12288;
/**
* Stores the data chunk size for data URI string transfers.
* @attribute _CHUNK_DATAURL_SIZE
* @type Number
* @private
* @readOnly
* @for Skylink
* @since 0.5.2
*/
Skylink.prototype._CHUNK_DATAURL_SIZE = 1212;
/**
* Function that converts Base64 string into Blob object.
* This is referenced from devnull69@stackoverflow.com #6850276.
* @method _base64ToBlob
* @private
* @for Skylink
* @since 0.1.0
*/
Skylink.prototype._base64ToBlob = function(dataURL) {
var byteString = atob(dataURL.replace(/\s\r\n/g, ''));
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var j = 0; j < byteString.length; j++) {
ia[j] = byteString.charCodeAt(j);
}
// write the ArrayBuffer to a blob, and you're done
return new Blob([ab]);
};
/**
* Function that converts a Blob object into Base64 string.
* @method _blobToBase64
* @private
* @for Skylink
* @since 0.1.0
*/
Skylink.prototype._blobToBase64 = function(data, callback) {
var fileReader = new FileReader();
fileReader.onload = function() {
// Load Blob as dataurl base64 string
var base64BinaryString = fileReader.result.split(',')[1];
callback(base64BinaryString);
};
fileReader.readAsDataURL(data);
};
/**
* Function that chunks Blob object based on the data chunk size provided.
* If provided Blob object size is lesser than or equals to the chunk size, it should return an array
* of length of <code>1</code>.
* @method _chunkBlobData
* @private
* @for Skylink
* @since 0.5.2
*/
Skylink.prototype._chunkBlobData = function(blob, chunkSize) {
var chunksArray = [];
var startCount = 0;
var endCount = 0;
var blobByteSize = blob.size;
if (blobByteSize > chunkSize) {
// File Size greater than Chunk size
while ((blobByteSize - 1) > endCount) {
endCount = startCount + chunkSize;
chunksArray.push(blob.slice(startCount, endCount));
startCount += chunkSize;
}
if ((blobByteSize - (startCount + 1)) > 0) {
chunksArray.push(blob.slice(startCount, blobByteSize - 1));
}
} else {
// File Size below Chunk size
chunksArray.push(blob);
}
return chunksArray;
};
/**
* Function that chunks large string into string chunks based on the data chunk size provided.
* If provided string length is lesser than or equals to the chunk size, it should return an array
* of length of <code>1</code>.
* @method _chunkDataURL
* @private
* @for Skylink
* @since 0.6.1
*/
Skylink.prototype._chunkDataURL = function(dataURL, chunkSize) {
var outputStr = dataURL; //encodeURIComponent(dataURL);
var dataURLArray = [];
var startCount = 0;
var endCount = 0;
var dataByteSize = dataURL.size || dataURL.length;
if (dataByteSize > chunkSize) {
// File Size greater than Chunk size
while ((dataByteSize - 1) > endCount) {
endCount = startCount + chunkSize;
dataURLArray.push(outputStr.slice(startCount, endCount));
startCount += chunkSize;
}
if ((dataByteSize - (startCount + 1)) > 0) {
chunksArray.push(outputStr.slice(startCount, dataByteSize - 1));
}
} else {
// File Size below Chunk size
dataURLArray.push(outputStr);
}
return dataURLArray;
};
/**
* Function that assembles the data string chunks into a large string.
* @method _assembleDataURL
* @private
* @for Skylink
* @since 0.6.1
*/
Skylink.prototype._assembleDataURL = function(dataURLArray) {
var outputStr = '';
for (var i = 0; i < dataURLArray.length; i++) {
try {
outputStr += dataURLArray[i];
} catch (error) {
console.error('Malformed', i, dataURLArray[i]);
}
}
return outputStr;
};
Skylink.prototype.DT_PROTOCOL_VERSION = '0.1.0';
/**
* The list of data transfers directions.
* @attribute DATA_TRANSFER_TYPE
* @param {String} UPLOAD <small>Value <code>"upload"</code></small>
* The value of the data transfer direction when User is uploading data to Peer.
* @param {String} DOWNLOAD <small>Value <code>"download"</code></small>
* The value of the data transfer direction when User is downloading data from Peer.
* @type JSON
* @readOnly
* @for Skylink
* @since 0.1.0
*/
Skylink.prototype.DATA_TRANSFER_TYPE = {
UPLOAD: 'upload',
DOWNLOAD: 'download'
};
/**
* The list of data transfers session types.
* @attribute DATA_TRANSFER_SESSION_TYPE
* @param {String} BLOB <small>Value <code>"blob"</code></small>
* The value of the session type for
* <a href="#method_sendURLData"><code>sendURLData()</code> method</a> data transfer.
* @param {String} DATA_URL <small>Value <code>"dataURL"</code></small>
* The value of the session type for
* <a href="#method_sendBlobData"><code>method_sendBlobData()</code> method</a> data transfer.
* @type JSON
* @readOnly
* @for Skylink
* @since 0.1.0
*/
Skylink.prototype.DATA_TRANSFER_SESSION_TYPE = {
BLOB: 'blob',
DATA_URL: 'dataURL'
};
/**
* The list of data transfer states.
* @attribute DATA_TRANSFER_STATE
* @param {String} UPLOAD_REQUEST <small>Value <code>"request"</code></small>
* The value of the state when receiving an upload data transfer request from Peer to User.
* <small>At this stage, the upload data transfer request from Peer may be accepted or rejected with the
* <a href="#method_acceptDataTransfer"><code>acceptDataTransfer()</code> method</a>.</small>
* @param {String} UPLOAD_STARTED <small>Value <code>"uploadStarted"</code></small>
* The value of the state when the data transfer request has been accepted
* and data transfer will start uploading data to Peer.
* <small>At this stage, the data transfer may be terminated with the
* <a href="#method_cancelDataTransfer"><code>cancelDataTransfer()</code> method</a>.</small>
* @param {String} DOWNLOAD_STARTED <small>Value <code>"downloadStarted"</code></small>
* The value of the state when the data transfer request has been accepted
* and data transfer will start downloading data from Peer.
* <small>At this stage, the data transfer may be terminated with the
* <a href="#method_cancelDataTransfer"><code>cancelDataTransfer()</code> method</a>.</small>
* @param {String} REJECTED <small>Value <code>"rejected"</code></small>
* The value of the state when upload data transfer request to Peer has been rejected and terminated.
* @param {String} UPLOADING <small>Value <code>"uploading"</code></small>
* The value of the state when data transfer is uploading data to Peer.
* @param {String} DOWNLOADING <small>Value <code>"downloading"</code></small>
* The value of the state when data transfer is downloading data from Peer.
* @param {String} UPLOAD_COMPLETED <small>Value <code>"uploadCompleted"</code></small>
* The value of the state when data transfer has uploaded successfully to Peer.
* @param {String} DOWNLOAD_COMPLETED <small>Value <code>"downloadCompleted"</code></small>
* The value of the state when data transfer has downloaded successfully from Peer.
* @param {String} CANCEL <small>Value <code>"cancel"</code></small>
* The value of the state when data transfer has been terminated from / to Peer.
* @param {String} ERROR <small>Value <code>"error"</code></small>
* The value of the state when data transfer has errors and has been terminated from / to Peer.
* @type JSON
* @readOnly
* @for Skylink
* @since 0.4.0
*/
Skylink.prototype.DATA_TRANSFER_STATE = {
UPLOAD_REQUEST: 'request',
UPLOAD_STARTED: 'uploadStarted',
DOWNLOAD_STARTED: 'downloadStarted',
REJECTED: 'rejected',
CANCEL: 'cancel',
ERROR: 'error',
UPLOADING: 'uploading',
DOWNLOADING: 'downloading',
UPLOAD_COMPLETED: 'uploadCompleted',
DOWNLOAD_COMPLETED: 'downloadCompleted'
};
/**
* Stores the fixed delimiter that concats the Datachannel label and actual transfer ID.
* @attribute _TRANSFER_DELIMITER
* @type String
* @readOnly
* @private
* @for Skylink
* @since 0.5.10
*/
Skylink.prototype._TRANSFER_DELIMITER = '_skylink__';
/**
* Stores the list of data transfer protocols.
* @attribute _DC_PROTOCOL_TYPE
* @param {String} WRQ The protocol to initiate data transfer.
* @param {String} ACK The protocol to request for data transfer chunk.
* Give <code>-1</code> to reject the request at the beginning and <code>0</code> to accept
* the data transfer request.
* @param {String} CANCEL The protocol to terminate data transfer.
* @param {String} ERROR The protocol when data transfer has errors and has to be terminated.
* @param {String} MESSAGE The protocol that is used to send P2P messages.
* @type JSON
* @readOnly
* @private
* @for Skylink
* @since 0.5.2
*/
Skylink.prototype._DC_PROTOCOL_TYPE = {
WRQ: 'WRQ',
ACK: 'ACK',
ERROR: 'ERROR',
CANCEL: 'CANCEL',
MESSAGE: 'MESSAGE'
};
/**
* Stores the list of types of SDKs that do not support simultaneous data transfers.
* @attribute _INTEROP_MULTI_TRANSFERS
* @type Array
* @readOnly
* @private
* @for Skylink
* @since 0.6.1
*/
Skylink.prototype._INTEROP_MULTI_TRANSFERS = ['Android', 'iOS'];
/**
* Stores the list of uploading data transfers chunks to Peers.
* @attribute _uploadDataTransfers
* @param {Array} <#transferId> The uploading data transfer chunks.
* @type JSON
* @private
* @for Skylink
* @since 0.4.1
*/
Skylink.prototype._uploadDataTransfers = {};
/**
* Stores the list of uploading data transfer sessions to Peers.
* @attribute _uploadDataSessions
* @param {JSON} <#transferId> The uploading data transfer session.
* @type JSON
* @private
* @for Skylink
* @since 0.4.1
*/
Skylink.prototype._uploadDataSessions = {};
/**
* Stores the list of downloading data transfers chunks to Peers.
* @attribute _downloadDataTransfers
* @param {Array} <#transferId> The downloading data transfer chunks.
* @type JSON
* @private
* @for Skylink
* @since 0.4.1
*/
Skylink.prototype._downloadDataTransfers = {};
/**
* Stores the list of downloading data transfer sessions to Peers.
* @attribute _downloadDataSessions
* @param {JSON} <#transferId> The downloading data transfer session.
* @type JSON
* @private
* @for Skylink
* @since 0.4.1
*/
Skylink.prototype._downloadDataSessions = {};
/**
* Stores the list of data transfer "wait-for-response" timeouts.
* @attribute _dataTransfersTimeout
* @param {Object} <#transferId> The data transfer session "wait-for-response" timeout.
* @type JSON
* @private
* @for Skylink
* @since 0.4.1
*/
Skylink.prototype._dataTransfersTimeout = {};
/**
* <blockquote class="info">
* Note that Android and iOS SDKs do not support simultaneous data transfers.
* </blockquote>
* Function that starts an uploading data transfer from User to Peers.
* @method sendBlobData
* @param {Blob} data The Blob object.
* @param {Number} [timeout=60] The timeout to wait for response from Peer.
* @param {String|Array} [targetPeerId] The target Peer ID to start data transfer with.
* - When provided as an Array, it will start uploading data transfers with all connections
* with all the Peer IDs provided.
* - When not provided, it will start uploading data transfers with all the currently connected Peers in the Room.
* @param {Function} [callback] The callback function fired when request has completed.
* <small>Function parameters signature is <code>function (error, success)</code></small>
* <small>Function request completion is determined by the <a href="#event_dataTransferState">
* <code>dataTransferState</code> event</a> triggering <code>state</code> parameter payload
* as <code>UPLOAD_COMPLETED</code> for all Peers targeted for request success.</small>
* @param {JSON} callback.error The error result in request.
* <small>Defined as <code>null</code> when there are no errors in request</small>
* @param {String} callback.error.transferId <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <code>callback.error.transferInfo.transferId</code> instead.
* </blockquote> The data transfer ID.
* <small>Defined only for single targeted Peer data transfer.</small>
* @param {String} callback.error.state <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <a href="#event_dataTransferState"><code>dataTransferState</code>
* event</a> instead. </blockquote> The data transfer state that resulted in error.
* <small>Defined only for single targeted Peer data transfer.</small> [Rel: Skylink.DATA_TRANSFER_STATE]
* @param {String} callback.error.peerId <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <code>callback.error.listOfPeers</code> instead.
* </blockquote> The targeted Peer ID for data transfer.
* <small>Defined only for single targeted Peer data transfer.</small>
* @param {Boolean} callback.error.isPrivate <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <code>callback.error.transferInfo.isPrivate</code> instead.
* </blockquote> The flag if data transfer is targeted or not, basing
* off the <code>targetPeerId</code> parameter being defined.
* <small>Defined only for single targeted Peer data transfer.</small>
* @param {Error|String} callback.error.error <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <code>callback.error.transferErrors</code> instead.
* </blockquote> The error received that resulted in error.
* <small>Defined only for single targeted Peer data transfer.</small>
* @param {Array} callback.error.listOfPeers The list Peer IDs targeted for the data transfer.
* @param {JSON} callback.error.transferErrors The list of data transfer errors.
* @param {Error|String} callback.error.transferErrors.#peerId The data transfer error associated
* with the Peer ID defined in <code>#peerId</code> property.
* <small>If <code>#peerId</code> value is <code>"self"</code>, it means that it is the error when there
* are no Peer connections to start data transfer with.</small>
* @param {JSON} callback.error.transferInfo The data transfer information.
* <small>Object signature matches the <code>transferInfo</code> parameter payload received in the
* <a href="#event_dataTransferState"><code>dataTransferState</code> event</a>.</small>
* @param {JSON} callback.success The success result in request.
* <small>Defined as <code>null</code> when there are errors in request</small>
* @param {String} callback.success.transferId <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <code>callback.success.transferInfo.transferId</code> instead.
* </blockquote> The data transfer ID.
* @param {String} callback.success.state <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <a href="#event_dataTransferState"><code>dataTransferState</code>
* event</a> instead. </blockquote> The data transfer state that resulted in error.
* <small>Defined only for single targeted Peer data transfer.</small> [Rel: Skylink.DATA_TRANSFER_STATE]
* @param {String} callback.success.peerId <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <code>callback.success.listOfPeers</code> instead.
* </blockquote> The targeted Peer ID for data transfer.
* <small>Defined only for single targeted Peer data transfer.</small>
* @param {Boolean} callback.success.isPrivate <blockquote class="info">
* <b>Deprecation Warning!</b> This property has been deprecated.
* Please use <code>callback.success.transferInfo.isPrivate</code> instead.
* </blockquote> The flag if data transfer is targeted or not, basing
* off the <code>targetPeerId</code> parameter being defined.