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

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