Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

moderator.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import { $iq, Strophe } from 'strophe.js';
  4. import Settings from '../settings/Settings';
  5. const AuthenticationEvents
  6. = require('../../service/authentication/AuthenticationEvents');
  7. const { XMPPEvents } = require('../../service/xmpp/XMPPEvents');
  8. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  9. const logger = getLogger(__filename);
  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. // Whether SIP gateway (jigasi) support is enabled. This is set
  45. // based on conference properties received in presence.
  46. this.sipGatewayEnabled = false;
  47. this.eventEmitter = emitter;
  48. this.connection = this.xmppService.connection;
  49. // FIXME: Message listener that talks to POPUP window
  50. /**
  51. *
  52. * @param event
  53. */
  54. function listener(event) {
  55. if (event.data && event.data.sessionId) {
  56. if (event.origin !== window.location.origin) {
  57. logger.warn(
  58. `Ignoring sessionId from different origin: ${
  59. event.origin}`);
  60. return;
  61. }
  62. Settings.sessionId = event.data.sessionId;
  63. // After popup is closed we will authenticate
  64. }
  65. }
  66. // Register
  67. if (window.addEventListener) {
  68. window.addEventListener('message', listener, false);
  69. } else {
  70. window.attachEvent('onmessage', listener);
  71. }
  72. }
  73. /* eslint-enable max-params */
  74. Moderator.prototype.isExternalAuthEnabled = function() {
  75. return this.externalAuthEnabled;
  76. };
  77. Moderator.prototype.isSipGatewayEnabled = function() {
  78. return this.sipGatewayEnabled;
  79. };
  80. Moderator.prototype.onMucMemberLeft = function(jid) {
  81. const resource = Strophe.getResourceFromJid(jid);
  82. if (resource === 'focus') {
  83. logger.info(
  84. 'Focus has left the room - leaving conference');
  85. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  86. }
  87. };
  88. Moderator.prototype.setFocusUserJid = function(focusJid) {
  89. if (!this.focusUserJid) {
  90. this.focusUserJid = focusJid;
  91. logger.info(`Focus jid set to: ${this.focusUserJid}`);
  92. }
  93. };
  94. Moderator.prototype.getFocusUserJid = function() {
  95. return this.focusUserJid;
  96. };
  97. Moderator.prototype.getFocusComponent = function() {
  98. // Get focus component address
  99. let focusComponent = this.options.connection.hosts.focus;
  100. // If not specified use default: 'focus.domain'
  101. if (!focusComponent) {
  102. focusComponent = `focus.${this.options.connection.hosts.domain}`;
  103. }
  104. return focusComponent;
  105. };
  106. Moderator.prototype.createConferenceIq = function() {
  107. // Generate create conference IQ
  108. const elem = $iq({ to: this.getFocusComponent(),
  109. type: 'set' });
  110. // Session Id used for authentication
  111. const { sessionId } = Settings;
  112. const machineUID = Settings.machineId;
  113. const config = this.options.conference;
  114. logger.info(`Session ID: ${sessionId} machine UID: ${machineUID}`);
  115. elem.c('conference', {
  116. xmlns: 'http://jitsi.org/protocol/focus',
  117. room: this.roomName,
  118. 'machine-uid': machineUID
  119. });
  120. if (sessionId) {
  121. elem.attrs({ 'session-id': sessionId });
  122. }
  123. elem.c(
  124. 'property', {
  125. name: 'disableRtx',
  126. value: Boolean(config.disableRtx)
  127. }).up();
  128. if (config.audioPacketDelay !== undefined) {
  129. elem.c(
  130. 'property', {
  131. name: 'audioPacketDelay',
  132. value: config.audioPacketDelay
  133. }).up();
  134. }
  135. if (config.startBitrate) {
  136. elem.c(
  137. 'property', {
  138. name: 'startBitrate',
  139. value: config.startBitrate
  140. }).up();
  141. }
  142. if (config.minBitrate) {
  143. elem.c(
  144. 'property', {
  145. name: 'minBitrate',
  146. value: config.minBitrate
  147. }).up();
  148. }
  149. if (this.options.conference.startAudioMuted !== undefined) {
  150. elem.c(
  151. 'property', {
  152. name: 'startAudioMuted',
  153. value: this.options.conference.startAudioMuted
  154. }).up();
  155. }
  156. if (this.options.conference.startVideoMuted !== undefined) {
  157. elem.c(
  158. 'property', {
  159. name: 'startVideoMuted',
  160. value: this.options.conference.startVideoMuted
  161. }).up();
  162. }
  163. // this flag determines whether the bridge will include this call in its
  164. // rtcstats reporting or not. If the site admin hasn't set the flag in
  165. // config.js, then the client defaults to false (see
  166. // react/features/rtcstats/functions.js in jitsi-meet). The server-side
  167. // components default to true to match the pre-existing behavior so we only
  168. // signal if false.
  169. const rtcstatsEnabled = this.options.conference?.analytics?.rtcstatsEnabled ?? false;
  170. if (!rtcstatsEnabled) {
  171. elem.c(
  172. 'property', {
  173. name: 'rtcstatsEnabled',
  174. value: rtcstatsEnabled
  175. }).up();
  176. }
  177. const { callStatsID, callStatsSecret, disableThirdPartyRequests, enableCallStats } = this.options.conference;
  178. const callstatsDisabled = !callStatsID || !callStatsSecret || !enableCallStats
  179. // Even though AppID and AppSecret may be specified, the integration
  180. // of callstats.io may be disabled because of globally-disallowed
  181. // requests to any third parties.
  182. || disableThirdPartyRequests === true;
  183. // since the default is true across all the server-side components, only signal if false.
  184. if (callstatsDisabled) {
  185. elem.c(
  186. 'property', {
  187. name: 'callstatsEnabled',
  188. value: !callstatsDisabled
  189. }).up();
  190. }
  191. elem.up();
  192. return elem;
  193. };
  194. Moderator.prototype.parseSessionId = function(resultIq) {
  195. // eslint-disable-next-line newline-per-chained-call
  196. const sessionId = $(resultIq).find('conference').attr('session-id');
  197. if (sessionId) {
  198. logger.info(`Received sessionId: ${sessionId}`);
  199. Settings.sessionId = sessionId;
  200. }
  201. };
  202. Moderator.prototype.parseConfigOptions = function(resultIq) {
  203. // eslint-disable-next-line newline-per-chained-call
  204. this.setFocusUserJid($(resultIq).find('conference').attr('focusjid'));
  205. const authenticationEnabled
  206. = $(resultIq).find(
  207. '>conference>property'
  208. + '[name=\'authentication\'][value=\'true\']').length > 0;
  209. logger.info(`Authentication enabled: ${authenticationEnabled}`);
  210. this.externalAuthEnabled = $(resultIq).find(
  211. '>conference>property'
  212. + '[name=\'externalAuth\'][value=\'true\']').length > 0;
  213. logger.info(
  214. `External authentication enabled: ${this.externalAuthEnabled}`);
  215. if (!this.externalAuthEnabled) {
  216. // We expect to receive sessionId in 'internal' authentication mode
  217. this.parseSessionId(resultIq);
  218. }
  219. // eslint-disable-next-line newline-per-chained-call
  220. const authIdentity = $(resultIq).find('>conference').attr('identity');
  221. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  222. authenticationEnabled, authIdentity);
  223. // Check if jicofo has jigasi support enabled.
  224. if ($(resultIq).find(
  225. '>conference>property'
  226. + '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  227. this.sipGatewayEnabled = true;
  228. }
  229. logger.info(`Sip gateway enabled: ${this.sipGatewayEnabled}`);
  230. };
  231. // FIXME We need to show the fact that we're waiting for the focus to the user
  232. // (or that the focus is not available)
  233. /**
  234. * Allocates the conference focus.
  235. *
  236. * @param {Function} callback - the function to be called back upon the
  237. * successful allocation of the conference focus
  238. * @returns {Promise} - Resolved when Jicofo allows to join the room. It's never
  239. * rejected and it'll keep on pinging Jicofo forever.
  240. */
  241. Moderator.prototype.allocateConferenceFocus = function() {
  242. return new Promise(resolve => {
  243. // Try to use focus user JID from the config
  244. this.setFocusUserJid(this.options.connection.focusUserJid);
  245. // Send create conference IQ
  246. this.connection.sendIQ(
  247. this.createConferenceIq(),
  248. result => this._allocateConferenceFocusSuccess(result, resolve),
  249. error => this._allocateConferenceFocusError(error, resolve));
  250. // XXX We're pressed for time here because we're beginning a complex
  251. // and/or lengthy conference-establishment process which supposedly
  252. // involves multiple RTTs. We don't have the time to wait for Strophe to
  253. // decide to send our IQ.
  254. this.connection.flush();
  255. });
  256. };
  257. /**
  258. * Invoked by {@link #allocateConferenceFocus} upon its request receiving an
  259. * error result.
  260. *
  261. * @param error - the error result of the request that
  262. * {@link #allocateConferenceFocus} sent
  263. * @param {Function} callback - the function to be called back upon the
  264. * successful allocation of the conference focus
  265. */
  266. Moderator.prototype._allocateConferenceFocusError = function(error, callback) {
  267. // If the session is invalid, remove and try again without session ID to get
  268. // a new one
  269. const invalidSession
  270. = $(error).find('>error>session-invalid').length
  271. || $(error).find('>error>not-acceptable').length;
  272. if (invalidSession) {
  273. logger.info('Session expired! - removing');
  274. Settings.sessionId = undefined;
  275. }
  276. if ($(error).find('>error>graceful-shutdown').length) {
  277. this.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  278. return;
  279. }
  280. // Check for error returned by the reservation system
  281. const reservationErr = $(error).find('>error>reservation-error');
  282. if (reservationErr.length) {
  283. // Trigger error event
  284. const errorCode = reservationErr.attr('error-code');
  285. const errorTextNode = $(error).find('>error>text');
  286. let errorMsg;
  287. if (errorTextNode) {
  288. errorMsg = errorTextNode.text();
  289. }
  290. this.eventEmitter.emit(
  291. XMPPEvents.RESERVATION_ERROR,
  292. errorCode,
  293. errorMsg);
  294. return;
  295. }
  296. // Not authorized to create new room
  297. if ($(error).find('>error>not-authorized').length) {
  298. logger.warn('Unauthorized to start the conference', error);
  299. const toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
  300. if (toDomain !== this.options.connection.hosts.anonymousdomain) {
  301. // FIXME "is external" should come either from the focus or
  302. // config.js
  303. this.externalAuthEnabled = true;
  304. }
  305. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  306. return;
  307. }
  308. // redirect
  309. if ($(error).find('>error>redirect').length) {
  310. const conferenceIQError = $(error).find('conference');
  311. const vnode = conferenceIQError.attr('vnode');
  312. const focusJid = conferenceIQError.attr('focusjid');
  313. logger.warn(`We have been redirected to: ${vnode} new focus Jid:${focusJid}`);
  314. this.eventEmitter.emit(XMPPEvents.REDIRECTED, vnode, focusJid);
  315. return;
  316. }
  317. const waitMs = this.getNextErrorTimeout();
  318. const errmsg = `Focus error, retry after ${waitMs}`;
  319. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  320. logger.error(errmsg, error);
  321. // Show message
  322. const focusComponent = this.getFocusComponent();
  323. const retrySec = waitMs / 1000;
  324. // FIXME: message is duplicated ? Do not show in case of session invalid
  325. // which means just a retry
  326. if (!invalidSession) {
  327. this.eventEmitter.emit(
  328. XMPPEvents.FOCUS_DISCONNECTED,
  329. focusComponent,
  330. retrySec);
  331. }
  332. // Reset response timeout
  333. this.getNextTimeout(true);
  334. window.setTimeout(
  335. () => this.allocateConferenceFocus().then(callback),
  336. waitMs);
  337. };
  338. /**
  339. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  340. * success (i.e. non-error) result.
  341. *
  342. * @param result - the success (i.e. non-error) result of the request that
  343. * {@link #allocateConferenceFocus} sent
  344. * @param {Function} callback - the function to be called back upon the
  345. * successful allocation of the conference focus
  346. */
  347. Moderator.prototype._allocateConferenceFocusSuccess = function(
  348. result,
  349. callback) {
  350. // Setup config options
  351. this.parseConfigOptions(result);
  352. // Reset the error timeout (because we haven't failed here).
  353. this.getNextErrorTimeout(true);
  354. // eslint-disable-next-line newline-per-chained-call
  355. if ($(result).find('conference').attr('ready') === 'true') {
  356. // Reset the non-error timeout (because we've succeeded here).
  357. this.getNextTimeout(true);
  358. // Exec callback
  359. callback();
  360. } else {
  361. const waitMs = this.getNextTimeout();
  362. logger.info(`Waiting for the focus... ${waitMs}`);
  363. window.setTimeout(
  364. () => this.allocateConferenceFocus().then(callback),
  365. waitMs);
  366. }
  367. };
  368. Moderator.prototype.authenticate = function() {
  369. return new Promise((resolve, reject) => {
  370. this.connection.sendIQ(
  371. this.createConferenceIq(),
  372. result => {
  373. this.parseSessionId(result);
  374. resolve();
  375. },
  376. errorIq => reject({
  377. error: $(errorIq).find('iq>error :first')
  378. .prop('tagName'),
  379. message: $(errorIq).find('iq>error>text')
  380. .text()
  381. })
  382. );
  383. });
  384. };
  385. Moderator.prototype.getLoginUrl = function(urlCallback, failureCallback) {
  386. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  387. };
  388. /**
  389. *
  390. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  391. * {@link Moderator#getPopupLoginUrl}
  392. * @param urlCb
  393. * @param failureCb
  394. */
  395. Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
  396. const iq = $iq({ to: this.getFocusComponent(),
  397. type: 'get' });
  398. const attrs = {
  399. xmlns: 'http://jitsi.org/protocol/focus',
  400. room: this.roomName,
  401. 'machine-uid': Settings.machineId
  402. };
  403. let str = 'auth url'; // for logger
  404. if (popup) {
  405. attrs.popup = true;
  406. str = `POPUP ${str}`;
  407. }
  408. iq.c('login-url', attrs);
  409. /**
  410. * Implements a failure callback which reports an error message and an error
  411. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  412. *
  413. * @param {string} errmsg the error messsage to report
  414. * @param {*} error the error to report (in addition to errmsg)
  415. */
  416. function reportError(errmsg, err) {
  417. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  418. logger.error(errmsg, err);
  419. failureCb(err);
  420. }
  421. this.connection.sendIQ(
  422. iq,
  423. result => {
  424. // eslint-disable-next-line newline-per-chained-call
  425. let url = $(result).find('login-url').attr('url');
  426. url = decodeURIComponent(url);
  427. if (url) {
  428. logger.info(`Got ${str}: ${url}`);
  429. urlCb(url);
  430. } else {
  431. reportError(`Failed to get ${str} from the focus`, result);
  432. }
  433. },
  434. reportError.bind(undefined, `Get ${str} error`)
  435. );
  436. };
  437. Moderator.prototype.getPopupLoginUrl = function(urlCallback, failureCallback) {
  438. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  439. };
  440. Moderator.prototype.logout = function(callback) {
  441. const iq = $iq({ to: this.getFocusComponent(),
  442. type: 'set' });
  443. const { sessionId } = Settings;
  444. if (!sessionId) {
  445. callback();
  446. return;
  447. }
  448. iq.c('logout', {
  449. xmlns: 'http://jitsi.org/protocol/focus',
  450. 'session-id': sessionId
  451. });
  452. this.connection.sendIQ(
  453. iq,
  454. result => {
  455. // eslint-disable-next-line newline-per-chained-call
  456. let logoutUrl = $(result).find('logout').attr('logout-url');
  457. if (logoutUrl) {
  458. logoutUrl = decodeURIComponent(logoutUrl);
  459. }
  460. logger.info(`Log out OK, url: ${logoutUrl}`, result);
  461. Settings.sessionId = undefined;
  462. callback(logoutUrl);
  463. },
  464. error => {
  465. const errmsg = 'Logout error';
  466. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  467. logger.error(errmsg, error);
  468. }
  469. );
  470. };