modified lib-jitsi-meet dev repo
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiConference.js 49KB

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