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.

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