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

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