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 49KB

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