/JitsiConference.js

https://github.com/jitsi/lib-jitsi-meet · JavaScript · 3538 lines · 1914 code · 483 blank · 1141 comment · 329 complexity · 459e2ba08f31305c122a6dd3d129948d MD5 · raw file

  1. /* global __filename, $, Promise */
  2. import EventEmitter from 'events';
  3. import { getLogger } from 'jitsi-meet-logger';
  4. import isEqual from 'lodash.isequal';
  5. import { Strophe } from 'strophe.js';
  6. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  7. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  8. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  9. import JitsiParticipant from './JitsiParticipant';
  10. import JitsiTrackError from './JitsiTrackError';
  11. import * as JitsiTrackErrors from './JitsiTrackErrors';
  12. import * as JitsiTrackEvents from './JitsiTrackEvents';
  13. import authenticateAndUpgradeRole from './authenticateAndUpgradeRole';
  14. import RTC from './modules/RTC/RTC';
  15. import browser from './modules/browser';
  16. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  17. import IceFailedHandling
  18. from './modules/connectivity/IceFailedHandling';
  19. import ParticipantConnectionStatusHandler
  20. from './modules/connectivity/ParticipantConnectionStatus';
  21. import * as DetectionEvents from './modules/detection/DetectionEvents';
  22. import NoAudioSignalDetection from './modules/detection/NoAudioSignalDetection';
  23. import P2PDominantSpeakerDetection from './modules/detection/P2PDominantSpeakerDetection';
  24. import VADAudioAnalyser from './modules/detection/VADAudioAnalyser';
  25. import VADNoiseDetection from './modules/detection/VADNoiseDetection';
  26. import VADTalkMutedDetection from './modules/detection/VADTalkMutedDetection';
  27. import { E2EEncryption } from './modules/e2ee/E2EEncryption';
  28. import E2ePing from './modules/e2eping/e2eping';
  29. import Jvb121EventGenerator from './modules/event/Jvb121EventGenerator';
  30. import { QualityController } from './modules/qualitycontrol/QualityController';
  31. import RecordingManager from './modules/recording/RecordingManager';
  32. import Settings from './modules/settings/Settings';
  33. import AudioOutputProblemDetector from './modules/statistics/AudioOutputProblemDetector';
  34. import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
  35. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  36. import Statistics from './modules/statistics/statistics';
  37. import Transcriber from './modules/transcription/transcriber';
  38. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  39. import RandomUtil from './modules/util/RandomUtil';
  40. import ComponentsVersions from './modules/version/ComponentsVersions';
  41. import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
  42. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  43. import { JITSI_MEET_MUC_TYPE } from './modules/xmpp/xmpp';
  44. import * as MediaType from './service/RTC/MediaType';
  45. import VideoType from './service/RTC/VideoType';
  46. import {
  47. ACTION_JINGLE_RESTART,
  48. ACTION_JINGLE_SI_RECEIVED,
  49. ACTION_JINGLE_SI_TIMEOUT,
  50. ACTION_JINGLE_TERMINATE,
  51. ACTION_P2P_DECLINED,
  52. ACTION_P2P_ESTABLISHED,
  53. ACTION_P2P_FAILED,
  54. ACTION_P2P_SWITCH_TO_JVB,
  55. ICE_ESTABLISHMENT_DURATION_DIFF,
  56. createConferenceEvent,
  57. createJingleEvent,
  58. createP2PEvent
  59. } from './service/statistics/AnalyticsEvents';
  60. import * as XMPPEvents from './service/xmpp/XMPPEvents';
  61. const logger = getLogger(__filename);
  62. /**
  63. * How long since Jicofo is supposed to send a session-initiate, before
  64. * {@link ACTION_JINGLE_SI_TIMEOUT} analytics event is sent (in ms).
  65. * @type {number}
  66. */
  67. const JINGLE_SI_TIMEOUT = 5000;
  68. /**
  69. * Creates a JitsiConference object with the given name and properties.
  70. * Note: this constructor is not a part of the public API (objects should be
  71. * created using JitsiConnection.createConference).
  72. * @param options.config properties / settings related to the conference that
  73. * will be created.
  74. * @param options.name the name of the conference
  75. * @param options.connection the JitsiConnection object for this
  76. * JitsiConference.
  77. * @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
  78. * collected by {@link AvgRTPStatsReporter}, before arithmetic mean is
  79. * calculated and submitted to the analytics module.
  80. * @param {boolean} [options.config.enableIceRestart=false] - enables the ICE
  81. * restart logic.
  82. * @param {boolean} [options.config.p2p.enabled] when set to <tt>true</tt>
  83. * the peer to peer mode will be enabled. It means that when there are only 2
  84. * participants in the conference an attempt to make direct connection will be
  85. * made. If the connection succeeds the conference will stop sending data
  86. * through the JVB connection and will use the direct one instead.
  87. * @param {number} [options.config.p2p.backToP2PDelay=5] a delay given in
  88. * seconds, before the conference switches back to P2P, after the 3rd
  89. * participant has left the room.
  90. * @param {number} [options.config.channelLastN=-1] The requested amount of
  91. * videos are going to be delivered after the value is in effect. Set to -1 for
  92. * unlimited or all available videos.
  93. * @param {number} [options.config.forceJVB121Ratio]
  94. * "Math.random() < forceJVB121Ratio" will determine whether a 2 people
  95. * conference should be moved to the JVB instead of P2P. The decision is made on
  96. * the responder side, after ICE succeeds on the P2P connection.
  97. * @param {*} [options.config.openBridgeChannel] Which kind of communication to
  98. * open with the videobridge. Values can be "datachannel", "websocket", true
  99. * (treat it as "datachannel"), undefined (treat it as "datachannel") and false
  100. * (don't open any channel).
  101. * @constructor
  102. *
  103. * FIXME Make all methods which are called from lib-internal classes
  104. * to non-public (use _). To name a few:
  105. * {@link JitsiConference.onLocalRoleChanged}
  106. * {@link JitsiConference.onUserRoleChanged}
  107. * {@link JitsiConference.onMemberLeft}
  108. * and so on...
  109. */
  110. export default function JitsiConference(options) {
  111. if (!options.name || options.name.toLowerCase() !== options.name) {
  112. const errmsg
  113. = 'Invalid conference name (no conference name passed or it '
  114. + 'contains invalid characters like capital letters)!';
  115. logger.error(errmsg);
  116. throw new Error(errmsg);
  117. }
  118. this.eventEmitter = new EventEmitter();
  119. this.options = options;
  120. this.eventManager = new JitsiConferenceEventManager(this);
  121. this.participants = {};
  122. this._init(options);
  123. this.componentsVersions = new ComponentsVersions(this);
  124. /**
  125. * Jingle session instance for the JVB connection.
  126. * @type {JingleSessionPC}
  127. */
  128. this.jvbJingleSession = null;
  129. this.lastDominantSpeaker = null;
  130. this.dtmfManager = null;
  131. this.somebodySupportsDTMF = false;
  132. this.authEnabled = false;
  133. this.startAudioMuted = false;
  134. this.startVideoMuted = false;
  135. this.startMutedPolicy = {
  136. audio: false,
  137. video: false
  138. };
  139. this.isMutedByFocus = false;
  140. // when muted by focus we receive the jid of the initiator of the mute
  141. this.mutedByFocusActor = null;
  142. // Flag indicates if the 'onCallEnded' method was ever called on this
  143. // instance. Used to log extra analytics event for debugging purpose.
  144. // We need to know if the potential issue happened before or after
  145. // the restart.
  146. this.wasStopped = false;
  147. // Conference properties, maintained by jicofo.
  148. this.properties = {};
  149. /**
  150. * The object which monitors local and remote connection statistics (e.g.
  151. * sending bitrate) and calculates a number which represents the connection
  152. * quality.
  153. */
  154. this.connectionQuality
  155. = new ConnectionQuality(this, this.eventEmitter, options);
  156. /**
  157. * Reports average RTP statistics to the analytics module.
  158. * @type {AvgRTPStatsReporter}
  159. */
  160. this.avgRtpStatsReporter
  161. = new AvgRTPStatsReporter(this, options.config.avgRtpStatsN || 15);
  162. /**
  163. * Detects issues with the audio of remote participants.
  164. * @type {AudioOutputProblemDetector}
  165. */
  166. this._audioOutputProblemDetector = new AudioOutputProblemDetector(this);
  167. /**
  168. * Indicates whether the connection is interrupted or not.
  169. */
  170. this.isJvbConnectionInterrupted = false;
  171. /**
  172. * The object which tracks active speaker times
  173. */
  174. this.speakerStatsCollector = new SpeakerStatsCollector(this);
  175. /* P2P related fields below: */
  176. /**
  177. * Stores reference to deferred start P2P task. It's created when 3rd
  178. * participant leaves the room in order to avoid ping pong effect (it
  179. * could be just a page reload).
  180. * @type {number|null}
  181. */
  182. this.deferredStartP2PTask = null;
  183. const delay
  184. = parseInt(options.config.p2p && options.config.p2p.backToP2PDelay, 10);
  185. /**
  186. * A delay given in seconds, before the conference switches back to P2P
  187. * after the 3rd participant has left.
  188. * @type {number}
  189. */
  190. this.backToP2PDelay = isNaN(delay) ? 5 : delay;
  191. logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
  192. /**
  193. * If set to <tt>true</tt> it means the P2P ICE is no longer connected.
  194. * When <tt>false</tt> it means that P2P ICE (media) connection is up
  195. * and running.
  196. * @type {boolean}
  197. */
  198. this.isP2PConnectionInterrupted = false;
  199. /**
  200. * Flag set to <tt>true</tt> when P2P session has been established
  201. * (ICE has been connected) and this conference is currently in the peer to
  202. * peer mode (P2P connection is the active one).
  203. * @type {boolean}
  204. */
  205. this.p2p = false;
  206. /**
  207. * A JingleSession for the direct peer to peer connection.
  208. * @type {JingleSessionPC}
  209. */
  210. this.p2pJingleSession = null;
  211. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  212. this.recordingManager = new RecordingManager(this.room);
  213. /**
  214. * If the conference.joined event has been sent this will store the timestamp when it happened.
  215. *
  216. * @type {undefined|number}
  217. * @private
  218. */
  219. this._conferenceJoinAnalyticsEventSent = undefined;
  220. /**
  221. * End-to-End Encryption. Make it available if supported.
  222. */
  223. if (this.isE2EESupported()) {
  224. logger.info('End-to-End Encryprtion is supported');
  225. this._e2eEncryption = new E2EEncryption(this);
  226. }
  227. }
  228. // FIXME convert JitsiConference to ES6 - ASAP !
  229. JitsiConference.prototype.constructor = JitsiConference;
  230. /**
  231. * Create a resource for the a jid. We use the room nickname (the resource part
  232. * of the occupant JID, see XEP-0045) as the endpoint ID in colibri. We require
  233. * endpoint IDs to be 8 hex digits because in some cases they get serialized
  234. * into a 32bit field.
  235. *
  236. * @param {string} jid - The id set onto the XMPP connection.
  237. * @param {boolean} isAuthenticatedUser - Whether or not the user has connected
  238. * to the XMPP service with a password.
  239. * @returns {string}
  240. * @static
  241. */
  242. JitsiConference.resourceCreator = function(jid, isAuthenticatedUser) {
  243. let mucNickname;
  244. if (isAuthenticatedUser) {
  245. // For authenticated users generate a random ID.
  246. mucNickname = RandomUtil.randomHexString(8).toLowerCase();
  247. } else {
  248. // We try to use the first part of the node (which for anonymous users
  249. // on prosody is a UUID) to match the previous behavior (and maybe make
  250. // debugging easier).
  251. mucNickname = Strophe.getNodeFromJid(jid).substr(0, 8)
  252. .toLowerCase();
  253. // But if this doesn't have the required format we just generate a new
  254. // random nickname.
  255. const re = /[0-9a-f]{8}/g;
  256. if (!re.test(mucNickname)) {
  257. mucNickname = RandomUtil.randomHexString(8).toLowerCase();
  258. }
  259. }
  260. return mucNickname;
  261. };
  262. /**
  263. * Initializes the conference object properties
  264. * @param options {object}
  265. * @param options.connection {JitsiConnection} overrides this.connection
  266. */
  267. JitsiConference.prototype._init = function(options = {}) {
  268. // Override connection and xmpp properties (Useful if the connection
  269. // reloaded)
  270. if (options.connection) {
  271. this.connection = options.connection;
  272. this.xmpp = this.connection.xmpp;
  273. // Setup XMPP events only if we have new connection object.
  274. this.eventManager.setupXMPPListeners();
  275. }
  276. const { config } = this.options;
  277. this._statsCurrentId = config.statisticsId ? config.statisticsId : Settings.callStatsUserName;
  278. this.room = this.xmpp.createRoom(
  279. this.options.name, {
  280. ...config,
  281. statsId: this._statsCurrentId
  282. },
  283. JitsiConference.resourceCreator
  284. );
  285. // Connection interrupted/restored listeners
  286. this._onIceConnectionInterrupted
  287. = this._onIceConnectionInterrupted.bind(this);
  288. this.room.addListener(
  289. XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
  290. this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
  291. this.room.addListener(
  292. XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
  293. this._onIceConnectionEstablished
  294. = this._onIceConnectionEstablished.bind(this);
  295. this.room.addListener(
  296. XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
  297. this._updateProperties = this._updateProperties.bind(this);
  298. this.room.addListener(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
  299. this._updateProperties);
  300. this._sendConferenceJoinAnalyticsEvent = this._sendConferenceJoinAnalyticsEvent.bind(this);
  301. this.room.addListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
  302. this.e2eping = new E2ePing(
  303. this,
  304. config,
  305. (message, to) => {
  306. try {
  307. this.sendMessage(
  308. message, to, true /* sendThroughVideobridge */);
  309. } catch (error) {
  310. logger.warn('Failed to send E2E ping request or response.', error && error.msg);
  311. }
  312. });
  313. if (!this.rtc) {
  314. this.rtc = new RTC(this, options);
  315. this.eventManager.setupRTCListeners();
  316. }
  317. this.qualityController = new QualityController(this);
  318. this.participantConnectionStatus
  319. = new ParticipantConnectionStatusHandler(
  320. this.rtc,
  321. this,
  322. {
  323. // Both these options are not public API, leaving it here only
  324. // as an entry point through config for tuning up purposes.
  325. // Default values should be adjusted as soon as optimal values
  326. // are discovered.
  327. rtcMuteTimeout: config._peerConnStatusRtcMuteTimeout,
  328. outOfLastNTimeout: config._peerConnStatusOutOfLastNTimeout
  329. });
  330. this.participantConnectionStatus.init();
  331. // Add the ability to enable callStats only on a percentage of users based on config.js settings.
  332. let enableCallStats = true;
  333. if (config.testing && config.testing.callStatsThreshold) {
  334. enableCallStats = (Math.random() * 100) <= config.testing.callStatsThreshold;
  335. }
  336. if (!this.statistics) {
  337. this.statistics = new Statistics(this.xmpp, {
  338. aliasName: this._statsCurrentId,
  339. userName: config.statisticsDisplayName ? config.statisticsDisplayName : this.myUserId(),
  340. confID: config.confID || `${this.connection.options.hosts.domain}/${this.options.name}`,
  341. siteID: config.siteID,
  342. customScriptUrl: config.callStatsCustomScriptUrl,
  343. callStatsID: config.callStatsID,
  344. callStatsSecret: config.callStatsSecret,
  345. callStatsApplicationLogsDisabled: config.callStatsApplicationLogsDisabled,
  346. enableCallStats,
  347. roomName: this.options.name,
  348. applicationName: config.applicationName,
  349. getWiFiStatsMethod: config.getWiFiStatsMethod
  350. });
  351. Statistics.analytics.addPermanentProperties({
  352. 'callstats_name': this._statsCurrentId
  353. });
  354. // Start performance observer for monitoring long tasks
  355. if (config.longTasksStatsInterval) {
  356. this.statistics.attachLongTasksStats(this);
  357. }
  358. }
  359. this.eventManager.setupChatRoomListeners();
  360. // Always add listeners because on reload we are executing leave and the
  361. // listeners are removed from statistics module.
  362. this.eventManager.setupStatisticsListeners();
  363. // Disable VAD processing on Safari since it causes audio input to
  364. // fail on some of the mobile devices.
  365. if (config.enableTalkWhileMuted && !browser.isSafari()) {
  366. // If VAD processor factory method is provided uses VAD based detection, otherwise fallback to audio level
  367. // based detection.
  368. if (config.createVADProcessor) {
  369. logger.info('Using VAD detection for generating talk while muted events');
  370. if (!this._audioAnalyser) {
  371. this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
  372. }
  373. const vadTalkMutedDetection = new VADTalkMutedDetection();
  374. vadTalkMutedDetection.on(DetectionEvents.VAD_TALK_WHILE_MUTED, () =>
  375. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
  376. this._audioAnalyser.addVADDetectionService(vadTalkMutedDetection);
  377. } else {
  378. logger.warn('No VAD Processor was provided. Talk while muted detection service was not initialized!');
  379. }
  380. }
  381. // Disable noisy mic detection on safari since it causes the audio input to
  382. // fail on Safari on iPadOS.
  383. if (config.enableNoisyMicDetection && !browser.isSafari()) {
  384. if (config.createVADProcessor) {
  385. if (!this._audioAnalyser) {
  386. this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
  387. }
  388. const vadNoiseDetection = new VADNoiseDetection();
  389. vadNoiseDetection.on(DetectionEvents.VAD_NOISY_DEVICE, () =>
  390. this.eventEmitter.emit(JitsiConferenceEvents.NOISY_MIC));
  391. this._audioAnalyser.addVADDetectionService(vadNoiseDetection);
  392. } else {
  393. logger.warn('No VAD Processor was provided. Noisy microphone detection service was not initialized!');
  394. }
  395. }
  396. // Generates events based on no audio input detector.
  397. if (config.enableNoAudioDetection) {
  398. this._noAudioSignalDetection = new NoAudioSignalDetection(this);
  399. this._noAudioSignalDetection.on(DetectionEvents.NO_AUDIO_INPUT, () => {
  400. this.eventEmitter.emit(JitsiConferenceEvents.NO_AUDIO_INPUT);
  401. });
  402. this._noAudioSignalDetection.on(DetectionEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal => {
  403. this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal);
  404. });
  405. }
  406. if ('channelLastN' in config) {
  407. this.setLastN(config.channelLastN);
  408. }
  409. /**
  410. * Emits {@link JitsiConferenceEvents.JVB121_STATUS}.
  411. * @type {Jvb121EventGenerator}
  412. */
  413. this.jvb121Status = new Jvb121EventGenerator(this);
  414. // creates dominant speaker detection that works only in p2p mode
  415. this.p2pDominantSpeakerDetection = new P2PDominantSpeakerDetection(this);
  416. if (config && config.deploymentInfo && config.deploymentInfo.userRegion) {
  417. this.setLocalParticipantProperty(
  418. 'region', config.deploymentInfo.userRegion);
  419. }
  420. };
  421. /**
  422. * Joins the conference.
  423. * @param password {string} the password
  424. */
  425. JitsiConference.prototype.join = function(password) {
  426. if (this.room) {
  427. this.room.join(password).then(() => this._maybeSetSITimeout());
  428. }
  429. };
  430. /**
  431. * Authenticates and upgrades the role of the local participant/user.
  432. *
  433. * @returns {Object} A <tt>thenable</tt> which (1) settles when the process of
  434. * authenticating and upgrading the role of the local participant/user finishes
  435. * and (2) has a <tt>cancel</tt> method that allows the caller to interrupt the
  436. * process.
  437. */
  438. JitsiConference.prototype.authenticateAndUpgradeRole = function(options) {
  439. return authenticateAndUpgradeRole.call(this, {
  440. ...options,
  441. onCreateResource: JitsiConference.resourceCreator
  442. });
  443. };
  444. /**
  445. * Check if joined to the conference.
  446. */
  447. JitsiConference.prototype.isJoined = function() {
  448. return this.room && this.room.joined;
  449. };
  450. /**
  451. * Tells whether or not the P2P mode is enabled in the configuration.
  452. * @return {boolean}
  453. */
  454. JitsiConference.prototype.isP2PEnabled = function() {
  455. return Boolean(this.options.config.p2p && this.options.config.p2p.enabled)
  456. // FIXME: remove once we have a default config template. -saghul
  457. || typeof this.options.config.p2p === 'undefined';
  458. };
  459. /**
  460. * When in P2P test mode, the conference will not automatically switch to P2P
  461. * when there 2 participants.
  462. * @return {boolean}
  463. */
  464. JitsiConference.prototype.isP2PTestModeEnabled = function() {
  465. return Boolean(this.options.config.testing
  466. && this.options.config.testing.p2pTestMode);
  467. };
  468. /**
  469. * Leaves the conference.
  470. * @returns {Promise}
  471. */
  472. JitsiConference.prototype.leave = function() {
  473. if (this.participantConnectionStatus) {
  474. this.participantConnectionStatus.dispose();
  475. this.participantConnectionStatus = null;
  476. }
  477. if (this.avgRtpStatsReporter) {
  478. this.avgRtpStatsReporter.dispose();
  479. this.avgRtpStatsReporter = null;
  480. }
  481. if (this._audioOutputProblemDetector) {
  482. this._audioOutputProblemDetector.dispose();
  483. this._audioOutputProblemDetector = null;
  484. }
  485. if (this.e2eping) {
  486. this.e2eping.stop();
  487. this.e2eping = null;
  488. }
  489. this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
  490. this.rtc.closeBridgeChannel();
  491. this._sendConferenceLeftAnalyticsEvent();
  492. if (this.statistics) {
  493. this.statistics.dispose();
  494. }
  495. this._delayedIceFailed && this._delayedIceFailed.cancel();
  496. // Close both JVb and P2P JingleSessions
  497. if (this.jvbJingleSession) {
  498. this.jvbJingleSession.close();
  499. this.jvbJingleSession = null;
  500. }
  501. if (this.p2pJingleSession) {
  502. this.p2pJingleSession.close();
  503. this.p2pJingleSession = null;
  504. }
  505. // leave the conference
  506. if (this.room) {
  507. const room = this.room;
  508. // Unregister connection state listeners
  509. room.removeListener(
  510. XMPPEvents.CONNECTION_INTERRUPTED,
  511. this._onIceConnectionInterrupted);
  512. room.removeListener(
  513. XMPPEvents.CONNECTION_RESTORED,
  514. this._onIceConnectionRestored);
  515. room.removeListener(
  516. XMPPEvents.CONNECTION_ESTABLISHED,
  517. this._onIceConnectionEstablished);
  518. room.removeListener(
  519. XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
  520. this._updateProperties);
  521. room.removeListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
  522. this.eventManager.removeXMPPListeners();
  523. this.room = null;
  524. return room.leave()
  525. .then(() => {
  526. if (this.rtc) {
  527. this.rtc.destroy();
  528. }
  529. })
  530. .catch(error => {
  531. // remove all participants because currently the conference
  532. // won't be usable anyway. This is done on success automatically
  533. // by the ChatRoom instance.
  534. this.getParticipants().forEach(
  535. participant => this.onMemberLeft(participant.getJid()));
  536. throw error;
  537. });
  538. }
  539. // If this.room == null we are calling second time leave().
  540. return Promise.reject(
  541. new Error('The conference is has been already left'));
  542. };
  543. /**
  544. * Returns the currently active media session if any.
  545. *
  546. * @returns {JingleSessionPC|undefined}
  547. * @private
  548. */
  549. JitsiConference.prototype._getActiveMediaSession = function() {
  550. return this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
  551. };
  552. /**
  553. * Returns an array containing all media sessions existing in this conference.
  554. *
  555. * @returns {Array<JingleSessionPC>}
  556. * @private
  557. */
  558. JitsiConference.prototype._getMediaSessions = function() {
  559. const sessions = [];
  560. this.jvbJingleSession && sessions.push(this.jvbJingleSession);
  561. this.p2pJingleSession && sessions.push(this.p2pJingleSession);
  562. return sessions;
  563. };
  564. /**
  565. * Returns name of this conference.
  566. */
  567. JitsiConference.prototype.getName = function() {
  568. return this.options.name;
  569. };
  570. /**
  571. * Returns the {@link JitsiConnection} used by this this conference.
  572. */
  573. JitsiConference.prototype.getConnection = function() {
  574. return this.connection;
  575. };
  576. /**
  577. * Check if authentication is enabled for this conference.
  578. */
  579. JitsiConference.prototype.isAuthEnabled = function() {
  580. return this.authEnabled;
  581. };
  582. /**
  583. * Check if user is logged in.
  584. */
  585. JitsiConference.prototype.isLoggedIn = function() {
  586. return Boolean(this.authIdentity);
  587. };
  588. /**
  589. * Get authorized login.
  590. */
  591. JitsiConference.prototype.getAuthLogin = function() {
  592. return this.authIdentity;
  593. };
  594. /**
  595. * Check if external authentication is enabled for this conference.
  596. */
  597. JitsiConference.prototype.isExternalAuthEnabled = function() {
  598. return this.room && this.room.moderator.isExternalAuthEnabled();
  599. };
  600. /**
  601. * Get url for external authentication.
  602. * @param {boolean} [urlForPopup] if true then return url for login popup,
  603. * else url of login page.
  604. * @returns {Promise}
  605. */
  606. JitsiConference.prototype.getExternalAuthUrl = function(urlForPopup) {
  607. return new Promise((resolve, reject) => {
  608. if (!this.isExternalAuthEnabled()) {
  609. reject();
  610. return;
  611. }
  612. if (urlForPopup) {
  613. this.room.moderator.getPopupLoginUrl(resolve, reject);
  614. } else {
  615. this.room.moderator.getLoginUrl(resolve, reject);
  616. }
  617. });
  618. };
  619. /**
  620. * Returns the local tracks of the given media type, or all local tracks if no
  621. * specific type is given.
  622. * @param {MediaType} [mediaType] Optional media type (audio or video).
  623. */
  624. JitsiConference.prototype.getLocalTracks = function(mediaType) {
  625. let tracks = [];
  626. if (this.rtc) {
  627. tracks = this.rtc.getLocalTracks(mediaType);
  628. }
  629. return tracks;
  630. };
  631. /**
  632. * Obtains local audio track.
  633. * @return {JitsiLocalTrack|null}
  634. */
  635. JitsiConference.prototype.getLocalAudioTrack = function() {
  636. return this.rtc ? this.rtc.getLocalAudioTrack() : null;
  637. };
  638. /**
  639. * Obtains local video track.
  640. * @return {JitsiLocalTrack|null}
  641. */
  642. JitsiConference.prototype.getLocalVideoTrack = function() {
  643. return this.rtc ? this.rtc.getLocalVideoTrack() : null;
  644. };
  645. /**
  646. * Obtains the performance statistics.
  647. * @returns {Object|null}
  648. */
  649. JitsiConference.prototype.getPerformanceStats = function() {
  650. return {
  651. longTasksStats: this.statistics.getLongTasksStats()
  652. };
  653. };
  654. /**
  655. * Attaches a handler for events(For example - "participant joined".) in the
  656. * conference. All possible event are defined in JitsiConferenceEvents.
  657. * @param eventId the event ID.
  658. * @param handler handler for the event.
  659. *
  660. * Note: consider adding eventing functionality by extending an EventEmitter
  661. * impl, instead of rolling ourselves
  662. */
  663. JitsiConference.prototype.on = function(eventId, handler) {
  664. if (this.eventEmitter) {
  665. this.eventEmitter.on(eventId, handler);
  666. }
  667. };
  668. /**
  669. * Removes event listener
  670. * @param eventId the event ID.
  671. * @param [handler] optional, the specific handler to unbind
  672. *
  673. * Note: consider adding eventing functionality by extending an EventEmitter
  674. * impl, instead of rolling ourselves
  675. */
  676. JitsiConference.prototype.off = function(eventId, handler) {
  677. if (this.eventEmitter) {
  678. this.eventEmitter.removeListener(eventId, handler);
  679. }
  680. };
  681. // Common aliases for event emitter
  682. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  683. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  684. /**
  685. * Receives notifications from other participants about commands / custom events
  686. * (sent by sendCommand or sendCommandOnce methods).
  687. * @param command {String} the name of the command
  688. * @param handler {Function} handler for the command
  689. */
  690. JitsiConference.prototype.addCommandListener = function(command, handler) {
  691. if (this.room) {
  692. this.room.addPresenceListener(command, handler);
  693. }
  694. };
  695. /**
  696. * Removes command listener
  697. * @param command {String} the name of the command
  698. * @param handler {Function} handler to remove for the command
  699. */
  700. JitsiConference.prototype.removeCommandListener = function(command, handler) {
  701. if (this.room) {
  702. this.room.removePresenceListener(command, handler);
  703. }
  704. };
  705. /**
  706. * Sends text message to the other participants in the conference
  707. * @param message the text message.
  708. * @param elementName the element name to encapsulate the message.
  709. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  710. */
  711. JitsiConference.prototype.sendTextMessage = function(
  712. message, elementName = 'body') {
  713. if (this.room) {
  714. const displayName = (this.room.getFromPresence('nick') || {}).value;
  715. this.room.sendMessage(message, elementName, displayName);
  716. }
  717. };
  718. /**
  719. * Send private text message to another participant of the conference
  720. * @param id the id of the participant to send a private message.
  721. * @param message the text message.
  722. * @param elementName the element name to encapsulate the message.
  723. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  724. */
  725. JitsiConference.prototype.sendPrivateTextMessage = function(
  726. id, message, elementName = 'body') {
  727. if (this.room) {
  728. this.room.sendPrivateMessage(id, message, elementName);
  729. }
  730. };
  731. /**
  732. * Send presence command.
  733. * @param name {String} the name of the command.
  734. * @param values {Object} with keys and values that will be sent.
  735. **/
  736. JitsiConference.prototype.sendCommand = function(name, values) {
  737. if (this.room) {
  738. this.room.addToPresence(name, values);
  739. this.room.sendPresence();
  740. } else {
  741. logger.warn('Not sending a command, room not initialized.');
  742. }
  743. };
  744. /**
  745. * Send presence command one time.
  746. * @param name {String} the name of the command.
  747. * @param values {Object} with keys and values that will be sent.
  748. **/
  749. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  750. this.sendCommand(name, values);
  751. this.removeCommand(name);
  752. };
  753. /**
  754. * Removes presence command.
  755. * @param name {String} the name of the command.
  756. **/
  757. JitsiConference.prototype.removeCommand = function(name) {
  758. if (this.room) {
  759. this.room.removeFromPresence(name);
  760. }
  761. };
  762. /**
  763. * Sets the display name for this conference.
  764. * @param name the display name to set
  765. */
  766. JitsiConference.prototype.setDisplayName = function(name) {
  767. if (this.room) {
  768. this.room.addToPresence('nick', {
  769. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  770. value: name
  771. });
  772. this.room.sendPresence();
  773. }
  774. };
  775. /**
  776. * Set new subject for this conference. (available only for moderator)
  777. * @param {string} subject new subject
  778. */
  779. JitsiConference.prototype.setSubject = function(subject) {
  780. if (this.room && this.isModerator()) {
  781. this.room.setSubject(subject);
  782. }
  783. };
  784. /**
  785. * Get a transcriber object for all current participants in this conference
  786. * @return {Transcriber} the transcriber object
  787. */
  788. JitsiConference.prototype.getTranscriber = function() {
  789. if (this.transcriber === undefined) {
  790. this.transcriber = new Transcriber();
  791. // add all existing local audio tracks to the transcriber
  792. const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
  793. for (const localAudio of localAudioTracks) {
  794. this.transcriber.addTrack(localAudio);
  795. }
  796. // and all remote audio tracks
  797. const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
  798. for (const remoteTrack of remoteAudioTracks) {
  799. this.transcriber.addTrack(remoteTrack);
  800. }
  801. }
  802. return this.transcriber;
  803. };
  804. /**
  805. * Returns the transcription status.
  806. *
  807. * @returns {String} "on" or "off".
  808. */
  809. JitsiConference.prototype.getTranscriptionStatus = function() {
  810. return this.room.transcriptionStatus;
  811. };
  812. /**
  813. * Adds JitsiLocalTrack object to the conference.
  814. * @param track the JitsiLocalTrack object.
  815. * @returns {Promise<JitsiLocalTrack>}
  816. * @throws {Error} if the specified track is a video track and there is already
  817. * another video track in the conference.
  818. */
  819. JitsiConference.prototype.addTrack = function(track) {
  820. if (track.isVideoTrack()) {
  821. // Ensure there's exactly 1 local video track in the conference.
  822. const localVideoTrack = this.rtc.getLocalVideoTrack();
  823. if (localVideoTrack) {
  824. // Don't be excessively harsh and severe if the API client happens
  825. // to attempt to add the same local video track twice.
  826. if (track === localVideoTrack) {
  827. return Promise.resolve(track);
  828. }
  829. return Promise.reject(new Error(
  830. 'cannot add second video track to the conference'));
  831. }
  832. }
  833. return this.replaceTrack(null, track);
  834. };
  835. /**
  836. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
  837. * @param {number} audioLevel the audio level
  838. * @param {TraceablePeerConnection} [tpc]
  839. */
  840. JitsiConference.prototype._fireAudioLevelChangeEvent = function(
  841. audioLevel,
  842. tpc) {
  843. const activeTpc = this.getActivePeerConnection();
  844. // There will be no TraceablePeerConnection if audio levels do not come from
  845. // a peerconnection. LocalStatsCollector.js measures audio levels using Web
  846. // Audio Analyser API and emits local audio levels events through
  847. // JitsiTrack.setAudioLevel, but does not provide TPC instance which is
  848. // optional.
  849. if (!tpc || activeTpc === tpc) {
  850. this.eventEmitter.emit(
  851. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  852. this.myUserId(), audioLevel);
  853. }
  854. };
  855. /**
  856. * Fires TRACK_MUTE_CHANGED change conference event.
  857. * @param track the JitsiTrack object related to the event.
  858. */
  859. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  860. // check if track was muted by focus and now is unmuted by user
  861. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  862. this.isMutedByFocus = false;
  863. // unmute local user on server
  864. this.room.muteParticipant(this.room.myroomjid, false);
  865. }
  866. let actorParticipant;
  867. if (this.mutedByFocusActor) {
  868. const actorId = Strophe.getResourceFromJid(this.mutedByFocusActor);
  869. actorParticipant = this.participants[actorId];
  870. }
  871. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track, actorParticipant);
  872. };
  873. /**
  874. * Clear JitsiLocalTrack properties and listeners.
  875. * @param track the JitsiLocalTrack object.
  876. */
  877. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  878. track._setConference(null);
  879. this.rtc.removeLocalTrack(track);
  880. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  881. track.muteHandler);
  882. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  883. track.audioLevelHandler);
  884. // send event for stopping screen sharing
  885. // FIXME: we assume we have only one screen sharing track
  886. // if we change this we need to fix this check
  887. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP) {
  888. this.statistics.sendScreenSharingEvent(false);
  889. }
  890. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  891. };
  892. /**
  893. * Removes JitsiLocalTrack from the conference and performs
  894. * a new offer/answer cycle.
  895. * @param {JitsiLocalTrack} track
  896. * @returns {Promise}
  897. */
  898. JitsiConference.prototype.removeTrack = function(track) {
  899. return this.replaceTrack(track, null);
  900. };
  901. /**
  902. * Replaces oldTrack with newTrack and performs a single offer/answer
  903. * cycle after both operations are done. Either oldTrack or newTrack
  904. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  905. * effectively just removes 'oldTrack'
  906. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  907. * @param {JitsiLocalTrack} newTrack the new stream to use
  908. * @returns {Promise} resolves when the replacement is finished
  909. */
  910. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  911. // First do the removal of the oldTrack at the JitsiConference level
  912. if (oldTrack) {
  913. if (oldTrack.disposed) {
  914. return Promise.reject(
  915. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  916. }
  917. }
  918. if (newTrack) {
  919. if (newTrack.disposed) {
  920. return Promise.reject(
  921. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  922. }
  923. }
  924. // Now replace the stream at the lower levels
  925. return this._doReplaceTrack(oldTrack, newTrack)
  926. .then(() => {
  927. if (oldTrack) {
  928. this.onLocalTrackRemoved(oldTrack);
  929. }
  930. if (newTrack) {
  931. // Now handle the addition of the newTrack at the
  932. // JitsiConference level
  933. this._setupNewTrack(newTrack);
  934. }
  935. return Promise.resolve();
  936. }, error => Promise.reject(new Error(error)));
  937. };
  938. /**
  939. * Replaces the tracks at the lower level by going through the Jingle session
  940. * and WebRTC peer connection. The method will resolve immediately if there is
  941. * currently no JingleSession started.
  942. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  943. * the process or <tt>null</t> if the method should act as "add track"
  944. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  945. * <tt>null</tt> if the method should act as "remove track"
  946. * @return {Promise} resolved when the process is done or rejected with a string
  947. * which describes the error.
  948. * @private
  949. */
  950. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  951. const replaceTrackPromises = [];
  952. if (this.jvbJingleSession) {
  953. replaceTrackPromises.push(
  954. this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  955. } else {
  956. logger.info('_doReplaceTrack - no JVB JingleSession');
  957. }
  958. if (this.p2pJingleSession) {
  959. replaceTrackPromises.push(
  960. this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  961. } else {
  962. logger.info('_doReplaceTrack - no P2P JingleSession');
  963. }
  964. return Promise.all(replaceTrackPromises);
  965. };
  966. /**
  967. * Operations related to creating a new track
  968. * @param {JitsiLocalTrack} newTrack the new track being created
  969. */
  970. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  971. if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
  972. && newTrack.videoType !== VideoType.DESKTOP)) {
  973. // Report active device to statistics
  974. const devices = RTC.getCurrentlyAvailableMediaDevices();
  975. const device
  976. = devices.find(
  977. d =>
  978. d.kind === `${newTrack.getTrack().kind}input`
  979. && d.label === newTrack.getTrack().label);
  980. if (device) {
  981. Statistics.sendActiveDeviceListEvent(
  982. RTC.getEventDataForActiveDevice(device));
  983. }
  984. }
  985. if (newTrack.isVideoTrack()) {
  986. this.removeCommand('videoType');
  987. this.sendCommand('videoType', {
  988. value: newTrack.videoType,
  989. attributes: {
  990. xmlns: 'http://jitsi.org/jitmeet/video'
  991. }
  992. });
  993. }
  994. this.rtc.addLocalTrack(newTrack);
  995. // ensure that we're sharing proper "is muted" state
  996. if (newTrack.isAudioTrack()) {
  997. this.room.setAudioMute(newTrack.isMuted());
  998. } else {
  999. this.room.setVideoMute(newTrack.isMuted());
  1000. }
  1001. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  1002. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  1003. newTrack.addEventListener(
  1004. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1005. newTrack.muteHandler);
  1006. newTrack.addEventListener(
  1007. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1008. newTrack.audioLevelHandler);
  1009. newTrack._setConference(this);
  1010. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  1011. };
  1012. /**
  1013. * Method called by the {@link JitsiLocalTrack} (a video one) in order to add
  1014. * back the underlying WebRTC MediaStream to the PeerConnection (which has
  1015. * removed on video mute).
  1016. * @param {JitsiLocalTrack} track the local track that will be added as part of
  1017. * the unmute operation.
  1018. * @return {Promise} resolved when the process is done or rejected with a string
  1019. * which describes the error.
  1020. */
  1021. JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
  1022. const addAsUnmutePromises = [];
  1023. if (this.jvbJingleSession) {
  1024. addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
  1025. } else {
  1026. logger.info(
  1027. 'Add local MediaStream as unmute -'
  1028. + ' no JVB Jingle session started yet');
  1029. }
  1030. if (this.p2pJingleSession) {
  1031. addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
  1032. } else {
  1033. logger.info(
  1034. 'Add local MediaStream as unmute -'
  1035. + ' no P2P Jingle session started yet');
  1036. }
  1037. return Promise.all(addAsUnmutePromises);
  1038. };
  1039. /**
  1040. * Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
  1041. * the underlying WebRTC MediaStream from the PeerConnection. The purpose of
  1042. * that is to stop sending any data and turn off the HW camera device.
  1043. * @param {JitsiLocalTrack} track the local track that will be removed.
  1044. * @return {Promise}
  1045. */
  1046. JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
  1047. const removeAsMutePromises = [];
  1048. if (this.jvbJingleSession) {
  1049. removeAsMutePromises.push(
  1050. this.jvbJingleSession.removeTrackAsMute(track));
  1051. } else {
  1052. logger.info(
  1053. 'Remove local MediaStream - no JVB JingleSession started yet');
  1054. }
  1055. if (this.p2pJingleSession) {
  1056. removeAsMutePromises.push(
  1057. this.p2pJingleSession.removeTrackAsMute(track));
  1058. } else {
  1059. logger.info(
  1060. 'Remove local MediaStream - no P2P JingleSession started yet');
  1061. }
  1062. return Promise.all(removeAsMutePromises);
  1063. };
  1064. /**
  1065. * Get role of the local user.
  1066. * @returns {string} user role: 'moderator' or 'none'
  1067. */
  1068. JitsiConference.prototype.getRole = function() {
  1069. return this.room.role;
  1070. };
  1071. /**
  1072. * Returns whether or not the current conference has been joined as a hidden
  1073. * user.
  1074. *
  1075. * @returns {boolean|null} True if hidden, false otherwise. Will return null if
  1076. * no connection is active.
  1077. */
  1078. JitsiConference.prototype.isHidden = function() {
  1079. if (!this.connection) {
  1080. return null;
  1081. }
  1082. return Strophe.getDomainFromJid(this.connection.getJid())
  1083. === this.options.config.hiddenDomain;
  1084. };
  1085. /**
  1086. * Check if local user is moderator.
  1087. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  1088. * we're no longer in the conference room then <tt>null</tt> is returned.
  1089. */
  1090. JitsiConference.prototype.isModerator = function() {
  1091. return this.room ? this.room.isModerator() : null;
  1092. };
  1093. /**
  1094. * Set password for the room.
  1095. * @param {string} password new password for the room.
  1096. * @returns {Promise}
  1097. */
  1098. JitsiConference.prototype.lock = function(password) {
  1099. if (!this.isModerator()) {
  1100. return Promise.reject(new Error('You are not moderator.'));
  1101. }
  1102. return new Promise((resolve, reject) => {
  1103. this.room.lockRoom(
  1104. password || '',
  1105. () => resolve(),
  1106. err => reject(err),
  1107. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  1108. });
  1109. };
  1110. /**
  1111. * Remove password from the room.
  1112. * @returns {Promise}
  1113. */
  1114. JitsiConference.prototype.unlock = function() {
  1115. return this.lock();
  1116. };
  1117. /**
  1118. * Elects the participant with the given id to be the selected participant in
  1119. * order to receive higher video quality (if simulcast is enabled).
  1120. * Or cache it if channel is not created and send it once channel is available.
  1121. * @param participantId the identifier of the participant
  1122. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1123. * @returns {void}
  1124. */
  1125. JitsiConference.prototype.selectParticipant = function(participantId) {
  1126. this.selectParticipants([ participantId ]);
  1127. };
  1128. /*
  1129. * Elects participants with given ids to be the selected participants in order
  1130. * to receive higher video quality (if simulcast is enabled). The argument
  1131. * should be an array of participant id strings or an empty array; an error will
  1132. * be thrown if a non-array is passed in. The error is thrown as a layer of
  1133. * protection against passing an invalid argument, as the error will happen in
  1134. * the bridge and may not be visible in the client.
  1135. *
  1136. * @param {Array<strings>} participantIds - An array of identifiers for
  1137. * participants.
  1138. * @returns {void}
  1139. */
  1140. JitsiConference.prototype.selectParticipants = function(participantIds) {
  1141. if (!Array.isArray(participantIds)) {
  1142. throw new Error('Invalid argument; participantIds must be an array.');
  1143. }
  1144. this.rtc.selectEndpoints(participantIds);
  1145. };
  1146. /**
  1147. * Elects the participant with the given id to be the pinned participant in
  1148. * order to always receive video for this participant (even when last n is
  1149. * enabled).
  1150. * @param participantId the identifier of the participant
  1151. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1152. */
  1153. JitsiConference.prototype.pinParticipant = function(participantId) {
  1154. this.rtc.pinEndpoint(participantId);
  1155. };
  1156. /**
  1157. * Obtains the current value for "lastN". See {@link setLastN} for more info.
  1158. * @returns {number}
  1159. */
  1160. JitsiConference.prototype.getLastN = function() {
  1161. return this.rtc.getLastN();
  1162. };
  1163. /**
  1164. * Selects a new value for "lastN". The requested amount of videos are going
  1165. * to be delivered after the value is in effect. Set to -1 for unlimited or
  1166. * all available videos.
  1167. * @param lastN the new number of videos the user would like to receive.
  1168. * @throws Error or RangeError if the given value is not a number or is smaller
  1169. * than -1.
  1170. */
  1171. JitsiConference.prototype.setLastN = function(lastN) {
  1172. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  1173. throw new Error(`Invalid value for lastN: ${lastN}`);
  1174. }
  1175. const n = Number(lastN);
  1176. if (n < -1) {
  1177. throw new RangeError('lastN cannot be smaller than -1');
  1178. }
  1179. this.rtc.setLastN(n);
  1180. // If the P2P session is not fully established yet, we wait until it gets
  1181. // established.
  1182. if (this.p2pJingleSession) {
  1183. const isVideoActive = n !== 0;
  1184. this.p2pJingleSession
  1185. .setMediaTransferActive(true, isVideoActive)
  1186. .catch(error => {
  1187. logger.error(
  1188. `Failed to adjust video transfer status (${isVideoActive})`,
  1189. error);
  1190. });
  1191. }
  1192. };
  1193. /**
  1194. * Checks if the participant given by participantId is currently included in
  1195. * the last N.
  1196. * @param {string} participantId the identifier of the participant we would
  1197. * like to check.
  1198. * @return {boolean} true if the participant with id is in the last N set or
  1199. * if there's no last N set, false otherwise.
  1200. * @deprecated this method should never be used to figure out the UI, but
  1201. * {@link ParticipantConnectionStatus} should be used instead.
  1202. */
  1203. JitsiConference.prototype.isInLastN = function(participantId) {
  1204. return this.rtc.isInLastN(participantId);
  1205. };
  1206. /**
  1207. * @return Array<JitsiParticipant> an array of all participants in this
  1208. * conference.
  1209. */
  1210. JitsiConference.prototype.getParticipants = function() {
  1211. return Object.values(this.participants);
  1212. };
  1213. /**
  1214. * Returns the number of participants in the conference, including the local
  1215. * participant.
  1216. * @param countHidden {boolean} Whether or not to include hidden participants
  1217. * in the count. Default: false.
  1218. **/
  1219. JitsiConference.prototype.getParticipantCount
  1220. = function(countHidden = false) {
  1221. let participants = this.getParticipants();
  1222. if (!countHidden) {
  1223. participants = participants.filter(p => !p.isHidden());
  1224. }
  1225. // Add one for the local participant.
  1226. return participants.length + 1;
  1227. };
  1228. /**
  1229. * @returns {JitsiParticipant} the participant in this conference with the
  1230. * specified id (or undefined if there isn't one).
  1231. * @param id the id of the participant.
  1232. */
  1233. JitsiConference.prototype.getParticipantById = function(id) {
  1234. return this.participants[id];
  1235. };
  1236. /**
  1237. * Grant owner rights to the participant.
  1238. * @param {string} id id of the participant to grant owner rights to.
  1239. */
  1240. JitsiConference.prototype.grantOwner = function(id) {
  1241. const participant = this.getParticipantById(id);
  1242. if (!participant) {
  1243. return;
  1244. }
  1245. this.room.setAffiliation(participant.getJid(), 'owner');
  1246. };
  1247. /**
  1248. * Kick participant from this conference.
  1249. * @param {string} id id of the participant to kick
  1250. */
  1251. JitsiConference.prototype.kickParticipant = function(id) {
  1252. const participant = this.getParticipantById(id);
  1253. if (!participant) {
  1254. return;
  1255. }
  1256. this.room.kick(participant.getJid());
  1257. };
  1258. /**
  1259. * Maybe clears the timeout which emits {@link ACTION_JINGLE_SI_TIMEOUT}
  1260. * analytics event.
  1261. * @private
  1262. */
  1263. JitsiConference.prototype._maybeClearSITimeout = function() {
  1264. if (this._sessionInitiateTimeout
  1265. && (this.jvbJingleSession || this.getParticipantCount() < 2)) {
  1266. window.clearTimeout(this._sessionInitiateTimeout);
  1267. this._sessionInitiateTimeout = null;
  1268. }
  1269. };
  1270. /**
  1271. * Sets a timeout which will emit {@link ACTION_JINGLE_SI_TIMEOUT} analytics
  1272. * event.
  1273. * @private
  1274. */
  1275. JitsiConference.prototype._maybeSetSITimeout = function() {
  1276. // Jicofo is supposed to invite if there are at least 2 participants
  1277. if (!this.jvbJingleSession
  1278. && this.getParticipantCount() >= 2
  1279. && !this._sessionInitiateTimeout) {
  1280. this._sessionInitiateTimeout = window.setTimeout(() => {
  1281. this._sessionInitiateTimeout = null;
  1282. Statistics.sendAnalytics(createJingleEvent(
  1283. ACTION_JINGLE_SI_TIMEOUT,
  1284. {
  1285. p2p: false,
  1286. value: JINGLE_SI_TIMEOUT
  1287. }));
  1288. }, JINGLE_SI_TIMEOUT);
  1289. }
  1290. };
  1291. /**
  1292. * Mutes a participant.
  1293. * @param {string} id The id of the participant to mute.
  1294. */
  1295. JitsiConference.prototype.muteParticipant = function(id) {
  1296. const participant = this.getParticipantById(id);
  1297. if (!participant) {
  1298. return;
  1299. }
  1300. this.room.muteParticipant(participant.getJid(), true);
  1301. };
  1302. /* eslint-disable max-params */
  1303. /**
  1304. * Notifies this JitsiConference that a new member has joined its chat room.
  1305. *
  1306. * FIXME This should NOT be exposed!
  1307. *
  1308. * @param jid the jid of the participant in the MUC
  1309. * @param nick the display name of the participant
  1310. * @param role the role of the participant in the MUC
  1311. * @param isHidden indicates if this is a hidden participant (system
  1312. * participant for example a recorder).
  1313. * @param statsID the participant statsID (optional)
  1314. * @param status the initial status if any
  1315. * @param identity the member identity, if any
  1316. * @param botType the member botType, if any
  1317. */
  1318. JitsiConference.prototype.onMemberJoined = function(
  1319. jid, nick, role, isHidden, statsID, status, identity, botType) {
  1320. const id = Strophe.getResourceFromJid(jid);
  1321. if (id === 'focus' || this.myUserId() === id) {
  1322. return;
  1323. }
  1324. const participant
  1325. = new JitsiParticipant(jid, this, nick, isHidden, statsID, status, identity);
  1326. participant._role = role;
  1327. participant._botType = botType;
  1328. this.participants[id] = participant;
  1329. this.eventEmitter.emit(
  1330. JitsiConferenceEvents.USER_JOINED,
  1331. id,
  1332. participant);
  1333. this._updateFeatures(participant);
  1334. this._maybeStartOrStopP2P();
  1335. this._maybeSetSITimeout();
  1336. };
  1337. /* eslint-enable max-params */
  1338. /**
  1339. * Updates features for a participant.
  1340. * @param {JitsiParticipant} participant - The participant to query for features.
  1341. * @returns {void}
  1342. * @private
  1343. */
  1344. JitsiConference.prototype._updateFeatures = function(participant) {
  1345. participant.getFeatures()
  1346. .then(features => {
  1347. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  1348. this.updateDTMFSupport();
  1349. if (features.has('http://jitsi.org/protocol/jigasi')) {
  1350. participant.setProperty('features_jigasi', true);
  1351. }
  1352. if (features.has('https://jitsi.org/meet/e2ee')) {
  1353. participant.setProperty('features_e2ee', true);
  1354. }
  1355. })
  1356. .catch(() => false);
  1357. };
  1358. /**
  1359. * Get notified when member bot type had changed.
  1360. * @param jid the member jid
  1361. * @param botType the new botType value
  1362. * @private
  1363. */
  1364. JitsiConference.prototype._onMemberBotTypeChanged = function(jid, botType) {
  1365. // find the participant and mark it as non bot, as the real one will join
  1366. // in a moment
  1367. const peers = this.getParticipants();
  1368. const botParticipant = peers.find(p => p.getJid() === jid);
  1369. if (botParticipant) {
  1370. botParticipant._botType = botType;
  1371. const id = Strophe.getResourceFromJid(jid);
  1372. this.eventEmitter.emit(
  1373. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1374. id,
  1375. botType);
  1376. }
  1377. // if botType changed to undefined, botType was removed, in case of
  1378. // poltergeist mode this is the moment when the poltergeist had exited and
  1379. // the real participant had already replaced it.
  1380. // In this case we can check and try p2p
  1381. if (!botParticipant._botType) {
  1382. this._maybeStartOrStopP2P();
  1383. }
  1384. };
  1385. JitsiConference.prototype.onMemberLeft = function(jid) {
  1386. const id = Strophe.getResourceFromJid(jid);
  1387. if (id === 'focus' || this.myUserId() === id) {
  1388. return;
  1389. }
  1390. const participant = this.participants[id];
  1391. delete this.participants[id];
  1392. const removedTracks = this.rtc.removeRemoteTracks(id);
  1393. removedTracks.forEach(
  1394. track =>
  1395. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  1396. // there can be no participant in case the member that left is focus
  1397. if (participant) {
  1398. this.eventEmitter.emit(
  1399. JitsiConferenceEvents.USER_LEFT, id, participant);
  1400. }
  1401. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  1402. this._maybeClearSITimeout();
  1403. };
  1404. /**
  1405. * Designates an event indicating that we were kicked from the XMPP MUC.
  1406. * @param {boolean} isSelfPresence - whether it is for local participant
  1407. * or another participant.
  1408. * @param {string} actorId - the id of the participant who was initiator
  1409. * of the kick.
  1410. * @param {string?} kickedParticipantId - when it is not a kick for local participant,
  1411. * this is the id of the participant which was kicked.
  1412. */
  1413. JitsiConference.prototype.onMemberKicked = function(isSelfPresence, actorId, kickedParticipantId) {
  1414. // This check which be true when we kick someone else. With the introduction of lobby
  1415. // the ChatRoom KICKED event is now also emitted for ourselves (the kicker) so we want to
  1416. // avoid emitting an event where `undefined` kicked someone.
  1417. if (actorId === this.myUserId()) {
  1418. return;
  1419. }
  1420. const actorParticipant = this.participants[actorId];
  1421. if (isSelfPresence) {
  1422. this.eventEmitter.emit(
  1423. JitsiConferenceEvents.KICKED, actorParticipant);
  1424. this.leave();
  1425. return;
  1426. }
  1427. const kickedParticipant = this.participants[kickedParticipantId];
  1428. this.eventEmitter.emit(
  1429. JitsiConferenceEvents.PARTICIPANT_KICKED, actorParticipant, kickedParticipant);
  1430. };
  1431. /**
  1432. * Method called on local MUC role change.
  1433. * @param {string} role the name of new user's role as defined by XMPP MUC.
  1434. */
  1435. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  1436. // Emit role changed for local JID
  1437. this.eventEmitter.emit(
  1438. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  1439. };
  1440. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  1441. const id = Strophe.getResourceFromJid(jid);
  1442. const participant = this.getParticipantById(id);
  1443. if (!participant) {
  1444. return;
  1445. }
  1446. participant._role = role;
  1447. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  1448. };
  1449. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  1450. const id = Strophe.getResourceFromJid(jid);
  1451. const participant = this.getParticipantById(id);
  1452. if (!participant) {
  1453. return;
  1454. }
  1455. if (participant._displayName === displayName) {
  1456. return;
  1457. }
  1458. participant._displayName = displayName;
  1459. this.eventEmitter.emit(
  1460. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1461. id,
  1462. displayName);
  1463. };
  1464. /**
  1465. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  1466. * the conference.
  1467. *
  1468. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  1469. * JitsiConference
  1470. */
  1471. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  1472. if (track.isP2P && !this.isP2PActive()) {
  1473. logger.info(
  1474. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  1475. return;
  1476. } else if (!track.isP2P && this.isP2PActive()) {
  1477. logger.info(
  1478. 'Trying to add remote JVB track, when in P2P - IGNORED');
  1479. return;
  1480. }
  1481. const id = track.getParticipantId();
  1482. const participant = this.getParticipantById(id);
  1483. if (!participant) {
  1484. logger.error(`No participant found for id: ${id}`);
  1485. return;
  1486. }
  1487. // Add track to JitsiParticipant.
  1488. participant._tracks.push(track);
  1489. if (this.transcriber) {
  1490. this.transcriber.addTrack(track);
  1491. }
  1492. const emitter = this.eventEmitter;
  1493. track.addEventListener(
  1494. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1495. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1496. track.addEventListener(
  1497. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1498. (audioLevel, tpc) => {
  1499. const activeTPC = this.getActivePeerConnection();
  1500. if (activeTPC === tpc) {
  1501. emitter.emit(
  1502. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1503. id,
  1504. audioLevel);
  1505. }
  1506. }
  1507. );
  1508. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1509. };
  1510. /**
  1511. * Callback called by the Jingle plugin when 'session-answer' is received.
  1512. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1513. * received.
  1514. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1515. */
  1516. // eslint-disable-next-line no-unused-vars
  1517. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1518. if (this.p2pJingleSession === session) {
  1519. logger.info('P2P setAnswer');
  1520. this.p2pJingleSession.setAnswer(answer);
  1521. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, this.p2pJingleSession);
  1522. }
  1523. };
  1524. /**
  1525. * Callback called by the Jingle plugin when 'transport-info' is received.
  1526. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1527. * received
  1528. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1529. * element
  1530. */
  1531. // eslint-disable-next-line no-unused-vars
  1532. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1533. if (this.p2pJingleSession === session) {
  1534. logger.info('P2P addIceCandidates');
  1535. this.p2pJingleSession.addIceCandidates(transportInfo);
  1536. }
  1537. };
  1538. /**
  1539. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1540. * the conference.
  1541. *
  1542. * @param {JitsiRemoteTrack} removedTrack
  1543. */
  1544. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1545. this.getParticipants().forEach(participant => {
  1546. const tracks = participant.getTracks();
  1547. for (let i = 0; i < tracks.length; i++) {
  1548. if (tracks[i] === removedTrack) {
  1549. // Since the tracks have been compared and are
  1550. // considered equal the result of splice can be ignored.
  1551. participant._tracks.splice(i, 1);
  1552. this.eventEmitter.emit(
  1553. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1554. if (this.transcriber) {
  1555. this.transcriber.removeTrack(removedTrack);
  1556. }
  1557. break;
  1558. }
  1559. }
  1560. }, this);
  1561. };
  1562. /**
  1563. * Handles an incoming call event for the P2P jingle session.
  1564. */
  1565. JitsiConference.prototype._onIncomingCallP2P = function(
  1566. jingleSession,
  1567. jingleOffer) {
  1568. let rejectReason;
  1569. if (!browser.supportsP2P()) {
  1570. rejectReason = {
  1571. reason: 'unsupported-applications',
  1572. reasonDescription: 'P2P not supported',
  1573. errorMsg: 'This client does not support P2P connections'
  1574. };
  1575. } else if (!this.isP2PEnabled() && !this.isP2PTestModeEnabled()) {
  1576. rejectReason = {
  1577. reason: 'decline',
  1578. reasonDescription: 'P2P disabled',
  1579. errorMsg: 'P2P mode disabled in the configuration'
  1580. };
  1581. } else if (this.p2pJingleSession) {
  1582. // Reject incoming P2P call (already in progress)
  1583. rejectReason = {
  1584. reason: 'busy',
  1585. reasonDescription: 'P2P already in progress',
  1586. errorMsg: 'Duplicated P2P "session-initiate"'
  1587. };
  1588. } else if (!this._shouldBeInP2PMode()) {
  1589. rejectReason = {
  1590. reason: 'decline',
  1591. reasonDescription: 'P2P requirements not met',
  1592. errorMsg: 'Received P2P "session-initiate" when should not be in P2P mode'
  1593. };
  1594. Statistics.sendAnalytics(createJingleEvent(ACTION_P2P_DECLINED));
  1595. }
  1596. if (rejectReason) {
  1597. this._rejectIncomingCall(jingleSession, rejectReason);
  1598. } else {
  1599. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1600. }
  1601. };
  1602. /**
  1603. * Handles an incoming call event.
  1604. */
  1605. JitsiConference.prototype.onIncomingCall = function(
  1606. jingleSession,
  1607. jingleOffer,
  1608. now) {
  1609. // Handle incoming P2P call
  1610. if (jingleSession.isP2P) {
  1611. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1612. } else {
  1613. if (!this.room.isFocus(jingleSession.remoteJid)) {
  1614. const description = 'Rejecting session-initiate from non-focus.';
  1615. this._rejectIncomingCall(
  1616. jingleSession, {
  1617. reason: 'security-error',
  1618. reasonDescription: description,
  1619. errorMsg: description
  1620. });
  1621. return;
  1622. }
  1623. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1624. }
  1625. };
  1626. /**
  1627. * Accepts an incoming call event for the JVB jingle session.
  1628. */
  1629. JitsiConference.prototype._acceptJvbIncomingCall = function(
  1630. jingleSession,
  1631. jingleOffer,
  1632. now) {
  1633. // Accept incoming call
  1634. this.jvbJingleSession = jingleSession;
  1635. this.room.connectionTimes['session.initiate'] = now;
  1636. this._sendConferenceJoinAnalyticsEvent();
  1637. if (this.wasStopped) {
  1638. Statistics.sendAnalyticsAndLog(
  1639. createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1640. }
  1641. const serverRegion
  1642. = $(jingleOffer)
  1643. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1644. .attr('region');
  1645. this.eventEmitter.emit(
  1646. JitsiConferenceEvents.SERVER_REGION_CHANGED,
  1647. serverRegion);
  1648. this._maybeClearSITimeout();
  1649. Statistics.sendAnalytics(createJingleEvent(
  1650. ACTION_JINGLE_SI_RECEIVED,
  1651. {
  1652. p2p: false,
  1653. value: now
  1654. }));
  1655. try {
  1656. jingleSession.initialize(this.room, this.rtc, {
  1657. ...this.options.config,
  1658. enableInsertableStreams: this._isE2EEEnabled()
  1659. });
  1660. } catch (error) {
  1661. GlobalOnErrorHandler.callErrorHandler(error);
  1662. }
  1663. // Open a channel with the videobridge.
  1664. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1665. // Add local tracks to the session
  1666. const localTracks = this.getLocalTracks();
  1667. try {
  1668. jingleSession.acceptOffer(
  1669. jingleOffer,
  1670. () => {
  1671. // If for any reason invite for the JVB session arrived after
  1672. // the P2P has been established already the media transfer needs
  1673. // to be turned off here.
  1674. if (this.isP2PActive() && this.jvbJingleSession) {
  1675. this._suspendMediaTransferForJvbConnection();
  1676. }
  1677. this.eventEmitter.emit(
  1678. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  1679. jingleSession);
  1680. if (!this.isP2PActive()) {
  1681. this.eventEmitter.emit(
  1682. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  1683. jingleSession);
  1684. }
  1685. },
  1686. error => {
  1687. GlobalOnErrorHandler.callErrorHandler(error);
  1688. logger.error(
  1689. 'Failed to accept incoming Jingle session', error);
  1690. },
  1691. localTracks
  1692. );
  1693. // Start callstats as soon as peerconnection is initialized,
  1694. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1695. // happen in case if user doesn't have or denied permission to
  1696. // both camera and microphone.
  1697. logger.info('Starting CallStats for JVB connection...');
  1698. this.statistics.startCallStats(
  1699. this.jvbJingleSession.peerconnection,
  1700. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1701. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1702. } catch (e) {
  1703. GlobalOnErrorHandler.callErrorHandler(e);
  1704. logger.error(e);
  1705. }
  1706. };
  1707. /**
  1708. * Sets the BridgeChannel.
  1709. *
  1710. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1711. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1712. * BridgeChannel mode.
  1713. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1714. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1715. */
  1716. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1717. let wsUrl = null;
  1718. const webSocket
  1719. = $(offerIq)
  1720. .find('>content>transport>web-socket')
  1721. .first();
  1722. if (webSocket.length === 1) {
  1723. wsUrl = webSocket[0].getAttribute('url');
  1724. }
  1725. let bridgeChannelType;
  1726. switch (this.options.config.openBridgeChannel) {
  1727. case 'datachannel':
  1728. case true:
  1729. case undefined:
  1730. bridgeChannelType = 'datachannel';
  1731. break;
  1732. case 'websocket':
  1733. bridgeChannelType = 'websocket';
  1734. break;
  1735. }
  1736. if (bridgeChannelType === 'datachannel') {
  1737. this.rtc.initializeBridgeChannel(pc, null);
  1738. } else if (bridgeChannelType === 'websocket' && wsUrl) {
  1739. this.rtc.initializeBridgeChannel(null, wsUrl);
  1740. }
  1741. };
  1742. /**
  1743. * Rejects incoming Jingle call.
  1744. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1745. * @param {object} [options]
  1746. * @param {string} options.reason the name of the reason element as defined
  1747. * by Jingle
  1748. * @param {string} options.reasonDescription the reason description which will
  1749. * be included in Jingle 'session-terminate' message.
  1750. * @param {string} options.errorMsg an error message to be logged on global
  1751. * error handler
  1752. * @private
  1753. */
  1754. JitsiConference.prototype._rejectIncomingCall = function(
  1755. jingleSession,
  1756. options) {
  1757. if (options && options.errorMsg) {
  1758. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1759. }
  1760. // Terminate the jingle session with a reason
  1761. jingleSession.terminate(
  1762. null /* success callback => we don't care */,
  1763. error => {
  1764. logger.warn(
  1765. 'An error occurred while trying to terminate'
  1766. + ' invalid Jingle session', error);
  1767. }, {
  1768. reason: options && options.reason,
  1769. reasonDescription: options && options.reasonDescription,
  1770. sendSessionTerminate: true
  1771. });
  1772. };
  1773. /**
  1774. * Handles the call ended event.
  1775. * XXX is this due to the remote side terminating the Jingle session?
  1776. *
  1777. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1778. * terminated.
  1779. * @param {String} reasonCondition the Jingle reason condition.
  1780. * @param {String|null} reasonText human readable reason text which may provide
  1781. * more details about why the call has been terminated.
  1782. */
  1783. JitsiConference.prototype.onCallEnded = function(
  1784. jingleSession,
  1785. reasonCondition,
  1786. reasonText) {
  1787. logger.info(
  1788. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  1789. jingleSession.isP2P}`);
  1790. if (jingleSession === this.jvbJingleSession) {
  1791. this.wasStopped = true;
  1792. Statistics.sendAnalytics(
  1793. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  1794. // Stop the stats
  1795. if (this.statistics) {
  1796. this.statistics.stopRemoteStats(
  1797. this.jvbJingleSession.peerconnection);
  1798. logger.info('Stopping JVB CallStats');
  1799. this.statistics.stopCallStats(
  1800. this.jvbJingleSession.peerconnection);
  1801. }
  1802. // Current JVB JingleSession is no longer valid, so set it to null
  1803. this.jvbJingleSession = null;
  1804. // Let the RTC service do any cleanups
  1805. this.rtc.onCallEnded();
  1806. } else if (jingleSession === this.p2pJingleSession) {
  1807. // It's the responder who decides to enforce JVB mode, so that both
  1808. // initiator and responder are aware if it was intentional.
  1809. if (reasonCondition === 'decline' && reasonText === 'force JVB121') {
  1810. logger.info('In forced JVB 121 mode...');
  1811. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  1812. } else if (reasonCondition === 'connectivity-error'
  1813. && reasonText === 'ICE FAILED') {
  1814. // It can happen that the other peer detects ICE failed and
  1815. // terminates the session, before we get the event on our side.
  1816. // But we are able to parse the reason and mark it here.
  1817. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  1818. }
  1819. this._stopP2PSession();
  1820. } else {
  1821. logger.error(
  1822. 'Received onCallEnded for invalid session',
  1823. jingleSession.sid,
  1824. jingleSession.remoteJid,
  1825. reasonCondition,
  1826. reasonText);
  1827. }
  1828. };
  1829. /**
  1830. * Handles the suspend detected event. Leaves the room and fires suspended.
  1831. * @param {JingleSessionPC} jingleSession
  1832. */
  1833. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1834. if (!jingleSession.isP2P) {
  1835. this.leave();
  1836. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1837. }
  1838. };
  1839. JitsiConference.prototype.updateDTMFSupport = function() {
  1840. let somebodySupportsDTMF = false;
  1841. const participants = this.getParticipants();
  1842. // check if at least 1 participant supports DTMF
  1843. for (let i = 0; i < participants.length; i += 1) {
  1844. if (participants[i].supportsDTMF()) {
  1845. somebodySupportsDTMF = true;
  1846. break;
  1847. }
  1848. }
  1849. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1850. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1851. this.eventEmitter.emit(
  1852. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1853. somebodySupportsDTMF);
  1854. }
  1855. };
  1856. /**
  1857. * Allows to check if there is at least one user in the conference
  1858. * that supports DTMF.
  1859. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1860. */
  1861. JitsiConference.prototype.isDTMFSupported = function() {
  1862. return this.somebodySupportsDTMF;
  1863. };
  1864. /**
  1865. * Returns the local user's ID
  1866. * @return {string} local user's ID
  1867. */
  1868. JitsiConference.prototype.myUserId = function() {
  1869. return (
  1870. this.room && this.room.myroomjid
  1871. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1872. : null);
  1873. };
  1874. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1875. const peerConnection = this.getActivePeerConnection();
  1876. if (peerConnection) {
  1877. peerConnection.sendTones(tones, duration, pause);
  1878. } else {
  1879. logger.warn('cannot sendTones: no peer connection');
  1880. }
  1881. };
  1882. /**
  1883. * Starts recording the current conference.
  1884. *
  1885. * @param {Object} options - Configuration for the recording. See
  1886. * {@link Chatroom#startRecording} for more info.
  1887. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  1888. */
  1889. JitsiConference.prototype.startRecording = function(options) {
  1890. if (this.room) {
  1891. return this.recordingManager.startRecording(options);
  1892. }
  1893. return Promise.reject(new Error('The conference is not created yet!'));
  1894. };
  1895. /**
  1896. * Stop a recording session.
  1897. *
  1898. * @param {string} sessionID - The ID of the recording session that
  1899. * should be stopped.
  1900. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  1901. */
  1902. JitsiConference.prototype.stopRecording = function(sessionID) {
  1903. if (this.room) {
  1904. return this.recordingManager.stopRecording(sessionID);
  1905. }
  1906. return Promise.reject(new Error('The conference is not created yet!'));
  1907. };
  1908. /**
  1909. * Returns true if the SIP calls are supported and false otherwise
  1910. */
  1911. JitsiConference.prototype.isSIPCallingSupported = function() {
  1912. if (this.room) {
  1913. return this.room.isSIPCallingSupported();
  1914. }
  1915. return false;
  1916. };
  1917. /**
  1918. * Dials a number.
  1919. * @param number the number
  1920. */
  1921. JitsiConference.prototype.dial = function(number) {
  1922. if (this.room) {
  1923. return this.room.dial(number);
  1924. }
  1925. return new Promise((resolve, reject) => {
  1926. reject(new Error('The conference is not created yet!'));
  1927. });
  1928. };
  1929. /**
  1930. * Hangup an existing call
  1931. */
  1932. JitsiConference.prototype.hangup = function() {
  1933. if (this.room) {
  1934. return this.room.hangup();
  1935. }
  1936. return new Promise((resolve, reject) => {
  1937. reject(new Error('The conference is not created yet!'));
  1938. });
  1939. };
  1940. /**
  1941. * Starts the transcription service.
  1942. */
  1943. JitsiConference.prototype.startTranscriber = function() {
  1944. return this.dial('jitsi_meet_transcribe');
  1945. };
  1946. /**
  1947. * Stops the transcription service.
  1948. */
  1949. JitsiConference.prototype.stopTranscriber = JitsiConference.prototype.hangup;
  1950. /**
  1951. * Returns the phone number for joining the conference.
  1952. */
  1953. JitsiConference.prototype.getPhoneNumber = function() {
  1954. if (this.room) {
  1955. return this.room.getPhoneNumber();
  1956. }
  1957. return null;
  1958. };
  1959. /**
  1960. * Returns the pin for joining the conference with phone.
  1961. */
  1962. JitsiConference.prototype.getPhonePin = function() {
  1963. if (this.room) {
  1964. return this.room.getPhonePin();
  1965. }
  1966. return null;
  1967. };
  1968. /**
  1969. * Returns the meeting unique ID if any.
  1970. *
  1971. * @returns {string|undefined}
  1972. */
  1973. JitsiConference.prototype.getMeetingUniqueId = function() {
  1974. if (this.room) {
  1975. return this.room.getMeetingId();
  1976. }
  1977. };
  1978. /**
  1979. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  1980. * which connection is currently active.
  1981. *
  1982. * @return {TraceablePeerConnection|null} null if there isn't any active
  1983. * <tt>TraceablePeerConnection</tt> currently available.
  1984. * @public (FIXME how to make package local ?)
  1985. */
  1986. JitsiConference.prototype.getActivePeerConnection = function() {
  1987. if (this.isP2PActive()) {
  1988. return this.p2pJingleSession.peerconnection;
  1989. }
  1990. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  1991. };
  1992. /**
  1993. * Returns the connection state for the current room. Its ice connection state
  1994. * for its session.
  1995. * NOTE that "completed" ICE state which can appear on the P2P connection will
  1996. * be converted to "connected".
  1997. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  1998. * peer connection at this time.
  1999. */
  2000. JitsiConference.prototype.getConnectionState = function() {
  2001. const peerConnection = this.getActivePeerConnection();
  2002. return peerConnection ? peerConnection.getConnectionState() : null;
  2003. };
  2004. /**
  2005. * Make all new participants mute their audio/video on join.
  2006. * @param policy {Object} object with 2 boolean properties for video and audio:
  2007. * @param {boolean} audio if audio should be muted.
  2008. * @param {boolean} video if video should be muted.
  2009. */
  2010. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  2011. if (!this.isModerator()) {
  2012. return;
  2013. }
  2014. this.startMutedPolicy = policy;
  2015. this.room.addToPresence('startmuted', {
  2016. attributes: {
  2017. audio: policy.audio,
  2018. video: policy.video,
  2019. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  2020. }
  2021. });
  2022. this.room.sendPresence();
  2023. };
  2024. /**
  2025. * Returns current start muted policy
  2026. * @returns {Object} with 2 properties - audio and video.
  2027. */
  2028. JitsiConference.prototype.getStartMutedPolicy = function() {
  2029. return this.startMutedPolicy;
  2030. };
  2031. /**
  2032. * Check if audio is muted on join.
  2033. */
  2034. JitsiConference.prototype.isStartAudioMuted = function() {
  2035. return this.startAudioMuted;
  2036. };
  2037. /**
  2038. * Check if video is muted on join.
  2039. */
  2040. JitsiConference.prototype.isStartVideoMuted = function() {
  2041. return this.startVideoMuted;
  2042. };
  2043. /**
  2044. * Returns measured connectionTimes.
  2045. */
  2046. JitsiConference.prototype.getConnectionTimes = function() {
  2047. return this.room.connectionTimes;
  2048. };
  2049. /**
  2050. * Sets a property for the local participant.
  2051. */
  2052. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  2053. this.sendCommand(`jitsi_participant_${name}`, { value });
  2054. };
  2055. /**
  2056. * Removes a property for the local participant and sends the updated presence.
  2057. */
  2058. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  2059. this.removeCommand(`jitsi_participant_${name}`);
  2060. this.room.sendPresence();
  2061. };
  2062. /**
  2063. * Gets a local participant property.
  2064. *
  2065. * @return value of the local participant property if the tagName exists in the
  2066. * list of properties, otherwise returns undefined.
  2067. */
  2068. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  2069. const property = this.room.presMap.nodes.find(prop =>
  2070. prop.tagName === `jitsi_participant_${name}`
  2071. );
  2072. return property ? property.value : undefined;
  2073. };
  2074. /**
  2075. * Sends the given feedback through CallStats if enabled.
  2076. *
  2077. * @param overallFeedback an integer between 1 and 5 indicating the
  2078. * user feedback
  2079. * @param detailedFeedback detailed feedback from the user. Not yet used
  2080. * @returns {Promise} Resolves if feedback is submitted successfully.
  2081. */
  2082. JitsiConference.prototype.sendFeedback = function(
  2083. overallFeedback,
  2084. detailedFeedback) {
  2085. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  2086. };
  2087. /**
  2088. * Returns true if the callstats integration is enabled, otherwise returns
  2089. * false.
  2090. *
  2091. * @returns true if the callstats integration is enabled, otherwise returns
  2092. * false.
  2093. */
  2094. JitsiConference.prototype.isCallstatsEnabled = function() {
  2095. return this.statistics.isCallstatsEnabled();
  2096. };
  2097. /**
  2098. * Finds the SSRC of a given track
  2099. *
  2100. * @param track
  2101. * @returns {number|undefined} the SSRC of the specificed track, otherwise undefined.
  2102. */
  2103. JitsiConference.prototype.getSsrcByTrack = function(track) {
  2104. return track.isLocal() ? this.getActivePeerConnection()?.getLocalSSRC(track) : track.getSSRC();
  2105. };
  2106. /**
  2107. * Handles track attached to container (Calls associateStreamWithVideoTag method
  2108. * from statistics module)
  2109. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  2110. * @param container the container
  2111. */
  2112. JitsiConference.prototype._onTrackAttach = function(track, container) {
  2113. const isLocal = track.isLocal();
  2114. let ssrc = null;
  2115. const isP2P = track.isP2P;
  2116. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  2117. const peerConnection
  2118. = isP2P
  2119. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  2120. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  2121. if (isLocal) {
  2122. // Local tracks have SSRC stored on per peer connection basis.
  2123. if (peerConnection) {
  2124. ssrc = peerConnection.getLocalSSRC(track);
  2125. }
  2126. } else {
  2127. ssrc = track.getSSRC();
  2128. }
  2129. if (!container.id || !ssrc || !peerConnection) {
  2130. return;
  2131. }
  2132. this.statistics.associateStreamWithVideoTag(
  2133. peerConnection,
  2134. ssrc,
  2135. isLocal,
  2136. remoteUserId,
  2137. track.getUsageLabel(),
  2138. container.id);
  2139. };
  2140. /**
  2141. * Logs an "application log" message.
  2142. * @param message {string} The message to log. Note that while this can be a
  2143. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  2144. * log valid JSON strings, with an "id" field used for distinguishing between
  2145. * message types. E.g.: {id: "recorder_status", status: "off"}
  2146. */
  2147. JitsiConference.prototype.sendApplicationLog = function(message) {
  2148. Statistics.sendLog(message);
  2149. };
  2150. /**
  2151. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  2152. * focus.
  2153. * @param mucJid the full MUC address of the user to be checked.
  2154. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2155. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2156. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2157. */
  2158. JitsiConference.prototype._isFocus = function(mucJid) {
  2159. return this.room ? this.room.isFocus(mucJid) : null;
  2160. };
  2161. /**
  2162. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2163. */
  2164. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2165. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2166. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2167. };
  2168. /**
  2169. * Sends a message via the data channel.
  2170. * @param to {string} the id of the endpoint that should receive the message.
  2171. * If "" the message will be sent to all participants.
  2172. * @param payload {object} the payload of the message.
  2173. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2174. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2175. */
  2176. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2177. this.rtc.sendChannelMessage(to, payload);
  2178. };
  2179. /**
  2180. * Sends a broadcast message via the data channel.
  2181. * @param payload {object} the payload of the message.
  2182. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2183. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2184. */
  2185. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2186. this.sendEndpointMessage('', payload);
  2187. };
  2188. /**
  2189. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2190. * broadcasts it to all endpoints in the conference.
  2191. * @param {string} to The ID of the endpoint/participant which is to receive
  2192. * the message, or '' to broadcast the message to all endpoints in the
  2193. * conference.
  2194. * @param {string|object} message the message to send. If this is of type
  2195. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2196. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2197. * JSON before being sent.
  2198. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2199. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2200. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2201. */
  2202. JitsiConference.prototype.sendMessage = function(
  2203. message,
  2204. to = '',
  2205. sendThroughVideobridge = false) {
  2206. const messageType = typeof message;
  2207. // Through videobridge we support only objects. Through XMPP we support
  2208. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2209. // regular chat messages).
  2210. if (messageType !== 'object'
  2211. && (sendThroughVideobridge || messageType !== 'string')) {
  2212. logger.error(`Can not send a message of type ${messageType}`);
  2213. return;
  2214. }
  2215. if (sendThroughVideobridge) {
  2216. this.sendEndpointMessage(to, message);
  2217. } else {
  2218. let messageToSend = message;
  2219. // Name of packet extension of message stanza to send the required
  2220. // message in.
  2221. let elementName = 'body';
  2222. if (messageType === 'object') {
  2223. elementName = 'json-message';
  2224. // Mark as valid JSON message if not already
  2225. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2226. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2227. }
  2228. try {
  2229. messageToSend = JSON.stringify(messageToSend);
  2230. } catch (e) {
  2231. logger.error('Can not send a message, stringify failed: ', e);
  2232. return;
  2233. }
  2234. }
  2235. if (to) {
  2236. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2237. } else {
  2238. // Broadcast
  2239. this.sendTextMessage(messageToSend, elementName);
  2240. }
  2241. }
  2242. };
  2243. JitsiConference.prototype.isConnectionInterrupted = function() {
  2244. return this.isP2PActive()
  2245. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2246. };
  2247. /**
  2248. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2249. * @param {JingleSessionPC} session
  2250. * @private
  2251. */
  2252. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2253. if (session.isP2P) {
  2254. this.isP2PConnectionInterrupted = true;
  2255. } else {
  2256. this.isJvbConnectionInterrupted = true;
  2257. }
  2258. if (session.isP2P === this.isP2PActive()) {
  2259. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2260. }
  2261. };
  2262. /**
  2263. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2264. * @param {JingleSessionPC} session
  2265. * @private
  2266. */
  2267. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2268. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2269. // eventually come up with the new offer (at least for the time being).
  2270. if (session.isP2P) {
  2271. // Add p2pFailed property to analytics to distinguish, between "good"
  2272. // and "bad" connection
  2273. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2274. if (this.p2pJingleSession) {
  2275. Statistics.sendAnalyticsAndLog(
  2276. createP2PEvent(
  2277. ACTION_P2P_FAILED,
  2278. {
  2279. initiator: this.p2pJingleSession.isInitiator
  2280. }));
  2281. }
  2282. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  2283. } else if (session && this.jvbJingleSession === session) {
  2284. this._delayedIceFailed = new IceFailedHandling(this);
  2285. this._delayedIceFailed.start(session);
  2286. }
  2287. };
  2288. /**
  2289. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2290. * @param {JingleSessionPC} session
  2291. * @private
  2292. */
  2293. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2294. if (session.isP2P) {
  2295. this.isP2PConnectionInterrupted = false;
  2296. } else {
  2297. this.isJvbConnectionInterrupted = false;
  2298. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2299. }
  2300. if (session.isP2P === this.isP2PActive()) {
  2301. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2302. }
  2303. };
  2304. /**
  2305. * Accept incoming P2P Jingle call.
  2306. * @param {JingleSessionPC} jingleSession the session instance
  2307. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2308. * @private
  2309. */
  2310. JitsiConference.prototype._acceptP2PIncomingCall = function(
  2311. jingleSession,
  2312. jingleOffer) {
  2313. this.isP2PConnectionInterrupted = false;
  2314. // Accept the offer
  2315. this.p2pJingleSession = jingleSession;
  2316. this._sendConferenceJoinAnalyticsEvent();
  2317. this.p2pJingleSession.initialize(
  2318. this.room,
  2319. this.rtc, {
  2320. ...this.options.config,
  2321. enableInsertableStreams: this._isE2EEEnabled()
  2322. });
  2323. logger.info('Starting CallStats for P2P connection...');
  2324. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2325. const participant = this.participants[remoteID];
  2326. if (participant) {
  2327. remoteID = participant.getStatsID() || remoteID;
  2328. }
  2329. this.statistics.startCallStats(
  2330. this.p2pJingleSession.peerconnection,
  2331. remoteID);
  2332. const localTracks = this.getLocalTracks();
  2333. this.p2pJingleSession.acceptOffer(
  2334. jingleOffer,
  2335. () => {
  2336. logger.debug('Got RESULT for P2P "session-accept"');
  2337. this.eventEmitter.emit(
  2338. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2339. this.p2pJingleSession);
  2340. },
  2341. error => {
  2342. logger.error(
  2343. 'Failed to accept incoming P2P Jingle session', error);
  2344. },
  2345. localTracks);
  2346. };
  2347. /**
  2348. * Adds remote tracks to the conference associated with the JVB session.
  2349. * @private
  2350. */
  2351. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2352. this._addRemoteTracks(
  2353. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2354. };
  2355. /**
  2356. * Adds remote tracks to the conference associated with the P2P session.
  2357. * @private
  2358. */
  2359. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2360. this._addRemoteTracks(
  2361. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2362. };
  2363. /**
  2364. * Generates fake "remote track added" events for given Jingle session.
  2365. * @param {string} logName the session's nickname which will appear in log
  2366. * messages.
  2367. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2368. * @private
  2369. */
  2370. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2371. for (const track of remoteTracks) {
  2372. logger.info(`Adding remote ${logName} track: ${track}`);
  2373. this.onRemoteTrackAdded(track);
  2374. }
  2375. };
  2376. /**
  2377. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2378. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2379. * the P2P connection if the event comes from the P2P session.
  2380. * @param {JingleSessionPC} jingleSession the session instance.
  2381. * @private
  2382. */
  2383. JitsiConference.prototype._onIceConnectionEstablished = function(
  2384. jingleSession) {
  2385. if (this.p2pJingleSession !== null) {
  2386. // store the establishment time of the p2p session as a field of the
  2387. // JitsiConference because the p2pJingleSession might get disposed (thus
  2388. // the value is lost).
  2389. this.p2pEstablishmentDuration
  2390. = this.p2pJingleSession.establishmentDuration;
  2391. }
  2392. if (this.jvbJingleSession !== null) {
  2393. this.jvbEstablishmentDuration
  2394. = this.jvbJingleSession.establishmentDuration;
  2395. }
  2396. let done = false;
  2397. const forceJVB121Ratio = this.options.config.forceJVB121Ratio;
  2398. // We don't care about the JVB case, there's nothing to be done
  2399. if (!jingleSession.isP2P) {
  2400. done = true;
  2401. } else if (this.p2pJingleSession !== jingleSession) {
  2402. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2403. done = true;
  2404. } else if (!jingleSession.isInitiator
  2405. && typeof forceJVB121Ratio === 'number'
  2406. && Math.random() < forceJVB121Ratio) {
  2407. logger.info(`Forcing JVB 121 mode (ratio=${forceJVB121Ratio})...`);
  2408. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2409. this._stopP2PSession('decline', 'force JVB121');
  2410. done = true;
  2411. }
  2412. if (!isNaN(this.p2pEstablishmentDuration)
  2413. && !isNaN(this.jvbEstablishmentDuration)) {
  2414. const establishmentDurationDiff
  2415. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2416. Statistics.sendAnalytics(
  2417. ICE_ESTABLISHMENT_DURATION_DIFF,
  2418. { value: establishmentDurationDiff });
  2419. }
  2420. if (jingleSession.isP2P === this.isP2PActive()) {
  2421. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2422. }
  2423. if (done) {
  2424. return;
  2425. }
  2426. // Update P2P status and emit events
  2427. this._setP2PStatus(true);
  2428. // Remove remote tracks
  2429. if (this.jvbJingleSession) {
  2430. this._removeRemoteJVBTracks();
  2431. } else {
  2432. logger.info('Not removing remote JVB tracks - no session yet');
  2433. }
  2434. this._addRemoteP2PTracks();
  2435. // Stop media transfer over the JVB connection
  2436. if (this.jvbJingleSession) {
  2437. this._suspendMediaTransferForJvbConnection();
  2438. }
  2439. logger.info('Starting remote stats with p2p connection');
  2440. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2441. Statistics.sendAnalyticsAndLog(
  2442. createP2PEvent(
  2443. ACTION_P2P_ESTABLISHED,
  2444. {
  2445. initiator: this.p2pJingleSession.isInitiator
  2446. }));
  2447. };
  2448. /**
  2449. * Called when the chat room reads a new list of properties from jicofo's
  2450. * presence. The properties may have changed, but they don't have to.
  2451. *
  2452. * @param {Object} properties - The properties keyed by the property name
  2453. * ('key').
  2454. * @private
  2455. */
  2456. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2457. const changed = !isEqual(properties, this.properties);
  2458. this.properties = properties;
  2459. if (changed) {
  2460. this.eventEmitter.emit(
  2461. JitsiConferenceEvents.PROPERTIES_CHANGED,
  2462. this.properties);
  2463. // Some of the properties need to be added to analytics events.
  2464. const analyticsKeys = [
  2465. // The number of jitsi-videobridge instances currently used for the
  2466. // conference.
  2467. 'bridge-count',
  2468. // The conference creation time (set by jicofo).
  2469. 'created-ms',
  2470. 'octo-enabled'
  2471. ];
  2472. analyticsKeys.forEach(key => {
  2473. if (properties[key] !== undefined) {
  2474. Statistics.analytics.addPermanentProperties({
  2475. [key.replace('-', '_')]: properties[key]
  2476. });
  2477. }
  2478. });
  2479. }
  2480. };
  2481. /**
  2482. * Gets a conference property with a given key.
  2483. *
  2484. * @param {string} key - The key.
  2485. * @returns {*} The value
  2486. */
  2487. JitsiConference.prototype.getProperty = function(key) {
  2488. return this.properties[key];
  2489. };
  2490. /**
  2491. * Clears the deferred start P2P task if it has been scheduled.
  2492. * @private
  2493. */
  2494. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2495. if (this.deferredStartP2PTask) {
  2496. logger.info('Cleared deferred start P2P task');
  2497. clearTimeout(this.deferredStartP2PTask);
  2498. this.deferredStartP2PTask = null;
  2499. }
  2500. };
  2501. /**
  2502. * Removes from the conference remote tracks associated with the JVB
  2503. * connection.
  2504. * @private
  2505. */
  2506. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2507. this._removeRemoteTracks(
  2508. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2509. };
  2510. /**
  2511. * Removes from the conference remote tracks associated with the P2P
  2512. * connection.
  2513. * @private
  2514. */
  2515. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2516. this._removeRemoteTracks(
  2517. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2518. };
  2519. /**
  2520. * Generates fake "remote track removed" events for given Jingle session.
  2521. * @param {string} sessionNickname the session's nickname which will appear in
  2522. * log messages.
  2523. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2524. * @private
  2525. */
  2526. JitsiConference.prototype._removeRemoteTracks = function(
  2527. sessionNickname,
  2528. remoteTracks) {
  2529. for (const track of remoteTracks) {
  2530. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2531. this.onRemoteTrackRemoved(track);
  2532. }
  2533. };
  2534. /**
  2535. * Resumes media transfer over the JVB connection.
  2536. * @private
  2537. */
  2538. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2539. logger.info('Resuming media transfer over the JVB connection...');
  2540. this.jvbJingleSession.setMediaTransferActive(true, true).then(
  2541. () => {
  2542. logger.info('Resumed media transfer over the JVB connection!');
  2543. },
  2544. error => {
  2545. logger.error(
  2546. 'Failed to resume media transfer over the JVB connection:',
  2547. error);
  2548. });
  2549. };
  2550. /**
  2551. * Sets new P2P status and updates some events/states hijacked from
  2552. * the <tt>JitsiConference</tt>.
  2553. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2554. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2555. * @private
  2556. */
  2557. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2558. if (this.p2p === newStatus) {
  2559. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2560. return;
  2561. }
  2562. this.p2p = newStatus;
  2563. if (newStatus) {
  2564. logger.info('Peer to peer connection established!');
  2565. // When we end up in a valid P2P session need to reset the properties
  2566. // in case they have persisted, after session with another peer.
  2567. Statistics.analytics.addPermanentProperties({
  2568. p2pFailed: false,
  2569. forceJvb121: false
  2570. });
  2571. // Sync up video transfer active in case p2pJingleSession not existed
  2572. // when the lastN value was being adjusted.
  2573. const isVideoActive = this.rtc.getLastN() !== 0;
  2574. this.p2pJingleSession
  2575. .setMediaTransferActive(true, isVideoActive)
  2576. .catch(error => {
  2577. logger.error(
  2578. 'Failed to sync up P2P video transfer status'
  2579. + `(${isVideoActive})`, error);
  2580. });
  2581. } else {
  2582. logger.info('Peer to peer connection closed!');
  2583. }
  2584. // Put the JVB connection on hold/resume
  2585. if (this.jvbJingleSession) {
  2586. this.statistics.sendConnectionResumeOrHoldEvent(
  2587. this.jvbJingleSession.peerconnection, !newStatus);
  2588. }
  2589. // Clear dtmfManager, so that it can be recreated with new connection
  2590. this.dtmfManager = null;
  2591. // Update P2P status
  2592. this.eventEmitter.emit(
  2593. JitsiConferenceEvents.P2P_STATUS,
  2594. this,
  2595. this.p2p);
  2596. this.eventEmitter.emit(
  2597. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  2598. this._getActiveMediaSession());
  2599. // Refresh connection interrupted/restored
  2600. this.eventEmitter.emit(
  2601. this.isConnectionInterrupted()
  2602. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2603. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2604. };
  2605. /**
  2606. * Starts new P2P session.
  2607. * @param {string} remoteJid the JID of the remote participant
  2608. * @private
  2609. */
  2610. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2611. this._maybeClearDeferredStartP2P();
  2612. if (this.p2pJingleSession) {
  2613. logger.error('P2P session already started!');
  2614. return;
  2615. }
  2616. this.isP2PConnectionInterrupted = false;
  2617. this.p2pJingleSession
  2618. = this.xmpp.connection.jingle.newP2PJingleSession(
  2619. this.room.myroomjid,
  2620. remoteJid);
  2621. logger.info(
  2622. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2623. this._sendConferenceJoinAnalyticsEvent();
  2624. this.p2pJingleSession.initialize(
  2625. this.room,
  2626. this.rtc, {
  2627. ...this.options.config,
  2628. enableInsertableStreams: this._isE2EEEnabled()
  2629. });
  2630. logger.info('Starting CallStats for P2P connection...');
  2631. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2632. const participant = this.participants[remoteID];
  2633. if (participant) {
  2634. remoteID = participant.getStatsID() || remoteID;
  2635. }
  2636. this.statistics.startCallStats(
  2637. this.p2pJingleSession.peerconnection,
  2638. remoteID);
  2639. // NOTE one may consider to start P2P with the local tracks detached,
  2640. // but no data will be sent until ICE succeeds anyway. And we switch
  2641. // immediately once the P2P ICE connects.
  2642. const localTracks = this.getLocalTracks();
  2643. this.p2pJingleSession.invite(localTracks);
  2644. };
  2645. /**
  2646. * Suspends media transfer over the JVB connection.
  2647. * @private
  2648. */
  2649. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2650. logger.info('Suspending media transfer over the JVB connection...');
  2651. this.jvbJingleSession.setMediaTransferActive(false, false).then(
  2652. () => {
  2653. logger.info('Suspended media transfer over the JVB connection !');
  2654. },
  2655. error => {
  2656. logger.error(
  2657. 'Failed to suspend media transfer over the JVB connection:',
  2658. error);
  2659. });
  2660. };
  2661. /**
  2662. * Method when called will decide whether it's the time to start or stop
  2663. * the P2P session.
  2664. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2665. * originates from the user left event.
  2666. * @private
  2667. */
  2668. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2669. if (!browser.supportsP2P()
  2670. || !this.isP2PEnabled()
  2671. || this.isP2PTestModeEnabled()) {
  2672. logger.info('Auto P2P disabled');
  2673. return;
  2674. }
  2675. const peers = this.getParticipants();
  2676. const peerCount = peers.length;
  2677. // FIXME 1 peer and it must *support* P2P switching
  2678. const shouldBeInP2P = this._shouldBeInP2PMode();
  2679. // Clear deferred "start P2P" task
  2680. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2681. this._maybeClearDeferredStartP2P();
  2682. }
  2683. // Start peer to peer session
  2684. if (!this.p2pJingleSession && shouldBeInP2P) {
  2685. const peer = peerCount && peers[0];
  2686. const myId = this.myUserId();
  2687. const peersId = peer.getId();
  2688. if (myId > peersId) {
  2689. logger.debug(
  2690. 'I\'m the bigger peersId - '
  2691. + 'the other peer should start P2P', myId, peersId);
  2692. return;
  2693. } else if (myId === peersId) {
  2694. logger.error('The same IDs ? ', myId, peersId);
  2695. return;
  2696. }
  2697. const jid = peer.getJid();
  2698. if (userLeftEvent) {
  2699. if (this.deferredStartP2PTask) {
  2700. logger.error('Deferred start P2P task\'s been set already!');
  2701. return;
  2702. }
  2703. logger.info(
  2704. `Will start P2P with: ${jid} after ${
  2705. this.backToP2PDelay} seconds...`);
  2706. this.deferredStartP2PTask = setTimeout(
  2707. this._startP2PSession.bind(this, jid),
  2708. this.backToP2PDelay * 1000);
  2709. } else {
  2710. logger.info(`Will start P2P with: ${jid}`);
  2711. this._startP2PSession(jid);
  2712. }
  2713. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2714. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2715. // Log that there will be a switch back to the JVB connection
  2716. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2717. Statistics.sendAnalyticsAndLog(
  2718. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2719. }
  2720. this._stopP2PSession();
  2721. }
  2722. };
  2723. /**
  2724. * Tells whether or not this conference should be currently in the P2P mode.
  2725. *
  2726. * @private
  2727. * @returns {boolean}
  2728. */
  2729. JitsiConference.prototype._shouldBeInP2PMode = function() {
  2730. const peers = this.getParticipants();
  2731. const peerCount = peers.length;
  2732. const hasBotPeer = peers.find(p => p._botType === 'poltergeist') !== undefined;
  2733. const shouldBeInP2P = peerCount === 1 && !hasBotPeer;
  2734. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  2735. return shouldBeInP2P;
  2736. };
  2737. /**
  2738. * Stops the current P2P session.
  2739. * @param {string} [reason="success"] one of the Jingle "reason" element
  2740. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2741. * @param {string} [reasonDescription="Turing off P2P session"] text
  2742. * description that will be included in the session terminate message
  2743. * @private
  2744. */
  2745. JitsiConference.prototype._stopP2PSession = function(
  2746. reason,
  2747. reasonDescription) {
  2748. if (!this.p2pJingleSession) {
  2749. logger.error('No P2P session to be stopped!');
  2750. return;
  2751. }
  2752. const wasP2PEstablished = this.isP2PActive();
  2753. // Swap remote tracks, but only if the P2P has been fully established
  2754. if (wasP2PEstablished) {
  2755. if (this.jvbJingleSession) {
  2756. this._resumeMediaTransferForJvbConnection();
  2757. }
  2758. // Remove remote P2P tracks
  2759. this._removeRemoteP2PTracks();
  2760. }
  2761. // Stop P2P stats
  2762. logger.info('Stopping remote stats for P2P connection');
  2763. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2764. logger.info('Stopping CallStats for P2P connection');
  2765. this.statistics.stopCallStats(this.p2pJingleSession.peerconnection);
  2766. this.p2pJingleSession.terminate(
  2767. () => {
  2768. logger.info('P2P session terminate RESULT');
  2769. },
  2770. error => {
  2771. // Because both initiator and responder are simultaneously
  2772. // terminating their JingleSessions in case of the 'to JVB switch'
  2773. // when 3rd participant joins, both will dispose their sessions and
  2774. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2775. // want to log this as an error since it's expected behaviour.
  2776. //
  2777. // We want them both to terminate, because in case of initiator's
  2778. // crash the responder would stay in P2P mode until ICE fails which
  2779. // could take up to 20 seconds.
  2780. //
  2781. // NOTE lack of 'reason' is considered as graceful session terminate
  2782. // where both initiator and responder terminate their sessions
  2783. // simultaneously.
  2784. if (reason) {
  2785. logger.error(
  2786. 'An error occurred while trying to terminate'
  2787. + ' P2P Jingle session', error);
  2788. }
  2789. }, {
  2790. reason: reason ? reason : 'success',
  2791. reasonDescription: reasonDescription
  2792. ? reasonDescription : 'Turing off P2P session',
  2793. sendSessionTerminate: this.room
  2794. && this.getParticipantById(
  2795. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2796. });
  2797. this.p2pJingleSession = null;
  2798. // Update P2P status and other affected events/states
  2799. this._setP2PStatus(false);
  2800. if (wasP2PEstablished) {
  2801. // Add back remote JVB tracks
  2802. if (this.jvbJingleSession) {
  2803. this._addRemoteJVBTracks();
  2804. } else {
  2805. logger.info('Not adding remote JVB tracks - no session yet');
  2806. }
  2807. }
  2808. };
  2809. /**
  2810. * Checks whether or not the conference is currently in the peer to peer mode.
  2811. * Being in peer to peer mode means that the direct connection has been
  2812. * established and the P2P connection is being used for media transmission.
  2813. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2814. */
  2815. JitsiConference.prototype.isP2PActive = function() {
  2816. return this.p2p;
  2817. };
  2818. /**
  2819. * Returns the current ICE state of the P2P connection.
  2820. * NOTE: method is used by the jitsi-meet-torture tests.
  2821. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2822. * no P2P connection.
  2823. */
  2824. JitsiConference.prototype.getP2PConnectionState = function() {
  2825. if (this.isP2PActive()) {
  2826. return this.p2pJingleSession.peerconnection.getConnectionState();
  2827. }
  2828. return null;
  2829. };
  2830. /**
  2831. * Manually starts new P2P session (should be used only in the tests).
  2832. */
  2833. JitsiConference.prototype.startP2PSession = function() {
  2834. const peers = this.getParticipants();
  2835. // Start peer to peer session
  2836. if (peers.length === 1) {
  2837. const peerJid = peers[0].getJid();
  2838. this._startP2PSession(peerJid);
  2839. } else {
  2840. throw new Error(
  2841. 'There must be exactly 1 participant to start the P2P session !');
  2842. }
  2843. };
  2844. /**
  2845. * Manually stops the current P2P session (should be used only in the tests)
  2846. */
  2847. JitsiConference.prototype.stopP2PSession = function() {
  2848. this._stopP2PSession();
  2849. };
  2850. /**
  2851. * Get a summary of how long current participants have been the dominant speaker
  2852. * @returns {object}
  2853. */
  2854. JitsiConference.prototype.getSpeakerStats = function() {
  2855. return this.speakerStatsCollector.getStats();
  2856. };
  2857. /**
  2858. * Sets the maximum video size the local participant should receive from remote
  2859. * participants.
  2860. *
  2861. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  2862. * this receiver is willing to receive.
  2863. * @returns {void}
  2864. */
  2865. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  2866. this.qualityController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  2867. };
  2868. /**
  2869. * Sets the maximum video size the local participant should send to remote
  2870. * participants.
  2871. * @param {number} maxFrameHeight - The user preferred max frame height.
  2872. * @returns {Promise} promise that will be resolved when the operation is
  2873. * successful and rejected otherwise.
  2874. */
  2875. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  2876. return this.qualityController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  2877. };
  2878. /**
  2879. * Creates a video SIP GW session and returns it if service is enabled. Before
  2880. * creating a session one need to check whether video SIP GW service is
  2881. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2882. * if there are available nodes to serve this request, after creating the
  2883. * session those nodes can be taken and the request about using the
  2884. * created session can fail.
  2885. *
  2886. * @param {string} sipAddress - The sip address to be used.
  2887. * @param {string} displayName - The display name to be used for this session.
  2888. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  2889. * initialised and there is no room.
  2890. */
  2891. JitsiConference.prototype.createVideoSIPGWSession
  2892. = function(sipAddress, displayName) {
  2893. if (!this.room) {
  2894. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  2895. }
  2896. return this.videoSIPGWHandler
  2897. .createVideoSIPGWSession(sipAddress, displayName);
  2898. };
  2899. /**
  2900. * Sends a conference.join analytics event.
  2901. *
  2902. * @returns {void}
  2903. */
  2904. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  2905. const meetingId = this.getMeetingUniqueId();
  2906. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  2907. return;
  2908. }
  2909. Statistics.sendAnalytics(createConferenceEvent('joined', {
  2910. meetingId,
  2911. participantId: `${meetingId}.${this._statsCurrentId}`
  2912. }));
  2913. this._conferenceJoinAnalyticsEventSent = Date.now();
  2914. };
  2915. /**
  2916. * Sends conference.left analytics event.
  2917. * @private
  2918. */
  2919. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  2920. const meetingId = this.getMeetingUniqueId();
  2921. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  2922. return;
  2923. }
  2924. Statistics.sendAnalytics(createConferenceEvent('left', {
  2925. meetingId,
  2926. participantId: `${meetingId}.${this._statsCurrentId}`,
  2927. stats: {
  2928. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  2929. perf: this.getPerformanceStats()
  2930. }
  2931. }));
  2932. };
  2933. /**
  2934. * Restarts all active media sessions.
  2935. *
  2936. * @returns {void}
  2937. */
  2938. JitsiConference.prototype._restartMediaSessions = function() {
  2939. if (this.p2pJingleSession) {
  2940. this.stopP2PSession();
  2941. }
  2942. if (this.jvbJingleSession) {
  2943. this.jvbJingleSession.terminate(
  2944. null /* success callback => we don't care */,
  2945. error => {
  2946. logger.warn('An error occurred while trying to terminate the JVB session', error);
  2947. }, {
  2948. reason: 'success',
  2949. reasonDescription: 'restart required',
  2950. requestRestart: true,
  2951. sendSessionTerminate: true
  2952. });
  2953. }
  2954. this._maybeStartOrStopP2P(false);
  2955. };
  2956. /**
  2957. * Returns whether End-To-End encryption is enabled.
  2958. *
  2959. * @returns {boolean}
  2960. */
  2961. JitsiConference.prototype._isE2EEEnabled = function() {
  2962. return this._e2eEncryption && this._e2eEncryption.isEnabled();
  2963. };
  2964. /**
  2965. * Returns whether End-To-End encryption is supported. Note that not all participants
  2966. * in the conference may support it.
  2967. *
  2968. * @returns {boolean}
  2969. */
  2970. JitsiConference.prototype.isE2EESupported = function() {
  2971. return E2EEncryption.isSupported(this.options.config);
  2972. };
  2973. /**
  2974. * Enables / disables End-to-End encryption.
  2975. *
  2976. * @param {boolean} enabled whether to enable E2EE or not.
  2977. * @returns {void}
  2978. */
  2979. JitsiConference.prototype.toggleE2EE = function(enabled) {
  2980. if (!this.isE2EESupported()) {
  2981. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  2982. return;
  2983. }
  2984. this._e2eEncryption.setEnabled(enabled);
  2985. };
  2986. /**
  2987. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  2988. *
  2989. * @returns {boolean} whether lobby is supported in the backend.
  2990. */
  2991. JitsiConference.prototype.isLobbySupported = function() {
  2992. return Boolean(this.room && this.room.getLobby().isSupported());
  2993. };
  2994. /**
  2995. * Returns <tt>true</tt> if the room has members only enabled.
  2996. *
  2997. * @returns {boolean} whether conference room is members only.
  2998. */
  2999. JitsiConference.prototype.isMembersOnly = function() {
  3000. return Boolean(this.room && this.room.membersOnlyEnabled);
  3001. };
  3002. /**
  3003. * Enables lobby by moderators
  3004. *
  3005. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3006. */
  3007. JitsiConference.prototype.enableLobby = function() {
  3008. if (this.room && this.isModerator()) {
  3009. return this.room.getLobby().enable();
  3010. }
  3011. return Promise.reject(
  3012. new Error('The conference not started or user is not moderator'));
  3013. };
  3014. /**
  3015. * Disabled lobby by moderators
  3016. *
  3017. * @returns {void}
  3018. */
  3019. JitsiConference.prototype.disableLobby = function() {
  3020. if (this.room && this.isModerator()) {
  3021. this.room.getLobby().disable();
  3022. }
  3023. };
  3024. /**
  3025. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3026. *
  3027. * @param {string} displayName Display name should be set to show it to moderators.
  3028. * @param {string} email Optional email is used to present avatar to the moderator.
  3029. * @returns {Promise<never>}
  3030. */
  3031. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3032. if (this.room) {
  3033. return this.room.getLobby().join(displayName, email);
  3034. }
  3035. return Promise.reject(new Error('The conference not started'));
  3036. };
  3037. /**
  3038. * Denies an occupant in the lobby room access to the conference.
  3039. * @param {string} id The participant id.
  3040. */
  3041. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3042. if (this.room) {
  3043. this.room.getLobby().denyAccess(id);
  3044. }
  3045. };
  3046. /**
  3047. * Approves the request to join the conference to a participant waiting in the lobby.
  3048. *
  3049. * @param {string} id The participant id.
  3050. */
  3051. JitsiConference.prototype.lobbyApproveAccess = function(id) {
  3052. if (this.room) {
  3053. this.room.getLobby().approveAccess(id);
  3054. }
  3055. };