您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

moderator.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. const waitMs = this.getNextErrorTimeout();
  309. const errmsg = `Focus error, retry after ${waitMs}`;
  310. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  311. logger.error(errmsg, error);
  312. // Show message
  313. const focusComponent = this.getFocusComponent();
  314. const retrySec = waitMs / 1000;
  315. // FIXME: message is duplicated ? Do not show in case of session invalid
  316. // which means just a retry
  317. if (!invalidSession) {
  318. this.eventEmitter.emit(
  319. XMPPEvents.FOCUS_DISCONNECTED,
  320. focusComponent,
  321. retrySec);
  322. }
  323. // Reset response timeout
  324. this.getNextTimeout(true);
  325. window.setTimeout(
  326. () => this.allocateConferenceFocus().then(callback),
  327. waitMs);
  328. };
  329. /**
  330. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  331. * success (i.e. non-error) result.
  332. *
  333. * @param result - the success (i.e. non-error) result of the request that
  334. * {@link #allocateConferenceFocus} sent
  335. * @param {Function} callback - the function to be called back upon the
  336. * successful allocation of the conference focus
  337. */
  338. Moderator.prototype._allocateConferenceFocusSuccess = function(
  339. result,
  340. callback) {
  341. // Setup config options
  342. this.parseConfigOptions(result);
  343. // Reset the error timeout (because we haven't failed here).
  344. this.getNextErrorTimeout(true);
  345. // eslint-disable-next-line newline-per-chained-call
  346. if ($(result).find('conference').attr('ready') === 'true') {
  347. // Reset the non-error timeout (because we've succeeded here).
  348. this.getNextTimeout(true);
  349. // Exec callback
  350. callback();
  351. } else {
  352. const waitMs = this.getNextTimeout();
  353. logger.info(`Waiting for the focus... ${waitMs}`);
  354. window.setTimeout(
  355. () => this.allocateConferenceFocus().then(callback),
  356. waitMs);
  357. }
  358. };
  359. Moderator.prototype.authenticate = function() {
  360. return new Promise((resolve, reject) => {
  361. this.connection.sendIQ(
  362. this.createConferenceIq(),
  363. result => {
  364. this.parseSessionId(result);
  365. resolve();
  366. },
  367. errorIq => reject({
  368. error: $(errorIq).find('iq>error :first')
  369. .prop('tagName'),
  370. message: $(errorIq).find('iq>error>text')
  371. .text()
  372. })
  373. );
  374. });
  375. };
  376. Moderator.prototype.getLoginUrl = function(urlCallback, failureCallback) {
  377. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  378. };
  379. /**
  380. *
  381. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  382. * {@link Moderator#getPopupLoginUrl}
  383. * @param urlCb
  384. * @param failureCb
  385. */
  386. Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
  387. const iq = $iq({ to: this.getFocusComponent(),
  388. type: 'get' });
  389. const attrs = {
  390. xmlns: 'http://jitsi.org/protocol/focus',
  391. room: this.roomName,
  392. 'machine-uid': Settings.machineId
  393. };
  394. let str = 'auth url'; // for logger
  395. if (popup) {
  396. attrs.popup = true;
  397. str = `POPUP ${str}`;
  398. }
  399. iq.c('login-url', attrs);
  400. /**
  401. * Implements a failure callback which reports an error message and an error
  402. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  403. *
  404. * @param {string} errmsg the error messsage to report
  405. * @param {*} error the error to report (in addition to errmsg)
  406. */
  407. function reportError(errmsg, err) {
  408. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  409. logger.error(errmsg, err);
  410. failureCb(err);
  411. }
  412. this.connection.sendIQ(
  413. iq,
  414. result => {
  415. // eslint-disable-next-line newline-per-chained-call
  416. let url = $(result).find('login-url').attr('url');
  417. url = decodeURIComponent(url);
  418. if (url) {
  419. logger.info(`Got ${str}: ${url}`);
  420. urlCb(url);
  421. } else {
  422. reportError(`Failed to get ${str} from the focus`, result);
  423. }
  424. },
  425. reportError.bind(undefined, `Get ${str} error`)
  426. );
  427. };
  428. Moderator.prototype.getPopupLoginUrl = function(urlCallback, failureCallback) {
  429. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  430. };
  431. Moderator.prototype.logout = function(callback) {
  432. const iq = $iq({ to: this.getFocusComponent(),
  433. type: 'set' });
  434. const { sessionId } = Settings;
  435. if (!sessionId) {
  436. callback();
  437. return;
  438. }
  439. iq.c('logout', {
  440. xmlns: 'http://jitsi.org/protocol/focus',
  441. 'session-id': sessionId
  442. });
  443. this.connection.sendIQ(
  444. iq,
  445. result => {
  446. // eslint-disable-next-line newline-per-chained-call
  447. let logoutUrl = $(result).find('logout').attr('logout-url');
  448. if (logoutUrl) {
  449. logoutUrl = decodeURIComponent(logoutUrl);
  450. }
  451. logger.info(`Log out OK, url: ${logoutUrl}`, result);
  452. Settings.sessionId = undefined;
  453. callback(logoutUrl);
  454. },
  455. error => {
  456. const errmsg = 'Logout error';
  457. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  458. logger.error(errmsg, error);
  459. }
  460. );
  461. };