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

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