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.

xmpp.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. /* global $, APP, config, Strophe*/
  2. var Moderator = require("./moderator");
  3. var EventEmitter = require("events");
  4. var Recording = require("./recording");
  5. var SDP = require("./SDP");
  6. var Settings = require("../settings/Settings");
  7. var Pako = require("pako");
  8. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9. var RTCEvents = require("../../service/RTC/RTCEvents");
  10. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11. var retry = require('retry');
  12. var eventEmitter = new EventEmitter();
  13. var connection = null;
  14. var authenticatedUser = false;
  15. function connect(jid, password) {
  16. var faultTolerantConnect = retry.operation({
  17. retries: 3
  18. });
  19. // fault tolerant connect
  20. faultTolerantConnect.attempt(function () {
  21. connection = XMPP.createConnection();
  22. Moderator.setConnection(connection);
  23. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  24. if (config.useIPv6) {
  25. // https://code.google.com/p/webrtc/issues/detail?id=2828
  26. if (!connection.jingle.pc_constraints.optional)
  27. connection.jingle.pc_constraints.optional = [];
  28. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  29. }
  30. // Include user info in MUC presence
  31. var settings = Settings.getSettings();
  32. if (settings.email) {
  33. connection.emuc.addEmailToPresence(settings.email);
  34. }
  35. if (settings.uid) {
  36. connection.emuc.addUserIdToPresence(settings.uid);
  37. }
  38. if (settings.displayName) {
  39. connection.emuc.addDisplayNameToPresence(settings.displayName);
  40. }
  41. // connection.connect() starts the connection process.
  42. //
  43. // As the connection process proceeds, the user supplied callback will
  44. // be triggered multiple times with status updates. The callback should
  45. // take two arguments - the status code and the error condition.
  46. //
  47. // The status code will be one of the values in the Strophe.Status
  48. // constants. The error condition will be one of the conditions defined
  49. // in RFC 3920 or the condition ‘strophe-parsererror’.
  50. //
  51. // The Parameters wait, hold and route are optional and only relevant
  52. // for BOSH connections. Please see XEP 124 for a more detailed
  53. // explanation of the optional parameters.
  54. //
  55. // Connection status constants for use by the connection handler
  56. // callback.
  57. //
  58. // Status.ERROR - An error has occurred (websockets specific)
  59. // Status.CONNECTING - The connection is currently being made
  60. // Status.CONNFAIL - The connection attempt failed
  61. // Status.AUTHENTICATING - The connection is authenticating
  62. // Status.AUTHFAIL - The authentication attempt failed
  63. // Status.CONNECTED - The connection has succeeded
  64. // Status.DISCONNECTED - The connection has been terminated
  65. // Status.DISCONNECTING - The connection is currently being terminated
  66. // Status.ATTACHED - The connection has been attached
  67. var anonymousConnectionFailed = false;
  68. var connectionFailed = false;
  69. var lastErrorMsg;
  70. connection.connect(jid, password, function (status, msg) {
  71. console.log('Strophe status changed to',
  72. Strophe.getStatusString(status), msg);
  73. if (status === Strophe.Status.CONNECTED) {
  74. if (config.useStunTurn) {
  75. connection.jingle.getStunAndTurnCredentials();
  76. }
  77. console.info("My Jabber ID: " + connection.jid);
  78. connection.ping.startInterval(config.hosts.domain);
  79. if (password)
  80. authenticatedUser = true;
  81. maybeDoJoin();
  82. } else if (status === Strophe.Status.CONNFAIL) {
  83. if (msg === 'x-strophe-bad-non-anon-jid') {
  84. anonymousConnectionFailed = true;
  85. } else {
  86. connectionFailed = true;
  87. }
  88. lastErrorMsg = msg;
  89. } else if (status === Strophe.Status.DISCONNECTED) {
  90. // Stop ping interval
  91. connection.ping.stopInterval();
  92. if (anonymousConnectionFailed) {
  93. // prompt user for username and password
  94. XMPP.promptLogin();
  95. } else {
  96. // Strophe already has built-in HTTP/BOSH error handling and
  97. // request retry logic. Requests are resent automatically
  98. // until their error count reaches 5. Strophe.js disconnects
  99. // if the error count is > 5. We are not replicating this
  100. // here.
  101. //
  102. // The "problem" is that failed HTTP/BOSH requests don't
  103. // trigger a callback with a status update, so when a
  104. // callback with status Strophe.Status.DISCONNECTED arrives,
  105. // we can't be sure if it's a graceful disconnect or if it's
  106. // triggered by some HTTP/BOSH error.
  107. //
  108. // But that's a minor issue in Jitsi Meet as we never
  109. // disconnect anyway, not even when the user closes the
  110. // browser window (which is kind of wrong, but the point is
  111. // that we should never ever get disconnected).
  112. //
  113. // On the other hand, failed connections due to XMPP layer
  114. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  115. //
  116. // Here we implement retry logic for failed connections due
  117. // to XMPP layer errors and we display an error to the user
  118. // if we get disconnected from the XMPP server permanently.
  119. // If the connection failed, retry.
  120. if (connectionFailed &&
  121. faultTolerantConnect.retry("connection-failed")) {
  122. return;
  123. }
  124. // If we failed to connect to the XMPP server, fire an event
  125. // to let all the interested module now about it.
  126. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  127. msg ? msg : lastErrorMsg);
  128. }
  129. } else if (status === Strophe.Status.AUTHFAIL) {
  130. // wrong password or username, prompt user
  131. XMPP.promptLogin();
  132. }
  133. });
  134. });
  135. }
  136. function maybeDoJoin() {
  137. if (connection && connection.connected &&
  138. Strophe.getResourceFromJid(connection.jid) &&
  139. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  140. // .connected is true while connecting?
  141. doJoin();
  142. }
  143. }
  144. function doJoin() {
  145. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  146. }
  147. function initStrophePlugins()
  148. {
  149. require("./strophe.emuc")(XMPP, eventEmitter);
  150. require("./strophe.jingle")(XMPP, eventEmitter);
  151. require("./strophe.moderate")(XMPP, eventEmitter);
  152. require("./strophe.util")();
  153. require("./strophe.ping")(XMPP, eventEmitter);
  154. require("./strophe.rayo")();
  155. require("./strophe.logger")();
  156. }
  157. /**
  158. * If given <tt>localStream</tt> is video one this method will advertise it's
  159. * video type in MUC presence.
  160. * @param localStream new or modified <tt>LocalStream</tt>.
  161. */
  162. function broadcastLocalVideoType(localStream) {
  163. if (localStream.videoType)
  164. XMPP.addToPresence('videoType', localStream.videoType);
  165. }
  166. function registerListeners() {
  167. APP.RTC.addStreamListener(
  168. function (localStream) {
  169. maybeDoJoin();
  170. broadcastLocalVideoType(localStream);
  171. },
  172. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  173. );
  174. APP.RTC.addStreamListener(
  175. broadcastLocalVideoType,
  176. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  177. );
  178. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  179. XMPP.addToPresence("devices", devices);
  180. });
  181. }
  182. var unload = (function () {
  183. var unloaded = false;
  184. return function () {
  185. if (unloaded) { return; }
  186. unloaded = true;
  187. if (connection && connection.connected) {
  188. // ensure signout
  189. $.ajax({
  190. type: 'POST',
  191. url: config.bosh,
  192. async: false,
  193. cache: false,
  194. contentType: 'application/xml',
  195. data: "<body rid='" +
  196. (connection.rid || connection._proto.rid) +
  197. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  198. (connection.sid || connection._proto.sid) +
  199. "' type='terminate'>" +
  200. "<presence xmlns='jabber:client' type='unavailable'/>" +
  201. "</body>",
  202. success: function (data) {
  203. console.log('signed out');
  204. console.log(data);
  205. },
  206. error: function (XMLHttpRequest, textStatus, errorThrown) {
  207. console.log('signout error',
  208. textStatus + ' (' + errorThrown + ')');
  209. }
  210. });
  211. }
  212. XMPP.disposeConference(true);
  213. };
  214. })();
  215. function setupEvents() {
  216. // In recent versions of FF the 'beforeunload' event is not fired when the
  217. // window or the tab is closed. It is only fired when we leave the page
  218. // (change URL). If this participant doesn't unload properly, then it
  219. // becomes a ghost for the rest of the participants that stay in the
  220. // conference. Thankfully handling the 'unload' event in addition to the
  221. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  222. // method at least once.
  223. //
  224. // The 'unload' method can safely be run multiple times, it will actually do
  225. // something only the first time that it's run, so we're don't have to worry
  226. // about browsers that fire both events.
  227. $(window).bind('beforeunload', unload);
  228. $(window).bind('unload', unload);
  229. }
  230. var XMPP = {
  231. getConnection: function(){ return connection; },
  232. sessionTerminated: false,
  233. /**
  234. * XMPP connection status
  235. */
  236. Status: Strophe.Status,
  237. /**
  238. * Remembers if we were muted by the focus.
  239. * @type {boolean}
  240. */
  241. forceMuted: false,
  242. start: function () {
  243. setupEvents();
  244. initStrophePlugins();
  245. registerListeners();
  246. Moderator.init(this, eventEmitter);
  247. Recording.init();
  248. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  249. // Force authenticated domain if room is appended with '?login=true'
  250. if (config.hosts.anonymousdomain &&
  251. window.location.search.indexOf("login=true") !== -1) {
  252. configDomain = config.hosts.domain;
  253. }
  254. var jid = configDomain || window.location.hostname;
  255. connect(jid, null);
  256. },
  257. createConnection: function () {
  258. var bosh = config.bosh || '/http-bind';
  259. return new Strophe.Connection(bosh);
  260. },
  261. getStatusString: function (status) {
  262. return Strophe.getStatusString(status);
  263. },
  264. promptLogin: function () {
  265. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  266. },
  267. joinRoom: function(roomName, useNicks, nick) {
  268. var roomjid = roomName;
  269. if (useNicks) {
  270. if (nick) {
  271. roomjid += '/' + nick;
  272. } else {
  273. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  274. }
  275. } else {
  276. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  277. if(!authenticatedUser)
  278. tmpJid = tmpJid.substr(0, 8);
  279. roomjid += '/' + tmpJid;
  280. }
  281. connection.emuc.doJoin(roomjid);
  282. },
  283. myJid: function () {
  284. if(!connection)
  285. return null;
  286. return connection.emuc.myroomjid;
  287. },
  288. myResource: function () {
  289. if(!connection || ! connection.emuc.myroomjid)
  290. return null;
  291. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  292. },
  293. disposeConference: function (onUnload) {
  294. var handler = connection.jingle.activecall;
  295. if (handler && handler.peerconnection) {
  296. // FIXME: probably removing streams is not required and close() should
  297. // be enough
  298. if (APP.RTC.localAudio) {
  299. handler.peerconnection.removeStream(
  300. APP.RTC.localAudio.getOriginalStream(), onUnload);
  301. }
  302. if (APP.RTC.localVideo) {
  303. handler.peerconnection.removeStream(
  304. APP.RTC.localVideo.getOriginalStream(), onUnload);
  305. }
  306. handler.peerconnection.close();
  307. }
  308. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  309. connection.jingle.activecall = null;
  310. if (!onUnload) {
  311. this.sessionTerminated = true;
  312. connection.emuc.doLeave();
  313. }
  314. },
  315. addListener: function(type, listener) {
  316. eventEmitter.on(type, listener);
  317. },
  318. removeListener: function (type, listener) {
  319. eventEmitter.removeListener(type, listener);
  320. },
  321. allocateConferenceFocus: function(roomName, callback) {
  322. Moderator.allocateConferenceFocus(roomName, callback);
  323. },
  324. getLoginUrl: function (roomName, callback) {
  325. Moderator.getLoginUrl(roomName, callback);
  326. },
  327. getPopupLoginUrl: function (roomName, callback) {
  328. Moderator.getPopupLoginUrl(roomName, callback);
  329. },
  330. isModerator: function () {
  331. return Moderator.isModerator();
  332. },
  333. isSipGatewayEnabled: function () {
  334. return Moderator.isSipGatewayEnabled();
  335. },
  336. isExternalAuthEnabled: function () {
  337. return Moderator.isExternalAuthEnabled();
  338. },
  339. isConferenceInProgress: function () {
  340. return connection && connection.jingle.activecall &&
  341. connection.jingle.activecall.peerconnection;
  342. },
  343. switchStreams: function (stream, oldStream, callback, isAudio) {
  344. if (this.isConferenceInProgress()) {
  345. // FIXME: will block switchInProgress on true value in case of exception
  346. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  347. } else {
  348. // We are done immediately
  349. console.warn("No conference handler or conference not started yet");
  350. callback();
  351. }
  352. },
  353. sendVideoInfoPresence: function (mute) {
  354. if(!connection)
  355. return;
  356. connection.emuc.addVideoInfoToPresence(mute);
  357. connection.emuc.sendPresence();
  358. },
  359. setVideoMute: function (mute, callback, options) {
  360. if(!connection)
  361. return;
  362. var self = this;
  363. var localCallback = function (mute) {
  364. self.sendVideoInfoPresence(mute);
  365. return callback(mute);
  366. };
  367. if(connection.jingle.activecall)
  368. {
  369. connection.jingle.activecall.setVideoMute(
  370. mute, localCallback, options);
  371. }
  372. else {
  373. localCallback(mute);
  374. }
  375. },
  376. setAudioMute: function (mute, callback) {
  377. if (!(connection && APP.RTC.localAudio)) {
  378. return false;
  379. }
  380. if (this.forceMuted && !mute) {
  381. console.info("Asking focus for unmute");
  382. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  383. // FIXME: wait for result before resetting muted status
  384. this.forceMuted = false;
  385. }
  386. if (mute == APP.RTC.localAudio.isMuted()) {
  387. // Nothing to do
  388. return true;
  389. }
  390. APP.RTC.localAudio.setMute(mute);
  391. this.sendAudioInfoPresence(mute, callback);
  392. return true;
  393. },
  394. sendAudioInfoPresence: function(mute, callback) {
  395. if(connection) {
  396. connection.emuc.addAudioInfoToPresence(mute);
  397. connection.emuc.sendPresence();
  398. }
  399. callback();
  400. return true;
  401. },
  402. toggleRecording: function (tokenEmptyCallback,
  403. recordingStateChangeCallback) {
  404. Recording.toggleRecording(tokenEmptyCallback,
  405. recordingStateChangeCallback, connection);
  406. },
  407. addToPresence: function (name, value, dontSend) {
  408. switch (name) {
  409. case "displayName":
  410. connection.emuc.addDisplayNameToPresence(value);
  411. break;
  412. case "prezi":
  413. connection.emuc.addPreziToPresence(value, 0);
  414. break;
  415. case "preziSlide":
  416. connection.emuc.addCurrentSlideToPresence(value);
  417. break;
  418. case "connectionQuality":
  419. connection.emuc.addConnectionInfoToPresence(value);
  420. break;
  421. case "email":
  422. connection.emuc.addEmailToPresence(value);
  423. break;
  424. case "devices":
  425. connection.emuc.addDevicesToPresence(value);
  426. break;
  427. case "videoType":
  428. connection.emuc.addVideoTypeToPresence(value);
  429. break;
  430. case "startMuted":
  431. if(!Moderator.isModerator())
  432. return;
  433. connection.emuc.addStartMutedToPresence(value[0],
  434. value[1]);
  435. break;
  436. default :
  437. console.log("Unknown tag for presence: " + name);
  438. return;
  439. }
  440. if (!dontSend)
  441. connection.emuc.sendPresence();
  442. },
  443. /**
  444. * Sends 'data' as a log message to the focus. Returns true iff a message
  445. * was sent.
  446. * @param data
  447. * @returns {boolean} true iff a message was sent.
  448. */
  449. sendLogs: function (data) {
  450. if(!connection.emuc.focusMucJid)
  451. return false;
  452. var deflate = true;
  453. var content = JSON.stringify(data);
  454. if (deflate) {
  455. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  456. }
  457. content = Base64.encode(content);
  458. // XEP-0337-ish
  459. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  460. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  461. id: 'PeerConnectionStats'});
  462. message.c('message').t(content).up();
  463. if (deflate) {
  464. message.c('tag', {name: "deflated", value: "true"}).up();
  465. }
  466. message.up();
  467. connection.send(message);
  468. return true;
  469. },
  470. // Gets the logs from strophe.jingle.
  471. getJingleLog: function () {
  472. return connection.jingle ? connection.jingle.getLog() : {};
  473. },
  474. // Gets the logs from strophe.
  475. getXmppLog: function () {
  476. return connection.logger ? connection.logger.log : null;
  477. },
  478. getPrezi: function () {
  479. return connection.emuc.getPrezi(this.myJid());
  480. },
  481. removePreziFromPresence: function () {
  482. connection.emuc.removePreziFromPresence();
  483. connection.emuc.sendPresence();
  484. },
  485. sendChatMessage: function (message, nickname) {
  486. connection.emuc.sendMessage(message, nickname);
  487. },
  488. setSubject: function (topic) {
  489. connection.emuc.setSubject(topic);
  490. },
  491. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  492. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  493. },
  494. dial: function (to, from, roomName,roomPass) {
  495. connection.rayo.dial(to, from, roomName,roomPass);
  496. },
  497. setMute: function (jid, mute) {
  498. connection.moderate.setMute(jid, mute);
  499. },
  500. eject: function (jid) {
  501. connection.moderate.eject(jid);
  502. },
  503. logout: function (callback) {
  504. Moderator.logout(callback);
  505. },
  506. findJidFromResource: function (resource) {
  507. return connection.emuc.findJidFromResource(resource);
  508. },
  509. getMembers: function () {
  510. return connection.emuc.members;
  511. },
  512. getJidFromSSRC: function (ssrc) {
  513. if (!this.isConferenceInProgress())
  514. return null;
  515. return connection.jingle.activecall.getSsrcOwner(ssrc);
  516. },
  517. // Returns true iff we have joined the MUC.
  518. isMUCJoined: function () {
  519. return connection.emuc.joined;
  520. },
  521. getSessions: function () {
  522. return connection.jingle.sessions;
  523. },
  524. removeStream: function (stream) {
  525. if (!this.isConferenceInProgress())
  526. return;
  527. connection.jingle.activecall.peerconnection.removeStream(stream);
  528. }
  529. };
  530. module.exports = XMPP;