Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /* eslint-disable newline-per-chained-call */
  2. import { getLogger } from '@jitsi/logger';
  3. import $ from 'jquery';
  4. import { $iq, Strophe } from 'strophe.js';
  5. import Settings from '../settings/Settings';
  6. const AuthenticationEvents
  7. = require('../../service/authentication/AuthenticationEvents');
  8. const { XMPPEvents } = require('../../service/xmpp/XMPPEvents');
  9. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  10. const logger = getLogger(__filename);
  11. /**
  12. *
  13. * @param step
  14. */
  15. function createExpBackoffTimer(step) {
  16. let count = 1;
  17. const maxTimeout = 120000;
  18. return function(reset) {
  19. // Reset call
  20. if (reset) {
  21. count = 1;
  22. return;
  23. }
  24. // Calculate next timeout
  25. const timeout = Math.pow(2, count - 1);
  26. count += 1;
  27. return Math.min(timeout * step, maxTimeout);
  28. };
  29. }
  30. /**
  31. *
  32. * @param roomName
  33. * @param xmpp
  34. * @param emitter
  35. * @param options
  36. */
  37. export default function Moderator(roomName, xmpp, emitter, options) {
  38. this.roomName = roomName;
  39. this.getNextTimeout = createExpBackoffTimer(1000);
  40. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  41. this.options = options;
  42. // External authentication stuff
  43. this.externalAuthEnabled = false;
  44. // Whether SIP gateway (jigasi) support is enabled. TODO: use presence so it can be changed based on jigasi
  45. // availability.
  46. this.sipGatewayEnabled = false;
  47. this.eventEmitter = emitter;
  48. this.connection = xmpp.connection;
  49. // The JID to which conference-iq requests are sent over XMPP.
  50. this.targetJid = this.options.hosts?.focus;
  51. // If not specified default to 'focus.domain'
  52. if (!this.targetJid) {
  53. this.targetJid = `focus.${this.options.hosts?.domain}`;
  54. }
  55. this.targetUrl = this.options.conferenceRequestUrl;
  56. // Whether to send conference requests over HTTP or XMPP
  57. this.mode = this.targetUrl ? 'http' : 'xmpp';
  58. logger.info(`Using ${this.mode} for conference requests.`);
  59. // The set of JIDs known to belong to jicofo. Populated from configuration
  60. // and responses from conference requests.
  61. this.focusUserJids = new Set();
  62. if (options.focusUserJid) {
  63. this.focusUserJids.add(options.focusUserJid);
  64. }
  65. // FIXME: Message listener that talks to POPUP window
  66. /**
  67. *
  68. * @param event
  69. */
  70. function listener(event) {
  71. if (event.data && event.data.sessionId) {
  72. if (event.origin !== window.location.origin) {
  73. logger.warn(`Ignoring sessionId from different origin: ${event.origin}`);
  74. return;
  75. }
  76. Settings.sessionId = event.data.sessionId;
  77. // After popup is closed we will authenticate
  78. }
  79. }
  80. // Register
  81. if (window.addEventListener) {
  82. window.addEventListener('message', listener, false);
  83. } else {
  84. window.attachEvent('onmessage', listener);
  85. }
  86. }
  87. Moderator.prototype.isFocusJid = function(jid) {
  88. if (!jid) {
  89. return false;
  90. }
  91. for (const focusJid of this.focusUserJids) {
  92. // jid may be a full JID, and focusUserJids may be bare JIDs
  93. if (jid.indexOf(`${focusJid}/`) === 0) {
  94. return true;
  95. }
  96. }
  97. return false;
  98. };
  99. Moderator.prototype.isExternalAuthEnabled = function() {
  100. return this.externalAuthEnabled;
  101. };
  102. Moderator.prototype.isSipGatewayEnabled = function() {
  103. return this.sipGatewayEnabled;
  104. };
  105. /**
  106. * Create a conference request based on the configured options and saved Settings.
  107. *
  108. * A conference request has the following format:
  109. * {
  110. * room: "room@example.com",
  111. * sessionId: "foo", // optional
  112. * machineUdi: "bar", // optional
  113. * identity: "baz", // optional
  114. * properties: { } // map string to string
  115. * }
  116. *
  117. * It can be encoded in either JSON or and IQ.
  118. *
  119. * @returns the created conference request.
  120. */
  121. Moderator.prototype._createConferenceRequest = function() {
  122. // Session Id used for authentication
  123. const { sessionId } = Settings;
  124. const config = this.options;
  125. const properties = {};
  126. if (config.startAudioMuted !== undefined) {
  127. properties.startAudioMuted = config.startAudioMuted;
  128. }
  129. if (config.startVideoMuted !== undefined) {
  130. properties.startVideoMuted = config.startVideoMuted;
  131. }
  132. // this flag determines whether the bridge will include this call in its
  133. // rtcstats reporting or not. If the site admin hasn't set the flag in
  134. // config.js, then the client defaults to false (see
  135. // react/features/rtcstats/functions.js in jitsi-meet). The server-side
  136. // components default to true to match the pre-existing behavior so we only
  137. // signal if false.
  138. const rtcstatsEnabled = config?.analytics?.rtcstatsEnabled ?? false;
  139. if (!rtcstatsEnabled) {
  140. properties.rtcstatsEnabled = false;
  141. }
  142. const conferenceRequest = {
  143. properties,
  144. machineUid: Settings.machineId,
  145. room: this.roomName
  146. };
  147. if (sessionId) {
  148. conferenceRequest.sessionId = sessionId;
  149. }
  150. return conferenceRequest;
  151. };
  152. /**
  153. * Create a conference request and encode it as an IQ.
  154. */
  155. Moderator.prototype._createConferenceIq = function() {
  156. const conferenceRequest = this._createConferenceRequest();
  157. // Generate create conference IQ
  158. const elem = $iq({ to: this.targetJid,
  159. type: 'set' });
  160. elem.c('conference', {
  161. xmlns: 'http://jitsi.org/protocol/focus',
  162. room: this.roomName,
  163. 'machine-uid': conferenceRequest.machineUid
  164. });
  165. if (conferenceRequest.sessionId) {
  166. elem.attrs({ 'session-id': conferenceRequest.sessionId });
  167. }
  168. for (const k in conferenceRequest.properties) {
  169. if (conferenceRequest.properties.hasOwnProperty(k)) {
  170. elem.c(
  171. 'property', {
  172. name: k,
  173. value: conferenceRequest.properties[k]
  174. }).up();
  175. }
  176. }
  177. return elem;
  178. };
  179. Moderator.prototype._parseConferenceIq = function(resultIq) {
  180. const conferenceRequest = { properties: {} };
  181. conferenceRequest.focusJid = $(resultIq).find('conference').attr('focusjid');
  182. conferenceRequest.sessionId = $(resultIq).find('conference').attr('session-id');
  183. conferenceRequest.identity = $(resultIq).find('>conference').attr('identity');
  184. conferenceRequest.ready = $(resultIq).find('conference').attr('ready') === 'true';
  185. conferenceRequest.vnode = $(resultIq).find('conference').attr('vnode');
  186. if ($(resultIq).find('>conference>property[name=\'authentication\'][value=\'true\']').length > 0) {
  187. conferenceRequest.properties.authentication = 'true';
  188. }
  189. if ($(resultIq).find('>conference>property[name=\'externalAuth\'][value=\'true\']').length > 0) {
  190. conferenceRequest.properties.externalAuth = 'true';
  191. }
  192. // Check if jicofo has jigasi support enabled.
  193. if ($(resultIq).find('>conference>property[name=\'sipGatewayEnabled\'][value=\'true\']').length > 0) {
  194. conferenceRequest.properties.sipGatewayEnabled = 'true';
  195. }
  196. return conferenceRequest;
  197. };
  198. // FIXME We need to show the fact that we're waiting for the focus to the user
  199. // (or that the focus is not available)
  200. /**
  201. * Allocates the conference focus.
  202. *
  203. * @param {Function} callback - the function to be called back upon the
  204. * successful allocation of the conference focus
  205. * @returns {Promise} - Resolved when Jicofo allows to join the room. It's never
  206. * rejected and it'll keep on pinging Jicofo forever.
  207. */
  208. Moderator.prototype.sendConferenceRequest = function() {
  209. return new Promise(resolve => {
  210. if (this.mode === 'xmpp') {
  211. logger.info(`Sending conference request over XMPP to ${this.targetJid}`);
  212. this.connection.sendIQ(
  213. this._createConferenceIq(),
  214. result => this._handleIqSuccess(result, resolve),
  215. error => this._handleIqError(error, resolve));
  216. // XXX We're pressed for time here because we're beginning a complex
  217. // and/or lengthy conference-establishment process which supposedly
  218. // involves multiple RTTs. We don't have the time to wait for Strophe to
  219. // decide to send our IQ.
  220. this.connection.flush();
  221. } else {
  222. logger.info(`Sending conference request over HTTP to ${this.targetUrl}`);
  223. fetch(this.targetUrl, {
  224. method: 'POST',
  225. body: JSON.stringify(this._createConferenceRequest()),
  226. headers: { 'Content-Type': 'application/json' }
  227. })
  228. .then(response => {
  229. if (!response.ok) {
  230. response.text().then(text => {
  231. logger.warn(`Received HTTP ${response.status} ${response.statusText}. Body: ${text}`);
  232. const sessionError = response.status === 400 && text.indexOf('400 invalid-session') > 0;
  233. const notAuthorized = response.status === 403;
  234. this._handleError(sessionError, notAuthorized, resolve);
  235. })
  236. .catch(error => {
  237. logger.warn(`Error: ${error}`);
  238. this._handleError();
  239. });
  240. // _handleError has either scheduled a retry or fired an event indicating failure.
  241. return;
  242. }
  243. response.json().then(resultJson => {
  244. this._handleSuccess(resultJson, resolve);
  245. });
  246. })
  247. .catch(error => {
  248. logger.warn(`Error: ${error}`);
  249. this._handleError();
  250. });
  251. }
  252. });
  253. };
  254. Moderator.prototype._handleSuccess = function(conferenceRequest, callback) {
  255. // Reset the error timeout (because we haven't failed here).
  256. this.getNextErrorTimeout(true);
  257. if (conferenceRequest.focusJid) {
  258. logger.info(`Adding focus JID: ${conferenceRequest.focusJid}`);
  259. this.focusUserJids.add(conferenceRequest.focusJid);
  260. } else {
  261. logger.warn('Conference request response contained no focusJid.');
  262. }
  263. const authenticationEnabled = conferenceRequest.properties.authentication === 'true';
  264. logger.info(`Authentication enabled: ${authenticationEnabled}`);
  265. this.externalAuthEnabled = conferenceRequest.properties.externalAuth === 'true';
  266. logger.info(`External authentication enabled: ${this.externalAuthEnabled}`);
  267. if (!this.externalAuthEnabled && conferenceRequest.sessionId) {
  268. logger.info(`Received sessionId: ${conferenceRequest.sessionId}`);
  269. Settings.sessionId = conferenceRequest.sessionId;
  270. }
  271. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED, authenticationEnabled, conferenceRequest.identity);
  272. this.sipGatewayEnabled = conferenceRequest.properties.sipGatewayEnabled;
  273. logger.info(`Sip gateway enabled: ${this.sipGatewayEnabled}`);
  274. if (conferenceRequest.ready) {
  275. // Reset the non-error timeout (because we've succeeded here).
  276. this.getNextTimeout(true);
  277. if (conferenceRequest.vnode) {
  278. logger.warn(`Redirected to: ${conferenceRequest.vnode} with focusJid ${conferenceRequest.focusJid} }`);
  279. this.eventEmitter.emit(XMPPEvents.REDIRECTED, conferenceRequest.vnode, conferenceRequest.focusJid);
  280. return;
  281. }
  282. logger.info('Conference-request successful, ready to join the MUC.');
  283. callback();
  284. } else {
  285. const waitMs = this.getNextTimeout();
  286. // This was a successful response, but the "ready" flag is not set. Retry after a timeout.
  287. logger.info(`Not ready yet, will retry in ${waitMs} ms.`);
  288. window.setTimeout(
  289. () => this.sendConferenceRequest().then(callback),
  290. waitMs);
  291. }
  292. };
  293. Moderator.prototype._handleError = function(sessionError, notAuthorized, callback) {
  294. // If the session is invalid, remove and try again without session ID to get
  295. // a new one
  296. if (sessionError) {
  297. logger.info('Session expired! - removing');
  298. Settings.sessionId = undefined;
  299. }
  300. // Not authorized to create new room
  301. if (notAuthorized) {
  302. logger.warn('Unauthorized to start the conference');
  303. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  304. return;
  305. }
  306. const waitMs = this.getNextErrorTimeout();
  307. if (sessionError && waitMs < 60000) {
  308. // If the session is invalid, retry a limited number of times and then fire an error.
  309. logger.info(`Invalid session, will retry after ${waitMs} ms.`);
  310. this.getNextTimeout(true);
  311. window.setTimeout(() => this.sendConferenceRequest().then(callback), waitMs);
  312. } else {
  313. const errmsg = 'Failed to get a successful response, giving up.';
  314. const error = new Error(errmsg);
  315. logger.error(errmsg, error);
  316. GlobalOnErrorHandler.callErrorHandler(error);
  317. // This is a "fatal" error and the user of the lib should handle it accordingly.
  318. // TODO: change the event name to something accurate.
  319. this.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED);
  320. }
  321. };
  322. /**
  323. * Invoked by {@link #sendConferenecRequest} upon its request receiving an
  324. * error result.
  325. *
  326. * @param error - the error result of the request that {@link sendConferenceRequest} sent
  327. * @param {Function} callback - the function to be called back upon the
  328. * successful allocation of the conference focus
  329. */
  330. Moderator.prototype._handleIqError = function(error, callback) {
  331. // The reservation system only works over XMPP. Handle the error separately.
  332. // Check for error returned by the reservation system
  333. const reservationErr = $(error).find('>error>reservation-error');
  334. if (reservationErr.length) {
  335. // Trigger error event
  336. const errorCode = reservationErr.attr('error-code');
  337. const errorTextNode = $(error).find('>error>text');
  338. let errorMsg;
  339. if (errorTextNode) {
  340. errorMsg = errorTextNode.text();
  341. }
  342. this.eventEmitter.emit(
  343. XMPPEvents.RESERVATION_ERROR,
  344. errorCode,
  345. errorMsg);
  346. return;
  347. }
  348. const invalidSession
  349. = Boolean($(error).find('>error>session-invalid').length
  350. || $(error).find('>error>not-acceptable').length);
  351. // Not authorized to create new room
  352. const notAuthorized = $(error).find('>error>not-authorized').length > 0;
  353. if (notAuthorized && Strophe.getDomainFromJid(error.getAttribute('to')) !== this.options.hosts.anonymousdomain) {
  354. // FIXME "is external" should come either from the focus or
  355. // config.js
  356. this.externalAuthEnabled = true;
  357. }
  358. this._handleError(invalidSession, notAuthorized, callback);
  359. };
  360. /**
  361. * Invoked by {@link #sendConferenecRequest} upon its request receiving a
  362. * success (i.e. non-error) result.
  363. *
  364. * @param result - the success (i.e. non-error) result of the request that {@link #sendConferenecRequest} sent
  365. * @param {Function} callback - the function to be called back upon the
  366. * successful allocation of the conference focus
  367. */
  368. Moderator.prototype._handleIqSuccess = function(
  369. result,
  370. callback) {
  371. // Setup config options
  372. const conferenceRequest = this._parseConferenceIq(result);
  373. this._handleSuccess(conferenceRequest, callback);
  374. };
  375. Moderator.prototype.authenticate = function() {
  376. return new Promise((resolve, reject) => {
  377. this.connection.sendIQ(
  378. this._createConferenceIq(),
  379. result => {
  380. const sessionId = $(result).find('conference').attr('session-id');
  381. if (sessionId) {
  382. logger.info(`Received sessionId: ${sessionId}`);
  383. Settings.sessionId = sessionId;
  384. } else {
  385. logger.warn('Response did not contain a session-id');
  386. }
  387. resolve();
  388. },
  389. errorIq => reject({
  390. error: $(errorIq).find('iq>error :first').prop('tagName'),
  391. message: $(errorIq).find('iq>error>text').text()
  392. })
  393. );
  394. });
  395. };
  396. Moderator.prototype.getLoginUrl = function(urlCallback, failureCallback) {
  397. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  398. };
  399. /**
  400. *
  401. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  402. * {@link Moderator#getPopupLoginUrl}
  403. * @param urlCb
  404. * @param failureCb
  405. */
  406. Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
  407. const iq = $iq({ to: this.targetJid,
  408. type: 'get' });
  409. const attrs = {
  410. xmlns: 'http://jitsi.org/protocol/focus',
  411. room: this.roomName,
  412. 'machine-uid': Settings.machineId
  413. };
  414. let str = 'auth url'; // for logger
  415. if (popup) {
  416. attrs.popup = true;
  417. str = `POPUP ${str}`;
  418. }
  419. iq.c('login-url', attrs);
  420. /**
  421. * Implements a failure callback which reports an error message and an error
  422. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  423. *
  424. * @param {string} errmsg the error messsage to report
  425. * @param {*} error the error to report (in addition to errmsg)
  426. */
  427. function reportError(errmsg, err) {
  428. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  429. logger.error(errmsg, err);
  430. failureCb(err);
  431. }
  432. this.connection.sendIQ(
  433. iq,
  434. result => {
  435. let url = $(result).find('login-url').attr('url');
  436. url = decodeURIComponent(url);
  437. if (url) {
  438. logger.info(`Got ${str}: ${url}`);
  439. urlCb(url);
  440. } else {
  441. reportError(`Failed to get ${str} from the focus`, result);
  442. }
  443. },
  444. reportError.bind(undefined, `Get ${str} error`)
  445. );
  446. };
  447. Moderator.prototype.getPopupLoginUrl = function(urlCallback, failureCallback) {
  448. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  449. };
  450. Moderator.prototype.logout = function(callback) {
  451. const iq = $iq({ to: this.targetJid,
  452. type: 'set' });
  453. const { sessionId } = Settings;
  454. if (!sessionId) {
  455. callback();
  456. return;
  457. }
  458. iq.c('logout', {
  459. xmlns: 'http://jitsi.org/protocol/focus',
  460. 'session-id': sessionId
  461. });
  462. this.connection.sendIQ(
  463. iq,
  464. result => {
  465. let logoutUrl = $(result).find('logout').attr('logout-url');
  466. if (logoutUrl) {
  467. logoutUrl = decodeURIComponent(logoutUrl);
  468. }
  469. logger.info(`Log out OK, url: ${logoutUrl}`, result);
  470. Settings.sessionId = undefined;
  471. callback(logoutUrl);
  472. },
  473. error => {
  474. const errmsg = 'Logout error';
  475. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  476. logger.error(errmsg, error);
  477. }
  478. );
  479. };