forked from jitsi/jitsi-meet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
1644 lines (1442 loc) · 52.2 KB
/
app.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
/* jshint -W117 */
/* application specific logic */
var connection = null;
var authenticatedUser = false;
var focus = null;
var activecall = null;
var RTC = null;
var nickname = null;
var sharedKey = '';
var recordingToken ='';
var roomUrl = null;
var roomName = null;
var ssrc2jid = {};
var mediaStreams = [];
var bridgeIsDown = false;
/**
* The stats collector that process stats data and triggers updates to app.js.
* @type {StatsCollector}
*/
var statsCollector = null;
/**
* The stats collector for the local stream.
* @type {LocalStatsCollector}
*/
var localStatsCollector = null;
/**
* Indicates whether ssrc is camera video or desktop stream.
* FIXME: remove those maps
*/
var ssrc2videoType = {};
var videoSrcToSsrc = {};
/**
* Currently focused video "src"(displayed in large video).
* @type {String}
*/
var focusedVideoSrc = null;
var mutedAudios = {};
var localVideoSrc = null;
var flipXLocalVideo = true;
var isFullScreen = false;
var currentVideoWidth = null;
var currentVideoHeight = null;
/**
* Method used to calculate large video size.
* @type {function ()}
*/
var getVideoSize;
/**
* Method used to get large video position.
* @type {function ()}
*/
var getVideoPosition;
/* window.onbeforeunload = closePageWarning; */
var sessionTerminated = false;
function init() {
Toolbar.setupButtonsFromConfig();
RTC = setupRTC();
if (RTC === null) {
window.location.href = 'webrtcrequired.html';
return;
} else if (RTC.browser !== 'chrome') {
window.location.href = 'chromeonly.html';
return;
}
obtainAudioAndVideoPermissions(function (stream) {
var audioStream = new webkitMediaStream();
var videoStream = new webkitMediaStream();
var audioTracks = stream.getAudioTracks();
var videoTracks = stream.getVideoTracks();
for (var i = 0; i < audioTracks.length; i++) {
audioStream.addTrack(audioTracks[i]);
}
VideoLayout.changeLocalAudio(audioStream);
startLocalRtpStatsCollector(audioStream);
for (i = 0; i < videoTracks.length; i++) {
videoStream.addTrack(videoTracks[i]);
}
VideoLayout.changeLocalVideo(videoStream, true);
maybeDoJoin();
});
var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
connect(jid);
}
function connect(jid, password) {
var localAudio, localVideo;
if (connection && connection.jingle) {
localAudio = connection.jingle.localAudio;
localVideo = connection.jingle.localVideo;
}
connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
if (nickname) {
connection.emuc.addDisplayNameToPresence(nickname);
}
if (connection.disco) {
// for chrome, add multistream cap
}
connection.jingle.pc_constraints = RTC.pc_constraints;
if (config.useIPv6) {
// https://code.google.com/p/webrtc/issues/detail?id=2828
if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
connection.jingle.pc_constraints.optional.push({googIPv6: true});
}
if (localAudio) connection.jingle.localAudio = localAudio;
if (localVideo) connection.jingle.localVideo = localVideo;
if(!password)
password = document.getElementById('password').value;
var anonymousConnectionFailed = false;
connection.connect(jid, password, function (status, msg) {
console.log('Strophe status changed to', Strophe.getStatusString(status));
if (status === Strophe.Status.CONNECTED) {
if (config.useStunTurn) {
connection.jingle.getStunAndTurnCredentials();
}
document.getElementById('connect').disabled = true;
if(password)
authenticatedUser = true;
maybeDoJoin();
} else if (status === Strophe.Status.CONNFAIL) {
if(msg === 'x-strophe-bad-non-anon-jid') {
anonymousConnectionFailed = true;
}
} else if (status === Strophe.Status.DISCONNECTED) {
if(anonymousConnectionFailed) {
// prompt user for username and password
$(document).trigger('passwordrequired.main');
}
} else if (status === Strophe.Status.AUTHFAIL) {
// wrong password or username, prompt user
$(document).trigger('passwordrequired.main');
}
});
}
/**
* We ask for audio and video combined stream in order to get permissions and
* not to ask twice.
*/
function obtainAudioAndVideoPermissions(callback) {
// Get AV
getUserMediaWithConstraints(
['audio', 'video'],
function (avStream) {
callback(avStream);
trackUsage('localMedia', {
audio: avStream.getAudioTracks().length,
video: avStream.getVideoTracks().length
});
},
function (error) {
console.error('failed to obtain audio/video stream - stop', error);
trackUsage('localMediaError', {
media: error.media || 'video',
name : error.name
});
messageHandler.showError("Error",
"Failed to obtain permissions to use the local microphone" +
"and/or camera.");
},
config.resolution || '360');
}
function maybeDoJoin() {
if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
&& (connection.jingle.localAudio || connection.jingle.localVideo)) {
doJoin();
}
}
function doJoin() {
var roomnode = null;
var path = window.location.pathname;
var roomjid;
// determinde the room node from the url
// TODO: just the roomnode or the whole bare jid?
if (config.getroomnode && typeof config.getroomnode === 'function') {
// custom function might be responsible for doing the pushstate
roomnode = config.getroomnode(path);
} else {
/* fall back to default strategy
* this is making assumptions about how the URL->room mapping happens.
* It currently assumes deployment at root, with a rewrite like the
* following one (for nginx):
location ~ ^/([a-zA-Z0-9]+)$ {
rewrite ^/(.*)$ / break;
}
*/
if (path.length > 1) {
roomnode = path.substr(1).toLowerCase();
} else {
var word = RoomNameGenerator.generateRoomWithoutSeparator();
roomnode = word.toLowerCase();
window.history.pushState('VideoChat',
'Room: ' + word, window.location.pathname + word);
}
}
roomName = roomnode + '@' + config.hosts.muc;
roomjid = roomName;
if (config.useNicks) {
var nick = window.prompt('Your nickname (optional)');
if (nick) {
roomjid += '/' + nick;
} else {
roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
}
} else {
var tmpJid = Strophe.getNodeFromJid(connection.jid);
if(!authenticatedUser)
tmpJid = tmpJid.substr(0, 8);
roomjid += '/' + tmpJid;
}
connection.emuc.doJoin(roomjid);
}
function waitForRemoteVideo(selector, ssrc, stream) {
if (selector.removed || !selector.parent().is(":visible")) {
console.warn("Media removed before had started", selector);
return;
}
if (stream.id === 'mixedmslabel') return;
if (selector[0].currentTime > 0) {
var videoStream = simulcast.getReceivingVideoStream(stream);
RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
// FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
// in order to get rid of too many maps
if (ssrc && selector.attr('src')) {
videoSrcToSsrc[selector.attr('src')] = ssrc;
} else {
console.warn("No ssrc given for video", selector);
messageHandler.showError('Warning', 'No ssrc was given for the video.');
}
$(document).trigger('videoactive.jingle', [selector]);
} else {
setTimeout(function () {
waitForRemoteVideo(selector, ssrc, stream);
}, 250);
}
}
$(document).bind('remotestreamadded.jingle', function (event, data, sid) {
waitForPresence(data, sid);
});
function waitForPresence(data, sid) {
var sess = connection.jingle.sessions[sid];
var thessrc;
// look up an associated JID for a stream id
if (data.stream.id.indexOf('mixedmslabel') === -1) {
// look only at a=ssrc: and _not_ at a=ssrc-group: lines
var ssrclines
= SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');
ssrclines = ssrclines.filter(function (line) {
// NOTE(gp) previously we filtered on the mslabel, but that property
// is not always present.
// return line.indexOf('mslabel:' + data.stream.label) !== -1;
return line.indexOf('msid:' + data.stream.id) !== -1;
});
if (ssrclines.length) {
thessrc = ssrclines[0].substring(7).split(' ')[0];
// We signal our streams (through Jingle to the focus) before we set
// our presence (through which peers associate remote streams to
// jids). So, it might arrive that a remote stream is added but
// ssrc2jid is not yet updated and thus data.peerjid cannot be
// successfully set. Here we wait for up to a second for the
// presence to arrive.
if (!ssrc2jid[thessrc]) {
// TODO(gp) limit wait duration to 1 sec.
setTimeout(function(d, s) {
return function() {
waitForPresence(d, s);
}
}(data, sid), 250);
return;
}
// ok to overwrite the one from focus? might save work in colibri.js
console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
if (ssrc2jid[thessrc]) {
data.peerjid = ssrc2jid[thessrc];
}
}
}
// NOTE(gp) now that we have simulcast, a media stream can have more than 1
// ssrc. We should probably take that into account in our MediaStream
// wrapper.
mediaStreams.push(new MediaStream(data, sid, thessrc));
var container;
var remotes = document.getElementById('remoteVideos');
if (data.peerjid) {
VideoLayout.ensurePeerContainerExists(data.peerjid);
container = document.getElementById(
'participant_' + Strophe.getResourceFromJid(data.peerjid));
} else {
if (data.stream.id !== 'mixedmslabel') {
console.error('can not associate stream',
data.stream.id,
'with a participant');
// We don't want to add it here since it will cause troubles
return;
}
// FIXME: for the mixed ms we dont need a video -- currently
container = document.createElement('span');
container.id = 'mixedstream';
container.className = 'videocontainer';
remotes.appendChild(container);
Util.playSoundNotification('userJoined');
}
var isVideo = data.stream.getVideoTracks().length > 0;
if (container) {
VideoLayout.addRemoteStreamElement( container,
sid,
data.stream,
data.peerjid,
thessrc);
}
// an attempt to work around https://github.com/jitsi/jitmeet/issues/32
if (isVideo &&
data.peerjid && sess.peerjid === data.peerjid &&
data.stream.getVideoTracks().length === 0 &&
connection.jingle.localVideo.getVideoTracks().length > 0) {
//
window.setTimeout(function () {
sendKeyframe(sess.peerconnection);
}, 3000);
}
}
/**
* Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
* @param videoSrc the video "src" identifier.
* @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
* belongs.
*/
function getJidFromVideoSrc(videoSrc)
{
if (videoSrc === localVideoSrc)
return connection.emuc.myroomjid;
var ssrc = videoSrcToSsrc[videoSrc];
if (!ssrc)
{
return null;
}
return ssrc2jid[ssrc];
}
// an attempt to work around https://github.com/jitsi/jitmeet/issues/32
function sendKeyframe(pc) {
console.log('sendkeyframe', pc.iceConnectionState);
if (pc.iceConnectionState !== 'connected') return; // safe...
pc.setRemoteDescription(
pc.remoteDescription,
function () {
pc.createAnswer(
function (modifiedAnswer) {
pc.setLocalDescription(
modifiedAnswer,
function () {
// noop
},
function (error) {
console.log('triggerKeyframe setLocalDescription failed', error);
messageHandler.showError();
}
);
},
function (error) {
console.log('triggerKeyframe createAnswer failed', error);
messageHandler.showError();
}
);
},
function (error) {
console.log('triggerKeyframe setRemoteDescription failed', error);
messageHandler.showError();
}
);
}
// Really mute video, i.e. dont even send black frames
function muteVideo(pc, unmute) {
// FIXME: this probably needs another of those lovely state safeguards...
// which checks for iceconn == connected and sigstate == stable
pc.setRemoteDescription(pc.remoteDescription,
function () {
pc.createAnswer(
function (answer) {
var sdp = new SDP(answer.sdp);
if (sdp.media.length > 1) {
if (unmute)
sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
else
sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
sdp.raw = sdp.session + sdp.media.join('');
answer.sdp = sdp.raw;
}
pc.setLocalDescription(answer,
function () {
console.log('mute SLD ok');
},
function (error) {
console.log('mute SLD error');
messageHandler.showError('Error',
'Oops! Something went wrong and we failed to ' +
'mute! (SLD Failure)');
}
);
},
function (error) {
console.log(error);
messageHandler.showError();
}
);
},
function (error) {
console.log('muteVideo SRD error');
messageHandler.showError('Error',
'Oops! Something went wrong and we failed to stop video!' +
'(SRD Failure)');
}
);
}
/**
* Callback for audio levels changed.
* @param jid JID of the user
* @param audioLevel the audio level value
*/
function audioLevelUpdated(jid, audioLevel)
{
var resourceJid;
if(jid === LocalStatsCollector.LOCAL_JID)
{
resourceJid = AudioLevels.LOCAL_LEVEL;
if(isAudioMuted())
{
audioLevel = 0;
}
}
else
{
resourceJid = Strophe.getResourceFromJid(jid);
}
AudioLevels.updateAudioLevel(resourceJid, audioLevel);
}
/**
* Starts the {@link StatsCollector} if the feature is enabled in config.js.
*/
function startRtpStatsCollector()
{
stopRTPStatsCollector();
if (config.enableRtpStats)
{
statsCollector = new StatsCollector(
getConferenceHandler().peerconnection, 200, audioLevelUpdated, 2000,
ConnectionQuality.updateLocalStats);
statsCollector.start();
}
}
/**
* Stops the {@link StatsCollector}.
*/
function stopRTPStatsCollector()
{
if (statsCollector)
{
statsCollector.stop();
statsCollector = null;
ConnectionQuality.stopSendingStats();
}
}
/**
* Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
* @param stream the stream that will be used for collecting statistics.
*/
function startLocalRtpStatsCollector(stream)
{
if(config.enableRtpStats)
{
localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
localStatsCollector.start();
}
}
/**
* Stops the {@link LocalStatsCollector}.
*/
function stopLocalRtpStatsCollector()
{
if(localStatsCollector)
{
localStatsCollector.stop();
localStatsCollector = null;
}
}
$(document).bind('callincoming.jingle', function (event, sid) {
var sess = connection.jingle.sessions[sid];
// TODO: do we check activecall == null?
activecall = sess;
startRtpStatsCollector();
// Bind data channel listener in case we're a regular participant
if (config.openSctp)
{
bindDataChannelListener(sess.peerconnection);
}
// TODO: check affiliation and/or role
console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
sess.usedrip = true; // not-so-naive trickle ice
sess.sendAnswer();
sess.accept();
});
$(document).bind('conferenceCreated.jingle', function (event, focus)
{
startRtpStatsCollector();
});
$(document).bind('conferenceCreated.jingle', function (event, focus)
{
// Bind data channel listener in case we're the focus
if (config.openSctp)
{
bindDataChannelListener(focus.peerconnection);
}
});
$(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
// Leave the room if my call has been remotely terminated.
if (connection.emuc.joined && focus == null && reason === 'kick') {
sessionTerminated = true;
connection.emuc.doLeave();
messageHandler.openMessageDialog("Session Terminated",
"Ouch! You have been kicked out of the meet!");
}
});
$(document).bind('setLocalDescription.jingle', function (event, sid) {
// put our ssrcs into presence so other clients can identify our stream
var sess = connection.jingle.sessions[sid];
var newssrcs = [];
var media = simulcast.parseMedia(sess.peerconnection.localDescription);
media.forEach(function (media) {
// TODO(gp) maybe exclude FID streams?
Object.keys(media.sources).forEach(function(ssrc) {
newssrcs.push({
'ssrc': ssrc,
'type': media.type,
'direction': media.direction
});
});
});
console.log('new ssrcs', newssrcs);
// Have to clear presence map to get rid of removed streams
connection.emuc.clearPresenceMedia();
if (newssrcs.length > 0) {
for (var i = 1; i <= newssrcs.length; i ++) {
// Change video type to screen
if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
newssrcs[i-1].type = 'screen';
}
connection.emuc.addMediaToPresence(i,
newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
}
connection.emuc.sendPresence();
}
});
$(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
switch (session.peerconnection.iceConnectionState) {
case 'checking':
session.timeChecking = (new Date()).getTime();
session.firstconnect = true;
break;
case 'completed': // on caller side
case 'connected':
if (session.firstconnect) {
session.firstconnect = false;
var metadata = {};
metadata.setupTime = (new Date()).getTime() - session.timeChecking;
session.peerconnection.getStats(function (res) {
res.result().forEach(function (report) {
if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
metadata.localCandidateType = report.stat('googLocalCandidateType');
metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
// log pair as well so we can get nice pie charts
metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
if (report.stat('googRemoteAddress').indexOf('[') === 0) {
metadata.ipv6 = true;
}
}
});
trackUsage('iceConnected', metadata);
});
}
break;
}
});
$(document).bind('joined.muc', function (event, jid, info) {
updateRoomUrl(window.location.href);
document.getElementById('localNick').appendChild(
document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
);
if (Object.keys(connection.emuc.members).length < 1) {
focus = new ColibriFocus(connection, config.hosts.bridge);
if (nickname !== null) {
focus.setEndpointDisplayName(connection.emuc.myroomjid,
nickname);
}
Toolbar.showSipCallButton(true);
Toolbar.showRecordingButton(false);
}
if (!focus)
{
Toolbar.showSipCallButton(false);
}
if (focus && config.etherpad_base) {
Etherpad.init();
}
VideoLayout.showFocusIndicator();
// Add myself to the contact list.
ContactList.addContact(jid);
// Once we've joined the muc show the toolbar
ToolbarToggler.showToolbar();
var displayName = !config.displayJids
? info.displayName : Strophe.getResourceFromJid(jid);
if (displayName)
$(document).trigger('displaynamechanged',
['localVideoContainer', displayName + ' (me)']);
});
$(document).bind('entered.muc', function (event, jid, info, pres) {
console.log('entered', jid, info);
messageHandler.notify(info.displayName || 'Somebody',
'connected',
'connected');
console.log('is focus? ' + (focus ? 'true' : 'false'));
// Add Peer's container
VideoLayout.ensurePeerContainerExists(jid);
if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantJoined"))
{
APIConnector.triggerEvent("participantJoined",{jid: jid});
}
if (focus !== null) {
// FIXME: this should prepare the video
if (focus.confid === null) {
console.log('make new conference with', jid);
focus.makeConference(Object.keys(connection.emuc.members),
function(error) {
connection.emuc.addBridgeIsDownToPresence();
connection.emuc.sendPresence();
}
);
Toolbar.showRecordingButton(true);
} else {
console.log('invite', jid, 'into conference');
focus.addNewParticipant(jid);
}
}
});
$(document).bind('left.muc', function (event, jid) {
console.log('left.muc', jid);
var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
'>.displayname').text();
messageHandler.notify(displayName || 'Somebody',
'disconnected',
'disconnected');
// Need to call this with a slight delay, otherwise the element couldn't be
// found for some reason.
// XXX(gp) it works fine without the timeout for me (with Chrome 38).
window.setTimeout(function () {
var container = document.getElementById(
'participant_' + Strophe.getResourceFromJid(jid));
if (container) {
VideoLayout.removeConnectionIndicator(jid);
// hide here, wait for video to close before removing
$(container).hide();
VideoLayout.resizeThumbnails();
}
}, 10);
if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantLeft"))
{
APIConnector.triggerEvent("participantLeft",{jid: jid});
}
// Unlock large video
if (focusedVideoSrc)
{
if (getJidFromVideoSrc(focusedVideoSrc) === jid)
{
console.info("Focused video owner has left the conference");
focusedVideoSrc = null;
}
}
connection.jingle.terminateByJid(jid);
if (focus == null
// I shouldn't be the one that left to enter here.
&& jid !== connection.emuc.myroomjid
&& connection.emuc.myroomjid === connection.emuc.list_members[0]
// If our session has been terminated for some reason
// (kicked, hangup), don't try to become the focus
&& !sessionTerminated) {
console.log('welcome to our new focus... myself');
focus = new ColibriFocus(connection, config.hosts.bridge);
if (nickname !== null) {
focus.setEndpointDisplayName(connection.emuc.myroomjid,
nickname);
}
Toolbar.showSipCallButton(true);
if (Object.keys(connection.emuc.members).length > 0) {
focus.makeConference(Object.keys(connection.emuc.members));
Toolbar.showRecordingButton(true);
}
$(document).trigger('focusechanged.muc', [focus]);
}
else if (focus && Object.keys(connection.emuc.members).length === 0) {
console.log('everyone left');
// FIXME: closing the connection is a hack to avoid some
// problems with reinit
disposeConference();
focus = new ColibriFocus(connection, config.hosts.bridge);
if (nickname !== null) {
focus.setEndpointDisplayName(connection.emuc.myroomjid,
nickname);
}
Toolbar.showSipCallButton(true);
Toolbar.showRecordingButton(false);
}
if (connection.emuc.getPrezi(jid)) {
$(document).trigger('presentationremoved.muc',
[jid, connection.emuc.getPrezi(jid)]);
}
});
$(document).bind('presence.muc', function (event, jid, info, pres) {
// Remove old ssrcs coming from the jid
Object.keys(ssrc2jid).forEach(function (ssrc) {
if (ssrc2jid[ssrc] == jid) {
delete ssrc2jid[ssrc];
}
if (ssrc2videoType[ssrc] == jid) {
delete ssrc2videoType[ssrc];
}
});
$(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
//console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
var ssrcV = ssrc.getAttribute('ssrc');
ssrc2jid[ssrcV] = jid;
var type = ssrc.getAttribute('type');
ssrc2videoType[ssrcV] = type;
// might need to update the direction if participant just went from sendrecv to recvonly
if (type === 'video' || type === 'screen') {
var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
switch (ssrc.getAttribute('direction')) {
case 'sendrecv':
el.show();
break;
case 'recvonly':
el.hide();
// FIXME: Check if we have to change large video
//VideoLayout.updateLargeVideo(el);
break;
}
}
});
var displayName = !config.displayJids
? info.displayName : Strophe.getResourceFromJid(jid);
if (displayName && displayName.length > 0)
$(document).trigger('displaynamechanged',
[jid, displayName]);
if (focus !== null && info.displayName !== null) {
focus.setEndpointDisplayName(jid, info.displayName);
}
//check if the video bridge is available
if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
bridgeIsDown = true;
messageHandler.showError("Error",
"Jitsi Videobridge is currently unavailable. Please try again later!");
}
});
$(document).bind('presence.status.muc', function (event, jid, info, pres) {
VideoLayout.setPresenceStatus(
'participant_' + Strophe.getResourceFromJid(jid), info.status);
});
$(document).bind('passwordrequired.muc', function (event, jid) {
console.log('on password required', jid);
// password is required
Toolbar.lockLockButton();
messageHandler.openTwoButtonDialog(null,
'<h2>Password required</h2>' +
'<input id="lockKey" type="text" placeholder="password" autofocus>',
true,
"Ok",
function (e, v, m, f) {},
function (event) {
document.getElementById('lockKey').focus();
},
function (e, v, m, f) {
if (v) {
var lockKey = document.getElementById('lockKey');
if (lockKey.value !== null) {
setSharedKey(lockKey.value);
connection.emuc.doJoin(jid, lockKey.value);
}
}
}
);
});
$(document).bind('passwordrequired.main', function (event) {
console.log('password is required');
messageHandler.openTwoButtonDialog(null,
'<h2>Password required</h2>' +
'<input id="passwordrequired.username" type="text" placeholder="[email protected]" autofocus>' +
'<input id="passwordrequired.password" type="password" placeholder="user password">',
true,
"Ok",
function (e, v, m, f) {
if (v) {
var username = document.getElementById('passwordrequired.username');
var password = document.getElementById('passwordrequired.password');
if (username.value !== null && password.value != null) {
connect(username.value, password.value);
}
}
},
function (event) {
document.getElementById('passwordrequired.username').focus();
}
);
});
/**
* Checks if video identified by given src is desktop stream.
* @param videoSrc eg.
* blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
* @returns {boolean}
*/
function isVideoSrcDesktop(videoSrc) {
// FIXME: fix this mapping mess...
// figure out if large video is desktop stream or just a camera
var isDesktop = false;
if (localVideoSrc === videoSrc) {
// local video
isDesktop = isUsingScreenStream;
} else {
// Do we have associations...
var videoSsrc = videoSrcToSsrc[videoSrc];
if (videoSsrc) {
var videoType = ssrc2videoType[videoSsrc];
if (videoType) {
// Finally there...
isDesktop = videoType === 'screen';
} else {
console.error("No video type for ssrc: " + videoSsrc);
}
} else {
console.error("No ssrc for src: " + videoSrc);
}
}
return isDesktop;
}
function getConferenceHandler() {
return focus ? focus : activecall;
}
function toggleVideo() {
buttonClick("#video", "icon-camera icon-camera-disabled");
if (!(connection && connection.jingle.localVideo))
return;
var sess = getConferenceHandler();
if (sess) {
sess.toggleVideoMute(
function (isMuted) {
if (isMuted) {
$('#video').removeClass("icon-camera");
$('#video').addClass("icon-camera icon-camera-disabled");
} else {
$('#video').removeClass("icon-camera icon-camera-disabled");
$('#video').addClass("icon-camera");
}
connection.emuc.addVideoInfoToPresence(isMuted);
connection.emuc.sendPresence();
}
);
}
}
/**
* Mutes / unmutes audio for the local participant.
*/
function toggleAudio() {
if (!(connection && connection.jingle.localAudio)) {
// We still click the button.
buttonClick("#mute", "icon-microphone icon-mic-disabled");
return;
}
// It is not clear what is the right way to handle multiple tracks.
// So at least make sure that they are all muted or all unmuted and
// that we send presence just once.
var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
if (localAudioTracks.length > 0) {
var audioEnabled = localAudioTracks[0].enabled;
for (var idx = 0; idx < localAudioTracks.length; idx++) {
localAudioTracks[idx].enabled = !audioEnabled;