Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 50KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  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. * @return Array<JitsiParticipant> an array of all participants in this
  746. * conference.
  747. */
  748. JitsiConference.prototype.getParticipants = function() {
  749. return Object.keys(this.participants).map(function(key) {
  750. return this.participants[key];
  751. }, this);
  752. };
  753. /**
  754. * Returns the number of participants in the conference, including the local
  755. * participant.
  756. * @param countHidden {boolean} Whether or not to include hidden participants
  757. * in the count. Default: false.
  758. **/
  759. JitsiConference.prototype.getParticipantCount
  760. = function(countHidden = false) {
  761. let participants = this.getParticipants();
  762. if (!countHidden) {
  763. participants = participants.filter(p => !p.isHidden());
  764. }
  765. // Add one for the local participant.
  766. return participants.length + 1;
  767. };
  768. /**
  769. * @returns {JitsiParticipant} the participant in this conference with the
  770. * specified id (or undefined if there isn't one).
  771. * @param id the id of the participant.
  772. */
  773. JitsiConference.prototype.getParticipantById = function(id) {
  774. return this.participants[id];
  775. };
  776. /**
  777. * Kick participant from this conference.
  778. * @param {string} id id of the participant to kick
  779. */
  780. JitsiConference.prototype.kickParticipant = function(id) {
  781. const participant = this.getParticipantById(id);
  782. if (!participant) {
  783. return;
  784. }
  785. this.room.kick(participant.getJid());
  786. };
  787. /**
  788. * Mutes a participant.
  789. * @param {string} id The id of the participant to mute.
  790. */
  791. JitsiConference.prototype.muteParticipant = function(id) {
  792. const participant = this.getParticipantById(id);
  793. if (!participant) {
  794. return;
  795. }
  796. this.room.muteParticipant(participant.getJid(), true);
  797. };
  798. /* eslint-disable max-params */
  799. /**
  800. * Notifies this JitsiConference that a new member has joined its chat room.
  801. *
  802. * FIXME This should NOT be exposed!
  803. *
  804. * @param jid the jid of the participant in the MUC
  805. * @param nick the display name of the participant
  806. * @param role the role of the participant in the MUC
  807. * @param isHidden indicates if this is a hidden participant (system
  808. * participant for example a recorder).
  809. */
  810. JitsiConference.prototype.onMemberJoined = function(jid, nick, role, isHidden) {
  811. const id = Strophe.getResourceFromJid(jid);
  812. if (id === 'focus' || this.myUserId() === id) {
  813. return;
  814. }
  815. const participant = new JitsiParticipant(jid, this, nick, isHidden);
  816. participant._role = role;
  817. this.participants[id] = participant;
  818. this.eventEmitter.emit(
  819. JitsiConferenceEvents.USER_JOINED,
  820. id,
  821. participant);
  822. this.xmpp.caps.getFeatures(jid)
  823. .then(features => {
  824. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  825. this.updateDTMFSupport();
  826. },
  827. error => logger.error(error));
  828. };
  829. /* eslint-enable max-params */
  830. JitsiConference.prototype.onMemberLeft = function(jid) {
  831. const id = Strophe.getResourceFromJid(jid);
  832. if (id === 'focus' || this.myUserId() === id) {
  833. return;
  834. }
  835. const participant = this.participants[id];
  836. delete this.participants[id];
  837. const removedTracks = this.rtc.removeRemoteTracks(id);
  838. removedTracks.forEach(
  839. track =>
  840. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  841. // there can be no participant in case the member that left is focus
  842. if (participant) {
  843. this.eventEmitter.emit(
  844. JitsiConferenceEvents.USER_LEFT, id, participant);
  845. }
  846. };
  847. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  848. const id = Strophe.getResourceFromJid(jid);
  849. const participant = this.getParticipantById(id);
  850. if (!participant) {
  851. return;
  852. }
  853. participant._role = role;
  854. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  855. };
  856. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  857. const id = Strophe.getResourceFromJid(jid);
  858. const participant = this.getParticipantById(id);
  859. if (!participant) {
  860. return;
  861. }
  862. if (participant._displayName === displayName) {
  863. return;
  864. }
  865. participant._displayName = displayName;
  866. this.eventEmitter.emit(
  867. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  868. id,
  869. displayName);
  870. };
  871. /**
  872. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  873. * the conference.
  874. *
  875. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  876. * JitsiConference
  877. */
  878. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  879. const id = track.getParticipantId();
  880. const participant = this.getParticipantById(id);
  881. if (!participant) {
  882. logger.error(`No participant found for id: ${id}`);
  883. return;
  884. }
  885. // Add track to JitsiParticipant.
  886. participant._tracks.push(track);
  887. if (this.transcriber) {
  888. this.transcriber.addTrack(track);
  889. }
  890. const emitter = this.eventEmitter;
  891. track.addEventListener(
  892. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  893. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  894. track.addEventListener(
  895. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  896. audioLevel => {
  897. emitter.emit(
  898. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  899. id,
  900. audioLevel);
  901. }
  902. );
  903. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  904. };
  905. /**
  906. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  907. * the conference.
  908. *
  909. * @param {JitsiRemoteTrack} removedTrack
  910. */
  911. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  912. let consumed = false;
  913. this.getParticipants().forEach(function(participant) {
  914. const tracks = participant.getTracks();
  915. for (let i = 0; i < tracks.length; i++) {
  916. if (tracks[i] === removedTrack) {
  917. // Since the tracks have been compared and are
  918. // considered equal the result of splice can be ignored.
  919. participant._tracks.splice(i, 1);
  920. this.eventEmitter.emit(
  921. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  922. if (this.transcriber) {
  923. this.transcriber.removeTrack(removedTrack);
  924. }
  925. consumed = true;
  926. break;
  927. }
  928. }
  929. }, this);
  930. if (!consumed) {
  931. logger.error(
  932. 'Failed to match remote track on remove'
  933. + ' with any of the participants',
  934. removedTrack.getStreamId(),
  935. removedTrack.getParticipantId());
  936. }
  937. };
  938. /**
  939. * Handles incoming call event.
  940. */
  941. JitsiConference.prototype.onIncomingCall
  942. = function(jingleSession, jingleOffer, now) {
  943. if (!this.room.isFocus(jingleSession.peerjid)) {
  944. // Error cause this should never happen unless something is wrong!
  945. const errmsg = `Rejecting session-initiate from non-focus user: ${
  946. jingleSession.peerjid}`;
  947. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  948. logger.error(errmsg);
  949. // Terminate the jingle session with a reason
  950. jingleSession.terminate(
  951. 'security-error', 'Only focus can start new sessions',
  952. null /* success callback => we don't care */,
  953. error => {
  954. logger.warn(
  955. 'An error occurred while trying to terminate invalid Jingle'
  956. + ' session',
  957. error);
  958. });
  959. return;
  960. }
  961. // Accept incoming call
  962. this.jingleSession = jingleSession;
  963. this.room.connectionTimes['session.initiate'] = now;
  964. // Log "session.restart"
  965. if (this.wasStopped) {
  966. Statistics.sendEventToAll('session.restart');
  967. }
  968. // add info whether call is cross-region
  969. let crossRegion = null;
  970. if (window.jitsiRegionInfo) {
  971. crossRegion = window.jitsiRegionInfo.CrossRegion;
  972. }
  973. Statistics.analytics.sendEvent(
  974. 'session.initiate', {
  975. value: now - this.room.connectionTimes['muc.joined'],
  976. label: crossRegion
  977. });
  978. try {
  979. jingleSession.initialize(false /* initiator */, this.room, this.rtc);
  980. } catch (error) {
  981. GlobalOnErrorHandler.callErrorHandler(error);
  982. }
  983. this.rtc.initializeDataChannels(jingleSession.peerconnection);
  984. // Add local Tracks to the ChatRoom
  985. this.getLocalTracks().forEach(localTrack => {
  986. let ssrcInfo = null;
  987. /**
  988. * We don't do this for Firefox because, on Firefox, we keep the
  989. * stream in the peer connection and just set 'enabled' on the
  990. * track to false (see JitsiLocalTrack::_setMute). This means
  991. * that if we generated an ssrc here and set it in the cache, it
  992. * would clash with the one firefox generates (since, unlike chrome,
  993. * the stream is still attached to the peer connection) and causes
  994. * problems between sdp-interop and trying to keep the ssrcs
  995. * consistent
  996. */
  997. if (localTrack.isVideoTrack()
  998. && localTrack.isMuted()
  999. && !RTCBrowserType.isFirefox()) {
  1000. /**
  1001. * Handles issues when the stream is added before the peerconnection
  1002. * is created. The peerconnection is created when second participant
  1003. * enters the call. In that use case the track doesn't have
  1004. * information about it's ssrcs and no jingle packets are sent. That
  1005. * can cause inconsistent behavior later.
  1006. *
  1007. * For example:
  1008. * If we mute the stream and than second participant enter it's
  1009. * remote SDP won't include that track. On unmute we are not sending
  1010. * any jingle packets which will brake the unmute.
  1011. *
  1012. * In order to solve issues like the above one here we have to
  1013. * generate the ssrc information for the track .
  1014. */
  1015. localTrack._setSSRC(this._generateNewStreamSSRCInfo());
  1016. ssrcInfo = {
  1017. mtype: localTrack.getType(),
  1018. type: 'addMuted',
  1019. ssrcs: localTrack.ssrc.ssrcs,
  1020. groups: localTrack.ssrc.groups,
  1021. msid: localTrack.initialMSID
  1022. };
  1023. }
  1024. try {
  1025. this._addLocalStream(
  1026. localTrack.getOriginalStream(),
  1027. () => {
  1028. // There is nothing to be done after the stream is added.
  1029. },
  1030. () => {
  1031. // TODO: Maybe report the error to the user?
  1032. },
  1033. ssrcInfo,
  1034. true /* don't modify SSRCs */);
  1035. } catch (e) {
  1036. GlobalOnErrorHandler.callErrorHandler(e);
  1037. logger.error(e);
  1038. }
  1039. });
  1040. // Generate the 'recvonly' SSRC in case there are no video tracks
  1041. if (!this.getLocalTracks(MediaType.VIDEO).length) {
  1042. jingleSession.generateRecvonlySsrc();
  1043. }
  1044. jingleSession.acceptOffer(jingleOffer, null,
  1045. error => {
  1046. GlobalOnErrorHandler.callErrorHandler(error);
  1047. logger.error(
  1048. 'Failed to accept incoming Jingle session', error);
  1049. }
  1050. );
  1051. // Start callstats as soon as peerconnection is initialized,
  1052. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1053. // happen in case if user doesn't have or denied permission to
  1054. // both camera and microphone.
  1055. this.statistics.startCallStats(jingleSession);
  1056. this.statistics.startRemoteStats(jingleSession.peerconnection);
  1057. };
  1058. /**
  1059. * Handles the call ended event.
  1060. * @param {JingleSessionPC} JingleSession the jingle session which has been
  1061. * terminated.
  1062. * @param {String} reasonCondition the Jingle reason condition.
  1063. * @param {String|null} reasonText human readable reason text which may provide
  1064. * more details about why the call has been terminated.
  1065. */
  1066. JitsiConference.prototype.onCallEnded
  1067. = function(JingleSession, reasonCondition, reasonText) {
  1068. logger.info(`Call ended: ${reasonCondition} - ${reasonText}`);
  1069. this.wasStopped = true;
  1070. // Send session.terminate event
  1071. Statistics.sendEventToAll('session.terminate');
  1072. // Stop the stats
  1073. if (this.statistics) {
  1074. this.statistics.stopRemoteStats();
  1075. this.statistics.stopCallStats();
  1076. }
  1077. // Current JingleSession is invalid so set it to null on the room
  1078. this.jingleSession = null;
  1079. // Let the RTC service do any cleanups
  1080. this.rtc.onCallEnded();
  1081. // PeerConnection has been closed which means that SSRCs stored in
  1082. // JitsiLocalTrack will not match those assigned by the old PeerConnection
  1083. // and SSRC replacement logic will not work as expected.
  1084. // We want to re-register 'ssrcHandler' of our local tracks, so that they
  1085. // will learn what their SSRC from the new PeerConnection which will be
  1086. // created on incoming call event.
  1087. const self = this;
  1088. this.getLocalTracks().forEach(localTrack => {
  1089. // Reset SSRC as it will no longer be valid
  1090. localTrack._setSSRC(null);
  1091. // Bind the handler to fetch new SSRC, it will un register itself once
  1092. // it reads the values
  1093. self.rtc.addListener(
  1094. RTCEvents.SENDRECV_STREAMS_CHANGED, localTrack.ssrcHandler);
  1095. });
  1096. };
  1097. /**
  1098. * Handles the suspend detected event. Leaves the room and fires suspended.
  1099. */
  1100. JitsiConference.prototype.onSuspendDetected = function() {
  1101. this.leave();
  1102. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1103. };
  1104. JitsiConference.prototype.updateDTMFSupport = function() {
  1105. let somebodySupportsDTMF = false;
  1106. const participants = this.getParticipants();
  1107. // check if at least 1 participant supports DTMF
  1108. for (let i = 0; i < participants.length; i += 1) {
  1109. if (participants[i].supportsDTMF()) {
  1110. somebodySupportsDTMF = true;
  1111. break;
  1112. }
  1113. }
  1114. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1115. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1116. this.eventEmitter.emit(
  1117. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1118. somebodySupportsDTMF);
  1119. }
  1120. };
  1121. /**
  1122. * Allows to check if there is at least one user in the conference
  1123. * that supports DTMF.
  1124. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1125. */
  1126. JitsiConference.prototype.isDTMFSupported = function() {
  1127. return this.somebodySupportsDTMF;
  1128. };
  1129. /**
  1130. * Returns the local user's ID
  1131. * @return {string} local user's ID
  1132. */
  1133. JitsiConference.prototype.myUserId = function() {
  1134. return (
  1135. this.room
  1136. && this.room.myroomjid
  1137. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1138. : null);
  1139. };
  1140. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1141. // FIXME P2P 'dtmfManager' must be cleared, after switching jingleSessions
  1142. if (!this.dtmfManager) {
  1143. if (!this.jingleSession) {
  1144. logger.warn('cannot sendTones: no jingle session');
  1145. return;
  1146. }
  1147. const peerConnection = this.jingleSession.peerconnection;
  1148. if (!peerConnection) {
  1149. logger.warn('cannot sendTones: no peer connection');
  1150. return;
  1151. }
  1152. const localAudio = this.getLocalAudioTrack();
  1153. if (!localAudio) {
  1154. logger.warn('cannot sendTones: no local audio stream');
  1155. return;
  1156. }
  1157. this.dtmfManager = new JitsiDTMFManager(localAudio, peerConnection);
  1158. }
  1159. this.dtmfManager.sendTones(tones, duration, pause);
  1160. };
  1161. /**
  1162. * Returns true if recording is supported and false if not.
  1163. */
  1164. JitsiConference.prototype.isRecordingSupported = function() {
  1165. if (this.room) {
  1166. return this.room.isRecordingSupported();
  1167. }
  1168. return false;
  1169. };
  1170. /**
  1171. * Returns null if the recording is not supported, "on" if the recording started
  1172. * and "off" if the recording is not started.
  1173. */
  1174. JitsiConference.prototype.getRecordingState = function() {
  1175. return this.room ? this.room.getRecordingState() : undefined;
  1176. };
  1177. /**
  1178. * Returns the url of the recorded video.
  1179. */
  1180. JitsiConference.prototype.getRecordingURL = function() {
  1181. return this.room ? this.room.getRecordingURL() : null;
  1182. };
  1183. /**
  1184. * Starts/stops the recording
  1185. */
  1186. JitsiConference.prototype.toggleRecording = function(options) {
  1187. if (this.room) {
  1188. return this.room.toggleRecording(options, (status, error) => {
  1189. this.eventEmitter.emit(
  1190. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  1191. });
  1192. }
  1193. this.eventEmitter.emit(
  1194. JitsiConferenceEvents.RECORDER_STATE_CHANGED, 'error',
  1195. new Error('The conference is not created yet!'));
  1196. };
  1197. /**
  1198. * Returns true if the SIP calls are supported and false otherwise
  1199. */
  1200. JitsiConference.prototype.isSIPCallingSupported = function() {
  1201. if (this.room) {
  1202. return this.room.isSIPCallingSupported();
  1203. }
  1204. return false;
  1205. };
  1206. /**
  1207. * Dials a number.
  1208. * @param number the number
  1209. */
  1210. JitsiConference.prototype.dial = function(number) {
  1211. if (this.room) {
  1212. return this.room.dial(number);
  1213. }
  1214. return new Promise((resolve, reject) => {
  1215. reject(new Error('The conference is not created yet!'));
  1216. });
  1217. };
  1218. /**
  1219. * Hangup an existing call
  1220. */
  1221. JitsiConference.prototype.hangup = function() {
  1222. if (this.room) {
  1223. return this.room.hangup();
  1224. }
  1225. return new Promise((resolve, reject) => {
  1226. reject(new Error('The conference is not created yet!'));
  1227. });
  1228. };
  1229. /**
  1230. * Returns the phone number for joining the conference.
  1231. */
  1232. JitsiConference.prototype.getPhoneNumber = function() {
  1233. if (this.room) {
  1234. return this.room.getPhoneNumber();
  1235. }
  1236. return null;
  1237. };
  1238. /**
  1239. * Returns the pin for joining the conference with phone.
  1240. */
  1241. JitsiConference.prototype.getPhonePin = function() {
  1242. if (this.room) {
  1243. return this.room.getPhonePin();
  1244. }
  1245. return null;
  1246. };
  1247. /**
  1248. * Returns the connection state for the current room. Its ice connection state
  1249. * for its session.
  1250. */
  1251. JitsiConference.prototype.getConnectionState = function() {
  1252. if (this.jingleSession) {
  1253. return this.jingleSession.getIceConnectionState();
  1254. }
  1255. return null;
  1256. };
  1257. /**
  1258. * Make all new participants mute their audio/video on join.
  1259. * @param policy {Object} object with 2 boolean properties for video and audio:
  1260. * @param {boolean} audio if audio should be muted.
  1261. * @param {boolean} video if video should be muted.
  1262. */
  1263. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  1264. if (!this.isModerator()) {
  1265. return;
  1266. }
  1267. this.startMutedPolicy = policy;
  1268. this.room.removeFromPresence('startmuted');
  1269. this.room.addToPresence('startmuted', {
  1270. attributes: {
  1271. audio: policy.audio,
  1272. video: policy.video,
  1273. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1274. }
  1275. });
  1276. this.room.sendPresence();
  1277. };
  1278. /**
  1279. * Returns current start muted policy
  1280. * @returns {Object} with 2 properties - audio and video.
  1281. */
  1282. JitsiConference.prototype.getStartMutedPolicy = function() {
  1283. return this.startMutedPolicy;
  1284. };
  1285. /**
  1286. * Check if audio is muted on join.
  1287. */
  1288. JitsiConference.prototype.isStartAudioMuted = function() {
  1289. return this.startAudioMuted;
  1290. };
  1291. /**
  1292. * Check if video is muted on join.
  1293. */
  1294. JitsiConference.prototype.isStartVideoMuted = function() {
  1295. return this.startVideoMuted;
  1296. };
  1297. /**
  1298. * Get object with internal logs.
  1299. */
  1300. JitsiConference.prototype.getLogs = function() {
  1301. const data = this.xmpp.getJingleLog();
  1302. const metadata = {};
  1303. metadata.time = new Date();
  1304. metadata.url = window.location.href;
  1305. metadata.ua = navigator.userAgent;
  1306. const log = this.xmpp.getXmppLog();
  1307. if (log) {
  1308. metadata.xmpp = log;
  1309. }
  1310. data.metadata = metadata;
  1311. return data;
  1312. };
  1313. /**
  1314. * Returns measured connectionTimes.
  1315. */
  1316. JitsiConference.prototype.getConnectionTimes = function() {
  1317. return this.room.connectionTimes;
  1318. };
  1319. /**
  1320. * Sets a property for the local participant.
  1321. */
  1322. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1323. this.sendCommand(`jitsi_participant_${name}`, { value });
  1324. };
  1325. /**
  1326. * Sends the given feedback through CallStats if enabled.
  1327. *
  1328. * @param overallFeedback an integer between 1 and 5 indicating the
  1329. * user feedback
  1330. * @param detailedFeedback detailed feedback from the user. Not yet used
  1331. */
  1332. JitsiConference.prototype.sendFeedback
  1333. = function(overallFeedback, detailedFeedback) {
  1334. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1335. };
  1336. /**
  1337. * Returns true if the callstats integration is enabled, otherwise returns
  1338. * false.
  1339. *
  1340. * @returns true if the callstats integration is enabled, otherwise returns
  1341. * false.
  1342. */
  1343. JitsiConference.prototype.isCallstatsEnabled = function() {
  1344. return this.statistics.isCallstatsEnabled();
  1345. };
  1346. /**
  1347. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1348. * from statistics module)
  1349. * @param track the track
  1350. * @param container the container
  1351. */
  1352. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1353. const ssrc = track.getSSRC();
  1354. if (!container.id || !ssrc) {
  1355. return;
  1356. }
  1357. this.statistics.associateStreamWithVideoTag(
  1358. ssrc, track.isLocal(), track.getUsageLabel(), container.id);
  1359. };
  1360. /**
  1361. * Logs an "application log" message.
  1362. * @param message {string} The message to log. Note that while this can be a
  1363. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1364. * log valid JSON strings, with an "id" field used for distinguishing between
  1365. * message types. E.g.: {id: "recorder_status", status: "off"}
  1366. */
  1367. JitsiConference.prototype.sendApplicationLog = function(message) {
  1368. Statistics.sendLog(message);
  1369. };
  1370. /**
  1371. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1372. * focus.
  1373. * @param mucJid the full MUC address of the user to be checked.
  1374. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1375. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1376. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1377. */
  1378. JitsiConference.prototype._isFocus = function(mucJid) {
  1379. return this.room ? this.room.isFocus(mucJid) : null;
  1380. };
  1381. /**
  1382. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1383. */
  1384. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  1385. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1386. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1387. };
  1388. /**
  1389. * Sends a message via the data channel.
  1390. * @param to {string} the id of the endpoint that should receive the message.
  1391. * If "" the message will be sent to all participants.
  1392. * @param payload {object} the payload of the message.
  1393. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1394. */
  1395. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  1396. this.rtc.sendDataChannelMessage(to, payload);
  1397. };
  1398. /**
  1399. * Sends a broadcast message via the data channel.
  1400. * @param payload {object} the payload of the message.
  1401. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1402. */
  1403. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  1404. this.sendEndpointMessage('', payload);
  1405. };
  1406. JitsiConference.prototype.isConnectionInterrupted = function() {
  1407. return this.connectionIsInterrupted;
  1408. };
  1409. /**
  1410. * Get a summary of how long current participants have been the dominant speaker
  1411. * @returns {object}
  1412. */
  1413. JitsiConference.prototype.getSpeakerStats = function() {
  1414. return this.speakerStatsCollector.getStats();
  1415. };
  1416. module.exports = JitsiConference;