Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 39KB

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