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

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