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

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