Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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