Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

moderator.js 15KB

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