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

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