Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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