-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
3007 lines (2753 loc) · 106 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
'use strict';
/**
* Default timeout for any pending request.
* @type {number}
*/
const DEFAULT_REQUEST_TIMEOUT = 60000
/**
* Item storage which is separate for each service. The `Map` key is the service `id`.
*/
const itemsStorage = new Map()
/**
* Pending request map. Pending request is when a service uses a Promise
* which will be fulfilled or rejected somewhere else in code. For exemple when
* a peer is waiting for a feedback from another peer before Promise has completed.
* @type {Map}
*/
const requestsStorage = new Map()
/**
* Abstract class which each service should inherit. Each service is independent
* and can store data temporarly in order to accomplish its task(s).
*/
class Service {
/**
* It should be invoked only by calling `super` from the children constructor.
*
* @param {number} id The service unique identifier
*/
constructor (id) {
/**
* The service unique identifier.
* @type {number}
*/
this.id = id
if (!itemsStorage.has(this.id)) itemsStorage.set(this.id, new WeakMap())
if (!requestsStorage.has(this.id)) requestsStorage.set(this.id, new WeakMap())
}
/**
* Add a new pending request identified by `obj` and `id`.
* @param {Object} obj
* @param {number} id
* @param {{resolve: Promise.resolve, reject:Promise.reject}} data
* @param {number} [timeout=DEFAULT_REQUEST_TIMEOUT] Timeout in milliseconds
*/
setPendingRequest (obj, id, data, timeout = DEFAULT_REQUEST_TIMEOUT) {
this.setTo(requestsStorage, obj, id, data)
setTimeout(() => { data.reject('Pending request timeout') }, timeout)
}
/**
* Get pending request identified by `obj` and `id`.
*
* @param {Object} obj
* @param {number} id
* @returns {{resolve: Promise.resolve, reject:Promise.reject}}
*/
getPendingRequest (obj, id) {
return this.getFrom(requestsStorage, obj, id)
}
/**
* Add item with `obj` and `ìd` as identifier.
* @param {Object} obj
* @param {number} id
* @param {Object} data
*/
setItem (obj, id, data) {
this.setTo(itemsStorage, obj, id, data)
}
/**
* Get item identified by `obj` and `id`.
*
* @param {Object} obj
* @param {number} id
*
* @returns {Object}
*/
getItem (obj, id) {
return this.getFrom(itemsStorage, obj, id)
}
/**
* Get all items belonging to `obj`.
*
* @param {Object} obj
* @returns {Map}
*/
getItems (obj) {
let items = itemsStorage.get(this.id).get(obj)
if (items) return items
else return new Map()
}
/**
* Remove item identified by `obj` and `id`.
*
* @param {Object} obj
* @param {number} id
*/
removeItem (obj, id) {
let currentServiceTemp = itemsStorage.get(this.id)
let idMap = currentServiceTemp.get(obj)
currentServiceTemp.get(obj).delete(id)
if (idMap.size === 0) currentServiceTemp.delete(obj)
}
/**
* @private
* @param {Map} storage
* @param {Object} obj
* @param {number} id
*
* @returns {Object}
*/
getFrom (storage, obj, id) {
let idMap = storage.get(this.id).get(obj)
if (idMap !== undefined) {
let item = idMap.get(id)
if (item !== undefined) return item
}
return null
}
/**
* @private
* @param {Map} storage
* @param {WebChannel} obj
* @param {number} id
* @param {Object} data
*
*/
setTo (storage, obj, id, data) {
let currentServiceTemp = storage.get(this.id)
let idMap
if (currentServiceTemp.has(obj)) {
idMap = currentServiceTemp.get(obj)
} else {
idMap = new Map()
currentServiceTemp.set(obj, idMap)
}
if (!idMap.has(id)) idMap.set(id, data)
}
}
/**
* It is responsible to preserve Web Channel
* structure intact (i.e. all peers have the same vision of the Web Channel).
* Among its duties are:
*
* - Add a new peer into Web Channel.
* - Remove a peer from Web Channel.
* - Send a broadcast message.
* - Send a message to a particular peer.
*
* @see FullyConnectedService
* @interface
*/
class TopologyInterface extends Service {
connectTo (wc, peerIds) {
let failed = []
if (peerIds.length === 0) return Promise.resolve(failed)
else {
return new Promise((resolve, reject) => {
let counter = 0
let cBuilder = ServiceFactory.get(CHANNEL_BUILDER)
peerIds.forEach(id => {
cBuilder.connectTo(wc, id)
.then(channel => this.onChannel(channel))
.then(() => { if (++counter === peerIds.length) resolve(failed) })
.catch(reason => {
failed.push({id, reason})
if (++counter === peerIds.length) resolve(failed)
})
})
})
}
}
/**
* Adds a new peer into Web Channel.
*
* @abstract
* @param {Channel} ch - Channel to be added (it should has
* the `webChannel` property).
* @return {Promise} - Resolved once the channel has been succesfully added,
* rejected otherwise.
*/
add (ch) {
throw new Error('Must be implemented by subclass!')
}
/**
* Send a message to all peers in Web Channel.
*
* @abstract
* @param {WebChannel} wc - Web Channel where the message will be propagated.
* @param {string} data - Data in stringified JSON format to be send.
*/
broadcast (wc, data) {
throw new Error('Must be implemented by subclass!')
}
/**
* Send a message to a particular peer in Web Channel.
*
* @abstract
* @param {string} id - Peer id.
* @param {WebChannel} wc - Web Channel where the message will be propagated.
* @param {string} data - Data in stringified JSON format to be send.
*/
sendTo (id, wc, data) {
throw new Error('Must be implemented by subclass!')
}
/**
* Leave Web Channel.
*
* @abstract
* @param {WebChannel} wc - Web Channel to leave.
*/
leave (wc) {
throw new Error('Must be implemented by subclass!')
}
}
/**
* One of the internal message type. The message is intended for the `WebChannel`
* members to notify them about the joining peer.
* @type {number}
*/
const SHOULD_ADD_NEW_JOINING_PEER = 1
/**
* Connection service of the peer who received a message of this type should
* establish connection with one or several peers.
*/
const SHOULD_CONNECT_TO = 2
/**
* One of the internal message type. The message sent by the joining peer to
* notify all `WebChannel` members about his arrivel.
* @type {number}
*/
const PEER_JOINED = 3
const TICK = 4
const TOCK = 5
/**
* Fully connected web channel manager. Implements fully connected topology
* network, when each peer is connected to each other.
*
* @extends module:webChannelManager~WebChannelTopologyInterface
*/
class FullyConnectedService extends TopologyInterface {
/**
* Add a peer to the `WebChannel`.
*
* @param {WebSocket|RTCDataChannel} channel
*
* @returns {Promise<number, string}
*/
add (channel) {
let wc = channel.webChannel
let peers = wc.members.slice()
for (let jpId of super.getItems(wc).keys()) peers[peers.length] = jpId
this.setJP(wc, channel.peerId, channel)
wc.sendInner(this.id, {code: SHOULD_ADD_NEW_JOINING_PEER, jpId: channel.peerId})
wc.sendInnerTo(channel, this.id, {code: SHOULD_CONNECT_TO, peers})
return new Promise((resolve, reject) => {
super.setPendingRequest(wc, channel.peerId, {resolve, reject})
})
}
/**
* Send message to all `WebChannel` members.
*
* @param {WebChannel} webChannel
* @param {ArrayBuffer} data
*/
broadcast (webChannel, data) {
for (let c of webChannel.channels) c.send(data)
}
sendTo (id, webChannel, data) {
for (let c of webChannel.channels) {
if (c.peerId === id) {
c.send(data)
return
}
}
}
sendInnerTo (recepient, wc, data) {
// If the peer sent a message to himself
if (recepient === wc.myId) wc.onChannelMessage(null, data)
else {
let jp = super.getItem(wc, wc.myId)
if (jp === null) jp = super.getItem(wc, recepient)
if (jp !== null) { // If me or recepient is joining the WebChannel
jp.channel.send(data)
} else if (wc.members.includes(recepient)) { // If recepient is a WebChannel member
this.sendTo(recepient, wc, data)
} else this.sendTo(wc.members[0], wc, data)
}
}
sendInner (wc, data) {
let jp = super.getItem(wc, wc.myId)
if (jp === null) this.broadcast(wc, data)
else jp.channel.send(data)
}
leave (wc) {
for (let c of wc.channels) {
c.clearHandlers()
c.close()
}
wc.channels.clear()
}
onChannel (channel) {
return new Promise((resolve, reject) => {
super.setPendingRequest(channel.webChannel, channel.peerId, {resolve, reject})
channel.webChannel.sendInnerTo(channel, this.id, {code: TICK})
})
}
/**
* Close event handler for each `Channel` in the `WebChannel`.
*
* @param {CloseEvent} closeEvt
* @param {Channel} channel
*
* @returns {boolean}
*/
onChannelClose (closeEvt, channel) {
// TODO: need to check if this is a peer leaving and thus he closed channels
// with all WebChannel members or this is abnormal channel closing
let wc = channel.webChannel
for (let c of wc.channels) {
if (c.peerId === channel.peerId) return wc.channels.delete(c)
}
let jps = super.getItems(wc)
jps.forEach(jp => jp.channels.delete(channel))
return false
}
/**
* Error event handler for each `Channel` in the `WebChannel`.
*
* @param {Event} evt
* @param {Channel} channel
*/
onChannelError (evt, channel) {
console.error(`Channel error with id: ${channel.peerId}: `, evt)
}
onMessage (channel, senderId, recepientId, msg) {
let wc = channel.webChannel
let jpMe
switch (msg.code) {
case SHOULD_CONNECT_TO:
jpMe = this.setJP(wc, wc.myId, channel)
jpMe.channels.add(channel)
super.connectTo(wc, msg.peers)
.then(failed => {
let msg = {code: PEER_JOINED}
jpMe.channels.forEach(ch => {
wc.sendInnerTo(ch, this.id, msg)
wc.channels.add(ch)
wc.onPeerJoin$(ch.peerId)
})
super.removeItem(wc, wc.myId)
super.getItems(wc).forEach(jp => wc.sendInnerTo(jp.channel, this.id, msg))
wc.onJoin()
})
break
case PEER_JOINED:
jpMe = super.getItem(wc, wc.myId)
super.removeItem(wc, senderId)
if (jpMe !== null) jpMe.channels.add(channel)
else {
wc.channels.add(channel)
wc.onPeerJoin$(senderId)
let request = super.getPendingRequest(wc, senderId)
if (request !== null) request.resolve(senderId)
}
break
case TICK:
this.setJP(wc, senderId, channel)
let isJoining = super.getItem(wc, wc.myId) !== null
wc.sendInnerTo(channel, this.id, {code: TOCK, isJoining})
break
case TOCK:
if (msg.isJoining) this.setJP(wc, senderId, channel)
else super.getItem(wc, wc.myId).channels.add(channel)
super.getPendingRequest(wc, senderId).resolve()
break
case SHOULD_ADD_NEW_JOINING_PEER:
this.setJP(wc, msg.jpId, channel)
break
}
}
/**
* @private
* @param {WebChannel} wc
* @param {number} jpId
* @param {WebSocket|RTCDataChannel} channel
*
* @returns {type} Description
*/
setJP (wc, jpId, channel) {
let jp = super.getItem(wc, jpId)
if (!jp) {
jp = new JoiningPeer(channel)
super.setItem(wc, jpId, jp)
} else jp.channel = channel
return jp
}
}
/**
* This class represents a temporary state of a peer, while he is about to join
* the web channel. During the joining process every peer in the web channel
* and the joining peer have an instance of this class with the same `id` and
* `intermediaryId` attribute values. After the joining process has been finished
* regardless of success, these instances will be deleted.
*/
class JoiningPeer {
constructor (channel, onJoin) {
/**
* The channel between the joining peer and intermediary peer. It is null
* for every peer, but the joining and intermediary peers.
*
* @type {Channel}
*/
this.channel = channel
/**
* This attribute is proper to each peer. Array of channels which will be
* added to the current peer once it becomes the member of the web channel.
* @type {Channel[]}
*/
this.channels = new Set()
}
}
!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){"use strict";!function(){var logging=require("./utils").log,browserDetails=require("./utils").browserDetails;module.exports.browserDetails=browserDetails,module.exports.extractVersion=require("./utils").extractVersion,module.exports.disableLog=require("./utils").disableLog;var chromeShim=require("./chrome/chrome_shim")||null,edgeShim=require("./edge/edge_shim")||null,firefoxShim=require("./firefox/firefox_shim")||null,safariShim=require("./safari/safari_shim")||null;switch(browserDetails.browser){case"opera":case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection)return void logging("Chrome shim is not included in this adapter release.");logging("adapter.js shimming chrome."),module.exports.browserShim=chromeShim,chromeShim.shimGetUserMedia(),chromeShim.shimMediaStream(),chromeShim.shimSourceObject(),chromeShim.shimPeerConnection(),chromeShim.shimOnTrack();break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection)return void logging("Firefox shim is not included in this adapter release.");logging("adapter.js shimming firefox."),module.exports.browserShim=firefoxShim,firefoxShim.shimGetUserMedia(),firefoxShim.shimSourceObject(),firefoxShim.shimPeerConnection(),firefoxShim.shimOnTrack();break;case"edge":if(!edgeShim||!edgeShim.shimPeerConnection)return void logging("MS edge shim is not included in this adapter release.");logging("adapter.js shimming edge."),module.exports.browserShim=edgeShim,edgeShim.shimGetUserMedia(),edgeShim.shimPeerConnection();break;case"safari":if(!safariShim)return void logging("Safari shim is not included in this adapter release.");logging("adapter.js shimming safari."),module.exports.browserShim=safariShim,safariShim.shimGetUserMedia();break;default:logging("Unsupported browser!")}}()},{"./chrome/chrome_shim":3,"./edge/edge_shim":1,"./firefox/firefox_shim":5,"./safari/safari_shim":7,"./utils":8}],3:[function(require,module,exports){"use strict";var logging=require("../utils.js").log,browserDetails=require("../utils.js").browserDetails,chromeShim={shimMediaStream:function(){window.MediaStream=window.MediaStream||window.webkitMediaStream},shimOnTrack:function(){"object"!=typeof window||!window.RTCPeerConnection||"ontrack"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(f){var self=this;this._ontrack&&(this.removeEventListener("track",this._ontrack),this.removeEventListener("addstream",this._ontrackpoly)),this.addEventListener("track",this._ontrack=f),this.addEventListener("addstream",this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",function(te){var event=new Event("track");event.track=te.track,event.receiver={track:te.track},event.streams=[e.stream],self.dispatchEvent(event)}),e.stream.getTracks().forEach(function(track){var event=new Event("track");event.track=track,event.receiver={track:track},event.streams=[e.stream],this.dispatchEvent(event)}.bind(this))}.bind(this))}})},shimSourceObject:function(){"object"==typeof window&&(!window.HTMLMediaElement||"srcObject"in window.HTMLMediaElement.prototype||Object.defineProperty(window.HTMLMediaElement.prototype,"srcObject",{get:function(){return this._srcObject},set:function(stream){var self=this;return this._srcObject=stream,this.src&&URL.revokeObjectURL(this.src),stream?(this.src=URL.createObjectURL(stream),stream.addEventListener("addtrack",function(){self.src&&URL.revokeObjectURL(self.src),self.src=URL.createObjectURL(stream)}),void stream.addEventListener("removetrack",function(){self.src&&URL.revokeObjectURL(self.src),self.src=URL.createObjectURL(stream)})):void(this.src="")}}))},shimPeerConnection:function(){window.RTCPeerConnection=function(pcConfig,pcConstraints){logging("PeerConnection"),pcConfig&&pcConfig.iceTransportPolicy&&(pcConfig.iceTransports=pcConfig.iceTransportPolicy);var pc=new webkitRTCPeerConnection(pcConfig,pcConstraints),origGetStats=pc.getStats.bind(pc);return pc.getStats=function(selector,successCallback,errorCallback){var self=this,args=arguments;if(arguments.length>0&&"function"==typeof selector)return origGetStats(selector,successCallback);var fixChromeStats_=function(response){var standardReport={},reports=response.result();return reports.forEach(function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:report.type};report.names().forEach(function(name){standardStats[name]=report.stat(name)}),standardReport[standardStats.id]=standardStats}),standardReport},makeMapStats=function(stats,legacyStats){var map=new Map(Object.keys(stats).map(function(key){return[key,stats[key]]}));return legacyStats=legacyStats||stats,Object.keys(legacyStats).forEach(function(key){map[key]=legacyStats[key]}),map};if(arguments.length>=2){var successCallbackWrapper_=function(response){args[1](makeMapStats(fixChromeStats_(response)))};return origGetStats.apply(this,[successCallbackWrapper_,arguments[0]])}return new Promise(function(resolve,reject){1===args.length&&"object"==typeof selector?origGetStats.apply(self,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject]):origGetStats.apply(self,[function(response){resolve(makeMapStats(fixChromeStats_(response),response.result()))},reject])}).then(successCallback,errorCallback)},pc},window.RTCPeerConnection.prototype=webkitRTCPeerConnection.prototype,webkitRTCPeerConnection.generateCertificate&&Object.defineProperty(window.RTCPeerConnection,"generateCertificate",{get:function(){return webkitRTCPeerConnection.generateCertificate}}),["createOffer","createAnswer"].forEach(function(method){var nativeMethod=webkitRTCPeerConnection.prototype[method];webkitRTCPeerConnection.prototype[method]=function(){var self=this;if(arguments.length<1||1===arguments.length&&"object"==typeof arguments[0]){var opts=1===arguments.length?arguments[0]:void 0;return new Promise(function(resolve,reject){nativeMethod.apply(self,[resolve,reject,opts])})}return nativeMethod.apply(this,arguments)}}),browserDetails.version<51&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=webkitRTCPeerConnection.prototype[method];webkitRTCPeerConnection.prototype[method]=function(){var args=arguments,self=this,promise=new Promise(function(resolve,reject){nativeMethod.apply(self,[args[0],resolve,reject])});return args.length<2?promise:promise.then(function(){args[1].apply(null,[])},function(err){args.length>=3&&args[2].apply(null,[err])})}}),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=webkitRTCPeerConnection.prototype[method];webkitRTCPeerConnection.prototype[method]=function(){return arguments[0]=new("addIceCandidate"===method?RTCIceCandidate:RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}});var nativeAddIceCandidate=RTCPeerConnection.prototype.addIceCandidate;RTCPeerConnection.prototype.addIceCandidate=function(){return null===arguments[0]?Promise.resolve():nativeAddIceCandidate.apply(this,arguments)}}};module.exports={shimMediaStream:chromeShim.shimMediaStream,shimOnTrack:chromeShim.shimOnTrack,shimSourceObject:chromeShim.shimSourceObject,shimPeerConnection:chromeShim.shimPeerConnection,shimGetUserMedia:require("./getusermedia")}},{"../utils.js":8,"./getusermedia":4}],4:[function(require,module,exports){"use strict";var logging=require("../utils.js").log;module.exports=function(){var constraintsToChrome_=function(c){if("object"!=typeof c||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"==typeof c[key]?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),oc={},oc[oldname_("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname_("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach(function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])})}}),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function(constraints,func){if(constraints=JSON.parse(JSON.stringify(constraints)),constraints&&constraints.audio&&(constraints.audio=constraintsToChrome_(constraints.audio)),constraints&&"object"==typeof constraints.video){var face=constraints.video.facingMode;if(face=face&&("object"==typeof face?face:{ideal:face}),face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&(!navigator.mediaDevices.getSupportedConstraints||!navigator.mediaDevices.getSupportedConstraints().facingMode)&&(delete constraints.video.facingMode,"environment"===face.exact||"environment"===face.ideal))return navigator.mediaDevices.enumerateDevices().then(function(devices){devices=devices.filter(function(d){return"videoinput"===d.kind});var back=devices.find(function(d){return d.label.toLowerCase().indexOf("back")!==-1})||devices.length&&devices[devices.length-1];return back&&(constraints.video.deviceId=face.exact?{exact:back.deviceId}:{ideal:back.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)});constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function(e){return{name:{PermissionDeniedError:"NotAllowedError",ConstraintNotSatisfiedError:"OverconstrainedError"}[e.name]||e.name,message:e.message,constraint:e.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}},getUserMedia_=function(constraints,onSuccess,onError){shimConstraints_(constraints,function(c){navigator.webkitGetUserMedia(c,onSuccess,function(e){onError(shimError_(e))})})};navigator.getUserMedia=getUserMedia_;var getUserMediaPromise_=function(constraints){return new Promise(function(resolve,reject){navigator.getUserMedia(constraints,resolve,reject)})};if(navigator.mediaDevices||(navigator.mediaDevices={getUserMedia:getUserMediaPromise_,enumerateDevices:function(){return new Promise(function(resolve){var kinds={audio:"audioinput",video:"videoinput"};return MediaStreamTrack.getSources(function(devices){resolve(devices.map(function(device){return{label:device.label,kind:kinds[device.kind],deviceId:device.id,groupId:""}}))})})}}),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,function(c){return origGetUserMedia(c).then(function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach(function(track){track.stop()}),new DOMException("","NotFoundError");return stream},function(e){return Promise.reject(shimError_(e))})})}}else navigator.mediaDevices.getUserMedia=function(constraints){return getUserMediaPromise_(constraints)};"undefined"==typeof navigator.mediaDevices.addEventListener&&(navigator.mediaDevices.addEventListener=function(){logging("Dummy mediaDevices.addEventListener called.")}),"undefined"==typeof navigator.mediaDevices.removeEventListener&&(navigator.mediaDevices.removeEventListener=function(){logging("Dummy mediaDevices.removeEventListener called.")})}},{"../utils.js":8}],5:[function(require,module,exports){"use strict";var browserDetails=require("../utils").browserDetails,firefoxShim={shimOnTrack:function(){"object"!=typeof window||!window.RTCPeerConnection||"ontrack"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(f){this._ontrack&&(this.removeEventListener("track",this._ontrack),this.removeEventListener("addstream",this._ontrackpoly)),this.addEventListener("track",this._ontrack=f),this.addEventListener("addstream",this._ontrackpoly=function(e){e.stream.getTracks().forEach(function(track){var event=new Event("track");event.track=track,event.receiver={track:track},event.streams=[e.stream],this.dispatchEvent(event)}.bind(this))}.bind(this))}})},shimSourceObject:function(){"object"==typeof window&&(!window.HTMLMediaElement||"srcObject"in window.HTMLMediaElement.prototype||Object.defineProperty(window.HTMLMediaElement.prototype,"srcObject",{get:function(){return this.mozSrcObject},set:function(stream){this.mozSrcObject=stream}}))},shimPeerConnection:function(){if("object"==typeof window&&(window.RTCPeerConnection||window.mozRTCPeerConnection)){window.RTCPeerConnection||(window.RTCPeerConnection=function(pcConfig,pcConstraints){if(browserDetails.version<38&&pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];if(server.hasOwnProperty("urls"))for(var j=0;j<server.urls.length;j++){var newServer={url:server.urls[j]};0===server.urls[j].indexOf("turn")&&(newServer.username=server.username,newServer.credential=server.credential),newIceServers.push(newServer)}else newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new mozRTCPeerConnection(pcConfig,pcConstraints)},window.RTCPeerConnection.prototype=mozRTCPeerConnection.prototype,mozRTCPeerConnection.generateCertificate&&Object.defineProperty(window.RTCPeerConnection,"generateCertificate",{get:function(){return mozRTCPeerConnection.generateCertificate}}),window.RTCSessionDescription=mozRTCSessionDescription,window.RTCIceCandidate=mozRTCIceCandidate),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){return arguments[0]=new("addIceCandidate"===method?RTCIceCandidate:RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}});var nativeAddIceCandidate=RTCPeerConnection.prototype.addIceCandidate;RTCPeerConnection.prototype.addIceCandidate=function(){return null===arguments[0]?Promise.resolve():nativeAddIceCandidate.apply(this,arguments)};var makeMapStats=function(stats){var map=new Map;return Object.keys(stats).forEach(function(key){map.set(key,stats[key]),map[key]=stats[key]}),map},nativeGetStats=RTCPeerConnection.prototype.getStats;RTCPeerConnection.prototype.getStats=function(selector,onSucc,onErr){return nativeGetStats.apply(this,[selector||null]).then(function(stats){return makeMapStats(stats)}).then(onSucc,onErr)}}}};module.exports={shimOnTrack:firefoxShim.shimOnTrack,shimSourceObject:firefoxShim.shimSourceObject,shimPeerConnection:firefoxShim.shimPeerConnection,shimGetUserMedia:require("./getusermedia")}},{"../utils":8,"./getusermedia":6}],6:[function(require,module,exports){"use strict";var logging=require("../utils").log,browserDetails=require("../utils").browserDetails;module.exports=function(){var shimError_=function(e){return{name:{SecurityError:"NotAllowedError",PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:{"The operation is insecure.":"The request is not allowed by the user agent or the platform in the current context."}[e.message]||e.message,constraint:e.constraint,toString:function(){return this.name+(this.message&&": ")+this.message}}},getUserMedia_=function(constraints,onSuccess,onError){var constraintsToFF37_=function(c){if("object"!=typeof c||c.require)return c;var require=[];return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r=c[key]="object"==typeof c[key]?c[key]:{ideal:c[key]};if(void 0===r.min&&void 0===r.max&&void 0===r.exact||require.push(key),void 0!==r.exact&&("number"==typeof r.exact?r.min=r.max=r.exact:c[key]=r.exact,delete r.exact),void 0!==r.ideal){c.advanced=c.advanced||[];var oc={};"number"==typeof r.ideal?oc[key]={min:r.ideal,max:r.ideal}:oc[key]=r.ideal,c.advanced.push(oc),delete r.ideal,Object.keys(r).length||delete c[key]}}}),require.length&&(c.require=require),c};return constraints=JSON.parse(JSON.stringify(constraints)),browserDetails.version<38&&(logging("spec: "+JSON.stringify(constraints)),constraints.audio&&(constraints.audio=constraintsToFF37_(constraints.audio)),constraints.video&&(constraints.video=constraintsToFF37_(constraints.video)),logging("ff37: "+JSON.stringify(constraints))),navigator.mozGetUserMedia(constraints,onSuccess,function(e){onError(shimError_(e))})},getUserMediaPromise_=function(constraints){return new Promise(function(resolve,reject){getUserMedia_(constraints,resolve,reject)})};if(navigator.mediaDevices||(navigator.mediaDevices={getUserMedia:getUserMediaPromise_,addEventListener:function(){},removeEventListener:function(){}}),navigator.mediaDevices.enumerateDevices=navigator.mediaDevices.enumerateDevices||function(){return new Promise(function(resolve){var infos=[{kind:"audioinput",deviceId:"default",label:"",groupId:""},{kind:"videoinput",deviceId:"default",label:"",groupId:""}];resolve(infos)})},browserDetails.version<41){var orgEnumerateDevices=navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);navigator.mediaDevices.enumerateDevices=function(){return orgEnumerateDevices().then(void 0,function(e){if("NotFoundError"===e.name)return[];throw e})}}if(browserDetails.version<49){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(c){return origGetUserMedia(c).then(function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach(function(track){track.stop()}),new DOMException("The object can not be found here.","NotFoundError");return stream},function(e){return Promise.reject(shimError_(e))})}}navigator.getUserMedia=function(constraints,onSuccess,onError){return browserDetails.version<44?getUserMedia_(constraints,onSuccess,onError):(console.warn("navigator.getUserMedia has been replaced by navigator.mediaDevices.getUserMedia"),void navigator.mediaDevices.getUserMedia(constraints).then(onSuccess,onError))}}},{"../utils":8}],7:[function(require,module,exports){"use strict";var safariShim={shimGetUserMedia:function(){navigator.getUserMedia=navigator.webkitGetUserMedia}};module.exports={shimGetUserMedia:safariShim.shimGetUserMedia}},{}],8:[function(require,module,exports){"use strict";var logDisabled_=!0,utils={disableLog:function(bool){return"boolean"!=typeof bool?new Error("Argument type: "+typeof bool+". Please use a boolean."):(logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled")},log:function(){if("object"==typeof window){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},extractVersion:function(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)},detectBrowser:function(){var result={};if(result.browser=null,result.version=null,"undefined"==typeof window||!window.navigator)return result.browser="Not a browser.",result;if(navigator.mozGetUserMedia)result.browser="firefox",result.version=this.extractVersion(navigator.userAgent,/Firefox\/([0-9]+)\./,1);else if(navigator.webkitGetUserMedia)if(window.webkitRTCPeerConnection)result.browser="chrome",result.version=this.extractVersion(navigator.userAgent,/Chrom(e|ium)\/([0-9]+)\./,2);else{if(!navigator.userAgent.match(/Version\/(\d+).(\d+)/))return result.browser="Unsupported webkit-based browser with GUM support but no WebRTC support.",result;result.browser="safari",result.version=this.extractVersion(navigator.userAgent,/AppleWebKit\/([0-9]+)\./,1)}else{if(!navigator.mediaDevices||!navigator.userAgent.match(/Edge\/(\d+).(\d+)$/))return result.browser="Not a supported browser.",result;result.browser="edge",result.version=this.extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2)}return result}};module.exports={log:utils.log,disableLog:utils.disableLog,browserDetails:utils.detectBrowser(),extractVersion:utils.extractVersion}},{}]},{},[2]);
let NodeCloseEvent = class CloseEvent {
constructor (options = {}) {
this.wasClean = options.wasClean
this.code = options.code
this.reason = options.reason
}
}
/**
* Utility class contains some helper static methods.
*/
class Util {
/**
* Create `CloseEvent`.
*
* @param {number} code
* @param {string} [reason=]
* @param {boolean} [wasClean=true]
*
* @returns {CloseEvent|NodeCloseEvent}
*/
static createCloseEvent (code, reason = '', wasClean = true) {
let obj = {wasClean, code, reason}
if (Util.isBrowser()) {
return new CloseEvent('netfluxClose', obj)
} else {
return new NodeCloseEvent(obj)
}
}
/**
* Check execution environment.
*
* @returns {boolean} Description
*/
static isBrowser () {
if (typeof window === 'undefined' || (typeof process !== 'undefined' && process.title === 'node')) {
return false
}
return true
}
/**
* Check whether the channel is a socket.
*
* @param {WebSocket|RTCDataChannel} channel
*
* @returns {boolean}
*/
static isSocket (channel) {
return channel.constructor.name === 'WebSocket'
}
/**
* Check whether the string is a valid URL.
*
* @param {string} str
*
* @returns {type} Description
*/
static isURL (str) {
let regex =
'^' +
// protocol identifier
'(?:(?:wss|ws)://)' +
// user:pass authentication
'(?:\\S+(?::\\S*)?@)?' +
'(?:'
let tld = '(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))?'
regex +=
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
'(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])' +
'(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' +
'(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))' +
'|' +
// host name
'(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' +
// domain name
'(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +
tld +
')' +
// port number
'(?::\\d{2,5})?' +
// resource path
'(?:[/?#]\\S*)?' +
'$'
if (!(new RegExp(regex, 'i')).exec(str)) return false
return true
}
}
const CONNECT_TIMEOUT = 30000
const REMOVE_ITEM_TIMEOUT = 5000
let src
/**
* @ignore
* @type {boolean}
*/
let webRTCAvailable = true
if (Util.isBrowser()) {
src = window
} else {
try {
src = require('wrtc')
} catch (err) {
src = {}
webRTCAvailable = false
}
}
const RTCPeerConnection$1 = src.RTCPeerConnection
const RTCIceCandidate$1 = src.RTCIceCandidate
/**
* Service class responsible to establish connections between peers via
* `RTCDataChannel`.
*
*/
class WebRTCService extends Service {
/**
* @param {number} id Service identifier
* @param {RTCIceServer} iceServers WebRTC configuration object
*/
constructor (id, iceServers) {
super(id)
/**
* @private
* @type {RTCIceServer}
*/
this.iceServers = iceServers
}
/**
* @param {Channel} channel
* @param {number} senderId
* @param {number} recepientId
* @param {Object} msg
*/
onMessage (channel, senderId, recepientId, msg) {
let wc = channel.webChannel
let item = super.getItem(wc, senderId)
if (!item) {
item = new CandidatesBuffer()
super.setItem(wc, senderId, item)
}
if ('offer' in msg) {
item.pc = this.createPeerConnection(candidate => {
wc.sendInnerTo(senderId, this.id, {candidate})
})
this.listenOnDataChannel(item.pc, dataCh => {
setTimeout(() => super.removeItem(wc, senderId), REMOVE_ITEM_TIMEOUT)
ServiceFactory.get(CHANNEL_BUILDER).onChannel(wc, dataCh, senderId)
})
this.createAnswer(item.pc, msg.offer, item.candidates)
.then(answer => wc.sendInnerTo(senderId, this.id, {answer}))
.catch(err => console.error(`During Establishing dataChannel connection over webChannel: ${err.message}`))
} if ('answer' in msg) {
item.pc.setRemoteDescription(msg.answer)
.then(() => item.pc.addReceivedCandidates(item.candidates))
.catch(err => console.error(`Set answer (webChannel): ${err.message}`))
} else if ('candidate' in msg) {
this.addIceCandidate(item, msg.candidate)
}
}
/**
* Establishes an `RTCDataChannel` with a peer identified by `id` trough `WebChannel`.
*
* @param {WebChannel} wc
* @param {number} id
*
* @returns {Promise<RTCDataChannel, string>}
*/
connectOverWebChannel (wc, id) {
let item = new CandidatesBuffer(this.createPeerConnection(candidate => {
wc.sendInnerTo(id, this.id, {candidate})
}))
super.setItem(wc, id, item)
return new Promise((resolve, reject) => {
setTimeout(reject, CONNECT_TIMEOUT, 'WebRTC connect timeout')
this.createDataChannel(item.pc, dataCh => {
setTimeout(() => super.removeItem(wc, id), REMOVE_ITEM_TIMEOUT)
resolve(dataCh)
})
this.createOffer(item.pc)
.then(offer => wc.sendInnerTo(id, this.id, {offer}))
.catch(reject)
})
}
/**
*
* @param {WebSocket} ws
* @param {function(channel: RTCDataChannel)} onChannel
*
*/
listenFromSignaling (ws, onChannel) {
ws.onmessage = evt => {
let msg = JSON.parse(evt.data)
if ('id' in msg && 'data' in msg) {
let item = super.getItem(ws, msg.id)
if (!item) {
item = new CandidatesBuffer(this.createPeerConnection(candidate => {
if (ws.readyState === 1) ws.send(JSON.stringify({id: msg.id, data: {candidate}}))
}))
super.setItem(ws, msg.id, item)
}
if ('offer' in msg.data) {
this.listenOnDataChannel(item.pc, dataCh => {
setTimeout(() => super.removeItem(ws, msg.id), REMOVE_ITEM_TIMEOUT)
onChannel(dataCh)
})
this.createAnswer(item.pc, msg.data.offer, item.candidates)
.then(answer => {
ws.send(JSON.stringify({id: msg.id, data: {answer}}))
})
.catch(err => {
console.error(`During establishing data channel connection through signaling: ${err.message}`)
})
} else if ('candidate' in msg.data) {
this.addIceCandidate(item, msg.data.candidate)
}
}
}
}
/**
*
* @param {type} ws
* @param {type} key Description
*
* @returns {type} Description
*/
connectOverSignaling (ws, key) {
let item = new CandidatesBuffer(this.createPeerConnection(candidate => {
if (ws.readyState === 1) ws.send(JSON.stringify({data: {candidate}}))
}))
super.setItem(ws, key, item)
return new Promise((resolve, reject) => {
ws.onclose = closeEvt => reject(closeEvt.reason)
ws.onmessage = evt => {
try {
let msg = JSON.parse(evt.data)
if ('data' in msg) {
if ('answer' in msg.data) {
item.pc.setRemoteDescription(msg.data.answer)
.then(() => item.pc.addReceivedCandidates(item.candidates))
.catch(err => reject(`Set answer (signaling): ${err.message}`))
} else if ('candidate' in msg.data) {
this.addIceCandidate(super.getItem(ws, key), msg.data.candidate)
}
}
} catch (err) {
reject(`Unknown message from the server ${ws.url}: ${evt.data}`)
}
}
this.createDataChannel(item.pc, dataCh => {
setTimeout(() => super.removeItem(ws, key), REMOVE_ITEM_TIMEOUT)
resolve(dataCh)
})
this.createOffer(item.pc)
.then(offer => ws.send(JSON.stringify({data: {offer}})))
.catch(reject)
})
}
/**
* Creates an SDP offer.
*
* @private
* @param {RTCPeerConnection} pc
* @return {Promise<RTCSessionDescription, string>} - Resolved when the offer has been succesfully created,
* set as local description and sent to the peer.
*/
createOffer (pc) {
return pc.createOffer()
.then(offer => pc.setLocalDescription(offer))
.then(() => {
return {
type: pc.localDescription.type,
sdp: pc.localDescription.sdp
}
})
}
/**
* Creates an SDP answer.
*
* @private
* @param {RTCPeerConnection} pc
* @param {string} offer
* @param {Array[string]} candidates
* @return {Promise<RTCSessionDescription, string>} - Resolved when the offer has been succesfully created,
* set as local description and sent to the peer.
*/
createAnswer (pc, offer, candidates) {
return pc.setRemoteDescription(offer)
.then(() => {
pc.addReceivedCandidates(candidates)
return pc.createAnswer()
})
.then(answer => pc.setLocalDescription(answer))
.then(() => {
return {
type: pc.localDescription.type,
sdp: pc.localDescription.sdp
}
})
}
/**
* Creates an instance of `RTCPeerConnection` and sets `onicecandidate` event handler.
*
* @private
* @param {function(candidate: Object)} onCandidate
* candidate event handler.
* @return {RTCPeerConnection}
*/
createPeerConnection (onCandidate) {
let pc = new RTCPeerConnection$1({iceServers: this.iceServers})
pc.isRemoteDescriptionSet = false
pc.addReceivedCandidates = candidates => {
pc.isRemoteDescriptionSet = true
for (let c of candidates) this.addIceCandidate({pc}, c)
}
pc.onicecandidate = evt => {
if (evt.candidate !== null) {
let candidate = {
candidate: evt.candidate.candidate,
sdpMid: evt.candidate.sdpMid,
sdpMLineIndex: evt.candidate.sdpMLineIndex
}
onCandidate(candidate)
}
}
return pc
}
/**
*
* @private
* @param {RTCPeerConnection} pc
* @param {function(dc: RTCDataChannel)} onOpen
*
*/
createDataChannel (pc, onOpen) {
let dc = pc.createDataChannel(null)
dc.onopen = evt => onOpen(dc)
this.setUpOnDisconnect(pc, dc)
}
/**
*
* @private
* @param {RTCPeerConnection} pc
* @param {function(dc: RTCDataChannel)} onOpen
*
*/
listenOnDataChannel (pc, onOpen) {
pc.ondatachannel = dcEvt => {
this.setUpOnDisconnect(pc, dcEvt.channel)
dcEvt.channel.onopen = evt => onOpen(dcEvt.channel)
}
}
/**
* @private
* @param {RTCPeerConnection} pc
* @param {RTCDataChannel} dataCh
*
* @returns {type} Description
*/
setUpOnDisconnect (pc, dataCh) {
pc.oniceconnectionstatechange = () => {
if (pc.iceConnectionState === 'disconnected') {
if (dataCh.onclose) dataCh.onclose(Util.createCloseEvent(4201, 'disconnected', false))
}
}
}
/**
* @private
* @param {CandidatesBuffer|null} obj
* @param {string} candidate
*
* @returns {type} Description
*/
addIceCandidate (obj, candidate) {
if (obj !== null && obj.pc && obj.pc.isRemoteDescriptionSet) {
obj.pc.addIceCandidate(new RTCIceCandidate$1(candidate))
.catch(evt => console.error(`Add ICE candidate: ${evt.message}`))
} else obj.candidates[obj.candidates.length] = candidate
}
}
/**
* @private
*/
class CandidatesBuffer {
constructor (pc = null, candidates = []) {
this.pc = pc
this.candidates = candidates
}
}
const WebSocket = Util.isBrowser() ? window.WebSocket : require('ws')
const CONNECT_TIMEOUT$1 = 10000
/**
* One of the web socket state constant.
* @ignore
* @type {number}
*/
const OPEN = WebSocket.OPEN
/**
* Service class responsible to establish connections between peers via
* `WebSocket`.
*/
class WebSocketService extends Service {
/**
* Creates WebSocket with server.
*
* @param {string} url - Server url
* @returns {Promise<WebSocket, string>} It is resolved once the WebSocket has been created and rejected otherwise
*/
connect (url) {
return new Promise((resolve, reject) => {
try {
let ws = new WebSocket(url)
ws.onopen = () => resolve(ws)
// Timeout for node (otherwise it will loop forever if incorrect address)
setTimeout(() => {
if (ws.readyState !== OPEN) {
reject(`WebSocket connection timeout with ${url}`)
}
}, CONNECT_TIMEOUT$1)
} catch (err) { reject(err.message) }
})
}
}
/**
* It is responsible to build a channel between two peers with a help of `WebSocketService` and `WebRTCService`.
* Its algorithm determine which channel (socket or dataChannel) should be created
* based on the services availability and peers' preferences.
*/
class ChannelBuilderService extends Service {
/**
* @param {number} id Service identifier
*/
constructor (id) {
super(id)
/**
* @private
*/
this.WS = [WEB_SOCKET]
/**
* @private
*/
this.WR = [WEB_RTC]
/**
* @private
*/
this.WS_WR = [WEB_SOCKET, WEB_RTC]
/**
* @private
*/
this.WR_WS = [WEB_RTC, WEB_SOCKET]
}
/**
* Establish a channel with the peer identified by `id`.
*
* @param {WebChannel} wc
* @param {number} id
*
* @returns {Promise<Channel, string>}
*/
connectTo (wc, id) {
return new Promise((resolve, reject) => {
super.setPendingRequest(wc, id, {resolve, reject})
wc.sendInnerTo(id, this.id, this.availableConnectors(wc))
})
}
/**
* @param {WebChannel} wc
*
* @returns {{listenOn: string, connectors: number[]}}
*/
availableConnectors (wc) {
let res = {}
let connectors = []
if (webRTCAvailable) connectors[connectors.length] = WEB_RTC
if (wc.settings.listenOn !== '') {
connectors[connectors.length] = WEB_SOCKET
res.listenOn = wc.settings.listenOn
}
if (connectors.length === 2 && connectors[0] !== wc.settings.connector) {
connectors.reverse()
}
res.connectors = connectors
return res
}
/**
* @param {WebChannel} wc
* @param {WebSocket|RTCDataChannel} channel
* @param {number} senderId
*/
onChannel (wc, channel, senderId) {
wc.initChannel(channel, senderId)
.then(channel => {
let pendReq = super.getPendingRequest(wc, senderId)
if (pendReq !== null) pendReq.resolve(channel)
})
}
/**
* @param {Channel} channel
* @param {number} senderId
* @param {number} recepientId
* @param {Object} msg
*/
onMessage (channel, senderId, recepientId, msg) {
let wc = channel.webChannel
let myConnectObj = this.availableConnectors(wc)
let myConnectors = myConnectObj.connectors
if ('failedReason' in msg) {
super.getPendingRequest(wc, senderId).reject(msg.failedReason)