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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. elem.c(
  158. 'property', {
  159. name: 'enableLipSync',
  160. value: false !== this.options.connection.enableLipSync
  161. }).up();
  162. if (this.options.conference.audioPacketDelay !== undefined) {
  163. elem.c(
  164. 'property', {
  165. name: 'audioPacketDelay',
  166. value: this.options.conference.audioPacketDelay
  167. }).up();
  168. }
  169. if (this.options.conference.startBitrate) {
  170. elem.c(
  171. 'property', {
  172. name: 'startBitrate',
  173. value: this.options.conference.startBitrate
  174. }).up();
  175. }
  176. if (this.options.conference.minBitrate) {
  177. elem.c(
  178. 'property', {
  179. name: 'minBitrate',
  180. value: this.options.conference.minBitrate
  181. }).up();
  182. }
  183. if (this.options.conference.openSctp !== undefined) {
  184. elem.c(
  185. 'property', {
  186. name: 'openSctp',
  187. value: this.options.conference.openSctp
  188. }).up();
  189. }
  190. if (this.options.conference.startAudioMuted !== undefined) {
  191. elem.c(
  192. 'property', {
  193. name: 'startAudioMuted',
  194. value: this.options.conference.startAudioMuted
  195. }).up();
  196. }
  197. if (this.options.conference.startVideoMuted !== undefined) {
  198. elem.c(
  199. 'property', {
  200. name: 'startVideoMuted',
  201. value: this.options.conference.startVideoMuted
  202. }).up();
  203. }
  204. if (this.options.conference.stereo !== undefined) {
  205. elem.c(
  206. 'property', {
  207. name: 'stereo',
  208. value: this.options.conference.stereo
  209. }).up();
  210. }
  211. elem.c(
  212. 'property', {
  213. name: 'simulcastMode',
  214. value: 'rewriting'
  215. }).up();
  216. if (this.options.conference.useRoomAsSharedDocumentName !== undefined) {
  217. elem.c(
  218. 'property', {
  219. name: 'useRoomAsSharedDocumentName',
  220. value: this.options.conference.useRoomAsSharedDocumentName
  221. }).up();
  222. }
  223. elem.up();
  224. return elem;
  225. };
  226. Moderator.prototype.parseSessionId = function (resultIq) {
  227. var sessionId = $(resultIq).find('conference').attr('session-id');
  228. if (sessionId) {
  229. logger.info('Received sessionId: ' + sessionId);
  230. this.settings.setSessionId(sessionId);
  231. }
  232. };
  233. Moderator.prototype.parseConfigOptions = function (resultIq) {
  234. this.setFocusUserJid(
  235. $(resultIq).find('conference').attr('focusjid'));
  236. var authenticationEnabled
  237. = $(resultIq).find(
  238. '>conference>property' +
  239. '[name=\'authentication\'][value=\'true\']').length > 0;
  240. logger.info("Authentication enabled: " + authenticationEnabled);
  241. this.externalAuthEnabled = $(resultIq).find(
  242. '>conference>property' +
  243. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  244. logger.info(
  245. 'External authentication enabled: ' + this.externalAuthEnabled);
  246. if (!this.externalAuthEnabled) {
  247. // We expect to receive sessionId in 'internal' authentication mode
  248. this.parseSessionId(resultIq);
  249. }
  250. var authIdentity = $(resultIq).find('>conference').attr('identity');
  251. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  252. authenticationEnabled, authIdentity);
  253. // Check if focus has auto-detected Jigasi component(this will be also
  254. // included if we have passed our host from the config)
  255. if ($(resultIq).find(
  256. '>conference>property' +
  257. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  258. this.sipGatewayEnabled = true;
  259. }
  260. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  261. };
  262. // FIXME We need to show the fact that we're waiting for the focus to the user
  263. // (or that the focus is not available)
  264. /**
  265. * Allocates the conference focus.
  266. *
  267. * @param {Function} callback - the function to be called back upon the
  268. * successful allocation of the conference focus
  269. */
  270. Moderator.prototype.allocateConferenceFocus = function (callback) {
  271. // Try to use focus user JID from the config
  272. this.setFocusUserJid(this.options.connection.focusUserJid);
  273. // Send create conference IQ
  274. var self = this;
  275. this.connection.sendIQ(
  276. this.createConferenceIq(),
  277. function (result) {
  278. self._allocateConferenceFocusSuccess(result, callback);
  279. },
  280. function (error) {
  281. self._allocateConferenceFocusError(error, callback);
  282. });
  283. // XXX We're pressed for time here because we're beginning a complex and/or
  284. // lengthy conference-establishment process which supposedly involves
  285. // multiple RTTs. We don't have the time to wait for Strophe to decide to
  286. // send our IQ.
  287. this.connection.flush();
  288. };
  289. /**
  290. * Invoked by {@link #allocateConferenceFocus} upon its request receiving an
  291. * error result.
  292. *
  293. * @param error - the error result of the request that
  294. * {@link #allocateConferenceFocus} sent
  295. * @param {Function} callback - the function to be called back upon the
  296. * successful allocation of the conference focus
  297. */
  298. Moderator.prototype._allocateConferenceFocusError = function (error, callback) {
  299. var self = this;
  300. // If the session is invalid, remove and try again without session ID to get
  301. // a new one
  302. var invalidSession = $(error).find('>error>session-invalid').length;
  303. if (invalidSession) {
  304. logger.info("Session expired! - removing");
  305. self.settings.clearSessionId();
  306. }
  307. if ($(error).find('>error>graceful-shutdown').length) {
  308. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  309. return;
  310. }
  311. // Check for error returned by the reservation system
  312. var reservationErr = $(error).find('>error>reservation-error');
  313. if (reservationErr.length) {
  314. // Trigger error event
  315. var errorCode = reservationErr.attr('error-code');
  316. var errorTextNode = $(error).find('>error>text');
  317. var errorMsg;
  318. if (errorTextNode) {
  319. errorMsg = errorTextNode.text();
  320. }
  321. self.eventEmitter.emit(
  322. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  323. return;
  324. }
  325. // Not authorized to create new room
  326. if ($(error).find('>error>not-authorized').length) {
  327. logger.warn("Unauthorized to start the conference", error);
  328. var toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
  329. if (toDomain !== self.options.connection.hosts.anonymousdomain) {
  330. //FIXME "is external" should come either from the focus or config.js
  331. self.externalAuthEnabled = true;
  332. }
  333. self.eventEmitter.emit(
  334. XMPPEvents.AUTHENTICATION_REQUIRED,
  335. function () {
  336. self.allocateConferenceFocus(callback);
  337. });
  338. return;
  339. }
  340. if(this.retries >= this.maxRetries) {
  341. self.eventEmitter.emit(
  342. XMPPEvents.ALLOCATE_FOCUS_MAX_RETRIES_ERROR);
  343. return;
  344. }
  345. this.retries++;
  346. var waitMs = self.getNextErrorTimeout();
  347. var errmsg = "Focus error, retry after "+ waitMs;
  348. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  349. logger.error(errmsg, error);
  350. // Show message
  351. var focusComponent = self.getFocusComponent();
  352. var retrySec = waitMs / 1000;
  353. //FIXME: message is duplicated ? Do not show in case of session invalid
  354. // which means just a retry
  355. if (!invalidSession) {
  356. self.eventEmitter.emit(
  357. XMPPEvents.FOCUS_DISCONNECTED, focusComponent, retrySec);
  358. }
  359. // Reset response timeout
  360. self.getNextTimeout(true);
  361. window.setTimeout(
  362. function () {
  363. self.allocateConferenceFocus(callback);
  364. },
  365. waitMs);
  366. };
  367. /**
  368. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  369. * success (i.e. non-error) result.
  370. *
  371. * @param result - the success (i.e. non-error) result of the request that
  372. * {@link #allocateConferenceFocus} sent
  373. * @param {Function} callback - the function to be called back upon the
  374. * successful allocation of the conference focus
  375. */
  376. Moderator.prototype._allocateConferenceFocusSuccess = function (
  377. result,
  378. callback) {
  379. // Setup config options
  380. this.parseConfigOptions(result);
  381. // Reset the error timeout (because we haven't failed here).
  382. this.getNextErrorTimeout(true);
  383. if ('true' === $(result).find('conference').attr('ready')) {
  384. // Reset the non-error timeout (because we've succeeded here).
  385. this.getNextTimeout(true);
  386. // Exec callback
  387. callback();
  388. } else {
  389. var waitMs = this.getNextTimeout();
  390. logger.info("Waiting for the focus... " + waitMs);
  391. var self = this;
  392. window.setTimeout(
  393. function () {
  394. self.allocateConferenceFocus(callback);
  395. },
  396. waitMs);
  397. }
  398. };
  399. Moderator.prototype.authenticate = function () {
  400. var self = this;
  401. return new Promise(function (resolve, reject) {
  402. self.connection.sendIQ(
  403. self.createConferenceIq(),
  404. function (result) {
  405. self.parseSessionId(result);
  406. resolve();
  407. }, function (error) {
  408. var code = $(error).find('>error').attr('code');
  409. reject(error, code);
  410. }
  411. );
  412. });
  413. };
  414. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  415. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  416. };
  417. /**
  418. *
  419. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  420. * {@link Moderator#getPopupLoginUrl}
  421. * @param urlCb
  422. * @param failureCb
  423. */
  424. Moderator.prototype._getLoginUrl = function (popup, urlCb, failureCb) {
  425. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  426. var attrs = {
  427. xmlns: 'http://jitsi.org/protocol/focus',
  428. room: this.roomName,
  429. 'machine-uid': this.settings.getUserId()
  430. };
  431. var str = 'auth url'; // for logger
  432. if (popup) {
  433. attrs.popup = true;
  434. str = 'POPUP ' + str;
  435. }
  436. iq.c('login-url', attrs);
  437. /**
  438. * Implements a failure callback which reports an error message and an error
  439. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  440. *
  441. * @param {string} errmsg the error messsage to report
  442. * @param {*} error the error to report (in addition to errmsg)
  443. */
  444. function reportError(errmsg, err) {
  445. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  446. logger.error(errmsg, err);
  447. failureCb(err);
  448. }
  449. this.connection.sendIQ(
  450. iq,
  451. function (result) {
  452. var url = $(result).find('login-url').attr('url');
  453. url = decodeURIComponent(url);
  454. if (url) {
  455. logger.info('Got ' + str + ': ' + url);
  456. urlCb(url);
  457. } else {
  458. reportError('Failed to get ' + str + ' from the focus', result);
  459. }
  460. },
  461. reportError.bind(undefined, 'Get ' + str + ' error')
  462. );
  463. };
  464. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  465. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  466. };
  467. Moderator.prototype.logout = function (callback) {
  468. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  469. var sessionId = this.settings.getSessionId();
  470. if (!sessionId) {
  471. callback();
  472. return;
  473. }
  474. iq.c('logout', {
  475. xmlns: 'http://jitsi.org/protocol/focus',
  476. 'session-id': sessionId
  477. });
  478. this.connection.sendIQ(
  479. iq,
  480. function (result) {
  481. var logoutUrl = $(result).find('logout').attr('logout-url');
  482. if (logoutUrl) {
  483. logoutUrl = decodeURIComponent(logoutUrl);
  484. }
  485. logger.info("Log out OK, url: " + logoutUrl, result);
  486. this.settings.clearSessionId();
  487. callback(logoutUrl);
  488. }.bind(this),
  489. function (error) {
  490. var errmsg = "Logout error";
  491. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  492. logger.error(errmsg, error);
  493. }
  494. );
  495. };
  496. module.exports = Moderator;