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

moderator.js 16KB

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