您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

XmppConnection.js 14KB

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