選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

moderator.js 19KB

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