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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /* global $, $iq, Promise, Strophe */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4. var AuthenticationEvents
  5. = require("../../service/authentication/AuthenticationEvents");
  6. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  7. import Settings from "../settings/Settings";
  8. function createExpBackoffTimer(step) {
  9. var count = 1;
  10. return function (reset) {
  11. // Reset call
  12. if (reset) {
  13. count = 1;
  14. return;
  15. }
  16. // Calculate next timeout
  17. var 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. this.focusUserJid;
  38. //FIXME:
  39. // Message listener that talks to POPUP window
  40. function listener(event) {
  41. if (event.data && event.data.sessionId) {
  42. if (event.origin !== window.location.origin) {
  43. logger.warn("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. var 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. var 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. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  94. // Session Id used for authentication
  95. var sessionId = Settings.getSessionId();
  96. var machineUID = Settings.getMachineId();
  97. logger.info(
  98. "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: !!this.options.conference.disableRtx
  134. }).up();
  135. elem.c(
  136. 'property', {
  137. name: 'enableLipSync',
  138. value: false !== this.options.connection.enableLipSync
  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. var sessionId = $(resultIq).find('conference').attr('session-id');
  201. if (sessionId) {
  202. logger.info('Received sessionId: ' + sessionId);
  203. Settings.setSessionId(sessionId);
  204. }
  205. };
  206. Moderator.prototype.parseConfigOptions = function (resultIq) {
  207. this.setFocusUserJid(
  208. $(resultIq).find('conference').attr('focusjid'));
  209. var authenticationEnabled
  210. = $(resultIq).find(
  211. '>conference>property' +
  212. '[name=\'authentication\'][value=\'true\']').length > 0;
  213. logger.info("Authentication enabled: " + authenticationEnabled);
  214. this.externalAuthEnabled = $(resultIq).find(
  215. '>conference>property' +
  216. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  217. logger.info(
  218. 'External authentication enabled: ' + this.externalAuthEnabled);
  219. if (!this.externalAuthEnabled) {
  220. // We expect to receive sessionId in 'internal' authentication mode
  221. this.parseSessionId(resultIq);
  222. }
  223. var authIdentity = $(resultIq).find('>conference').attr('identity');
  224. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  225. authenticationEnabled, authIdentity);
  226. // Check if focus has auto-detected Jigasi component(this will be also
  227. // included if we have passed our host from the config)
  228. if ($(resultIq).find(
  229. '>conference>property' +
  230. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  231. this.sipGatewayEnabled = true;
  232. }
  233. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  234. };
  235. // FIXME We need to show the fact that we're waiting for the focus to the user
  236. // (or that the focus is not available)
  237. /**
  238. * Allocates the conference focus.
  239. *
  240. * @param {Function} callback - the function to be called back upon the
  241. * successful allocation of the conference focus
  242. */
  243. Moderator.prototype.allocateConferenceFocus = function (callback) {
  244. // Try to use focus user JID from the config
  245. this.setFocusUserJid(this.options.connection.focusUserJid);
  246. // Send create conference IQ
  247. this.connection.sendIQ(
  248. this.createConferenceIq(),
  249. result => this._allocateConferenceFocusSuccess(result, callback),
  250. error => this._allocateConferenceFocusError(error, callback));
  251. // XXX We're pressed for time here because we're beginning a complex and/or
  252. // lengthy conference-establishment process which supposedly involves
  253. // multiple RTTs. We don't have the time to wait for Strophe to decide to
  254. // send our IQ.
  255. this.connection.flush();
  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. var invalidSession = $(error).find('>error>session-invalid').length;
  270. if (invalidSession) {
  271. logger.info("Session expired! - removing");
  272. Settings.clearSessionId();
  273. }
  274. if ($(error).find('>error>graceful-shutdown').length) {
  275. this.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  276. return;
  277. }
  278. // Check for error returned by the reservation system
  279. var reservationErr = $(error).find('>error>reservation-error');
  280. if (reservationErr.length) {
  281. // Trigger error event
  282. var errorCode = reservationErr.attr('error-code');
  283. var errorTextNode = $(error).find('>error>text');
  284. var errorMsg;
  285. if (errorTextNode) {
  286. errorMsg = errorTextNode.text();
  287. }
  288. this.eventEmitter.emit(
  289. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  290. return;
  291. }
  292. // Not authorized to create new room
  293. if ($(error).find('>error>not-authorized').length) {
  294. logger.warn("Unauthorized to start the conference", error);
  295. var toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
  296. if (toDomain !== this.options.connection.hosts.anonymousdomain) {
  297. //FIXME "is external" should come either from the focus or config.js
  298. this.externalAuthEnabled = true;
  299. }
  300. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  301. return;
  302. }
  303. var waitMs = this.getNextErrorTimeout();
  304. var errmsg = "Focus error, retry after "+ waitMs;
  305. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  306. logger.error(errmsg, error);
  307. // Show message
  308. var focusComponent = this.getFocusComponent();
  309. var retrySec = waitMs / 1000;
  310. //FIXME: message is duplicated ? Do not show in case of session invalid
  311. // which means just a retry
  312. if (!invalidSession) {
  313. this.eventEmitter.emit(
  314. XMPPEvents.FOCUS_DISCONNECTED, focusComponent, retrySec);
  315. }
  316. // Reset response timeout
  317. this.getNextTimeout(true);
  318. window.setTimeout( () => this.allocateConferenceFocus(callback), waitMs);
  319. };
  320. /**
  321. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  322. * success (i.e. non-error) result.
  323. *
  324. * @param result - the success (i.e. non-error) result of the request that
  325. * {@link #allocateConferenceFocus} sent
  326. * @param {Function} callback - the function to be called back upon the
  327. * successful allocation of the conference focus
  328. */
  329. Moderator.prototype._allocateConferenceFocusSuccess = function (
  330. result,
  331. callback) {
  332. // Setup config options
  333. this.parseConfigOptions(result);
  334. // Reset the error timeout (because we haven't failed here).
  335. this.getNextErrorTimeout(true);
  336. if ('true' === $(result).find('conference').attr('ready')) {
  337. // Reset the non-error timeout (because we've succeeded here).
  338. this.getNextTimeout(true);
  339. // Exec callback
  340. callback();
  341. } else {
  342. var waitMs = this.getNextTimeout();
  343. logger.info("Waiting for the focus... " + waitMs);
  344. window.setTimeout(() => this.allocateConferenceFocus(callback),
  345. waitMs);
  346. }
  347. };
  348. Moderator.prototype.authenticate = function () {
  349. return new Promise((resolve, reject) => {
  350. this.connection.sendIQ(
  351. this.createConferenceIq(),
  352. result => {
  353. this.parseSessionId(result);
  354. resolve();
  355. }, error => {
  356. var code = $(error).find('>error').attr('code');
  357. reject(error, code);
  358. }
  359. );
  360. });
  361. };
  362. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  363. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  364. };
  365. /**
  366. *
  367. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  368. * {@link Moderator#getPopupLoginUrl}
  369. * @param urlCb
  370. * @param failureCb
  371. */
  372. Moderator.prototype._getLoginUrl = function (popup, urlCb, failureCb) {
  373. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  374. var attrs = {
  375. xmlns: 'http://jitsi.org/protocol/focus',
  376. room: this.roomName,
  377. 'machine-uid': Settings.getMachineId()
  378. };
  379. var str = 'auth url'; // for logger
  380. if (popup) {
  381. attrs.popup = true;
  382. str = 'POPUP ' + str;
  383. }
  384. iq.c('login-url', attrs);
  385. /**
  386. * Implements a failure callback which reports an error message and an error
  387. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  388. *
  389. * @param {string} errmsg the error messsage to report
  390. * @param {*} error the error to report (in addition to errmsg)
  391. */
  392. function reportError(errmsg, err) {
  393. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  394. logger.error(errmsg, err);
  395. failureCb(err);
  396. }
  397. this.connection.sendIQ(
  398. iq,
  399. function (result) {
  400. var url = $(result).find('login-url').attr('url');
  401. url = decodeURIComponent(url);
  402. if (url) {
  403. logger.info('Got ' + str + ': ' + url);
  404. urlCb(url);
  405. } else {
  406. reportError('Failed to get ' + str + ' from the focus', result);
  407. }
  408. },
  409. reportError.bind(undefined, 'Get ' + str + ' error')
  410. );
  411. };
  412. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  413. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  414. };
  415. Moderator.prototype.logout = function (callback) {
  416. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  417. var sessionId = Settings.getSessionId();
  418. if (!sessionId) {
  419. callback();
  420. return;
  421. }
  422. iq.c('logout', {
  423. xmlns: 'http://jitsi.org/protocol/focus',
  424. 'session-id': sessionId
  425. });
  426. this.connection.sendIQ(
  427. iq,
  428. function (result) {
  429. var logoutUrl = $(result).find('logout').attr('logout-url');
  430. if (logoutUrl) {
  431. logoutUrl = decodeURIComponent(logoutUrl);
  432. }
  433. logger.info("Log out OK, url: " + logoutUrl, result);
  434. Settings.clearSessionId();
  435. callback(logoutUrl);
  436. }.bind(this),
  437. function (error) {
  438. var errmsg = "Logout error";
  439. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  440. logger.error(errmsg, error);
  441. }
  442. );
  443. };
  444. module.exports = Moderator;