Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

moderator.js 16KB

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