Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

XmppConnection.js 12KB

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