Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

moderator.js 18KB

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