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

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