modified lib-jitsi-meet dev repo
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JitsiConference.js 49KB

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