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 21KB

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