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.

XmppConnection.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. import { getLogger } from 'jitsi-meet-logger';
  2. import { $pres, Strophe } from 'strophe.js';
  3. import 'strophejs-plugin-stream-management';
  4. import Listenable from '../util/Listenable';
  5. import LastSuccessTracker from './StropheBoshLastSuccess';
  6. const logger = getLogger(__filename);
  7. /**
  8. * The lib-jitsi-meet layer for {@link Strophe.Connection}.
  9. */
  10. export default class XmppConnection extends Listenable {
  11. /**
  12. * The list of {@link XmppConnection} events.
  13. *
  14. * @returns {Object}
  15. */
  16. static get Events() {
  17. return {
  18. CONN_STATUS_CHANGED: 'CONN_STATUS_CHANGED'
  19. };
  20. }
  21. /**
  22. * The list of Xmpp connection statuses.
  23. *
  24. * @returns {Strophe.Status}
  25. */
  26. static get Status() {
  27. return Strophe.Status;
  28. }
  29. /**
  30. * Initializes new connection instance.
  31. *
  32. * @param {Object} options
  33. * @param {String} options.serviceUrl - The BOSH or WebSocket service URL.
  34. * @param {String} [options.enableWebsocketResume=true] - True/false to control the stream resumption functionality.
  35. * It will enable automatically by default if supported by the XMPP server.
  36. * @param {Number} [options.websocketKeepAlive=240000] - The websocket keep alive interval. It's 4 minutes by
  37. * default with jitter. Pass -1 to disable. The actual interval equation is:
  38. * jitterDelay = (interval * 0.2) + (0.8 * interval * Math.random())
  39. * The keep alive is HTTP GET request to the {@link options.serviceUrl}.
  40. */
  41. constructor({ enableWebsocketResume, websocketKeepAlive, serviceUrl }) {
  42. super();
  43. this._options = {
  44. enableWebsocketResume: typeof enableWebsocketResume === 'undefined' ? true : enableWebsocketResume,
  45. websocketKeepAlive: typeof websocketKeepAlive === 'undefined' ? 4 * 60 * 1000 : Number(websocketKeepAlive)
  46. };
  47. this._stropheConn = new Strophe.Connection(serviceUrl);
  48. this._usesWebsocket = serviceUrl.startsWith('ws:') || serviceUrl.startsWith('wss:');
  49. // The default maxRetries is 5, which is too long.
  50. this._stropheConn.maxRetries = 3;
  51. if (!this._usesWebsocket) {
  52. this._lastSuccessTracker = new LastSuccessTracker();
  53. this._lastSuccessTracker.startTracking(this._stropheConn);
  54. }
  55. }
  56. /**
  57. * A getter for the connected state.
  58. *
  59. * @returns {boolean}
  60. */
  61. get connected() {
  62. return this._status === Strophe.Status.CONNECTED;
  63. }
  64. /**
  65. * Retrieves the feature discovery plugin instance.
  66. *
  67. * @returns {Strophe.Connection.disco}
  68. */
  69. get disco() {
  70. return this._stropheConn.disco;
  71. }
  72. /**
  73. * A getter for the disconnecting state.
  74. *
  75. * @returns {boolean}
  76. */
  77. get disconnecting() {
  78. return this._stropheConn.disconnecting === true;
  79. }
  80. /**
  81. * A getter for the domain.
  82. *
  83. * @returns {string|null}
  84. */
  85. get domain() {
  86. return this._stropheConn.domain;
  87. }
  88. /**
  89. * Tells if Websocket is used as the transport for the current XMPP connection. Returns true for Websocket or false
  90. * for BOSH.
  91. * @returns {boolean}
  92. */
  93. get isUsingWebSocket() {
  94. return this._usesWebsocket;
  95. }
  96. /**
  97. * A getter for the JID.
  98. *
  99. * @returns {string|null}
  100. */
  101. get jid() {
  102. return this._stropheConn.jid;
  103. }
  104. /**
  105. * Returns headers for the last BOSH response received.
  106. *
  107. * @returns {string}
  108. */
  109. get lastResponseHeaders() {
  110. return this._stropheConn._proto && this._stropheConn._proto.lastResponseHeaders;
  111. }
  112. /**
  113. * A getter for the logger plugin instance.
  114. *
  115. * @returns {*}
  116. */
  117. get logger() {
  118. return this._stropheConn.logger;
  119. }
  120. /**
  121. * A getter for the connection options.
  122. *
  123. * @returns {*}
  124. */
  125. get options() {
  126. return this._stropheConn.options;
  127. }
  128. /**
  129. * A getter for the service URL.
  130. *
  131. * @returns {string}
  132. */
  133. get service() {
  134. return this._stropheConn.service;
  135. }
  136. /**
  137. * Returns the current connection status.
  138. *
  139. * @returns {Strophe.Status}
  140. */
  141. get status() {
  142. return this._status;
  143. }
  144. /**
  145. * Adds a connection plugin to this instance.
  146. *
  147. * @param {string} name - The name of the plugin or rather a key under which it will be stored on this connection
  148. * instance.
  149. * @param {ConnectionPluginListenable} plugin - The plugin to add.
  150. */
  151. addConnectionPlugin(name, plugin) {
  152. this[name] = plugin;
  153. plugin.init(this);
  154. }
  155. /**
  156. * See {@link Strophe.Connection.addHandler}
  157. *
  158. * @returns {void}
  159. */
  160. addHandler(...args) {
  161. this._stropheConn.addHandler(...args);
  162. }
  163. /**
  164. * See {@link Strophe.Connection.attach}.
  165. *
  166. * @returns {void}
  167. */
  168. attach(...args) {
  169. this._stropheConn.attach(...args);
  170. }
  171. /**
  172. * Wraps Strophe.Connection.connect method in order to intercept the connection status updates.
  173. * See {@link Strophe.Connection.connect} for the params description.
  174. *
  175. * @returns {void}
  176. */
  177. connect(jid, pass, callback, ...args) {
  178. const connectCb = (status, condition) => {
  179. this._status = status;
  180. let blockCallback = false;
  181. if (status === Strophe.Status.CONNECTED) {
  182. this._maybeEnableStreamResume();
  183. this._maybeStartWSKeepAlive();
  184. } else if (status === Strophe.Status.DISCONNECTED) {
  185. // FIXME add RECONNECTING state instead of blocking the DISCONNECTED update
  186. blockCallback = this._tryResumingConnection();
  187. if (!blockCallback) {
  188. clearTimeout(this._wsKeepAlive);
  189. }
  190. }
  191. if (!blockCallback) {
  192. callback(status, condition);
  193. this.eventEmitter.emit(XmppConnection.Events.CONN_STATUS_CHANGED, status);
  194. }
  195. };
  196. this._stropheConn.connect(jid, pass, connectCb, ...args);
  197. }
  198. /**
  199. * The method is meant to be used for testing. It's a shortcut for closing the WebSocket.
  200. *
  201. * @returns {void}
  202. */
  203. closeWebsocket() {
  204. this._stropheConn._proto && this._stropheConn._proto.socket && this._stropheConn._proto.socket.close();
  205. }
  206. /**
  207. * See {@link Strophe.Connection.disconnect}.
  208. *
  209. * @returns {void}
  210. */
  211. disconnect(...args) {
  212. clearTimeout(this._resumeTimeout);
  213. clearTimeout(this._wsKeepAlive);
  214. this._stropheConn.disconnect(...args);
  215. }
  216. /**
  217. * See {@link Strophe.Connection.flush}.
  218. *
  219. * @returns {void}
  220. */
  221. flush(...args) {
  222. this._stropheConn.flush(...args);
  223. }
  224. /**
  225. * See {@link LastRequestTracker.getTimeSinceLastSuccess}.
  226. *
  227. * @returns {number|null}
  228. */
  229. getTimeSinceLastBOSHSuccess() {
  230. return this._lastSuccessTracker
  231. ? this._lastSuccessTracker.getTimeSinceLastSuccess()
  232. : null;
  233. }
  234. /**
  235. * Requests a resume token from the server if enabled and all requirements are met.
  236. *
  237. * @private
  238. */
  239. _maybeEnableStreamResume() {
  240. if (!this._options.enableWebsocketResume) {
  241. return;
  242. }
  243. const { streamManagement } = this._stropheConn;
  244. if (!this.isUsingWebSocket) {
  245. logger.warn('Stream resume enabled, but WebSockets are not enabled');
  246. } else if (!streamManagement) {
  247. logger.warn('Stream resume enabled, but Strophe streamManagement plugin is not installed');
  248. } else if (!streamManagement.isSupported()) {
  249. logger.warn('Stream resume enabled, but XEP-0198 is not supported by the server');
  250. } else if (!streamManagement.getResumeToken()) {
  251. logger.info('Enabling XEP-0198 stream management');
  252. streamManagement.enable(/* resume */ true);
  253. }
  254. }
  255. /**
  256. * Starts the Websocket keep alive if enabled.
  257. *
  258. * @private
  259. * @returns {void}
  260. */
  261. _maybeStartWSKeepAlive() {
  262. const { websocketKeepAlive } = this._options;
  263. if (this._usesWebsocket && websocketKeepAlive > 0) {
  264. this._wsKeepAlive || logger.info(`WebSocket keep alive interval: ${websocketKeepAlive}ms`);
  265. clearTimeout(this._wsKeepAlive);
  266. const intervalWithJitter
  267. = /* base */ (websocketKeepAlive * 0.2) + /* jitter */ (Math.random() * 0.8 * websocketKeepAlive);
  268. logger.debug(`Scheduling next WebSocket keep-alive in ${intervalWithJitter}ms`);
  269. this._wsKeepAlive = setTimeout(() => {
  270. const url = this.service.replace('wss', 'https').replace('ws', 'http');
  271. fetch(url).catch(
  272. error => {
  273. logger.error(`Websocket Keep alive failed for url: ${url}`, { error });
  274. })
  275. .then(() => this._maybeStartWSKeepAlive());
  276. }, intervalWithJitter);
  277. }
  278. }
  279. /**
  280. * Send a stanza. This function is called to push data onto the send queue to go out over the wire.
  281. *
  282. * @param {Element|Strophe.Builder} stanza - The stanza to send.
  283. * @returns {void}
  284. */
  285. send(stanza) {
  286. if (!this.connected) {
  287. throw new Error('Not connected');
  288. }
  289. this._stropheConn.send(stanza);
  290. }
  291. /**
  292. * Helper function to send IQ stanzas.
  293. *
  294. * @param {Element} elem - The stanza to send.
  295. * @param {Function} callback - The callback function for a successful request.
  296. * @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
  297. * be null.
  298. * @param {number} timeout - The time specified in milliseconds for a timeout to occur.
  299. * @returns {number} - The id used to send the IQ.
  300. */
  301. sendIQ(elem, callback, errback, timeout) {
  302. if (!this.connected) {
  303. errback('Not connected');
  304. return;
  305. }
  306. return this._stropheConn.sendIQ(elem, callback, errback, timeout);
  307. }
  308. /**
  309. * Helper function to send presence stanzas. The main benefit is for sending presence stanzas for which you expect
  310. * a responding presence stanza with the same id (for example when leaving a chat room).
  311. *
  312. * @param {Element} elem - The stanza to send.
  313. * @param {Function} callback - The callback function for a successful request.
  314. * @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
  315. * be null.
  316. * @param {number} timeout - The time specified in milliseconds for a timeout to occur.
  317. * @returns {number} - The id used to send the presence.
  318. */
  319. sendPresence(elem, callback, errback, timeout) {
  320. if (!this.connected) {
  321. errback('Not connected');
  322. return;
  323. }
  324. this._stropheConn.sendPresence(elem, callback, errback, timeout);
  325. }
  326. /**
  327. * FIXME.
  328. *
  329. * @returns {void}
  330. */
  331. sendUnavailableBeacon() {
  332. this._stropheConn._changeConnectStatus(Strophe.Status.DISCONNECTING);
  333. this._stropheConn.disconnecting = true;
  334. const body = this._stropheConn._proto._buildBody()
  335. .attrs({
  336. type: 'terminate'
  337. });
  338. const pres = $pres({
  339. xmlns: Strophe.NS.CLIENT,
  340. type: 'unavailable'
  341. });
  342. body.cnode(pres.tree());
  343. const res = navigator.sendBeacon(
  344. `https:${this.service}`,
  345. Strophe.serialize(body.tree()));
  346. logger.info(`Successfully send unavailable beacon ${res}`);
  347. this._stropheConn._proto._abortAllRequests();
  348. this._stropheConn._doDisconnect();
  349. }
  350. /**
  351. * Tries to use stream management plugin to resume dropped XMPP connection. The streamManagement plugin clears
  352. * the resume token if any connection error occurs which would put it in unrecoverable state, so as long as
  353. * the token is present it means the connection can be resumed.
  354. *
  355. * @private
  356. * @returns {boolean}
  357. */
  358. _tryResumingConnection() {
  359. const { streamManagement } = this._stropheConn;
  360. const resumeToken = streamManagement && streamManagement.getResumeToken();
  361. if (resumeToken) {
  362. clearTimeout(this._resumeTimeout);
  363. this._resumeTimeout = setTimeout(() => {
  364. logger.info('Trying to resume the XMPP connection');
  365. const url = new URL(this._stropheConn.service);
  366. url.searchParams.set('previd', resumeToken);
  367. // FIXME remove XmppConnection 'service' setter
  368. this._stropheConn.service = url.toString();
  369. streamManagement.resume();
  370. }, 3000 /* FIXME calculate delay with jitter */);
  371. return true;
  372. }
  373. return false;
  374. }
  375. }