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.

moderator.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /* global $, $iq, Promise, Strophe */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4. var AuthenticationEvents
  5. = require("../../service/authentication/AuthenticationEvents");
  6. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  7. function createExpBackoffTimer(step) {
  8. var count = 1;
  9. return function (reset) {
  10. // Reset call
  11. if (reset) {
  12. count = 1;
  13. return;
  14. }
  15. // Calculate next timeout
  16. var timeout = Math.pow(2, count - 1);
  17. count += 1;
  18. return timeout * step;
  19. };
  20. }
  21. function Moderator(roomName, xmpp, emitter, settings, options) {
  22. this.roomName = roomName;
  23. this.xmppService = xmpp;
  24. this.getNextTimeout = createExpBackoffTimer(1000);
  25. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  26. // External authentication stuff
  27. this.externalAuthEnabled = false;
  28. this.settings = settings;
  29. this.options = options;
  30. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  31. // it will be enabled automatically if focus detects the component through
  32. // service discovery.
  33. this.sipGatewayEnabled = this.options.connection.hosts &&
  34. this.options.connection.hosts.call_control !== undefined;
  35. this.eventEmitter = emitter;
  36. this.connection = this.xmppService.connection;
  37. this.focusUserJid;
  38. //FIXME:
  39. // Message listener that talks to POPUP window
  40. function listener(event) {
  41. if (event.data && event.data.sessionId) {
  42. if (event.origin !== window.location.origin) {
  43. logger.warn("Ignoring sessionId from different origin: " +
  44. event.origin);
  45. return;
  46. }
  47. settings.setSessionId(event.data.sessionId);
  48. // After popup is closed we will authenticate
  49. }
  50. }
  51. // Register
  52. if (window.addEventListener) {
  53. window.addEventListener("message", listener, false);
  54. } else {
  55. window.attachEvent("onmessage", listener);
  56. }
  57. }
  58. Moderator.prototype.isExternalAuthEnabled = function () {
  59. return this.externalAuthEnabled;
  60. };
  61. Moderator.prototype.isSipGatewayEnabled = function () {
  62. return this.sipGatewayEnabled;
  63. };
  64. Moderator.prototype.onMucMemberLeft = function (jid) {
  65. logger.info("Someone left is it focus ? " + jid);
  66. var resource = Strophe.getResourceFromJid(jid);
  67. if (resource === 'focus') {
  68. logger.info(
  69. "Focus has left the room - leaving conference");
  70. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  71. }
  72. };
  73. Moderator.prototype.setFocusUserJid = function (focusJid) {
  74. if (!this.focusUserJid) {
  75. this.focusUserJid = focusJid;
  76. logger.info("Focus jid set to: " + this.focusUserJid);
  77. }
  78. };
  79. Moderator.prototype.getFocusUserJid = function () {
  80. return this.focusUserJid;
  81. };
  82. Moderator.prototype.getFocusComponent = function () {
  83. // Get focus component address
  84. var focusComponent = this.options.connection.hosts.focus;
  85. // If not specified use default: 'focus.domain'
  86. if (!focusComponent) {
  87. focusComponent = 'focus.' + this.options.connection.hosts.domain;
  88. }
  89. return focusComponent;
  90. };
  91. Moderator.prototype.createConferenceIq = function () {
  92. // Generate create conference IQ
  93. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  94. // Session Id used for authentication
  95. var sessionId = this.settings.getSessionId();
  96. var machineUID = this.settings.getUserId();
  97. logger.info(
  98. "Session ID: " + sessionId + " machine UID: " + machineUID);
  99. elem.c('conference', {
  100. xmlns: 'http://jitsi.org/protocol/focus',
  101. room: this.roomName,
  102. 'machine-uid': machineUID
  103. });
  104. if (sessionId) {
  105. elem.attrs({ 'session-id': sessionId});
  106. }
  107. if (this.options.connection.enforcedBridge !== undefined) {
  108. elem.c(
  109. 'property', {
  110. name: 'enforcedBridge',
  111. value: this.options.connection.enforcedBridge
  112. }).up();
  113. }
  114. // Tell the focus we have Jigasi configured
  115. if (this.options.connection.hosts !== undefined &&
  116. this.options.connection.hosts.call_control !== undefined) {
  117. elem.c(
  118. 'property', {
  119. name: 'call_control',
  120. value: this.options.connection.hosts.call_control
  121. }).up();
  122. }
  123. if (this.options.conference.channelLastN !== undefined) {
  124. elem.c(
  125. 'property', {
  126. name: 'channelLastN',
  127. value: this.options.conference.channelLastN
  128. }).up();
  129. }
  130. if (this.options.conference.adaptiveLastN !== undefined) {
  131. elem.c(
  132. 'property', {
  133. name: 'adaptiveLastN',
  134. value: this.options.conference.adaptiveLastN
  135. }).up();
  136. }
  137. if (this.options.conference.disableAdaptiveSimulcast !== undefined ||
  138. this.options.conference.disableSimulcast) {
  139. // disableSimulcast implies disableAdaptiveSimulcast.
  140. var value = this.options.conference.disableSimulcast ? true :
  141. this.options.conference.disableAdaptiveSimulcast;
  142. elem.c(
  143. 'property', {
  144. name: 'disableAdaptiveSimulcast',
  145. value: value
  146. }).up();
  147. }
  148. // TODO: re-enable once rtx is stable
  149. //if (this.options.conference.disableRtx !== undefined) {
  150. elem.c(
  151. 'property', {
  152. name: 'disableRtx',
  153. //value: this.options.conference.disableRtx
  154. value: true
  155. }).up();
  156. //}
  157. if (this.options.connection.enableLipSync !== undefined) {
  158. elem.c(
  159. 'property', {
  160. name: 'enableLipSync',
  161. value: this.options.connection.enableLipSync
  162. }).up();
  163. }
  164. if (this.options.conference.audioPacketDelay !== undefined) {
  165. elem.c(
  166. 'property', {
  167. name: 'audioPacketDelay',
  168. value: this.options.conference.audioPacketDelay
  169. }).up();
  170. }
  171. if (this.options.conference.startBitrate) {
  172. elem.c(
  173. 'property', {
  174. name: 'startBitrate',
  175. value: this.options.conference.startBitrate
  176. }).up();
  177. }
  178. if (this.options.conference.minBitrate) {
  179. elem.c(
  180. 'property', {
  181. name: 'minBitrate',
  182. value: this.options.conference.minBitrate
  183. }).up();
  184. }
  185. if (this.options.conference.openSctp !== undefined) {
  186. elem.c(
  187. 'property', {
  188. name: 'openSctp',
  189. value: this.options.conference.openSctp
  190. }).up();
  191. }
  192. if (this.options.conference.startAudioMuted !== undefined) {
  193. elem.c(
  194. 'property', {
  195. name: 'startAudioMuted',
  196. value: this.options.conference.startAudioMuted
  197. }).up();
  198. }
  199. if (this.options.conference.startVideoMuted !== undefined) {
  200. elem.c(
  201. 'property', {
  202. name: 'startVideoMuted',
  203. value: this.options.conference.startVideoMuted
  204. }).up();
  205. }
  206. if (this.options.conference.stereo !== undefined) {
  207. elem.c(
  208. 'property', {
  209. name: 'stereo',
  210. value: this.options.conference.stereo
  211. }).up();
  212. }
  213. elem.c(
  214. 'property', {
  215. name: 'simulcastMode',
  216. value: 'rewriting'
  217. }).up();
  218. if (this.options.conference.useRoomAsSharedDocumentName !== undefined) {
  219. elem.c(
  220. 'property', {
  221. name: 'useRoomAsSharedDocumentName',
  222. value: this.options.conference.useRoomAsSharedDocumentName
  223. }).up();
  224. }
  225. elem.up();
  226. return elem;
  227. };
  228. Moderator.prototype.parseSessionId = function (resultIq) {
  229. var sessionId = $(resultIq).find('conference').attr('session-id');
  230. if (sessionId) {
  231. logger.info('Received sessionId: ' + sessionId);
  232. this.settings.setSessionId(sessionId);
  233. }
  234. };
  235. Moderator.prototype.parseConfigOptions = function (resultIq) {
  236. this.setFocusUserJid(
  237. $(resultIq).find('conference').attr('focusjid'));
  238. var authenticationEnabled
  239. = $(resultIq).find(
  240. '>conference>property' +
  241. '[name=\'authentication\'][value=\'true\']').length > 0;
  242. logger.info("Authentication enabled: " + authenticationEnabled);
  243. this.externalAuthEnabled = $(resultIq).find(
  244. '>conference>property' +
  245. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  246. logger.info(
  247. 'External authentication enabled: ' + this.externalAuthEnabled);
  248. if (!this.externalAuthEnabled) {
  249. // We expect to receive sessionId in 'internal' authentication mode
  250. this.parseSessionId(resultIq);
  251. }
  252. var authIdentity = $(resultIq).find('>conference').attr('identity');
  253. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  254. authenticationEnabled, authIdentity);
  255. // Check if focus has auto-detected Jigasi component(this will be also
  256. // included if we have passed our host from the config)
  257. if ($(resultIq).find(
  258. '>conference>property' +
  259. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  260. this.sipGatewayEnabled = true;
  261. }
  262. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  263. };
  264. // FIXME We need to show the fact that we're waiting for the focus to the user
  265. // (or that the focus is not available)
  266. /**
  267. * Allocates the conference focus.
  268. *
  269. * @param {Function} callback - the function to be called back upon the
  270. * successful allocation of the conference focus
  271. */
  272. Moderator.prototype.allocateConferenceFocus = function (callback) {
  273. // Try to use focus user JID from the config
  274. this.setFocusUserJid(this.options.connection.focusUserJid);
  275. // Send create conference IQ
  276. var self = this;
  277. this.connection.sendIQ(
  278. this.createConferenceIq(),
  279. function (result) {
  280. self._allocateConferenceFocusSuccess(result, callback);
  281. },
  282. function (error) {
  283. self._allocateConferenceFocusError(error, callback);
  284. });
  285. // XXX We're pressed for time here because we're beginning a complex and/or
  286. // lengthy conference-establishment process which supposedly involves
  287. // multiple RTTs. We don't have the time to wait for Strophe to decide to
  288. // send our IQ.
  289. this.connection.flush();
  290. };
  291. /**
  292. * Invoked by {@link #allocateConferenceFocus} upon its request receiving an
  293. * error result.
  294. *
  295. * @param error - the error result of the request that
  296. * {@link #allocateConferenceFocus} sent
  297. * @param {Function} callback - the function to be called back upon the
  298. * successful allocation of the conference focus
  299. */
  300. Moderator.prototype._allocateConferenceFocusError = function (error, callback) {
  301. var self = this;
  302. // If the session is invalid, remove and try again without session ID to get
  303. // a new one
  304. var invalidSession = $(error).find('>error>session-invalid').length;
  305. if (invalidSession) {
  306. logger.info("Session expired! - removing");
  307. self.settings.clearSessionId();
  308. }
  309. if ($(error).find('>error>graceful-shutdown').length) {
  310. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  311. return;
  312. }
  313. // Check for error returned by the reservation system
  314. var reservationErr = $(error).find('>error>reservation-error');
  315. if (reservationErr.length) {
  316. // Trigger error event
  317. var errorCode = reservationErr.attr('error-code');
  318. var errorTextNode = $(error).find('>error>text');
  319. var errorMsg;
  320. if (errorTextNode) {
  321. errorMsg = errorTextNode.text();
  322. }
  323. self.eventEmitter.emit(
  324. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  325. return;
  326. }
  327. // Not authorized to create new room
  328. if ($(error).find('>error>not-authorized').length) {
  329. logger.warn("Unauthorized to start the conference", error);
  330. var toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
  331. if (toDomain !== self.options.connection.hosts.anonymousdomain) {
  332. //FIXME "is external" should come either from the focus or config.js
  333. self.externalAuthEnabled = true;
  334. }
  335. self.eventEmitter.emit(
  336. XMPPEvents.AUTHENTICATION_REQUIRED,
  337. function () {
  338. self.allocateConferenceFocus(callback);
  339. });
  340. return;
  341. }
  342. if(this.retries >= this.maxRetries) {
  343. self.eventEmitter.emit(
  344. XMPPEvents.ALLOCATE_FOCUS_MAX_RETRIES_ERROR);
  345. return;
  346. }
  347. this.retries++;
  348. var waitMs = self.getNextErrorTimeout();
  349. var errmsg = "Focus error, retry after "+ waitMs;
  350. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  351. logger.error(errmsg, error);
  352. // Show message
  353. var focusComponent = self.getFocusComponent();
  354. var retrySec = waitMs / 1000;
  355. //FIXME: message is duplicated ? Do not show in case of session invalid
  356. // which means just a retry
  357. if (!invalidSession) {
  358. self.eventEmitter.emit(
  359. XMPPEvents.FOCUS_DISCONNECTED, focusComponent, retrySec);
  360. }
  361. // Reset response timeout
  362. self.getNextTimeout(true);
  363. window.setTimeout(
  364. function () {
  365. self.allocateConferenceFocus(callback);
  366. },
  367. waitMs);
  368. };
  369. /**
  370. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  371. * success (i.e. non-error) result.
  372. *
  373. * @param result - the success (i.e. non-error) result of the request that
  374. * {@link #allocateConferenceFocus} sent
  375. * @param {Function} callback - the function to be called back upon the
  376. * successful allocation of the conference focus
  377. */
  378. Moderator.prototype._allocateConferenceFocusSuccess = function (
  379. result,
  380. callback) {
  381. // Setup config options
  382. this.parseConfigOptions(result);
  383. // Reset the error timeout (because we haven't failed here).
  384. this.getNextErrorTimeout(true);
  385. if ('true' === $(result).find('conference').attr('ready')) {
  386. // Reset the non-error timeout (because we've succeeded here).
  387. this.getNextTimeout(true);
  388. // Exec callback
  389. callback();
  390. } else {
  391. var waitMs = this.getNextTimeout();
  392. logger.info("Waiting for the focus... " + waitMs);
  393. var self = this;
  394. window.setTimeout(
  395. function () {
  396. self.allocateConferenceFocus(callback);
  397. },
  398. waitMs);
  399. }
  400. };
  401. Moderator.prototype.authenticate = function () {
  402. var self = this;
  403. return new Promise(function (resolve, reject) {
  404. self.connection.sendIQ(
  405. self.createConferenceIq(),
  406. function (result) {
  407. self.parseSessionId(result);
  408. resolve();
  409. }, function (error) {
  410. var code = $(error).find('>error').attr('code');
  411. reject(error, code);
  412. }
  413. );
  414. });
  415. };
  416. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  417. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  418. };
  419. /**
  420. *
  421. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  422. * {@link Moderator#getPopupLoginUrl}
  423. * @param urlCb
  424. * @param failureCb
  425. */
  426. Moderator.prototype._getLoginUrl = function (popup, urlCb, failureCb) {
  427. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  428. var attrs = {
  429. xmlns: 'http://jitsi.org/protocol/focus',
  430. room: this.roomName,
  431. 'machine-uid': this.settings.getUserId()
  432. };
  433. var str = 'auth url'; // for logger
  434. if (popup) {
  435. attrs.popup = true;
  436. str = 'POPUP ' + str;
  437. }
  438. iq.c('login-url', attrs);
  439. /**
  440. * Implements a failure callback which reports an error message and an error
  441. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  442. *
  443. * @param {string} errmsg the error messsage to report
  444. * @param {*} error the error to report (in addition to errmsg)
  445. */
  446. function reportError(errmsg, err) {
  447. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  448. logger.error(errmsg, err);
  449. failureCb(err);
  450. }
  451. this.connection.sendIQ(
  452. iq,
  453. function (result) {
  454. var url = $(result).find('login-url').attr('url');
  455. url = decodeURIComponent(url);
  456. if (url) {
  457. logger.info('Got ' + str + ': ' + url);
  458. urlCb(url);
  459. } else {
  460. reportError('Failed to get ' + str + ' from the focus', result);
  461. }
  462. },
  463. reportError.bind(undefined, 'Get ' + str + ' error')
  464. );
  465. };
  466. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  467. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  468. };
  469. Moderator.prototype.logout = function (callback) {
  470. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  471. var sessionId = this.settings.getSessionId();
  472. if (!sessionId) {
  473. callback();
  474. return;
  475. }
  476. iq.c('logout', {
  477. xmlns: 'http://jitsi.org/protocol/focus',
  478. 'session-id': sessionId
  479. });
  480. this.connection.sendIQ(
  481. iq,
  482. function (result) {
  483. var logoutUrl = $(result).find('logout').attr('logout-url');
  484. if (logoutUrl) {
  485. logoutUrl = decodeURIComponent(logoutUrl);
  486. }
  487. logger.info("Log out OK, url: " + logoutUrl, result);
  488. this.settings.clearSessionId();
  489. callback(logoutUrl);
  490. }.bind(this),
  491. function (error) {
  492. var errmsg = "Logout error";
  493. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  494. logger.error(errmsg, error);
  495. }
  496. );
  497. };
  498. module.exports = Moderator;