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

moderator.js 16KB

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