您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 49KB

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