Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

moderator.js 18KB

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