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 49KB

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