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

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