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

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