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

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