You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 50KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. /* global __filename, Strophe, Promise */
  2. import ComponentsVersions from './modules/version/ComponentsVersions';
  3. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  4. import { getLogger } from 'jitsi-meet-logger';
  5. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  6. import EventEmitter from 'events';
  7. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  8. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  9. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  10. import JitsiDTMFManager from './modules/DTMF/JitsiDTMFManager';
  11. import JitsiParticipant from './JitsiParticipant';
  12. import JitsiTrackError from './JitsiTrackError';
  13. import * as JitsiTrackErrors from './JitsiTrackErrors';
  14. import * as JitsiTrackEvents from './JitsiTrackEvents';
  15. import * as MediaType from './service/RTC/MediaType';
  16. import ParticipantConnectionStatus
  17. from './modules/connectivity/ParticipantConnectionStatus';
  18. import RTC from './modules/RTC/RTC';
  19. import RTCBrowserType from './modules/RTC/RTCBrowserType.js';
  20. import * as RTCEvents from './service/RTC/RTCEvents';
  21. import Statistics from './modules/statistics/statistics';
  22. import TalkMutedDetection from './modules/TalkMutedDetection';
  23. import Transcriber from './modules/transcription/transcriber';
  24. import VideoType from './service/RTC/VideoType';
  25. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  26. const logger = getLogger(__filename);
  27. /**
  28. * Creates a JitsiConference object with the given name and properties.
  29. * Note: this constructor is not a part of the public API (objects should be
  30. * created using JitsiConnection.createConference).
  31. * @param options.config properties / settings related to the conference that
  32. * will be created.
  33. * @param options.name the name of the conference
  34. * @param options.connection the JitsiConnection object for this
  35. * JitsiConference.
  36. * @constructor
  37. */
  38. function JitsiConference(options) {
  39. if (!options.name || options.name.toLowerCase() !== options.name) {
  40. const errmsg
  41. = 'Invalid conference name (no conference name passed or it '
  42. + 'contains invalid characters like capital letters)!';
  43. logger.error(errmsg);
  44. throw new Error(errmsg);
  45. }
  46. this.eventEmitter = new EventEmitter();
  47. this.options = options;
  48. this.eventManager = new JitsiConferenceEventManager(this);
  49. this._init(options);
  50. this.componentsVersions = new ComponentsVersions(this);
  51. this.participants = {};
  52. /**
  53. * Jingle Session instance
  54. * @type {JingleSessionPC}
  55. */
  56. this.jingleSession = null;
  57. this.lastDominantSpeaker = null;
  58. this.dtmfManager = null;
  59. this.somebodySupportsDTMF = false;
  60. this.authEnabled = false;
  61. this.startAudioMuted = false;
  62. this.startVideoMuted = false;
  63. this.startMutedPolicy = {
  64. audio: false,
  65. video: false
  66. };
  67. this.availableDevices = {
  68. audio: undefined,
  69. video: undefined
  70. };
  71. this.isMutedByFocus = false;
  72. // Flag indicates if the 'onCallEnded' method was ever called on this
  73. // instance. Used to log extra analytics event for debugging purpose.
  74. // We need to know if the potential issue happened before or after
  75. // the restart.
  76. this.wasStopped = false;
  77. /**
  78. * The object which monitors local and remote connection statistics (e.g.
  79. * sending bitrate) and calculates a number which represents the connection
  80. * quality.
  81. */
  82. this.connectionQuality
  83. = new ConnectionQuality(this, this.eventEmitter, options);
  84. /**
  85. * Indicates whether the connection is interrupted or not.
  86. */
  87. this.connectionIsInterrupted = false;
  88. /**
  89. * The object which tracks active speaker times
  90. */
  91. this.speakerStatsCollector = new SpeakerStatsCollector(this);
  92. }
  93. /**
  94. * Initializes the conference object properties
  95. * @param options {object}
  96. * @param connection {JitsiConnection} overrides this.connection
  97. */
  98. JitsiConference.prototype._init = function(options = {}) {
  99. // Override connection and xmpp properties (Usefull if the connection
  100. // reloaded)
  101. if (options.connection) {
  102. this.connection = options.connection;
  103. this.xmpp = this.connection.xmpp;
  104. // Setup XMPP events only if we have new connection object.
  105. this.eventManager.setupXMPPListeners();
  106. }
  107. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  108. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  109. if (!this.rtc) {
  110. this.rtc = new RTC(this, options);
  111. this.eventManager.setupRTCListeners();
  112. }
  113. this.participantConnectionStatus
  114. = new ParticipantConnectionStatus(
  115. this.rtc, this,
  116. options.config.peerDisconnectedThroughRtcTimeout);
  117. this.participantConnectionStatus.init();
  118. if (!this.statistics) {
  119. this.statistics = new Statistics(this.xmpp, {
  120. callStatsID: this.options.config.callStatsID,
  121. callStatsSecret: this.options.config.callStatsSecret,
  122. callStatsConfIDNamespace:
  123. this.options.config.callStatsConfIDNamespace
  124. || window.location.hostname,
  125. callStatsCustomScriptUrl:
  126. this.options.config.callStatsCustomScriptUrl,
  127. roomName: this.options.name
  128. });
  129. }
  130. this.eventManager.setupChatRoomListeners();
  131. // Always add listeners because on reload we are executing leave and the
  132. // listeners are removed from statistics module.
  133. this.eventManager.setupStatisticsListeners();
  134. if (this.options.config.enableTalkWhileMuted) {
  135. // eslint-disable-next-line no-new
  136. new TalkMutedDetection(
  137. this,
  138. () =>
  139. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
  140. }
  141. };
  142. /**
  143. * Joins the conference.
  144. * @param password {string} the password
  145. */
  146. JitsiConference.prototype.join = function(password) {
  147. if (this.room) {
  148. this.room.join(password);
  149. }
  150. };
  151. /**
  152. * Check if joined to the conference.
  153. */
  154. JitsiConference.prototype.isJoined = function() {
  155. return this.room && this.room.joined;
  156. };
  157. /**
  158. * Leaves the conference.
  159. * @returns {Promise}
  160. */
  161. JitsiConference.prototype.leave = function() {
  162. if (this.participantConnectionStatus) {
  163. this.participantConnectionStatus.dispose();
  164. this.participantConnectionStatus = null;
  165. }
  166. this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
  167. this.rtc.closeAllDataChannels();
  168. if (this.statistics) {
  169. this.statistics.dispose();
  170. }
  171. // leave the conference
  172. if (this.room) {
  173. const room = this.room;
  174. this.room = null;
  175. return room.leave().catch(() => {
  176. // remove all participants because currently the conference won't
  177. // be usable anyway. This is done on success automatically by the
  178. // ChatRoom instance.
  179. this.getParticipants().forEach(
  180. participant => this.onMemberLeft(participant.getJid()));
  181. // Close the JingleSession
  182. if (this.jingleSession) {
  183. this.jingleSession.close();
  184. this.jingleSession = null;
  185. }
  186. });
  187. }
  188. // If this.room == null we are calling second time leave().
  189. return Promise.reject(
  190. new Error('The conference is has been already left'));
  191. };
  192. /**
  193. * Returns name of this conference.
  194. */
  195. JitsiConference.prototype.getName = function() {
  196. return this.options.name;
  197. };
  198. /**
  199. * Check if authentication is enabled for this conference.
  200. */
  201. JitsiConference.prototype.isAuthEnabled = function() {
  202. return this.authEnabled;
  203. };
  204. /**
  205. * Check if user is logged in.
  206. */
  207. JitsiConference.prototype.isLoggedIn = function() {
  208. return Boolean(this.authIdentity);
  209. };
  210. /**
  211. * Get authorized login.
  212. */
  213. JitsiConference.prototype.getAuthLogin = function() {
  214. return this.authIdentity;
  215. };
  216. /**
  217. * Check if external authentication is enabled for this conference.
  218. */
  219. JitsiConference.prototype.isExternalAuthEnabled = function() {
  220. return this.room && this.room.moderator.isExternalAuthEnabled();
  221. };
  222. /**
  223. * Get url for external authentication.
  224. * @param {boolean} [urlForPopup] if true then return url for login popup,
  225. * else url of login page.
  226. * @returns {Promise}
  227. */
  228. JitsiConference.prototype.getExternalAuthUrl = function(urlForPopup) {
  229. return new Promise((resolve, reject) => {
  230. if (!this.isExternalAuthEnabled()) {
  231. reject();
  232. return;
  233. }
  234. if (urlForPopup) {
  235. this.room.moderator.getPopupLoginUrl(resolve, reject);
  236. } else {
  237. this.room.moderator.getLoginUrl(resolve, reject);
  238. }
  239. });
  240. };
  241. /**
  242. * Returns the local tracks of the given media type, or all local tracks if no
  243. * specific type is given.
  244. * @param {MediaType} [mediaType] Optional media type (audio or video).
  245. */
  246. JitsiConference.prototype.getLocalTracks = function(mediaType) {
  247. let tracks = [];
  248. if (this.rtc) {
  249. tracks = this.rtc.getLocalTracks(mediaType);
  250. }
  251. return tracks;
  252. };
  253. /**
  254. * Obtains local audio track.
  255. * @return {JitsiLocalTrack|null}
  256. */
  257. JitsiConference.prototype.getLocalAudioTrack = function() {
  258. return this.rtc ? this.rtc.getLocalAudioTrack() : null;
  259. };
  260. /**
  261. * Obtains local video track.
  262. * @return {JitsiLocalTrack|null}
  263. */
  264. JitsiConference.prototype.getLocalVideoTrack = function() {
  265. return this.rtc ? this.rtc.getLocalVideoTrack() : null;
  266. };
  267. /**
  268. * Attaches a handler for events(For example - "participant joined".) in the
  269. * conference. All possible event are defined in JitsiConferenceEvents.
  270. * @param eventId the event ID.
  271. * @param handler handler for the event.
  272. *
  273. * Note: consider adding eventing functionality by extending an EventEmitter
  274. * impl, instead of rolling ourselves
  275. */
  276. JitsiConference.prototype.on = function(eventId, handler) {
  277. if (this.eventEmitter) {
  278. this.eventEmitter.on(eventId, handler);
  279. }
  280. };
  281. /**
  282. * Removes event listener
  283. * @param eventId the event ID.
  284. * @param [handler] optional, the specific handler to unbind
  285. *
  286. * Note: consider adding eventing functionality by extending an EventEmitter
  287. * impl, instead of rolling ourselves
  288. */
  289. JitsiConference.prototype.off = function(eventId, handler) {
  290. if (this.eventEmitter) {
  291. this.eventEmitter.removeListener(eventId, handler);
  292. }
  293. };
  294. // Common aliases for event emitter
  295. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  296. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  297. /**
  298. * Receives notifications from other participants about commands / custom events
  299. * (sent by sendCommand or sendCommandOnce methods).
  300. * @param command {String} the name of the command
  301. * @param handler {Function} handler for the command
  302. */
  303. JitsiConference.prototype.addCommandListener = function(command, handler) {
  304. if (this.room) {
  305. this.room.addPresenceListener(command, handler);
  306. }
  307. };
  308. /**
  309. * Removes command listener
  310. * @param command {String} the name of the command
  311. */
  312. JitsiConference.prototype.removeCommandListener = function(command) {
  313. if (this.room) {
  314. this.room.removePresenceListener(command);
  315. }
  316. };
  317. /**
  318. * Sends text message to the other participants in the conference
  319. * @param message the text message.
  320. */
  321. JitsiConference.prototype.sendTextMessage = function(message) {
  322. if (this.room) {
  323. this.room.sendMessage(message);
  324. }
  325. };
  326. /**
  327. * Send presence command.
  328. * @param name {String} the name of the command.
  329. * @param values {Object} with keys and values that will be sent.
  330. **/
  331. JitsiConference.prototype.sendCommand = function(name, values) {
  332. if (this.room) {
  333. this.room.addToPresence(name, values);
  334. this.room.sendPresence();
  335. }
  336. };
  337. /**
  338. * Send presence command one time.
  339. * @param name {String} the name of the command.
  340. * @param values {Object} with keys and values that will be sent.
  341. **/
  342. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  343. this.sendCommand(name, values);
  344. this.removeCommand(name);
  345. };
  346. /**
  347. * Removes presence command.
  348. * @param name {String} the name of the command.
  349. **/
  350. JitsiConference.prototype.removeCommand = function(name) {
  351. if (this.room) {
  352. this.room.removeFromPresence(name);
  353. }
  354. };
  355. /**
  356. * Sets the display name for this conference.
  357. * @param name the display name to set
  358. */
  359. JitsiConference.prototype.setDisplayName = function(name) {
  360. if (this.room) {
  361. // remove previously set nickname
  362. this.room.removeFromPresence('nick');
  363. this.room.addToPresence('nick', {
  364. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  365. value: name
  366. });
  367. this.room.sendPresence();
  368. }
  369. };
  370. /**
  371. * Set new subject for this conference. (available only for moderator)
  372. * @param {string} subject new subject
  373. */
  374. JitsiConference.prototype.setSubject = function(subject) {
  375. if (this.room && this.isModerator()) {
  376. this.room.setSubject(subject);
  377. }
  378. };
  379. /**
  380. * Get a transcriber object for all current participants in this conference
  381. * @return {Transcriber} the transcriber object
  382. */
  383. JitsiConference.prototype.getTranscriber = function() {
  384. if (this.transcriber === undefined) {
  385. this.transcriber = new Transcriber();
  386. // add all existing local audio tracks to the transcriber
  387. const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
  388. for (const localAudio of localAudioTracks) {
  389. this.transcriber.addTrack(localAudio);
  390. }
  391. // and all remote audio tracks
  392. const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
  393. for (const remoteTrack of remoteAudioTracks) {
  394. this.transcriber.addTrack(remoteTrack);
  395. }
  396. }
  397. return this.transcriber;
  398. };
  399. /**
  400. * Adds JitsiLocalTrack object to the conference.
  401. * @param track the JitsiLocalTrack object.
  402. * @returns {Promise<JitsiLocalTrack>}
  403. * @throws {Error} if the specified track is a video track and there is already
  404. * another video track in the conference.
  405. */
  406. JitsiConference.prototype.addTrack = function(track) {
  407. if (track.isVideoTrack()) {
  408. // Ensure there's exactly 1 local video track in the conference.
  409. const localVideoTrack = this.rtc.getLocalVideoTrack();
  410. if (localVideoTrack) {
  411. // Don't be excessively harsh and severe if the API client happens
  412. // to attempt to add the same local video track twice.
  413. if (track === localVideoTrack) {
  414. return Promise.resolve(track);
  415. }
  416. return Promise.reject(new Error(
  417. 'cannot add second video track to the conference'));
  418. }
  419. }
  420. return this.replaceTrack(null, track);
  421. };
  422. /**
  423. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  424. * @param audioLevel the audio level
  425. */
  426. JitsiConference.prototype._fireAudioLevelChangeEvent = function(audioLevel) {
  427. this.eventEmitter.emit(
  428. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  429. this.myUserId(), audioLevel);
  430. };
  431. /**
  432. * Fires TRACK_MUTE_CHANGED change conference event.
  433. * @param track the JitsiTrack object related to the event.
  434. */
  435. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  436. // check if track was muted by focus and now is unmuted by user
  437. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  438. this.isMutedByFocus = false;
  439. // unmute local user on server
  440. this.room.muteParticipant(this.room.myroomjid, false);
  441. }
  442. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  443. };
  444. /**
  445. * Clear JitsiLocalTrack properties and listeners.
  446. * @param track the JitsiLocalTrack object.
  447. */
  448. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  449. track._setSSRC(null);
  450. track._setConference(null);
  451. this.rtc.removeLocalTrack(track);
  452. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  453. track.muteHandler);
  454. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  455. track.audioLevelHandler);
  456. this.rtc.removeListener(RTCEvents.SENDRECV_STREAMS_CHANGED,
  457. track.ssrcHandler);
  458. // send event for stopping screen sharing
  459. // FIXME: we assume we have only one screen sharing track
  460. // if we change this we need to fix this check
  461. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP) {
  462. this.statistics.sendScreenSharingEvent(false);
  463. }
  464. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  465. };
  466. /**
  467. * Removes JitsiLocalTrack from the conference and performs
  468. * a new offer/answer cycle.
  469. * @param {JitsiLocalTrack} track
  470. * @returns {Promise}
  471. */
  472. JitsiConference.prototype.removeTrack = function(track) {
  473. return this.replaceTrack(track, null);
  474. };
  475. /**
  476. * Replaces oldTrack with newTrack and performs a single offer/answer
  477. * cycle after both operations are done. Either oldTrack or newTrack
  478. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  479. * effectively just removes 'oldTrack'
  480. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  481. * @param {JitsiLocalTrack} newTrack the new stream to use
  482. * @returns {Promise} resolves when the replacement is finished
  483. */
  484. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  485. // First do the removal of the oldTrack at the JitsiConference level
  486. if (oldTrack) {
  487. if (oldTrack.disposed) {
  488. return Promise.reject(
  489. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  490. }
  491. }
  492. if (newTrack) {
  493. if (newTrack.disposed) {
  494. return Promise.reject(
  495. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  496. }
  497. // Set up the ssrcHandler for the new track before we add it at the
  498. // lower levels
  499. newTrack.ssrcHandler = function(conference, ssrcMap) {
  500. const trackSSRCInfo = ssrcMap.get(this.getMSID());
  501. if (trackSSRCInfo) {
  502. this._setSSRC(trackSSRCInfo);
  503. conference.rtc.removeListener(
  504. RTCEvents.SENDRECV_STREAMS_CHANGED,
  505. this.ssrcHandler);
  506. }
  507. }.bind(newTrack, this);
  508. this.rtc.addListener(RTCEvents.SENDRECV_STREAMS_CHANGED,
  509. newTrack.ssrcHandler);
  510. }
  511. // Now replace the stream at the lower levels
  512. return this._doReplaceTrack(oldTrack, newTrack)
  513. .then(() => {
  514. if (oldTrack) {
  515. this.onLocalTrackRemoved(oldTrack);
  516. }
  517. if (newTrack) {
  518. // Now handle the addition of the newTrack at the
  519. // JitsiConference level
  520. this._setupNewTrack(newTrack);
  521. }
  522. return Promise.resolve();
  523. }, error => Promise.reject(new Error(error)));
  524. };
  525. /**
  526. * Replaces the tracks at the lower level by going through the Jingle session
  527. * and WebRTC peer connection. The method will resolve immediately if there is
  528. * currently no JingleSession started.
  529. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  530. * the process or <tt>null</t> if the method should act as "add track"
  531. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  532. * <tt>null</tt> if the method should act as "remove track"
  533. * @return {Promise}
  534. * @private
  535. */
  536. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  537. if (this.jingleSession) {
  538. return this.jingleSession.replaceTrack(oldTrack, newTrack);
  539. }
  540. return Promise.resolve();
  541. };
  542. /**
  543. * Operations related to creating a new track
  544. * @param {JitsiLocalTrack} newTrack the new track being created
  545. */
  546. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  547. if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
  548. && newTrack.videoType !== VideoType.DESKTOP)) {
  549. // Report active device to statistics
  550. const devices = RTC.getCurrentlyAvailableMediaDevices();
  551. const device
  552. = devices.find(
  553. d =>
  554. d.kind === `${newTrack.getTrack().kind}input`
  555. && d.label === newTrack.getTrack().label);
  556. if (device) {
  557. Statistics.sendActiveDeviceListEvent(
  558. RTC.getEventDataForActiveDevice(device));
  559. }
  560. }
  561. if (newTrack.isVideoTrack()) {
  562. this.removeCommand('videoType');
  563. this.sendCommand('videoType', {
  564. value: newTrack.videoType,
  565. attributes: {
  566. xmlns: 'http://jitsi.org/jitmeet/video'
  567. }
  568. });
  569. }
  570. this.rtc.addLocalTrack(newTrack);
  571. if (newTrack.startMuted) {
  572. newTrack.mute();
  573. }
  574. // ensure that we're sharing proper "is muted" state
  575. if (newTrack.isAudioTrack()) {
  576. this.room.setAudioMute(newTrack.isMuted());
  577. } else {
  578. this.room.setVideoMute(newTrack.isMuted());
  579. }
  580. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  581. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  582. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  583. newTrack.muteHandler);
  584. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  585. newTrack.audioLevelHandler);
  586. newTrack._setConference(this);
  587. // send event for starting screen sharing
  588. // FIXME: we assume we have only one screen sharing track
  589. // if we change this we need to fix this check
  590. if (newTrack.isVideoTrack() && newTrack.videoType === VideoType.DESKTOP) {
  591. this.statistics.sendScreenSharingEvent(true);
  592. }
  593. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  594. };
  595. /* eslint-disable max-params */
  596. /**
  597. * Adds loca WebRTC stream to the conference.
  598. * @param {MediaStream} stream new stream that will be added.
  599. * @param {function} callback callback executed after successful stream
  600. * addition.
  601. * @param {function(error)} errorCallback callback executed if stream addition
  602. * fail.
  603. * @param {object} ssrcInfo object with information about the SSRCs associated
  604. * with the stream.
  605. * @param {boolean} [dontModifySources] if <tt>true</tt> _modifySources won't be
  606. * called. The option is used for adding stream, before the Jingle call is
  607. * started. That is before the 'session-accept' is sent.
  608. */
  609. JitsiConference.prototype._addLocalStream = function(
  610. stream,
  611. callback,
  612. errorCallback,
  613. ssrcInfo,
  614. dontModifySources) {
  615. if (this.jingleSession) {
  616. this.jingleSession.addStream(
  617. stream,
  618. callback,
  619. errorCallback,
  620. ssrcInfo,
  621. dontModifySources);
  622. } else {
  623. // We are done immediately
  624. logger.warn('Add local MediaStream - no JingleSession started yet');
  625. callback();
  626. }
  627. };
  628. /**
  629. * Remove local WebRTC media stream.
  630. * @param {MediaStream} stream the stream that will be removed.
  631. * @param {function} callback callback executed after successful stream removal.
  632. * @param {function} errorCallback callback executed if stream removal fail.
  633. * @param {object} ssrcInfo object with information about the SSRCs associated
  634. * with the stream.
  635. */
  636. JitsiConference.prototype.removeLocalStream = function(
  637. stream,
  638. callback,
  639. errorCallback,
  640. ssrcInfo) {
  641. if (this.jingleSession) {
  642. this.jingleSession.removeStream(
  643. stream,
  644. callback,
  645. errorCallback,
  646. ssrcInfo);
  647. } else {
  648. // We are done immediately
  649. logger.warn('Remove local MediaStream - no JingleSession started yet');
  650. callback();
  651. }
  652. };
  653. /* eslint-enable max-params */
  654. /**
  655. * Generate ssrc info object for a stream with the following properties:
  656. * - ssrcs - Array of the ssrcs associated with the stream.
  657. * - groups - Array of the groups associated with the stream.
  658. */
  659. JitsiConference.prototype._generateNewStreamSSRCInfo = function() {
  660. if (!this.jingleSession) {
  661. logger.warn('The call haven\'t been started. '
  662. + 'Cannot generate ssrc info at the moment!');
  663. return null;
  664. }
  665. return this.jingleSession.generateNewStreamSSRCInfo();
  666. };
  667. /**
  668. * Get role of the local user.
  669. * @returns {string} user role: 'moderator' or 'none'
  670. */
  671. JitsiConference.prototype.getRole = function() {
  672. return this.room.role;
  673. };
  674. /**
  675. * Check if local user is moderator.
  676. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  677. * we're no longer in the conference room then <tt>null</tt> is returned.
  678. */
  679. JitsiConference.prototype.isModerator = function() {
  680. return this.room ? this.room.isModerator() : null;
  681. };
  682. /**
  683. * Set password for the room.
  684. * @param {string} password new password for the room.
  685. * @returns {Promise}
  686. */
  687. JitsiConference.prototype.lock = function(password) {
  688. if (!this.isModerator()) {
  689. return Promise.reject();
  690. }
  691. return new Promise((resolve, reject) => {
  692. this.room.lockRoom(
  693. password || '',
  694. () => resolve(),
  695. err => reject(err),
  696. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  697. });
  698. };
  699. /**
  700. * Remove password from the room.
  701. * @returns {Promise}
  702. */
  703. JitsiConference.prototype.unlock = function() {
  704. return this.lock();
  705. };
  706. /**
  707. * Elects the participant with the given id to be the selected participant in
  708. * order to receive higher video quality (if simulcast is enabled).
  709. * Or cache it if channel is not created and send it once channel is available.
  710. * @param participantId the identifier of the participant
  711. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  712. */
  713. JitsiConference.prototype.selectParticipant = function(participantId) {
  714. this.rtc.selectEndpoint(participantId);
  715. };
  716. /**
  717. * Elects the participant with the given id to be the pinned participant in
  718. * order to always receive video for this participant (even when last n is
  719. * enabled).
  720. * @param participantId the identifier of the participant
  721. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  722. */
  723. JitsiConference.prototype.pinParticipant = function(participantId) {
  724. this.rtc.pinEndpoint(participantId);
  725. };
  726. /**
  727. * Selects a new value for "lastN". The requested amount of videos are going
  728. * to be delivered after the value is in effect. Set to -1 for unlimited or
  729. * all available videos.
  730. * @param lastN the new number of videos the user would like to receive.
  731. * @throws Error or RangeError if the given value is not a number or is smaller
  732. * than -1.
  733. */
  734. JitsiConference.prototype.setLastN = function(lastN) {
  735. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  736. throw new Error(`Invalid value for lastN: ${lastN}`);
  737. }
  738. const n = Number(lastN);
  739. if (n < -1) {
  740. throw new RangeError('lastN cannot be smaller than -1');
  741. }
  742. this.rtc.setLastN(n);
  743. };
  744. /**
  745. * Checks if the participant given by participantId is currently included in
  746. * the last N.
  747. * @param {string} participantId the identifier of the participant we would
  748. * like to check
  749. * @return {boolean} true if the participant with id is in the last N set or
  750. * if there's no last N set, false otherwise
  751. */
  752. JitsiConference.prototype.isInLastN = function(participantId) {
  753. return this.rtc.isInLastN(participantId);
  754. };
  755. /**
  756. * @return Array<JitsiParticipant> an array of all participants in this
  757. * conference.
  758. */
  759. JitsiConference.prototype.getParticipants = function() {
  760. return Object.keys(this.participants).map(function(key) {
  761. return this.participants[key];
  762. }, this);
  763. };
  764. /**
  765. * Returns the number of participants in the conference, including the local
  766. * participant.
  767. * @param countHidden {boolean} Whether or not to include hidden participants
  768. * in the count. Default: false.
  769. **/
  770. JitsiConference.prototype.getParticipantCount
  771. = function(countHidden = false) {
  772. let participants = this.getParticipants();
  773. if (!countHidden) {
  774. participants = participants.filter(p => !p.isHidden());
  775. }
  776. // Add one for the local participant.
  777. return participants.length + 1;
  778. };
  779. /**
  780. * @returns {JitsiParticipant} the participant in this conference with the
  781. * specified id (or undefined if there isn't one).
  782. * @param id the id of the participant.
  783. */
  784. JitsiConference.prototype.getParticipantById = function(id) {
  785. return this.participants[id];
  786. };
  787. /**
  788. * Kick participant from this conference.
  789. * @param {string} id id of the participant to kick
  790. */
  791. JitsiConference.prototype.kickParticipant = function(id) {
  792. const participant = this.getParticipantById(id);
  793. if (!participant) {
  794. return;
  795. }
  796. this.room.kick(participant.getJid());
  797. };
  798. /**
  799. * Mutes a participant.
  800. * @param {string} id The id of the participant to mute.
  801. */
  802. JitsiConference.prototype.muteParticipant = function(id) {
  803. const participant = this.getParticipantById(id);
  804. if (!participant) {
  805. return;
  806. }
  807. this.room.muteParticipant(participant.getJid(), true);
  808. };
  809. /* eslint-disable max-params */
  810. /**
  811. * Notifies this JitsiConference that a new member has joined its chat room.
  812. *
  813. * FIXME This should NOT be exposed!
  814. *
  815. * @param jid the jid of the participant in the MUC
  816. * @param nick the display name of the participant
  817. * @param role the role of the participant in the MUC
  818. * @param isHidden indicates if this is a hidden participant (system
  819. * participant for example a recorder).
  820. */
  821. JitsiConference.prototype.onMemberJoined = function(jid, nick, role, isHidden) {
  822. const id = Strophe.getResourceFromJid(jid);
  823. if (id === 'focus' || this.myUserId() === id) {
  824. return;
  825. }
  826. const participant = new JitsiParticipant(jid, this, nick, isHidden);
  827. participant._role = role;
  828. this.participants[id] = participant;
  829. this.eventEmitter.emit(
  830. JitsiConferenceEvents.USER_JOINED,
  831. id,
  832. participant);
  833. this.xmpp.caps.getFeatures(jid)
  834. .then(features => {
  835. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  836. this.updateDTMFSupport();
  837. },
  838. error => logger.error(error));
  839. };
  840. /* eslint-enable max-params */
  841. JitsiConference.prototype.onMemberLeft = function(jid) {
  842. const id = Strophe.getResourceFromJid(jid);
  843. if (id === 'focus' || this.myUserId() === id) {
  844. return;
  845. }
  846. const participant = this.participants[id];
  847. delete this.participants[id];
  848. const removedTracks = this.rtc.removeRemoteTracks(id);
  849. removedTracks.forEach(
  850. track =>
  851. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  852. // there can be no participant in case the member that left is focus
  853. if (participant) {
  854. this.eventEmitter.emit(
  855. JitsiConferenceEvents.USER_LEFT, id, participant);
  856. }
  857. };
  858. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  859. const id = Strophe.getResourceFromJid(jid);
  860. const participant = this.getParticipantById(id);
  861. if (!participant) {
  862. return;
  863. }
  864. participant._role = role;
  865. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  866. };
  867. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  868. const id = Strophe.getResourceFromJid(jid);
  869. const participant = this.getParticipantById(id);
  870. if (!participant) {
  871. return;
  872. }
  873. if (participant._displayName === displayName) {
  874. return;
  875. }
  876. participant._displayName = displayName;
  877. this.eventEmitter.emit(
  878. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  879. id,
  880. displayName);
  881. };
  882. /**
  883. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  884. * the conference.
  885. *
  886. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  887. * JitsiConference
  888. */
  889. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  890. const id = track.getParticipantId();
  891. const participant = this.getParticipantById(id);
  892. if (!participant) {
  893. logger.error(`No participant found for id: ${id}`);
  894. return;
  895. }
  896. // Add track to JitsiParticipant.
  897. participant._tracks.push(track);
  898. if (this.transcriber) {
  899. this.transcriber.addTrack(track);
  900. }
  901. const emitter = this.eventEmitter;
  902. track.addEventListener(
  903. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  904. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  905. track.addEventListener(
  906. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  907. audioLevel => {
  908. emitter.emit(
  909. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  910. id,
  911. audioLevel);
  912. }
  913. );
  914. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  915. };
  916. /**
  917. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  918. * the conference.
  919. *
  920. * @param {JitsiRemoteTrack} removedTrack
  921. */
  922. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  923. let consumed = false;
  924. this.getParticipants().forEach(function(participant) {
  925. const tracks = participant.getTracks();
  926. for (let i = 0; i < tracks.length; i++) {
  927. if (tracks[i] === removedTrack) {
  928. // Since the tracks have been compared and are
  929. // considered equal the result of splice can be ignored.
  930. participant._tracks.splice(i, 1);
  931. this.eventEmitter.emit(
  932. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  933. if (this.transcriber) {
  934. this.transcriber.removeTrack(removedTrack);
  935. }
  936. consumed = true;
  937. break;
  938. }
  939. }
  940. }, this);
  941. if (!consumed) {
  942. logger.error(
  943. 'Failed to match remote track on remove'
  944. + ' with any of the participants',
  945. removedTrack.getStreamId(),
  946. removedTrack.getParticipantId());
  947. }
  948. };
  949. /**
  950. * Handles incoming call event.
  951. */
  952. JitsiConference.prototype.onIncomingCall
  953. = function(jingleSession, jingleOffer, now) {
  954. if (!this.room.isFocus(jingleSession.peerjid)) {
  955. // Error cause this should never happen unless something is wrong!
  956. const errmsg = `Rejecting session-initiate from non-focus user: ${
  957. jingleSession.peerjid}`;
  958. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  959. logger.error(errmsg);
  960. // Terminate the jingle session with a reason
  961. jingleSession.terminate(
  962. 'security-error', 'Only focus can start new sessions',
  963. null /* success callback => we don't care */,
  964. error => {
  965. logger.warn(
  966. 'An error occurred while trying to terminate invalid Jingle'
  967. + ' session',
  968. error);
  969. });
  970. return;
  971. }
  972. // Accept incoming call
  973. this.jingleSession = jingleSession;
  974. this.room.connectionTimes['session.initiate'] = now;
  975. // Log "session.restart"
  976. if (this.wasStopped) {
  977. Statistics.sendEventToAll('session.restart');
  978. }
  979. // add info whether call is cross-region
  980. let crossRegion = null;
  981. if (window.jitsiRegionInfo) {
  982. crossRegion = window.jitsiRegionInfo.CrossRegion;
  983. }
  984. Statistics.analytics.sendEvent(
  985. 'session.initiate', {
  986. value: now - this.room.connectionTimes['muc.joined'],
  987. label: crossRegion
  988. });
  989. try {
  990. jingleSession.initialize(false /* initiator */, this.room, this.rtc);
  991. } catch (error) {
  992. GlobalOnErrorHandler.callErrorHandler(error);
  993. }
  994. this.rtc.initializeDataChannels(jingleSession.peerconnection);
  995. // Add local Tracks to the ChatRoom
  996. this.getLocalTracks().forEach(localTrack => {
  997. let ssrcInfo = null;
  998. /**
  999. * We don't do this for Firefox because, on Firefox, we keep the
  1000. * stream in the peer connection and just set 'enabled' on the
  1001. * track to false (see JitsiLocalTrack::_setMute). This means
  1002. * that if we generated an ssrc here and set it in the cache, it
  1003. * would clash with the one firefox generates (since, unlike chrome,
  1004. * the stream is still attached to the peer connection) and causes
  1005. * problems between sdp-interop and trying to keep the ssrcs
  1006. * consistent
  1007. */
  1008. if (localTrack.isVideoTrack()
  1009. && localTrack.isMuted()
  1010. && !RTCBrowserType.isFirefox()) {
  1011. /**
  1012. * Handles issues when the stream is added before the peerconnection
  1013. * is created. The peerconnection is created when second participant
  1014. * enters the call. In that use case the track doesn't have
  1015. * information about it's ssrcs and no jingle packets are sent. That
  1016. * can cause inconsistent behavior later.
  1017. *
  1018. * For example:
  1019. * If we mute the stream and than second participant enter it's
  1020. * remote SDP won't include that track. On unmute we are not sending
  1021. * any jingle packets which will brake the unmute.
  1022. *
  1023. * In order to solve issues like the above one here we have to
  1024. * generate the ssrc information for the track .
  1025. */
  1026. localTrack._setSSRC(this._generateNewStreamSSRCInfo());
  1027. ssrcInfo = {
  1028. mtype: localTrack.getType(),
  1029. type: 'addMuted',
  1030. ssrcs: localTrack.ssrc.ssrcs,
  1031. groups: localTrack.ssrc.groups,
  1032. msid: localTrack.initialMSID
  1033. };
  1034. }
  1035. try {
  1036. this._addLocalStream(
  1037. localTrack.getOriginalStream(),
  1038. () => {
  1039. // There is nothing to be done after the stream is added.
  1040. },
  1041. () => {
  1042. // TODO: Maybe report the error to the user?
  1043. },
  1044. ssrcInfo,
  1045. true /* don't modify SSRCs */);
  1046. } catch (e) {
  1047. GlobalOnErrorHandler.callErrorHandler(e);
  1048. logger.error(e);
  1049. }
  1050. });
  1051. // Generate the 'recvonly' SSRC in case there are no video tracks
  1052. if (!this.getLocalTracks(MediaType.VIDEO).length) {
  1053. jingleSession.generateRecvonlySsrc();
  1054. }
  1055. jingleSession.acceptOffer(jingleOffer, null,
  1056. error => {
  1057. GlobalOnErrorHandler.callErrorHandler(error);
  1058. logger.error(
  1059. 'Failed to accept incoming Jingle session', error);
  1060. }
  1061. );
  1062. // Start callstats as soon as peerconnection is initialized,
  1063. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1064. // happen in case if user doesn't have or denied permission to
  1065. // both camera and microphone.
  1066. this.statistics.startCallStats(jingleSession);
  1067. this.statistics.startRemoteStats(jingleSession.peerconnection);
  1068. };
  1069. /**
  1070. * Handles the call ended event.
  1071. * @param {JingleSessionPC} JingleSession the jingle session which has been
  1072. * terminated.
  1073. * @param {String} reasonCondition the Jingle reason condition.
  1074. * @param {String|null} reasonText human readable reason text which may provide
  1075. * more details about why the call has been terminated.
  1076. */
  1077. JitsiConference.prototype.onCallEnded
  1078. = function(JingleSession, reasonCondition, reasonText) {
  1079. logger.info(`Call ended: ${reasonCondition} - ${reasonText}`);
  1080. this.wasStopped = true;
  1081. // Send session.terminate event
  1082. Statistics.sendEventToAll('session.terminate');
  1083. // Stop the stats
  1084. if (this.statistics) {
  1085. this.statistics.stopRemoteStats();
  1086. this.statistics.stopCallStats();
  1087. }
  1088. // Current JingleSession is invalid so set it to null on the room
  1089. this.jingleSession = null;
  1090. // Let the RTC service do any cleanups
  1091. this.rtc.onCallEnded();
  1092. // PeerConnection has been closed which means that SSRCs stored in
  1093. // JitsiLocalTrack will not match those assigned by the old PeerConnection
  1094. // and SSRC replacement logic will not work as expected.
  1095. // We want to re-register 'ssrcHandler' of our local tracks, so that they
  1096. // will learn what their SSRC from the new PeerConnection which will be
  1097. // created on incoming call event.
  1098. const self = this;
  1099. this.getLocalTracks().forEach(localTrack => {
  1100. // Reset SSRC as it will no longer be valid
  1101. localTrack._setSSRC(null);
  1102. // Bind the handler to fetch new SSRC, it will un register itself once
  1103. // it reads the values
  1104. self.rtc.addListener(
  1105. RTCEvents.SENDRECV_STREAMS_CHANGED, localTrack.ssrcHandler);
  1106. });
  1107. };
  1108. /**
  1109. * Handles the suspend detected event. Leaves the room and fires suspended.
  1110. */
  1111. JitsiConference.prototype.onSuspendDetected = function() {
  1112. this.leave();
  1113. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1114. };
  1115. JitsiConference.prototype.updateDTMFSupport = function() {
  1116. let somebodySupportsDTMF = false;
  1117. const participants = this.getParticipants();
  1118. // check if at least 1 participant supports DTMF
  1119. for (let i = 0; i < participants.length; i += 1) {
  1120. if (participants[i].supportsDTMF()) {
  1121. somebodySupportsDTMF = true;
  1122. break;
  1123. }
  1124. }
  1125. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1126. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1127. this.eventEmitter.emit(
  1128. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1129. somebodySupportsDTMF);
  1130. }
  1131. };
  1132. /**
  1133. * Allows to check if there is at least one user in the conference
  1134. * that supports DTMF.
  1135. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1136. */
  1137. JitsiConference.prototype.isDTMFSupported = function() {
  1138. return this.somebodySupportsDTMF;
  1139. };
  1140. /**
  1141. * Returns the local user's ID
  1142. * @return {string} local user's ID
  1143. */
  1144. JitsiConference.prototype.myUserId = function() {
  1145. return (
  1146. this.room
  1147. && this.room.myroomjid
  1148. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1149. : null);
  1150. };
  1151. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1152. // FIXME P2P 'dtmfManager' must be cleared, after switching jingleSessions
  1153. if (!this.dtmfManager) {
  1154. if (!this.jingleSession) {
  1155. logger.warn('cannot sendTones: no jingle session');
  1156. return;
  1157. }
  1158. const peerConnection = this.jingleSession.peerconnection;
  1159. if (!peerConnection) {
  1160. logger.warn('cannot sendTones: no peer connection');
  1161. return;
  1162. }
  1163. const localAudio = this.getLocalAudioTrack();
  1164. if (!localAudio) {
  1165. logger.warn('cannot sendTones: no local audio stream');
  1166. return;
  1167. }
  1168. this.dtmfManager = new JitsiDTMFManager(localAudio, peerConnection);
  1169. }
  1170. this.dtmfManager.sendTones(tones, duration, pause);
  1171. };
  1172. /**
  1173. * Returns true if recording is supported and false if not.
  1174. */
  1175. JitsiConference.prototype.isRecordingSupported = function() {
  1176. if (this.room) {
  1177. return this.room.isRecordingSupported();
  1178. }
  1179. return false;
  1180. };
  1181. /**
  1182. * Returns null if the recording is not supported, "on" if the recording started
  1183. * and "off" if the recording is not started.
  1184. */
  1185. JitsiConference.prototype.getRecordingState = function() {
  1186. return this.room ? this.room.getRecordingState() : undefined;
  1187. };
  1188. /**
  1189. * Returns the url of the recorded video.
  1190. */
  1191. JitsiConference.prototype.getRecordingURL = function() {
  1192. return this.room ? this.room.getRecordingURL() : null;
  1193. };
  1194. /**
  1195. * Starts/stops the recording
  1196. */
  1197. JitsiConference.prototype.toggleRecording = function(options) {
  1198. if (this.room) {
  1199. return this.room.toggleRecording(options, (status, error) => {
  1200. this.eventEmitter.emit(
  1201. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  1202. });
  1203. }
  1204. this.eventEmitter.emit(
  1205. JitsiConferenceEvents.RECORDER_STATE_CHANGED, 'error',
  1206. new Error('The conference is not created yet!'));
  1207. };
  1208. /**
  1209. * Returns true if the SIP calls are supported and false otherwise
  1210. */
  1211. JitsiConference.prototype.isSIPCallingSupported = function() {
  1212. if (this.room) {
  1213. return this.room.isSIPCallingSupported();
  1214. }
  1215. return false;
  1216. };
  1217. /**
  1218. * Dials a number.
  1219. * @param number the number
  1220. */
  1221. JitsiConference.prototype.dial = function(number) {
  1222. if (this.room) {
  1223. return this.room.dial(number);
  1224. }
  1225. return new Promise((resolve, reject) => {
  1226. reject(new Error('The conference is not created yet!'));
  1227. });
  1228. };
  1229. /**
  1230. * Hangup an existing call
  1231. */
  1232. JitsiConference.prototype.hangup = function() {
  1233. if (this.room) {
  1234. return this.room.hangup();
  1235. }
  1236. return new Promise((resolve, reject) => {
  1237. reject(new Error('The conference is not created yet!'));
  1238. });
  1239. };
  1240. /**
  1241. * Returns the phone number for joining the conference.
  1242. */
  1243. JitsiConference.prototype.getPhoneNumber = function() {
  1244. if (this.room) {
  1245. return this.room.getPhoneNumber();
  1246. }
  1247. return null;
  1248. };
  1249. /**
  1250. * Returns the pin for joining the conference with phone.
  1251. */
  1252. JitsiConference.prototype.getPhonePin = function() {
  1253. if (this.room) {
  1254. return this.room.getPhonePin();
  1255. }
  1256. return null;
  1257. };
  1258. /**
  1259. * Returns the connection state for the current room. Its ice connection state
  1260. * for its session.
  1261. */
  1262. JitsiConference.prototype.getConnectionState = function() {
  1263. if (this.jingleSession) {
  1264. return this.jingleSession.getIceConnectionState();
  1265. }
  1266. return null;
  1267. };
  1268. /**
  1269. * Make all new participants mute their audio/video on join.
  1270. * @param policy {Object} object with 2 boolean properties for video and audio:
  1271. * @param {boolean} audio if audio should be muted.
  1272. * @param {boolean} video if video should be muted.
  1273. */
  1274. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  1275. if (!this.isModerator()) {
  1276. return;
  1277. }
  1278. this.startMutedPolicy = policy;
  1279. this.room.removeFromPresence('startmuted');
  1280. this.room.addToPresence('startmuted', {
  1281. attributes: {
  1282. audio: policy.audio,
  1283. video: policy.video,
  1284. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1285. }
  1286. });
  1287. this.room.sendPresence();
  1288. };
  1289. /**
  1290. * Returns current start muted policy
  1291. * @returns {Object} with 2 properties - audio and video.
  1292. */
  1293. JitsiConference.prototype.getStartMutedPolicy = function() {
  1294. return this.startMutedPolicy;
  1295. };
  1296. /**
  1297. * Check if audio is muted on join.
  1298. */
  1299. JitsiConference.prototype.isStartAudioMuted = function() {
  1300. return this.startAudioMuted;
  1301. };
  1302. /**
  1303. * Check if video is muted on join.
  1304. */
  1305. JitsiConference.prototype.isStartVideoMuted = function() {
  1306. return this.startVideoMuted;
  1307. };
  1308. /**
  1309. * Get object with internal logs.
  1310. */
  1311. JitsiConference.prototype.getLogs = function() {
  1312. const data = this.xmpp.getJingleLog();
  1313. const metadata = {};
  1314. metadata.time = new Date();
  1315. metadata.url = window.location.href;
  1316. metadata.ua = navigator.userAgent;
  1317. const log = this.xmpp.getXmppLog();
  1318. if (log) {
  1319. metadata.xmpp = log;
  1320. }
  1321. data.metadata = metadata;
  1322. return data;
  1323. };
  1324. /**
  1325. * Returns measured connectionTimes.
  1326. */
  1327. JitsiConference.prototype.getConnectionTimes = function() {
  1328. return this.room.connectionTimes;
  1329. };
  1330. /**
  1331. * Sets a property for the local participant.
  1332. */
  1333. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1334. this.sendCommand(`jitsi_participant_${name}`, { value });
  1335. };
  1336. /**
  1337. * Sends the given feedback through CallStats if enabled.
  1338. *
  1339. * @param overallFeedback an integer between 1 and 5 indicating the
  1340. * user feedback
  1341. * @param detailedFeedback detailed feedback from the user. Not yet used
  1342. */
  1343. JitsiConference.prototype.sendFeedback
  1344. = function(overallFeedback, detailedFeedback) {
  1345. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1346. };
  1347. /**
  1348. * Returns true if the callstats integration is enabled, otherwise returns
  1349. * false.
  1350. *
  1351. * @returns true if the callstats integration is enabled, otherwise returns
  1352. * false.
  1353. */
  1354. JitsiConference.prototype.isCallstatsEnabled = function() {
  1355. return this.statistics.isCallstatsEnabled();
  1356. };
  1357. /**
  1358. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1359. * from statistics module)
  1360. * @param track the track
  1361. * @param container the container
  1362. */
  1363. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1364. const ssrc = track.getSSRC();
  1365. if (!container.id || !ssrc) {
  1366. return;
  1367. }
  1368. this.statistics.associateStreamWithVideoTag(
  1369. ssrc, track.isLocal(), track.getUsageLabel(), container.id);
  1370. };
  1371. /**
  1372. * Logs an "application log" message.
  1373. * @param message {string} The message to log. Note that while this can be a
  1374. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1375. * log valid JSON strings, with an "id" field used for distinguishing between
  1376. * message types. E.g.: {id: "recorder_status", status: "off"}
  1377. */
  1378. JitsiConference.prototype.sendApplicationLog = function(message) {
  1379. Statistics.sendLog(message);
  1380. };
  1381. /**
  1382. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1383. * focus.
  1384. * @param mucJid the full MUC address of the user to be checked.
  1385. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1386. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1387. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1388. */
  1389. JitsiConference.prototype._isFocus = function(mucJid) {
  1390. return this.room ? this.room.isFocus(mucJid) : null;
  1391. };
  1392. /**
  1393. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1394. */
  1395. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  1396. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1397. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1398. };
  1399. /**
  1400. * Sends a message via the data channel.
  1401. * @param to {string} the id of the endpoint that should receive the message.
  1402. * If "" the message will be sent to all participants.
  1403. * @param payload {object} the payload of the message.
  1404. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1405. */
  1406. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  1407. this.rtc.sendDataChannelMessage(to, payload);
  1408. };
  1409. /**
  1410. * Sends a broadcast message via the data channel.
  1411. * @param payload {object} the payload of the message.
  1412. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1413. */
  1414. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  1415. this.sendEndpointMessage('', payload);
  1416. };
  1417. JitsiConference.prototype.isConnectionInterrupted = function() {
  1418. return this.connectionIsInterrupted;
  1419. };
  1420. /**
  1421. * Get a summary of how long current participants have been the dominant speaker
  1422. * @returns {object}
  1423. */
  1424. JitsiConference.prototype.getSpeakerStats = function() {
  1425. return this.speakerStatsCollector.getStats();
  1426. };
  1427. module.exports = JitsiConference;