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

moderator.js 18KB

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