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

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