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

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