forked from jitsi/lib-jitsi-meet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JitsiConference.js
3781 lines (3260 loc) · 123 KB
/
JitsiConference.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
/* global __filename, $, Promise */
import EventEmitter from 'events';
import { getLogger } from 'jitsi-meet-logger';
import isEqual from 'lodash.isequal';
import { Strophe } from 'strophe.js';
import * as JitsiConferenceErrors from './JitsiConferenceErrors';
import JitsiConferenceEventManager from './JitsiConferenceEventManager';
import * as JitsiConferenceEvents from './JitsiConferenceEvents';
import JitsiParticipant from './JitsiParticipant';
import JitsiTrackError from './JitsiTrackError';
import * as JitsiTrackErrors from './JitsiTrackErrors';
import * as JitsiTrackEvents from './JitsiTrackEvents';
import authenticateAndUpgradeRole from './authenticateAndUpgradeRole';
import { CodecSelection } from './modules/RTC/CodecSelection';
import RTC from './modules/RTC/RTC';
import browser from './modules/browser';
import ConnectionQuality from './modules/connectivity/ConnectionQuality';
import IceFailedHandling
from './modules/connectivity/IceFailedHandling';
import ParticipantConnectionStatusHandler
from './modules/connectivity/ParticipantConnectionStatus';
import * as DetectionEvents from './modules/detection/DetectionEvents';
import NoAudioSignalDetection from './modules/detection/NoAudioSignalDetection';
import P2PDominantSpeakerDetection from './modules/detection/P2PDominantSpeakerDetection';
import VADAudioAnalyser from './modules/detection/VADAudioAnalyser';
import VADNoiseDetection from './modules/detection/VADNoiseDetection';
import VADTalkMutedDetection from './modules/detection/VADTalkMutedDetection';
import { E2EEncryption } from './modules/e2ee/E2EEncryption';
import E2ePing from './modules/e2eping/e2eping';
import Jvb121EventGenerator from './modules/event/Jvb121EventGenerator';
import { ReceiveVideoController } from './modules/qualitycontrol/ReceiveVideoController';
import { SendVideoController } from './modules/qualitycontrol/SendVideoController';
import RecordingManager from './modules/recording/RecordingManager';
import Settings from './modules/settings/Settings';
import AudioOutputProblemDetector from './modules/statistics/AudioOutputProblemDetector';
import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
import Statistics from './modules/statistics/statistics';
import Transcriber from './modules/transcription/transcriber';
import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
import RandomUtil from './modules/util/RandomUtil';
import ComponentsVersions from './modules/version/ComponentsVersions';
import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
import {
FEATURE_E2EE,
FEATURE_JIGASI,
JITSI_MEET_MUC_TYPE
} from './modules/xmpp/xmpp';
import CodecMimeType from './service/RTC/CodecMimeType';
import * as MediaType from './service/RTC/MediaType';
import VideoType from './service/RTC/VideoType';
import {
ACTION_JINGLE_RESTART,
ACTION_JINGLE_SI_RECEIVED,
ACTION_JINGLE_SI_TIMEOUT,
ACTION_JINGLE_TERMINATE,
ACTION_P2P_DECLINED,
ACTION_P2P_ESTABLISHED,
ACTION_P2P_FAILED,
ACTION_P2P_SWITCH_TO_JVB,
ICE_ESTABLISHMENT_DURATION_DIFF,
createConferenceEvent,
createJingleEvent,
createP2PEvent
} from './service/statistics/AnalyticsEvents';
import * as XMPPEvents from './service/xmpp/XMPPEvents';
const logger = getLogger(__filename);
/**
* How long since Jicofo is supposed to send a session-initiate, before
* {@link ACTION_JINGLE_SI_TIMEOUT} analytics event is sent (in ms).
* @type {number}
*/
const JINGLE_SI_TIMEOUT = 5000;
/**
* Creates a JitsiConference object with the given name and properties.
* Note: this constructor is not a part of the public API (objects should be
* created using JitsiConnection.createConference).
* @param options.config properties / settings related to the conference that
* will be created.
* @param options.name the name of the conference
* @param options.connection the JitsiConnection object for this
* JitsiConference.
* @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
* collected by {@link AvgRTPStatsReporter}, before arithmetic mean is
* calculated and submitted to the analytics module.
* @param {boolean} [options.config.enableIceRestart=false] - enables the ICE
* restart logic.
* @param {boolean} [options.config.p2p.enabled] when set to <tt>true</tt>
* the peer to peer mode will be enabled. It means that when there are only 2
* participants in the conference an attempt to make direct connection will be
* made. If the connection succeeds the conference will stop sending data
* through the JVB connection and will use the direct one instead.
* @param {number} [options.config.p2p.backToP2PDelay=5] a delay given in
* seconds, before the conference switches back to P2P, after the 3rd
* participant has left the room.
* @param {number} [options.config.channelLastN=-1] The requested amount of
* videos are going to be delivered after the value is in effect. Set to -1 for
* unlimited or all available videos.
* @param {number} [options.config.forceJVB121Ratio]
* "Math.random() < forceJVB121Ratio" will determine whether a 2 people
* conference should be moved to the JVB instead of P2P. The decision is made on
* the responder side, after ICE succeeds on the P2P connection.
* @constructor
*
* FIXME Make all methods which are called from lib-internal classes
* to non-public (use _). To name a few:
* {@link JitsiConference.onLocalRoleChanged}
* {@link JitsiConference.onUserRoleChanged}
* {@link JitsiConference.onMemberLeft}
* and so on...
*/
export default function JitsiConference(options) {
if (!options.name || options.name.toLowerCase() !== options.name) {
const errmsg
= 'Invalid conference name (no conference name passed or it '
+ 'contains invalid characters like capital letters)!';
logger.error(errmsg);
throw new Error(errmsg);
}
this.eventEmitter = new EventEmitter();
this.options = options;
this.eventManager = new JitsiConferenceEventManager(this);
this.participants = {};
this._init(options);
this.componentsVersions = new ComponentsVersions(this);
/**
* Jingle session instance for the JVB connection.
* @type {JingleSessionPC}
*/
this.jvbJingleSession = null;
this.lastDominantSpeaker = null;
this.dtmfManager = null;
this.somebodySupportsDTMF = false;
this.authEnabled = false;
this.startAudioMuted = false;
this.startVideoMuted = false;
this.startMutedPolicy = {
audio: false,
video: false
};
this.isMutedByFocus = false;
// when muted by focus we receive the jid of the initiator of the mute
this.mutedByFocusActor = null;
this.isVideoMutedByFocus = false;
// when video muted by focus we receive the jid of the initiator of the mute
this.mutedVideoByFocusActor = null;
// Flag indicates if the 'onCallEnded' method was ever called on this
// instance. Used to log extra analytics event for debugging purpose.
// We need to know if the potential issue happened before or after
// the restart.
this.wasStopped = false;
// Conference properties, maintained by jicofo.
this.properties = {};
/**
* The object which monitors local and remote connection statistics (e.g.
* sending bitrate) and calculates a number which represents the connection
* quality.
*/
this.connectionQuality
= new ConnectionQuality(this, this.eventEmitter, options);
/**
* Reports average RTP statistics to the analytics module.
* @type {AvgRTPStatsReporter}
*/
this.avgRtpStatsReporter
= new AvgRTPStatsReporter(this, options.config.avgRtpStatsN || 15);
/**
* Detects issues with the audio of remote participants.
* @type {AudioOutputProblemDetector}
*/
this._audioOutputProblemDetector = new AudioOutputProblemDetector(this);
/**
* Indicates whether the connection is interrupted or not.
*/
this.isJvbConnectionInterrupted = false;
/**
* The object which tracks active speaker times
*/
this.speakerStatsCollector = new SpeakerStatsCollector(this);
/* P2P related fields below: */
/**
* Stores reference to deferred start P2P task. It's created when 3rd
* participant leaves the room in order to avoid ping pong effect (it
* could be just a page reload).
* @type {number|null}
*/
this.deferredStartP2PTask = null;
const delay
= parseInt(options.config.p2p && options.config.p2p.backToP2PDelay, 10);
/**
* A delay given in seconds, before the conference switches back to P2P
* after the 3rd participant has left.
* @type {number}
*/
this.backToP2PDelay = isNaN(delay) ? 5 : delay;
logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
/**
* If set to <tt>true</tt> it means the P2P ICE is no longer connected.
* When <tt>false</tt> it means that P2P ICE (media) connection is up
* and running.
* @type {boolean}
*/
this.isP2PConnectionInterrupted = false;
/**
* Flag set to <tt>true</tt> when P2P session has been established
* (ICE has been connected) and this conference is currently in the peer to
* peer mode (P2P connection is the active one).
* @type {boolean}
*/
this.p2p = false;
/**
* A JingleSession for the direct peer to peer connection.
* @type {JingleSessionPC}
*/
this.p2pJingleSession = null;
this.videoSIPGWHandler = new VideoSIPGW(this.room);
this.recordingManager = new RecordingManager(this.room);
/**
* If the conference.joined event has been sent this will store the timestamp when it happened.
*
* @type {undefined|number}
* @private
*/
this._conferenceJoinAnalyticsEventSent = undefined;
/**
* End-to-End Encryption. Make it available if supported.
*/
if (this.isE2EESupported()) {
logger.info('End-to-End Encryprtion is supported');
this._e2eEncryption = new E2EEncryption(this);
}
}
// FIXME convert JitsiConference to ES6 - ASAP !
JitsiConference.prototype.constructor = JitsiConference;
/**
* Create a resource for the a jid. We use the room nickname (the resource part
* of the occupant JID, see XEP-0045) as the endpoint ID in colibri. We require
* endpoint IDs to be 8 hex digits because in some cases they get serialized
* into a 32bit field.
*
* @param {string} jid - The id set onto the XMPP connection.
* @param {boolean} isAuthenticatedUser - Whether or not the user has connected
* to the XMPP service with a password.
* @returns {string}
* @static
*/
JitsiConference.resourceCreator = function(jid, isAuthenticatedUser) {
let mucNickname;
if (isAuthenticatedUser) {
// For authenticated users generate a random ID.
mucNickname = RandomUtil.randomHexString(8).toLowerCase();
} else {
// We try to use the first part of the node (which for anonymous users
// on prosody is a UUID) to match the previous behavior (and maybe make
// debugging easier).
mucNickname = Strophe.getNodeFromJid(jid).substr(0, 8)
.toLowerCase();
// But if this doesn't have the required format we just generate a new
// random nickname.
const re = /[0-9a-f]{8}/g;
if (!re.test(mucNickname)) {
mucNickname = RandomUtil.randomHexString(8).toLowerCase();
}
}
return mucNickname;
};
/**
* Initializes the conference object properties
* @param options {object}
* @param options.connection {JitsiConnection} overrides this.connection
*/
JitsiConference.prototype._init = function(options = {}) {
// Override connection and xmpp properties (Useful if the connection
// reloaded)
if (options.connection) {
this.connection = options.connection;
this.xmpp = this.connection.xmpp;
// Setup XMPP events only if we have new connection object.
this.eventManager.setupXMPPListeners();
}
const { config } = this.options;
// Get the codec preference settings from config.js.
// 'preferH264' and 'disableH264' settings have been deprecated for a while,
// 'preferredCodec' and 'disabledCodec' will have precedence over them.
const codecSettings = {
disabledCodec: config.videoQuality
? config.videoQuality.disabledCodec
: config.p2p && config.p2p.disableH264 && CodecMimeType.H264,
enforcePreferredCodec: config.videoQuality && config.videoQuality.enforcePreferredCodec,
jvbCodec: (config.videoQuality && config.videoQuality.preferredCodec)
|| (config.preferH264 && CodecMimeType.H264),
p2pCodec: config.p2p
? config.p2p.preferredCodec || (config.p2p.preferH264 && CodecMimeType.H264)
: CodecMimeType.VP8
};
this.codecSelection = new CodecSelection(this, codecSettings);
this._statsCurrentId = config.statisticsId ? config.statisticsId : Settings.callStatsUserName;
this.room = this.xmpp.createRoom(
this.options.name, {
...config,
statsId: this._statsCurrentId
},
JitsiConference.resourceCreator
);
// Connection interrupted/restored listeners
this._onIceConnectionInterrupted
= this._onIceConnectionInterrupted.bind(this);
this.room.addListener(
XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
this.room.addListener(
XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
this._onIceConnectionEstablished
= this._onIceConnectionEstablished.bind(this);
this.room.addListener(
XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
this._updateProperties = this._updateProperties.bind(this);
this.room.addListener(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
this._updateProperties);
this._sendConferenceJoinAnalyticsEvent = this._sendConferenceJoinAnalyticsEvent.bind(this);
this.room.addListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
this.e2eping = new E2ePing(
this,
config,
(message, to) => {
try {
this.sendMessage(
message, to, true /* sendThroughVideobridge */);
} catch (error) {
logger.warn('Failed to send E2E ping request or response.', error && error.msg);
}
});
if (!this.rtc) {
this.rtc = new RTC(this, options);
this.eventManager.setupRTCListeners();
}
this.receiveVideoController = new ReceiveVideoController(this, this.rtc);
this.sendVideoController = new SendVideoController(this, this.rtc);
this.participantConnectionStatus
= new ParticipantConnectionStatusHandler(
this.rtc,
this,
{
// Both these options are not public API, leaving it here only
// as an entry point through config for tuning up purposes.
// Default values should be adjusted as soon as optimal values
// are discovered.
rtcMuteTimeout: config._peerConnStatusRtcMuteTimeout,
outOfLastNTimeout: config._peerConnStatusOutOfLastNTimeout
});
this.participantConnectionStatus.init();
// Add the ability to enable callStats only on a percentage of users based on config.js settings.
let enableCallStats = true;
if (config.testing && config.testing.callStatsThreshold) {
enableCallStats = (Math.random() * 100) <= config.testing.callStatsThreshold;
}
if (!this.statistics) {
this.statistics = new Statistics(this.xmpp, {
aliasName: this._statsCurrentId,
userName: config.statisticsDisplayName ? config.statisticsDisplayName : this.myUserId(),
confID: config.confID || `${this.connection.options.hosts.domain}/${this.options.name}`,
siteID: config.siteID,
customScriptUrl: config.callStatsCustomScriptUrl,
callStatsID: config.callStatsID,
callStatsSecret: config.callStatsSecret,
callStatsApplicationLogsDisabled: config.callStatsApplicationLogsDisabled,
enableCallStats,
roomName: this.options.name,
applicationName: config.applicationName,
getWiFiStatsMethod: config.getWiFiStatsMethod
});
Statistics.analytics.addPermanentProperties({
'callstats_name': this._statsCurrentId
});
// Start performance observer for monitoring long tasks
if (config.longTasksStatsInterval) {
this.statistics.attachLongTasksStats(this);
}
}
this.eventManager.setupChatRoomListeners();
// Always add listeners because on reload we are executing leave and the
// listeners are removed from statistics module.
this.eventManager.setupStatisticsListeners();
// Disable VAD processing on Safari since it causes audio input to
// fail on some of the mobile devices.
if (config.enableTalkWhileMuted && browser.supportsVADDetection()) {
// If VAD processor factory method is provided uses VAD based detection, otherwise fallback to audio level
// based detection.
if (config.createVADProcessor) {
logger.info('Using VAD detection for generating talk while muted events');
if (!this._audioAnalyser) {
this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
}
const vadTalkMutedDetection = new VADTalkMutedDetection();
vadTalkMutedDetection.on(DetectionEvents.VAD_TALK_WHILE_MUTED, () =>
this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
this._audioAnalyser.addVADDetectionService(vadTalkMutedDetection);
} else {
logger.warn('No VAD Processor was provided. Talk while muted detection service was not initialized!');
}
}
// Disable noisy mic detection on safari since it causes the audio input to
// fail on Safari on iPadOS.
if (config.enableNoisyMicDetection && browser.supportsVADDetection()) {
if (config.createVADProcessor) {
if (!this._audioAnalyser) {
this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
}
const vadNoiseDetection = new VADNoiseDetection();
vadNoiseDetection.on(DetectionEvents.VAD_NOISY_DEVICE, () =>
this.eventEmitter.emit(JitsiConferenceEvents.NOISY_MIC));
this._audioAnalyser.addVADDetectionService(vadNoiseDetection);
} else {
logger.warn('No VAD Processor was provided. Noisy microphone detection service was not initialized!');
}
}
// Generates events based on no audio input detector.
if (config.enableNoAudioDetection) {
this._noAudioSignalDetection = new NoAudioSignalDetection(this);
this._noAudioSignalDetection.on(DetectionEvents.NO_AUDIO_INPUT, () => {
this.eventEmitter.emit(JitsiConferenceEvents.NO_AUDIO_INPUT);
});
this._noAudioSignalDetection.on(DetectionEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal => {
this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal);
});
}
if ('channelLastN' in config) {
this.setLastN(config.channelLastN);
}
/**
* Emits {@link JitsiConferenceEvents.JVB121_STATUS}.
* @type {Jvb121EventGenerator}
*/
this.jvb121Status = new Jvb121EventGenerator(this);
// creates dominant speaker detection that works only in p2p mode
this.p2pDominantSpeakerDetection = new P2PDominantSpeakerDetection(this);
if (config && config.deploymentInfo && config.deploymentInfo.userRegion) {
this.setLocalParticipantProperty(
'region', config.deploymentInfo.userRegion);
}
// Publish the codec type to presence.
this.setLocalParticipantProperty('codecType', this.codecSelection.getPreferredCodec());
};
/**
* Joins the conference.
* @param password {string} the password
* @param replaceParticipant {boolean} whether the current join replaces
* an existing participant with same jwt from the meeting.
*/
JitsiConference.prototype.join = function(password, replaceParticipant = false) {
if (this.room) {
this.room.join(password, replaceParticipant).then(() => this._maybeSetSITimeout());
}
};
/**
* Authenticates and upgrades the role of the local participant/user.
*
* @returns {Object} A <tt>thenable</tt> which (1) settles when the process of
* authenticating and upgrading the role of the local participant/user finishes
* and (2) has a <tt>cancel</tt> method that allows the caller to interrupt the
* process.
*/
JitsiConference.prototype.authenticateAndUpgradeRole = function(options) {
return authenticateAndUpgradeRole.call(this, {
...options,
onCreateResource: JitsiConference.resourceCreator
});
};
/**
* Check if joined to the conference.
*/
JitsiConference.prototype.isJoined = function() {
return this.room && this.room.joined;
};
/**
* Tells whether or not the P2P mode is enabled in the configuration.
* @return {boolean}
*/
JitsiConference.prototype.isP2PEnabled = function() {
return Boolean(this.options.config.p2p && this.options.config.p2p.enabled)
// FIXME: remove once we have a default config template. -saghul
|| typeof this.options.config.p2p === 'undefined';
};
/**
* When in P2P test mode, the conference will not automatically switch to P2P
* when there 2 participants.
* @return {boolean}
*/
JitsiConference.prototype.isP2PTestModeEnabled = function() {
return Boolean(this.options.config.testing
&& this.options.config.testing.p2pTestMode);
};
/**
* Leaves the conference.
* @returns {Promise}
*/
JitsiConference.prototype.leave = function() {
if (this.participantConnectionStatus) {
this.participantConnectionStatus.dispose();
this.participantConnectionStatus = null;
}
if (this.avgRtpStatsReporter) {
this.avgRtpStatsReporter.dispose();
this.avgRtpStatsReporter = null;
}
if (this._audioOutputProblemDetector) {
this._audioOutputProblemDetector.dispose();
this._audioOutputProblemDetector = null;
}
if (this.e2eping) {
this.e2eping.stop();
this.e2eping = null;
}
this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
this.rtc.closeBridgeChannel();
this._sendConferenceLeftAnalyticsEvent();
if (this.statistics) {
this.statistics.dispose();
}
this._delayedIceFailed && this._delayedIceFailed.cancel();
// Close both JVb and P2P JingleSessions
if (this.jvbJingleSession) {
this.jvbJingleSession.close();
this.jvbJingleSession = null;
}
if (this.p2pJingleSession) {
this.p2pJingleSession.close();
this.p2pJingleSession = null;
}
// leave the conference
if (this.room) {
const room = this.room;
// Unregister connection state listeners
room.removeListener(
XMPPEvents.CONNECTION_INTERRUPTED,
this._onIceConnectionInterrupted);
room.removeListener(
XMPPEvents.CONNECTION_RESTORED,
this._onIceConnectionRestored);
room.removeListener(
XMPPEvents.CONNECTION_ESTABLISHED,
this._onIceConnectionEstablished);
room.removeListener(
XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
this._updateProperties);
room.removeListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
this.eventManager.removeXMPPListeners();
this.room = null;
return room.leave()
.then(() => {
if (this.rtc) {
this.rtc.destroy();
}
})
.catch(error => {
// remove all participants because currently the conference
// won't be usable anyway. This is done on success automatically
// by the ChatRoom instance.
this.getParticipants().forEach(
participant => this.onMemberLeft(participant.getJid()));
throw error;
});
}
// If this.room == null we are calling second time leave().
return Promise.reject(
new Error('The conference is has been already left'));
};
/**
* Returns the currently active media session if any.
*
* @returns {JingleSessionPC|undefined}
* @private
*/
JitsiConference.prototype._getActiveMediaSession = function() {
return this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
};
/**
* Returns an array containing all media sessions existing in this conference.
*
* @returns {Array<JingleSessionPC>}
* @private
*/
JitsiConference.prototype._getMediaSessions = function() {
const sessions = [];
this.jvbJingleSession && sessions.push(this.jvbJingleSession);
this.p2pJingleSession && sessions.push(this.p2pJingleSession);
return sessions;
};
/**
* Returns name of this conference.
*/
JitsiConference.prototype.getName = function() {
return this.options.name;
};
/**
* Returns the {@link JitsiConnection} used by this this conference.
*/
JitsiConference.prototype.getConnection = function() {
return this.connection;
};
/**
* Check if authentication is enabled for this conference.
*/
JitsiConference.prototype.isAuthEnabled = function() {
return this.authEnabled;
};
/**
* Check if user is logged in.
*/
JitsiConference.prototype.isLoggedIn = function() {
return Boolean(this.authIdentity);
};
/**
* Get authorized login.
*/
JitsiConference.prototype.getAuthLogin = function() {
return this.authIdentity;
};
/**
* Check if external authentication is enabled for this conference.
*/
JitsiConference.prototype.isExternalAuthEnabled = function() {
return this.room && this.room.moderator.isExternalAuthEnabled();
};
/**
* Get url for external authentication.
* @param {boolean} [urlForPopup] if true then return url for login popup,
* else url of login page.
* @returns {Promise}
*/
JitsiConference.prototype.getExternalAuthUrl = function(urlForPopup) {
return new Promise((resolve, reject) => {
if (!this.isExternalAuthEnabled()) {
reject();
return;
}
if (urlForPopup) {
this.room.moderator.getPopupLoginUrl(resolve, reject);
} else {
this.room.moderator.getLoginUrl(resolve, reject);
}
});
};
/**
* Returns the local tracks of the given media type, or all local tracks if no
* specific type is given.
* @param {MediaType} [mediaType] Optional media type (audio or video).
*/
JitsiConference.prototype.getLocalTracks = function(mediaType) {
let tracks = [];
if (this.rtc) {
tracks = this.rtc.getLocalTracks(mediaType);
}
return tracks;
};
/**
* Obtains local audio track.
* @return {JitsiLocalTrack|null}
*/
JitsiConference.prototype.getLocalAudioTrack = function() {
return this.rtc ? this.rtc.getLocalAudioTrack() : null;
};
/**
* Obtains local video track.
* @return {JitsiLocalTrack|null}
*/
JitsiConference.prototype.getLocalVideoTrack = function() {
return this.rtc ? this.rtc.getLocalVideoTrack() : null;
};
/**
* Obtains the performance statistics.
* @returns {Object|null}
*/
JitsiConference.prototype.getPerformanceStats = function() {
return {
longTasksStats: this.statistics.getLongTasksStats()
};
};
/**
* Attaches a handler for events(For example - "participant joined".) in the
* conference. All possible event are defined in JitsiConferenceEvents.
* @param eventId the event ID.
* @param handler handler for the event.
*
* Note: consider adding eventing functionality by extending an EventEmitter
* impl, instead of rolling ourselves
*/
JitsiConference.prototype.on = function(eventId, handler) {
if (this.eventEmitter) {
this.eventEmitter.on(eventId, handler);
}
};
/**
* Removes event listener
* @param eventId the event ID.
* @param [handler] optional, the specific handler to unbind
*
* Note: consider adding eventing functionality by extending an EventEmitter
* impl, instead of rolling ourselves
*/
JitsiConference.prototype.off = function(eventId, handler) {
if (this.eventEmitter) {
this.eventEmitter.removeListener(eventId, handler);
}
};
// Common aliases for event emitter
JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
/**
* Receives notifications from other participants about commands / custom events
* (sent by sendCommand or sendCommandOnce methods).
* @param command {String} the name of the command
* @param handler {Function} handler for the command
*/
JitsiConference.prototype.addCommandListener = function(command, handler) {
if (this.room) {
this.room.addPresenceListener(command, handler);
}
};
/**
* Removes command listener
* @param command {String} the name of the command
* @param handler {Function} handler to remove for the command
*/
JitsiConference.prototype.removeCommandListener = function(command, handler) {
if (this.room) {
this.room.removePresenceListener(command, handler);
}
};
/**
* Sends text message to the other participants in the conference
* @param message the text message.
* @param elementName the element name to encapsulate the message.
* @deprecated Use 'sendMessage' instead. TODO: this should be private.
*/
JitsiConference.prototype.sendTextMessage = function(
message, elementName = 'body') {
if (this.room) {
this.room.sendMessage(message, elementName);
}
};
/**
* Send private text message to another participant of the conference
* @param id the id of the participant to send a private message.
* @param message the text message.
* @param elementName the element name to encapsulate the message.
* @deprecated Use 'sendMessage' instead. TODO: this should be private.
*/
JitsiConference.prototype.sendPrivateTextMessage = function(
id, message, elementName = 'body') {
if (this.room) {
this.room.sendPrivateMessage(id, message, elementName);
}
};
/**
* Send presence command.
* @param name {String} the name of the command.
* @param values {Object} with keys and values that will be sent.
**/
JitsiConference.prototype.sendCommand = function(name, values) {
if (this.room) {
this.room.addOrReplaceInPresence(name, values) && this.room.sendPresence();
} else {
logger.warn('Not sending a command, room not initialized.');
}
};
/**
* Send presence command one time.
* @param name {String} the name of the command.
* @param values {Object} with keys and values that will be sent.
**/
JitsiConference.prototype.sendCommandOnce = function(name, values) {
this.sendCommand(name, values);
this.removeCommand(name);
};
/**
* Removes presence command.
* @param name {String} the name of the command.
**/
JitsiConference.prototype.removeCommand = function(name) {
if (this.room) {
this.room.removeFromPresence(name);
}
};
/**
* Sets the display name for this conference.
* @param name the display name to set
*/
JitsiConference.prototype.setDisplayName = function(name) {
if (this.room) {
this.room.addOrReplaceInPresence('nick', {
attributes: { xmlns: 'http://jabber.org/protocol/nick' },
value: name
}) && this.room.sendPresence();
}
};
/**
* Set new subject for this conference. (available only for moderator)
* @param {string} subject new subject
*/
JitsiConference.prototype.setSubject = function(subject) {
if (this.room && this.isModerator()) {
this.room.setSubject(subject);
} else {
logger.warn(`Failed to set subject, ${this.room ? '' : 'not in a room, '}${
this.isModerator() ? '' : 'participant is not a moderator'}`);
}
};
/**
* Get a transcriber object for all current participants in this conference
* @return {Transcriber} the transcriber object
*/
JitsiConference.prototype.getTranscriber = function() {
if (this.transcriber === undefined) {
this.transcriber = new Transcriber();
// add all existing local audio tracks to the transcriber
const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
for (const localAudio of localAudioTracks) {
this.transcriber.addTrack(localAudio);
}
// and all remote audio tracks
const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
for (const remoteTrack of remoteAudioTracks) {
this.transcriber.addTrack(remoteTrack);
}
}
return this.transcriber;
};
/**
* Returns the transcription status.
*
* @returns {String} "on" or "off".
*/
JitsiConference.prototype.getTranscriptionStatus = function() {
return this.room.transcriptionStatus;
};
/**
* Adds JitsiLocalTrack object to the conference.
* @param {JitsiLocalTrack} track the JitsiLocalTrack object.
* @returns {Promise<JitsiLocalTrack>}
* @throws {Error} if the specified track is a video track and there is already
* another video track in the conference.
*/
JitsiConference.prototype.addTrack = function(track) {
const mediaType = track.getType();
const localTracks = this.rtc.getLocalTracks(mediaType);
// Ensure there's exactly 1 local track of each media type in the conference.
if (localTracks.length > 0) {
// Don't be excessively harsh and severe if the API client happens to attempt to add the same local track twice.
if (track === localTracks[0]) {
return Promise.resolve(track);
}
return Promise.reject(new Error(`Cannot add second ${mediaType} track to the conference`));
}
return this.replaceTrack(null, track);
};
/**
* Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
* @param {number} audioLevel the audio level
* @param {TraceablePeerConnection} [tpc]
*/
JitsiConference.prototype._fireAudioLevelChangeEvent = function(