You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 41KB

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