modified lib-jitsi-meet dev repo
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

moderator.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. if (config.startBitrate) {
  124. elem.c(
  125. 'property', {
  126. name: 'startBitrate',
  127. value: config.startBitrate
  128. }).up();
  129. }
  130. if (config.minBitrate) {
  131. elem.c(
  132. 'property', {
  133. name: 'minBitrate',
  134. value: config.minBitrate
  135. }).up();
  136. }
  137. if (this.options.conference.startAudioMuted !== undefined) {
  138. elem.c(
  139. 'property', {
  140. name: 'startAudioMuted',
  141. value: this.options.conference.startAudioMuted
  142. }).up();
  143. }
  144. if (this.options.conference.startVideoMuted !== undefined) {
  145. elem.c(
  146. 'property', {
  147. name: 'startVideoMuted',
  148. value: this.options.conference.startVideoMuted
  149. }).up();
  150. }
  151. // this flag determines whether the bridge will include this call in its
  152. // rtcstats reporting or not. If the site admin hasn't set the flag in
  153. // config.js, then the client defaults to false (see
  154. // react/features/rtcstats/functions.js in jitsi-meet). The server-side
  155. // components default to true to match the pre-existing behavior so we only
  156. // signal if false.
  157. const rtcstatsEnabled = this.options.conference?.analytics?.rtcstatsEnabled ?? false;
  158. if (!rtcstatsEnabled) {
  159. elem.c(
  160. 'property', {
  161. name: 'rtcstatsEnabled',
  162. value: false
  163. }).up();
  164. }
  165. return elem;
  166. };
  167. Moderator.prototype.parseSessionId = function(resultIq) {
  168. // eslint-disable-next-line newline-per-chained-call
  169. const sessionId = $(resultIq).find('conference').attr('session-id');
  170. if (sessionId) {
  171. logger.info(`Received sessionId: ${sessionId}`);
  172. Settings.sessionId = sessionId;
  173. }
  174. };
  175. Moderator.prototype.parseConfigOptions = function(resultIq) {
  176. // eslint-disable-next-line newline-per-chained-call
  177. this.setFocusUserJid($(resultIq).find('conference').attr('focusjid'));
  178. const authenticationEnabled
  179. = $(resultIq).find(
  180. '>conference>property'
  181. + '[name=\'authentication\'][value=\'true\']').length > 0;
  182. logger.info(`Authentication enabled: ${authenticationEnabled}`);
  183. this.externalAuthEnabled = $(resultIq).find(
  184. '>conference>property'
  185. + '[name=\'externalAuth\'][value=\'true\']').length > 0;
  186. logger.info(
  187. `External authentication enabled: ${this.externalAuthEnabled}`);
  188. if (!this.externalAuthEnabled) {
  189. // We expect to receive sessionId in 'internal' authentication mode
  190. this.parseSessionId(resultIq);
  191. }
  192. // eslint-disable-next-line newline-per-chained-call
  193. const authIdentity = $(resultIq).find('>conference').attr('identity');
  194. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  195. authenticationEnabled, authIdentity);
  196. // Check if jicofo has jigasi support enabled.
  197. if ($(resultIq).find(
  198. '>conference>property'
  199. + '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  200. this.sipGatewayEnabled = true;
  201. }
  202. logger.info(`Sip gateway enabled: ${this.sipGatewayEnabled}`);
  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.allocateConferenceFocus = function() {
  215. return new Promise(resolve => {
  216. // Try to use focus user JID from the config
  217. this.setFocusUserJid(this.options.connection.focusUserJid);
  218. // Send create conference IQ
  219. this.connection.sendIQ(
  220. this.createConferenceIq(),
  221. result => this._allocateConferenceFocusSuccess(result, resolve),
  222. error => this._allocateConferenceFocusError(error, resolve));
  223. // XXX We're pressed for time here because we're beginning a complex
  224. // and/or lengthy conference-establishment process which supposedly
  225. // involves multiple RTTs. We don't have the time to wait for Strophe to
  226. // decide to send our IQ.
  227. this.connection.flush();
  228. });
  229. };
  230. /**
  231. * Invoked by {@link #allocateConferenceFocus} upon its request receiving an
  232. * error result.
  233. *
  234. * @param error - the error result of the request that
  235. * {@link #allocateConferenceFocus} sent
  236. * @param {Function} callback - the function to be called back upon the
  237. * successful allocation of the conference focus
  238. */
  239. Moderator.prototype._allocateConferenceFocusError = function(error, callback) {
  240. // If the session is invalid, remove and try again without session ID to get
  241. // a new one
  242. const invalidSession
  243. = $(error).find('>error>session-invalid').length
  244. || $(error).find('>error>not-acceptable').length;
  245. if (invalidSession) {
  246. logger.info('Session expired! - removing');
  247. Settings.sessionId = undefined;
  248. }
  249. if ($(error).find('>error>graceful-shutdown').length) {
  250. this.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  251. return;
  252. }
  253. // Check for error returned by the reservation system
  254. const reservationErr = $(error).find('>error>reservation-error');
  255. if (reservationErr.length) {
  256. // Trigger error event
  257. const errorCode = reservationErr.attr('error-code');
  258. const errorTextNode = $(error).find('>error>text');
  259. let errorMsg;
  260. if (errorTextNode) {
  261. errorMsg = errorTextNode.text();
  262. }
  263. this.eventEmitter.emit(
  264. XMPPEvents.RESERVATION_ERROR,
  265. errorCode,
  266. errorMsg);
  267. return;
  268. }
  269. // Not authorized to create new room
  270. if ($(error).find('>error>not-authorized').length) {
  271. logger.warn('Unauthorized to start the conference', error);
  272. const toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
  273. if (toDomain !== this.options.connection.hosts.anonymousdomain) {
  274. // FIXME "is external" should come either from the focus or
  275. // config.js
  276. this.externalAuthEnabled = true;
  277. }
  278. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  279. return;
  280. }
  281. const waitMs = this.getNextErrorTimeout();
  282. const errmsg = `Focus error, retry after ${waitMs}`;
  283. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  284. logger.error(errmsg, error);
  285. // Show message
  286. const focusComponent = this.getFocusComponent();
  287. const retrySec = waitMs / 1000;
  288. // FIXME: message is duplicated ? Do not show in case of session invalid
  289. // which means just a retry
  290. if (!invalidSession) {
  291. this.eventEmitter.emit(
  292. XMPPEvents.FOCUS_DISCONNECTED,
  293. focusComponent,
  294. retrySec);
  295. }
  296. // Reset response timeout
  297. this.getNextTimeout(true);
  298. window.setTimeout(
  299. () => this.allocateConferenceFocus().then(callback),
  300. waitMs);
  301. };
  302. /**
  303. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  304. * success (i.e. non-error) result.
  305. *
  306. * @param result - the success (i.e. non-error) result of the request that
  307. * {@link #allocateConferenceFocus} sent
  308. * @param {Function} callback - the function to be called back upon the
  309. * successful allocation of the conference focus
  310. */
  311. Moderator.prototype._allocateConferenceFocusSuccess = function(
  312. result,
  313. callback) {
  314. // Setup config options
  315. this.parseConfigOptions(result);
  316. // Reset the error timeout (because we haven't failed here).
  317. this.getNextErrorTimeout(true);
  318. // eslint-disable-next-line newline-per-chained-call
  319. if ($(result).find('conference').attr('ready') === 'true') {
  320. // Reset the non-error timeout (because we've succeeded here).
  321. this.getNextTimeout(true);
  322. const vnode = $(result).find('conference')
  323. .attr('vnode');
  324. if (vnode) {
  325. logger.warn(`We have been redirected to: ${vnode} new focus Jid:${this.getFocusUserJid()}`);
  326. this.eventEmitter.emit(XMPPEvents.REDIRECTED, vnode, this.getFocusUserJid());
  327. return;
  328. }
  329. // Exec callback
  330. callback();
  331. } else {
  332. const waitMs = this.getNextTimeout();
  333. logger.info(`Waiting for the focus... ${waitMs}`);
  334. window.setTimeout(
  335. () => this.allocateConferenceFocus().then(callback),
  336. waitMs);
  337. }
  338. };
  339. Moderator.prototype.authenticate = function() {
  340. return new Promise((resolve, reject) => {
  341. this.connection.sendIQ(
  342. this.createConferenceIq(),
  343. result => {
  344. this.parseSessionId(result);
  345. resolve();
  346. },
  347. errorIq => reject({
  348. error: $(errorIq).find('iq>error :first')
  349. .prop('tagName'),
  350. message: $(errorIq).find('iq>error>text')
  351. .text()
  352. })
  353. );
  354. });
  355. };
  356. Moderator.prototype.getLoginUrl = function(urlCallback, failureCallback) {
  357. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  358. };
  359. /**
  360. *
  361. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  362. * {@link Moderator#getPopupLoginUrl}
  363. * @param urlCb
  364. * @param failureCb
  365. */
  366. Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
  367. const iq = $iq({ to: this.getFocusComponent(),
  368. type: 'get' });
  369. const attrs = {
  370. xmlns: 'http://jitsi.org/protocol/focus',
  371. room: this.roomName,
  372. 'machine-uid': Settings.machineId
  373. };
  374. let str = 'auth url'; // for logger
  375. if (popup) {
  376. attrs.popup = true;
  377. str = `POPUP ${str}`;
  378. }
  379. iq.c('login-url', attrs);
  380. /**
  381. * Implements a failure callback which reports an error message and an error
  382. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  383. *
  384. * @param {string} errmsg the error messsage to report
  385. * @param {*} error the error to report (in addition to errmsg)
  386. */
  387. function reportError(errmsg, err) {
  388. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  389. logger.error(errmsg, err);
  390. failureCb(err);
  391. }
  392. this.connection.sendIQ(
  393. iq,
  394. result => {
  395. // eslint-disable-next-line newline-per-chained-call
  396. let url = $(result).find('login-url').attr('url');
  397. url = decodeURIComponent(url);
  398. if (url) {
  399. logger.info(`Got ${str}: ${url}`);
  400. urlCb(url);
  401. } else {
  402. reportError(`Failed to get ${str} from the focus`, result);
  403. }
  404. },
  405. reportError.bind(undefined, `Get ${str} error`)
  406. );
  407. };
  408. Moderator.prototype.getPopupLoginUrl = function(urlCallback, failureCallback) {
  409. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  410. };
  411. Moderator.prototype.logout = function(callback) {
  412. const iq = $iq({ to: this.getFocusComponent(),
  413. type: 'set' });
  414. const { sessionId } = Settings;
  415. if (!sessionId) {
  416. callback();
  417. return;
  418. }
  419. iq.c('logout', {
  420. xmlns: 'http://jitsi.org/protocol/focus',
  421. 'session-id': sessionId
  422. });
  423. this.connection.sendIQ(
  424. iq,
  425. result => {
  426. // eslint-disable-next-line newline-per-chained-call
  427. let logoutUrl = $(result).find('logout').attr('logout-url');
  428. if (logoutUrl) {
  429. logoutUrl = decodeURIComponent(logoutUrl);
  430. }
  431. logger.info(`Log out OK, url: ${logoutUrl}`, result);
  432. Settings.sessionId = undefined;
  433. callback(logoutUrl);
  434. },
  435. error => {
  436. const errmsg = 'Logout error';
  437. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  438. logger.error(errmsg, error);
  439. }
  440. );
  441. };