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

XmppConnection.js 14KB

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