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

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