forked from simplewebrtc/SimpleWebRTC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplewebrtc.bundle.js
16724 lines (14645 loc) · 471 KB
/
simplewebrtc.bundle.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
(function(e){if("function"==typeof bootstrap)bootstrap("simplewebrtc",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeSimpleWebRTC=e}else"undefined"!=typeof window?window.SimpleWebRTC=e():global.SimpleWebRTC=e()})(function(){var define,ses,bootstrap,module,exports;
return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
var WebRTC = require('./webrtc');
var WildEmitter = require('wildemitter');
var webrtcSupport = require('webrtcsupport');
var attachMediaStream = require('attachmediastream');
var mockconsole = require('mockconsole');
var SocketIoConnection = require('./socketioconnection');
function SimpleWebRTC(opts) {
var self = this;
var options = opts || {};
var config = this.config = {
url: 'https://sandbox.simplewebrtc.com:443/',
socketio: {/* 'force new connection':true*/},
connection: null,
debug: false,
localVideoEl: '',
remoteVideosEl: '',
enableDataChannels: true,
autoRequestMedia: false,
autoRemoveVideos: true,
adjustPeerVolume: false,
peerVolumeWhenSpeaking: 0.25,
media: {
video: true,
audio: true
},
receiveMedia: {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
},
localVideo: {
autoplay: true,
mirror: true,
muted: true
}
};
var item, connection;
// We also allow a 'logger' option. It can be any object that implements
// log, warn, and error methods.
// We log nothing by default, following "the rule of silence":
// http://www.linfo.org/rule_of_silence.html
this.logger = function () {
// we assume that if you're in debug mode and you didn't
// pass in a logger, you actually want to log as much as
// possible.
if (opts.debug) {
return opts.logger || console;
} else {
// or we'll use your logger which should have its own logic
// for output. Or we'll return the no-op.
return opts.logger || mockconsole;
}
}();
// set our config from options
for (item in options) {
this.config[item] = options[item];
}
// attach detected support for convenience
this.capabilities = webrtcSupport;
// call WildEmitter constructor
WildEmitter.call(this);
// create default SocketIoConnection if it's not passed in
if (this.config.connection === null) {
connection = this.connection = new SocketIoConnection(this.config);
} else {
connection = this.connection = this.config.connection;
}
connection.on('connect', function () {
self.emit('connectionReady', connection.getSessionid());
self.sessionReady = true;
self.testReadiness();
});
connection.on('message', function (message) {
var peers = self.webrtc.getPeers(message.from, message.roomType);
var peer;
if (message.type === 'offer') {
if (peers.length) {
peers.forEach(function (p) {
if (p.sid == message.sid) peer = p;
});
//if (!peer) peer = peers[0]; // fallback for old protocol versions
}
if (!peer) {
peer = self.webrtc.createPeer({
id: message.from,
sid: message.sid,
type: message.roomType,
enableDataChannels: self.config.enableDataChannels && message.roomType !== 'screen',
sharemyscreen: message.roomType === 'screen' && !message.broadcaster,
broadcaster: message.roomType === 'screen' && !message.broadcaster ? self.connection.getSessionid() : null
});
self.emit('createdPeer', peer);
}
peer.handleMessage(message);
} else if (peers.length) {
peers.forEach(function (peer) {
if (message.sid) {
if (peer.sid === message.sid) {
peer.handleMessage(message);
}
} else {
peer.handleMessage(message);
}
});
}
});
connection.on('remove', function (room) {
if (room.id !== self.connection.getSessionid()) {
self.webrtc.removePeers(room.id, room.type);
}
});
// instantiate our main WebRTC helper
// using same logger from logic here
opts.logger = this.logger;
opts.debug = false;
this.webrtc = new WebRTC(opts);
// attach a few methods from underlying lib to simple.
['mute', 'unmute', 'pauseVideo', 'resumeVideo', 'pause', 'resume', 'sendToAll', 'sendDirectlyToAll', 'getPeers'].forEach(function (method) {
self[method] = self.webrtc[method].bind(self.webrtc);
});
// proxy events from WebRTC
this.webrtc.on('*', function () {
self.emit.apply(self, arguments);
});
// log all events in debug mode
if (config.debug) {
this.on('*', this.logger.log.bind(this.logger, 'SimpleWebRTC event:'));
}
// check for readiness
this.webrtc.on('localStream', function () {
self.testReadiness();
});
this.webrtc.on('message', function (payload) {
self.connection.emit('message', payload);
});
this.webrtc.on('peerStreamAdded', this.handlePeerStreamAdded.bind(this));
this.webrtc.on('peerStreamRemoved', this.handlePeerStreamRemoved.bind(this));
// echo cancellation attempts
if (this.config.adjustPeerVolume) {
this.webrtc.on('speaking', this.setVolumeForAll.bind(this, this.config.peerVolumeWhenSpeaking));
this.webrtc.on('stoppedSpeaking', this.setVolumeForAll.bind(this, 1));
}
connection.on('stunservers', function (args) {
// resets/overrides the config
self.webrtc.config.peerConnectionConfig.iceServers = args;
self.emit('stunservers', args);
});
connection.on('turnservers', function (args) {
// appends to the config
self.webrtc.config.peerConnectionConfig.iceServers = self.webrtc.config.peerConnectionConfig.iceServers.concat(args);
self.emit('turnservers', args);
});
this.webrtc.on('iceFailed', function (peer) {
// local ice failure
});
this.webrtc.on('connectivityError', function (peer) {
// remote ice failure
});
// sending mute/unmute to all peers
this.webrtc.on('audioOn', function () {
self.webrtc.sendToAll('unmute', {name: 'audio'});
});
this.webrtc.on('audioOff', function () {
self.webrtc.sendToAll('mute', {name: 'audio'});
});
this.webrtc.on('videoOn', function () {
self.webrtc.sendToAll('unmute', {name: 'video'});
});
this.webrtc.on('videoOff', function () {
self.webrtc.sendToAll('mute', {name: 'video'});
});
// screensharing events
this.webrtc.on('localScreen', function (stream) {
var item,
el = document.createElement('video'),
container = self.getRemoteVideoContainer();
el.oncontextmenu = function () { return false; };
el.id = 'localScreen';
attachMediaStream(stream, el);
if (container) {
container.appendChild(el);
}
self.emit('localScreenAdded', el);
self.connection.emit('shareScreen');
self.webrtc.peers.forEach(function (existingPeer) {
var peer;
if (existingPeer.type === 'video') {
peer = self.webrtc.createPeer({
id: existingPeer.id,
type: 'screen',
sharemyscreen: true,
enableDataChannels: false,
receiveMedia: {
offerToReceiveAudio: 0,
offerToReceiveVideo: 0
},
broadcaster: self.connection.getSessionid(),
});
self.emit('createdPeer', peer);
peer.start();
}
});
});
this.webrtc.on('localScreenStopped', function (stream) {
self.stopScreenShare();
/*
self.connection.emit('unshareScreen');
self.webrtc.peers.forEach(function (peer) {
if (peer.sharemyscreen) {
peer.end();
}
});
*/
});
this.webrtc.on('channelMessage', function (peer, label, data) {
if (data.type == 'volume') {
self.emit('remoteVolumeChange', peer, data.volume);
}
});
if (this.config.autoRequestMedia) this.startLocalVideo();
}
SimpleWebRTC.prototype = Object.create(WildEmitter.prototype, {
constructor: {
value: SimpleWebRTC
}
});
SimpleWebRTC.prototype.leaveRoom = function () {
if (this.roomName) {
this.connection.emit('leave');
while (this.webrtc.peers.length) {
this.webrtc.peers.shift().end();
}
if (this.getLocalScreen()) {
this.stopScreenShare();
}
this.emit('leftRoom', this.roomName);
this.roomName = undefined;
}
};
SimpleWebRTC.prototype.disconnect = function () {
this.connection.disconnect();
delete this.connection;
};
SimpleWebRTC.prototype.handlePeerStreamAdded = function (peer) {
var self = this;
var container = this.getRemoteVideoContainer();
var video = attachMediaStream(peer.stream);
// store video element as part of peer for easy removal
peer.videoEl = video;
video.id = this.getDomId(peer);
if (container) container.appendChild(video);
this.emit('videoAdded', video, peer);
// send our mute status to new peer if we're muted
// currently called with a small delay because it arrives before
// the video element is created otherwise (which happens after
// the async setRemoteDescription-createAnswer)
window.setTimeout(function () {
if (!self.webrtc.isAudioEnabled()) {
peer.send('mute', {name: 'audio'});
}
if (!self.webrtc.isVideoEnabled()) {
peer.send('mute', {name: 'video'});
}
}, 250);
};
SimpleWebRTC.prototype.handlePeerStreamRemoved = function (peer) {
var container = this.getRemoteVideoContainer();
var videoEl = peer.videoEl;
if (this.config.autoRemoveVideos && container && videoEl) {
container.removeChild(videoEl);
}
if (videoEl) this.emit('videoRemoved', videoEl, peer);
};
SimpleWebRTC.prototype.getDomId = function (peer) {
return [peer.id, peer.type, peer.broadcaster ? 'broadcasting' : 'incoming'].join('_');
};
// set volume on video tag for all peers takse a value between 0 and 1
SimpleWebRTC.prototype.setVolumeForAll = function (volume) {
this.webrtc.peers.forEach(function (peer) {
if (peer.videoEl) peer.videoEl.volume = volume;
});
};
SimpleWebRTC.prototype.joinRoom = function (name, cb) {
var self = this;
this.roomName = name;
this.connection.emit('join', name, function (err, roomDescription) {
console.log('join CB', err, roomDescription);
if (err) {
self.emit('error', err);
} else {
var id,
client,
type,
peer;
for (id in roomDescription.clients) {
client = roomDescription.clients[id];
for (type in client) {
if (client[type]) {
peer = self.webrtc.createPeer({
id: id,
type: type,
enableDataChannels: self.config.enableDataChannels && type !== 'screen',
receiveMedia: {
offerToReceiveAudio: type !== 'screen' && self.config.receiveMedia.offerToReceiveAudio ? 1 : 0,
offerToReceiveVideo: self.config.receiveMedia.offerToReceiveVideo
}
});
self.emit('createdPeer', peer);
peer.start();
}
}
}
}
if (cb) cb(err, roomDescription);
self.emit('joinedRoom', name);
});
};
SimpleWebRTC.prototype.getEl = function (idOrEl) {
if (typeof idOrEl === 'string') {
return document.getElementById(idOrEl);
} else {
return idOrEl;
}
};
SimpleWebRTC.prototype.startLocalVideo = function () {
var self = this;
this.webrtc.startLocalMedia(this.config.media, function (err, stream) {
if (err) {
self.emit('localMediaError', err);
} else {
attachMediaStream(stream, self.getLocalVideoContainer(), self.config.localVideo);
}
});
};
SimpleWebRTC.prototype.stopLocalVideo = function () {
this.webrtc.stopLocalMedia();
};
// this accepts either element ID or element
// and either the video tag itself or a container
// that will be used to put the video tag into.
SimpleWebRTC.prototype.getLocalVideoContainer = function () {
var el = this.getEl(this.config.localVideoEl);
if (el && el.tagName === 'VIDEO') {
el.oncontextmenu = function () { return false; };
return el;
} else if (el) {
var video = document.createElement('video');
video.oncontextmenu = function () { return false; };
el.appendChild(video);
return video;
} else {
return;
}
};
SimpleWebRTC.prototype.getRemoteVideoContainer = function () {
return this.getEl(this.config.remoteVideosEl);
};
SimpleWebRTC.prototype.shareScreen = function (cb) {
this.webrtc.startScreenShare(cb);
};
SimpleWebRTC.prototype.getLocalScreen = function () {
return this.webrtc.localScreen;
};
SimpleWebRTC.prototype.stopScreenShare = function () {
this.connection.emit('unshareScreen');
var videoEl = document.getElementById('localScreen');
var container = this.getRemoteVideoContainer();
var stream = this.getLocalScreen();
if (this.config.autoRemoveVideos && container && videoEl) {
container.removeChild(videoEl);
}
// a hack to emit the event the removes the video
// element that we want
if (videoEl) this.emit('videoRemoved', videoEl);
if (stream) {
stream.getTracks().forEach(function (track) { track.stop(); });
}
this.webrtc.peers.forEach(function (peer) {
if (peer.broadcaster) {
peer.end();
}
});
//delete this.webrtc.localScreen;
};
SimpleWebRTC.prototype.testReadiness = function () {
var self = this;
if (this.sessionReady) {
if (!this.config.media.video && !this.config.media.audio) {
self.emit('readyToCall', self.connection.getSessionid());
} else if (this.webrtc.localStreams.length > 0) {
self.emit('readyToCall', self.connection.getSessionid());
}
}
};
SimpleWebRTC.prototype.createRoom = function (name, cb) {
this.roomName = name;
if (arguments.length === 2) {
this.connection.emit('create', name, cb);
} else {
this.connection.emit('create', name);
}
};
SimpleWebRTC.prototype.sendFile = function () {
if (!webrtcSupport.dataChannel) {
return this.emit('error', new Error('DataChannelNotSupported'));
}
};
module.exports = SimpleWebRTC;
},{"./socketioconnection":3,"./webrtc":2,"attachmediastream":6,"mockconsole":7,"webrtcsupport":4,"wildemitter":5}],4:[function(require,module,exports){
// created by @HenrikJoreteg
var prefix;
var version;
if (window.mozRTCPeerConnection || navigator.mozGetUserMedia) {
prefix = 'moz';
version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
} else if (window.webkitRTCPeerConnection || navigator.webkitGetUserMedia) {
prefix = 'webkit';
version = navigator.userAgent.match(/Chrom(e|ium)/) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
}
var PC = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var IceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
var MediaStream = window.webkitMediaStream || window.MediaStream;
var screenSharing = window.location.protocol === 'https:' &&
((prefix === 'webkit' && version >= 26) ||
(prefix === 'moz' && version >= 33))
var AudioContext = window.AudioContext || window.webkitAudioContext;
var videoEl = document.createElement('video');
var supportVp8 = videoEl && videoEl.canPlayType && videoEl.canPlayType('video/webm; codecs="vp8", vorbis') === "probably";
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia || navigator.mozGetUserMedia;
// export support flags and constructors.prototype && PC
module.exports = {
prefix: prefix,
browserVersion: version,
support: !!PC && !!getUserMedia,
// new support style
supportRTCPeerConnection: !!PC,
supportVp8: supportVp8,
supportGetUserMedia: !!getUserMedia,
supportDataChannel: !!(PC && PC.prototype && PC.prototype.createDataChannel),
supportWebAudio: !!(AudioContext && AudioContext.prototype.createMediaStreamSource),
supportMediaStream: !!(MediaStream && MediaStream.prototype.removeTrack),
supportScreenSharing: !!screenSharing,
// constructors
AudioContext: AudioContext,
PeerConnection: PC,
SessionDescription: SessionDescription,
IceCandidate: IceCandidate,
MediaStream: MediaStream,
getUserMedia: getUserMedia
};
},{}],5:[function(require,module,exports){
/*
WildEmitter.js is a slim little event emitter by @henrikjoreteg largely based
on @visionmedia's Emitter from UI Kit.
Why? I wanted it standalone.
I also wanted support for wildcard emitters like this:
emitter.on('*', function (eventName, other, event, payloads) {
});
emitter.on('somenamespace*', function (eventName, payloads) {
});
Please note that callbacks triggered by wildcard registered events also get
the event name as the first argument.
*/
module.exports = WildEmitter;
function WildEmitter() {
this.isWildEmitter = true;
this.callbacks = {};
}
// Listen on the given `event` with `fn`. Store a group name if present.
WildEmitter.prototype.on = function (event, groupName, fn) {
var hasGroup = (arguments.length === 3),
group = hasGroup ? arguments[1] : undefined,
func = hasGroup ? arguments[2] : arguments[1];
func._groupName = group;
(this.callbacks[event] = this.callbacks[event] || []).push(func);
return this;
};
// Adds an `event` listener that will be invoked a single
// time then automatically removed.
WildEmitter.prototype.once = function (event, groupName, fn) {
var self = this,
hasGroup = (arguments.length === 3),
group = hasGroup ? arguments[1] : undefined,
func = hasGroup ? arguments[2] : arguments[1];
function on() {
self.off(event, on);
func.apply(this, arguments);
}
this.on(event, group, on);
return this;
};
// Unbinds an entire group
WildEmitter.prototype.releaseGroup = function (groupName) {
var item, i, len, handlers;
for (item in this.callbacks) {
handlers = this.callbacks[item];
for (i = 0, len = handlers.length; i < len; i++) {
if (handlers[i]._groupName === groupName) {
//console.log('removing');
// remove it and shorten the array we're looping through
handlers.splice(i, 1);
i--;
len--;
}
}
}
return this;
};
// Remove the given callback for `event` or all
// registered callbacks.
WildEmitter.prototype.off = function (event, fn) {
var callbacks = this.callbacks[event],
i;
if (!callbacks) return this;
// remove all handlers
if (arguments.length === 1) {
delete this.callbacks[event];
return this;
}
// remove specific handler
i = callbacks.indexOf(fn);
callbacks.splice(i, 1);
if (callbacks.length === 0) {
delete this.callbacks[event];
}
return this;
};
/// Emit `event` with the given args.
// also calls any `*` handlers
WildEmitter.prototype.emit = function (event) {
var args = [].slice.call(arguments, 1),
callbacks = this.callbacks[event],
specialCallbacks = this.getWildcardCallbacks(event),
i,
len,
item,
listeners;
if (callbacks) {
listeners = callbacks.slice();
for (i = 0, len = listeners.length; i < len; ++i) {
if (listeners[i]) {
listeners[i].apply(this, args);
} else {
break;
}
}
}
if (specialCallbacks) {
len = specialCallbacks.length;
listeners = specialCallbacks.slice();
for (i = 0, len = listeners.length; i < len; ++i) {
if (listeners[i]) {
listeners[i].apply(this, [event].concat(args));
} else {
break;
}
}
}
return this;
};
// Helper for for finding special wildcard event handlers that match the event
WildEmitter.prototype.getWildcardCallbacks = function (eventName) {
var item,
split,
result = [];
for (item in this.callbacks) {
split = item.split('*');
if (item === '*' || (split.length === 2 && eventName.slice(0, split[0].length) === split[0])) {
result = result.concat(this.callbacks[item]);
}
}
return result;
};
},{}],7:[function(require,module,exports){
var methods = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(",");
var l = methods.length;
var fn = function () {};
var mockconsole = {};
while (l--) {
mockconsole[methods[l]] = fn;
}
module.exports = mockconsole;
},{}],2:[function(require,module,exports){
var util = require('util');
var webrtc = require('webrtcsupport');
var WildEmitter = require('wildemitter');
var mockconsole = require('mockconsole');
var localMedia = require('localmedia');
var Peer = require('./peer');
function WebRTC(opts) {
var self = this;
var options = opts || {};
var config = this.config = {
debug: false,
// makes the entire PC config overridable
peerConnectionConfig: {
iceServers: [{'urls': 'stun:stun.l.google.com:19302'}]
},
peerConnectionConstraints: {
optional: []
},
receiveMedia: {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
},
enableDataChannels: true
};
var item;
// expose screensharing check
this.screenSharingSupport = webrtc.screenSharing;
// We also allow a 'logger' option. It can be any object that implements
// log, warn, and error methods.
// We log nothing by default, following "the rule of silence":
// http://www.linfo.org/rule_of_silence.html
this.logger = function () {
// we assume that if you're in debug mode and you didn't
// pass in a logger, you actually want to log as much as
// possible.
if (opts.debug) {
return opts.logger || console;
} else {
// or we'll use your logger which should have its own logic
// for output. Or we'll return the no-op.
return opts.logger || mockconsole;
}
}();
// set options
for (item in options) {
this.config[item] = options[item];
}
// check for support
if (!webrtc.support) {
this.logger.error('Your browser doesn\'t seem to support WebRTC');
}
// where we'll store our peer connections
this.peers = [];
// call localMedia constructor
localMedia.call(this, this.config);
this.on('speaking', function () {
if (!self.hardMuted) {
// FIXME: should use sendDirectlyToAll, but currently has different semantics wrt payload
self.peers.forEach(function (peer) {
if (peer.enableDataChannels) {
var dc = peer.getDataChannel('hark');
if (dc.readyState != 'open') return;
dc.send(JSON.stringify({type: 'speaking'}));
}
});
}
});
this.on('stoppedSpeaking', function () {
if (!self.hardMuted) {
// FIXME: should use sendDirectlyToAll, but currently has different semantics wrt payload
self.peers.forEach(function (peer) {
if (peer.enableDataChannels) {
var dc = peer.getDataChannel('hark');
if (dc.readyState != 'open') return;
dc.send(JSON.stringify({type: 'stoppedSpeaking'}));
}
});
}
});
this.on('volumeChange', function (volume, treshold) {
if (!self.hardMuted) {
// FIXME: should use sendDirectlyToAll, but currently has different semantics wrt payload
self.peers.forEach(function (peer) {
if (peer.enableDataChannels) {
var dc = peer.getDataChannel('hark');
if (dc.readyState != 'open') return;
dc.send(JSON.stringify({type: 'volume', volume: volume }));
}
});
}
});
// log events in debug mode
if (this.config.debug) {
this.on('*', function (event, val1, val2) {
var logger;
// if you didn't pass in a logger and you explicitly turning on debug
// we're just going to assume you're wanting log output with console
if (self.config.logger === mockconsole) {
logger = console;
} else {
logger = self.logger;
}
logger.log('event:', event, val1, val2);
});
}
}
util.inherits(WebRTC, localMedia);
WebRTC.prototype.createPeer = function (opts) {
var peer;
opts.parent = this;
peer = new Peer(opts);
this.peers.push(peer);
return peer;
};
// removes peers
WebRTC.prototype.removePeers = function (id, type) {
this.getPeers(id, type).forEach(function (peer) {
peer.end();
});
};
// fetches all Peer objects by session id and/or type
WebRTC.prototype.getPeers = function (sessionId, type) {
return this.peers.filter(function (peer) {
return (!sessionId || peer.id === sessionId) && (!type || peer.type === type);
});
};
// sends message to all
WebRTC.prototype.sendToAll = function (message, payload) {
this.peers.forEach(function (peer) {
peer.send(message, payload);
});
};
// sends message to all using a datachannel
// only sends to anyone who has an open datachannel
WebRTC.prototype.sendDirectlyToAll = function (channel, message, payload) {
this.peers.forEach(function (peer) {
if (peer.enableDataChannels) {
peer.sendDirectly(channel, message, payload);
}
});
};
module.exports = WebRTC;
},{"./peer":9,"localmedia":10,"mockconsole":7,"util":8,"webrtcsupport":4,"wildemitter":5}],3:[function(require,module,exports){
var io = require('socket.io-client');
function SocketIoConnection(config) {
this.connection = io.connect(config.url, config.socketio);
}
SocketIoConnection.prototype.on = function (ev, fn) {
this.connection.on(ev, fn);
};
SocketIoConnection.prototype.emit = function () {
this.connection.emit.apply(this.connection, arguments);
};
SocketIoConnection.prototype.getSessionid = function () {
return this.connection.id;
};
SocketIoConnection.prototype.disconnect = function () {
return this.connection.disconnect();
};
module.exports = SocketIoConnection;
},{"socket.io-client":11}],8:[function(require,module,exports){
var events = require('events');
exports.isArray = isArray;
exports.isDate = function(obj){return Object.prototype.toString.call(obj) === '[object Date]'};
exports.isRegExp = function(obj){return Object.prototype.toString.call(obj) === '[object RegExp]'};
exports.print = function () {};
exports.puts = function () {};
exports.debug = function() {};
exports.inspect = function(obj, showHidden, depth, colors) {
var seen = [];
var stylize = function(str, styleType) {
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
var styles =
{ 'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39] };
var style =
{ 'special': 'cyan',
'number': 'blue',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red' }[styleType];
if (style) {
return '\u001b[' + styles[style][0] + 'm' + str +
'\u001b[' + styles[style][1] + 'm';
} else {
return str;
}
};
if (! colors) {
stylize = function(str, styleType) { return str; };
}
function format(value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (value && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special
value !== exports &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
return value.inspect(recurseTimes);
}
// Primitive types cannot have properties
switch (typeof value) {
case 'undefined':
return stylize('undefined', 'undefined');
case 'string':
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return stylize(simple, 'string');
case 'number':
return stylize('' + value, 'number');
case 'boolean':
return stylize('' + value, 'boolean');
}
// For some reason typeof null is "object", so special case here.
if (value === null) {
return stylize('null', 'null');
}
// Look up the keys of the object.
var visible_keys = Object_keys(value);
var keys = showHidden ? Object_getOwnPropertyNames(value) : visible_keys;
// Functions without properties can be shortcutted.
if (typeof value === 'function' && keys.length === 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
var name = value.name ? ': ' + value.name : '';
return stylize('[Function' + name + ']', 'special');
}
}
// Dates without properties can be shortcutted
if (isDate(value) && keys.length === 0) {
return stylize(value.toUTCString(), 'date');
}
var base, type, braces;
// Determine the object type
if (isArray(value)) {
type = 'Array';
braces = ['[', ']'];
} else {
type = 'Object';
braces = ['{', '}'];
}
// Make functions say that they are functions
if (typeof value === 'function') {
var n = value.name ? ': ' + value.name : '';
base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';
} else {
base = '';
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + value.toUTCString();
}
if (keys.length === 0) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
return stylize('[Object]', 'special');
}
}
seen.push(value);