You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

moderator.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. /*
  2. * Copyright @ 2015 Atlassian Pty Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /* global $, $iq, APP, config, connection, UI, messageHandler,
  17. roomName, sessionTerminated, Strophe, Util */
  18. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  19. var Settings = require("../settings/Settings");
  20. var AuthenticationEvents
  21. = require("../../service/authentication/AuthenticationEvents");
  22. /**
  23. * Contains logic responsible for enabling/disabling functionality available
  24. * only to moderator users.
  25. */
  26. var connection = null;
  27. var focusUserJid;
  28. function createExpBackoffTimer(step) {
  29. var count = 1;
  30. return function (reset) {
  31. // Reset call
  32. if (reset) {
  33. count = 1;
  34. return;
  35. }
  36. // Calculate next timeout
  37. var timeout = Math.pow(2, count - 1);
  38. count += 1;
  39. return timeout * step;
  40. };
  41. }
  42. var getNextTimeout = createExpBackoffTimer(1000);
  43. var getNextErrorTimeout = createExpBackoffTimer(1000);
  44. // External authentication stuff
  45. var externalAuthEnabled = false;
  46. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  47. // it will be enabled automatically if focus detects the component through
  48. // service discovery.
  49. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  50. var eventEmitter = null;
  51. var Moderator = {
  52. isModerator: function () {
  53. return connection && connection.emuc.isModerator();
  54. },
  55. isPeerModerator: function (peerJid) {
  56. return connection &&
  57. connection.emuc.getMemberRole(peerJid) === 'moderator';
  58. },
  59. isExternalAuthEnabled: function () {
  60. return externalAuthEnabled;
  61. },
  62. isSipGatewayEnabled: function () {
  63. return sipGatewayEnabled;
  64. },
  65. setConnection: function (con) {
  66. connection = con;
  67. },
  68. init: function (xmpp, emitter) {
  69. this.xmppService = xmpp;
  70. eventEmitter = emitter;
  71. // Message listener that talks to POPUP window
  72. function listener(event) {
  73. if (event.data && event.data.sessionId) {
  74. if (event.origin !== window.location.origin) {
  75. console.warn(
  76. "Ignoring sessionId from different origin: " + event.origin);
  77. return;
  78. }
  79. localStorage.setItem('sessionId', event.data.sessionId);
  80. // After popup is closed we will authenticate
  81. }
  82. }
  83. // Register
  84. if (window.addEventListener) {
  85. window.addEventListener("message", listener, false);
  86. } else {
  87. window.attachEvent("onmessage", listener);
  88. }
  89. },
  90. onMucMemberLeft: function (jid) {
  91. console.info("Someone left is it focus ? " + jid);
  92. var resource = Strophe.getResourceFromJid(jid);
  93. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  94. console.info(
  95. "Focus has left the room - leaving conference");
  96. //hangUp();
  97. // We'd rather reload to have everything re-initialized
  98. // FIXME: show some message before reload
  99. location.reload();
  100. }
  101. },
  102. setFocusUserJid: function (focusJid) {
  103. if (!focusUserJid) {
  104. focusUserJid = focusJid;
  105. console.info("Focus jid set to: " + focusUserJid);
  106. }
  107. },
  108. getFocusUserJid: function () {
  109. return focusUserJid;
  110. },
  111. getFocusComponent: function () {
  112. // Get focus component address
  113. var focusComponent = config.hosts.focus;
  114. // If not specified use default: 'focus.domain'
  115. if (!focusComponent) {
  116. focusComponent = 'focus.' + config.hosts.domain;
  117. }
  118. return focusComponent;
  119. },
  120. createConferenceIq: function (roomName) {
  121. // Generate create conference IQ
  122. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  123. // Session Id used for authentication
  124. var sessionId = localStorage.getItem('sessionId');
  125. var machineUID = Settings.getSettings().uid;
  126. console.info(
  127. "Session ID: " + sessionId + " machine UID: " + machineUID);
  128. elem.c('conference', {
  129. xmlns: 'http://jitsi.org/protocol/focus',
  130. room: roomName,
  131. 'machine-uid': machineUID
  132. });
  133. if (sessionId) {
  134. elem.attrs({ 'session-id': sessionId});
  135. }
  136. if (config.hosts.bridge !== undefined) {
  137. elem.c(
  138. 'property',
  139. { name: 'bridge', value: config.hosts.bridge})
  140. .up();
  141. }
  142. // Tell the focus we have Jigasi configured
  143. if (config.hosts.call_control !== undefined) {
  144. elem.c(
  145. 'property',
  146. { name: 'call_control', value: config.hosts.call_control})
  147. .up();
  148. }
  149. if (config.channelLastN !== undefined) {
  150. elem.c(
  151. 'property',
  152. { name: 'channelLastN', value: config.channelLastN})
  153. .up();
  154. }
  155. if (config.adaptiveLastN !== undefined) {
  156. elem.c(
  157. 'property',
  158. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  159. .up();
  160. }
  161. if (config.adaptiveSimulcast !== undefined) {
  162. elem.c(
  163. 'property',
  164. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  165. .up();
  166. }
  167. if (config.openSctp !== undefined) {
  168. elem.c(
  169. 'property',
  170. { name: 'openSctp', value: config.openSctp})
  171. .up();
  172. }
  173. if(config.startAudioMuted !== undefined)
  174. {
  175. elem.c(
  176. 'property',
  177. { name: 'startAudioMuted', value: config.startAudioMuted})
  178. .up();
  179. }
  180. if(config.startVideoMuted !== undefined)
  181. {
  182. elem.c(
  183. 'property',
  184. { name: 'startVideoMuted', value: config.startVideoMuted})
  185. .up();
  186. }
  187. elem.c(
  188. 'property',
  189. { name: 'simulcastMode', value: 'rewriting'})
  190. .up();
  191. elem.up();
  192. return elem;
  193. },
  194. parseSessionId: function (resultIq) {
  195. var sessionId = $(resultIq).find('conference').attr('session-id');
  196. if (sessionId) {
  197. console.info('Received sessionId: ' + sessionId);
  198. localStorage.setItem('sessionId', sessionId);
  199. }
  200. },
  201. parseConfigOptions: function (resultIq) {
  202. Moderator.setFocusUserJid(
  203. $(resultIq).find('conference').attr('focusjid'));
  204. var authenticationEnabled
  205. = $(resultIq).find(
  206. '>conference>property' +
  207. '[name=\'authentication\'][value=\'true\']').length > 0;
  208. console.info("Authentication enabled: " + authenticationEnabled);
  209. externalAuthEnabled
  210. = $(resultIq).find(
  211. '>conference>property' +
  212. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  213. console.info('External authentication enabled: ' + externalAuthEnabled);
  214. if (!externalAuthEnabled) {
  215. // We expect to receive sessionId in 'internal' authentication mode
  216. Moderator.parseSessionId(resultIq);
  217. }
  218. var authIdentity = $(resultIq).find('>conference').attr('identity');
  219. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  220. authenticationEnabled, authIdentity);
  221. // Check if focus has auto-detected Jigasi component(this will be also
  222. // included if we have passed our host from the config)
  223. if ($(resultIq).find(
  224. '>conference>property' +
  225. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  226. sipGatewayEnabled = true;
  227. }
  228. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  229. },
  230. // FIXME: we need to show the fact that we're waiting for the focus
  231. // to the user(or that focus is not available)
  232. allocateConferenceFocus: function (roomName, callback) {
  233. // Try to use focus user JID from the config
  234. Moderator.setFocusUserJid(config.focusUserJid);
  235. // Send create conference IQ
  236. var iq = Moderator.createConferenceIq(roomName);
  237. var self = this;
  238. connection.sendIQ(
  239. iq,
  240. function (result) {
  241. // Setup config options
  242. Moderator.parseConfigOptions(result);
  243. if ('true' === $(result).find('conference').attr('ready')) {
  244. // Reset both timers
  245. getNextTimeout(true);
  246. getNextErrorTimeout(true);
  247. // Exec callback
  248. callback();
  249. } else {
  250. var waitMs = getNextTimeout();
  251. console.info("Waiting for the focus... " + waitMs);
  252. // Reset error timeout
  253. getNextErrorTimeout(true);
  254. window.setTimeout(
  255. function () {
  256. Moderator.allocateConferenceFocus(
  257. roomName, callback);
  258. }, waitMs);
  259. }
  260. },
  261. function (error) {
  262. // Invalid session ? remove and try again
  263. // without session ID to get a new one
  264. var invalidSession
  265. = $(error).find('>error>session-invalid').length;
  266. if (invalidSession) {
  267. console.info("Session expired! - removing");
  268. localStorage.removeItem("sessionId");
  269. }
  270. if ($(error).find('>error>graceful-shutdown').length) {
  271. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  272. return;
  273. }
  274. // Check for error returned by the reservation system
  275. var reservationErr = $(error).find('>error>reservation-error');
  276. if (reservationErr.length) {
  277. // Trigger error event
  278. var errorCode = reservationErr.attr('error-code');
  279. var errorMsg;
  280. if ($(error).find('>error>text')) {
  281. errorMsg = $(error).find('>error>text').text();
  282. }
  283. eventEmitter.emit(
  284. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  285. return;
  286. }
  287. // Not authorized to create new room
  288. if ($(error).find('>error>not-authorized').length) {
  289. console.warn("Unauthorized to start the conference", error);
  290. var toDomain
  291. = Strophe.getDomainFromJid(error.getAttribute('to'));
  292. if (toDomain !== config.hosts.anonymousdomain) {
  293. // FIXME: "is external" should come either from
  294. // the focus or config.js
  295. externalAuthEnabled = true;
  296. }
  297. eventEmitter.emit(
  298. XMPPEvents.AUTHENTICATION_REQUIRED,
  299. function () {
  300. Moderator.allocateConferenceFocus(
  301. roomName, callback);
  302. });
  303. return;
  304. }
  305. var waitMs = getNextErrorTimeout();
  306. console.error("Focus error, retry after " + waitMs, error);
  307. // Show message
  308. var focusComponent = Moderator.getFocusComponent();
  309. var retrySec = waitMs / 1000;
  310. // FIXME: message is duplicated ?
  311. // Do not show in case of session invalid
  312. // which means just a retry
  313. if (!invalidSession) {
  314. APP.UI.messageHandler.notify(
  315. null, "notify.focus",
  316. 'disconnected', "notify.focusFail",
  317. {component: focusComponent, ms: retrySec});
  318. }
  319. // Reset response timeout
  320. getNextTimeout(true);
  321. window.setTimeout(
  322. function () {
  323. Moderator.allocateConferenceFocus(roomName, callback);
  324. }, waitMs);
  325. }
  326. );
  327. },
  328. getLoginUrl: function (roomName, urlCallback) {
  329. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  330. iq.c('login-url', {
  331. xmlns: 'http://jitsi.org/protocol/focus',
  332. room: roomName,
  333. 'machine-uid': Settings.getSettings().uid
  334. });
  335. connection.sendIQ(
  336. iq,
  337. function (result) {
  338. var url = $(result).find('login-url').attr('url');
  339. url = url = decodeURIComponent(url);
  340. if (url) {
  341. console.info("Got auth url: " + url);
  342. urlCallback(url);
  343. } else {
  344. console.error(
  345. "Failed to get auth url from the focus", result);
  346. }
  347. },
  348. function (error) {
  349. console.error("Get auth url error", error);
  350. }
  351. );
  352. },
  353. getPopupLoginUrl: function (roomName, urlCallback) {
  354. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  355. iq.c('login-url', {
  356. xmlns: 'http://jitsi.org/protocol/focus',
  357. room: roomName,
  358. 'machine-uid': Settings.getSettings().uid,
  359. popup: true
  360. });
  361. connection.sendIQ(
  362. iq,
  363. function (result) {
  364. var url = $(result).find('login-url').attr('url');
  365. url = url = decodeURIComponent(url);
  366. if (url) {
  367. console.info("Got POPUP auth url: " + url);
  368. urlCallback(url);
  369. } else {
  370. console.error(
  371. "Failed to get POPUP auth url from the focus", result);
  372. }
  373. },
  374. function (error) {
  375. console.error('Get POPUP auth url error', error);
  376. }
  377. );
  378. },
  379. logout: function (callback) {
  380. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  381. var sessionId = localStorage.getItem('sessionId');
  382. if (!sessionId) {
  383. callback();
  384. return;
  385. }
  386. iq.c('logout', {
  387. xmlns: 'http://jitsi.org/protocol/focus',
  388. 'session-id': sessionId
  389. });
  390. connection.sendIQ(
  391. iq,
  392. function (result) {
  393. var logoutUrl = $(result).find('logout').attr('logout-url');
  394. if (logoutUrl) {
  395. logoutUrl = decodeURIComponent(logoutUrl);
  396. }
  397. console.info("Log out OK, url: " + logoutUrl, result);
  398. localStorage.removeItem('sessionId');
  399. callback(logoutUrl);
  400. },
  401. function (error) {
  402. console.error("Logout error", error);
  403. }
  404. );
  405. }
  406. };
  407. module.exports = Moderator;