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

XmppConnection.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. /**
  171. * See {@link Strophe.Connection.attach}.
  172. *
  173. * @returns {void}
  174. */
  175. attach(...args) {
  176. this._stropheConn.attach(...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. const connectCb = (status, ...cbArgs) => {
  186. this._status = status;
  187. let blockCallback = false;
  188. if (status === Strophe.Status.CONNECTED) {
  189. this._maybeEnableStreamResume();
  190. this._maybeStartWSKeepAlive();
  191. this._resumeRetryN = 0;
  192. } else if (status === Strophe.Status.DISCONNECTED) {
  193. // FIXME add RECONNECTING state instead of blocking the DISCONNECTED update
  194. blockCallback = this._tryResumingConnection();
  195. if (!blockCallback) {
  196. clearTimeout(this._wsKeepAlive);
  197. }
  198. }
  199. if (!blockCallback) {
  200. callback(status, ...cbArgs);
  201. this.eventEmitter.emit(XmppConnection.Events.CONN_STATUS_CHANGED, status);
  202. }
  203. };
  204. this._stropheConn.connect(jid, pass, connectCb, ...args);
  205. }
  206. /**
  207. * The method is meant to be used for testing. It's a shortcut for closing the WebSocket.
  208. *
  209. * @returns {void}
  210. */
  211. closeWebsocket() {
  212. this._stropheConn._proto && this._stropheConn._proto.socket && this._stropheConn._proto.socket.close();
  213. }
  214. /**
  215. * See {@link Strophe.Connection.disconnect}.
  216. *
  217. * @returns {void}
  218. */
  219. disconnect(...args) {
  220. clearTimeout(this._resumeTimeout);
  221. clearTimeout(this._wsKeepAlive);
  222. this._stropheConn.disconnect(...args);
  223. }
  224. /**
  225. * See {@link Strophe.Connection.flush}.
  226. *
  227. * @returns {void}
  228. */
  229. flush(...args) {
  230. this._stropheConn.flush(...args);
  231. }
  232. /**
  233. * See {@link LastRequestTracker.getTimeSinceLastSuccess}.
  234. *
  235. * @returns {number|null}
  236. */
  237. getTimeSinceLastBOSHSuccess() {
  238. return this._lastSuccessTracker
  239. ? this._lastSuccessTracker.getTimeSinceLastSuccess()
  240. : null;
  241. }
  242. /**
  243. * Requests a resume token from the server if enabled and all requirements are met.
  244. *
  245. * @private
  246. */
  247. _maybeEnableStreamResume() {
  248. if (!this._options.enableWebsocketResume) {
  249. return;
  250. }
  251. const { streamManagement } = this._stropheConn;
  252. if (!this.isUsingWebSocket) {
  253. logger.warn('Stream resume enabled, but WebSockets are not enabled');
  254. } else if (!streamManagement) {
  255. logger.warn('Stream resume enabled, but Strophe streamManagement plugin is not installed');
  256. } else if (!streamManagement.isSupported()) {
  257. logger.warn('Stream resume enabled, but XEP-0198 is not supported by the server');
  258. } else if (!streamManagement.getResumeToken()) {
  259. logger.info('Enabling XEP-0198 stream management');
  260. streamManagement.enable(/* resume */ true);
  261. }
  262. }
  263. /**
  264. * Starts the Websocket keep alive if enabled.
  265. *
  266. * @private
  267. * @returns {void}
  268. */
  269. _maybeStartWSKeepAlive() {
  270. const { websocketKeepAlive } = this._options;
  271. if (this._usesWebsocket && websocketKeepAlive > 0) {
  272. this._wsKeepAlive || logger.info(`WebSocket keep alive interval: ${websocketKeepAlive}ms`);
  273. clearTimeout(this._wsKeepAlive);
  274. const intervalWithJitter
  275. = /* base */ (websocketKeepAlive * 0.2) + /* jitter */ (Math.random() * 0.8 * websocketKeepAlive);
  276. logger.debug(`Scheduling next WebSocket keep-alive in ${intervalWithJitter}ms`);
  277. this._wsKeepAlive = setTimeout(() => {
  278. const url = this.service.replace('wss', 'https').replace('ws', 'http');
  279. fetch(url).catch(
  280. error => {
  281. logger.error(`Websocket Keep alive failed for url: ${url}`, { error });
  282. })
  283. .then(() => this._maybeStartWSKeepAlive());
  284. }, intervalWithJitter);
  285. }
  286. }
  287. /**
  288. * Send a stanza. This function is called to push data onto the send queue to go out over the wire.
  289. *
  290. * @param {Element|Strophe.Builder} stanza - The stanza to send.
  291. * @returns {void}
  292. */
  293. send(stanza) {
  294. if (!this.connected) {
  295. throw new Error('Not connected');
  296. }
  297. this._stropheConn.send(stanza);
  298. }
  299. /**
  300. * Helper function to send IQ stanzas.
  301. *
  302. * @param {Element} elem - The stanza to send.
  303. * @param {Function} callback - The callback function for a successful request.
  304. * @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
  305. * be null.
  306. * @param {number} timeout - The time specified in milliseconds for a timeout to occur.
  307. * @returns {number} - The id used to send the IQ.
  308. */
  309. sendIQ(elem, callback, errback, timeout) {
  310. if (!this.connected) {
  311. errback('Not connected');
  312. return;
  313. }
  314. return this._stropheConn.sendIQ(elem, callback, errback, timeout);
  315. }
  316. /**
  317. * Helper function to send presence stanzas. The main benefit is for sending presence stanzas for which you expect
  318. * a responding presence stanza with the same id (for example when leaving a chat room).
  319. *
  320. * @param {Element} elem - The stanza to send.
  321. * @param {Function} callback - The callback function for a successful request.
  322. * @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
  323. * be null.
  324. * @param {number} timeout - The time specified in milliseconds for a timeout to occur.
  325. * @returns {number} - The id used to send the presence.
  326. */
  327. sendPresence(elem, callback, errback, timeout) {
  328. if (!this.connected) {
  329. errback('Not connected');
  330. return;
  331. }
  332. this._stropheConn.sendPresence(elem, callback, errback, timeout);
  333. }
  334. /**
  335. * The method gracefully closes the BOSH connection by using 'navigator.sendBeacon'.
  336. *
  337. * @returns {boolean} - true if the beacon was sent.
  338. */
  339. sendUnavailableBeacon() {
  340. if (!navigator.sendBeacon || this.connection.disconnecting || !this.connection.connected) {
  341. return false;
  342. }
  343. this._stropheConn._changeConnectStatus(Strophe.Status.DISCONNECTING);
  344. this._stropheConn.disconnecting = true;
  345. const body = this._stropheConn._proto._buildBody()
  346. .attrs({
  347. type: 'terminate'
  348. });
  349. const pres = $pres({
  350. xmlns: Strophe.NS.CLIENT,
  351. type: 'unavailable'
  352. });
  353. body.cnode(pres.tree());
  354. const res = navigator.sendBeacon(
  355. `https:${this.service}`,
  356. Strophe.serialize(body.tree()));
  357. logger.info(`Successfully send unavailable beacon ${res}`);
  358. this._stropheConn._proto._abortAllRequests();
  359. this._stropheConn._doDisconnect();
  360. return true;
  361. }
  362. /**
  363. * Tries to use stream management plugin to resume dropped XMPP connection. The streamManagement plugin clears
  364. * the resume token if any connection error occurs which would put it in unrecoverable state, so as long as
  365. * the token is present it means the connection can be resumed.
  366. *
  367. * @private
  368. * @returns {boolean}
  369. */
  370. _tryResumingConnection() {
  371. const { streamManagement } = this._stropheConn;
  372. const resumeToken = streamManagement && streamManagement.getResumeToken();
  373. if (resumeToken) {
  374. clearTimeout(this._resumeTimeout);
  375. // FIXME detect internet offline
  376. // The retry delay will be:
  377. // 1st retry: 1.5s - 3s
  378. // 2nd retry: 3s - 9s
  379. // 3rd retry: 3s - 27s
  380. this._resumeRetryN = Math.min(3, this._resumeRetryN + 1);
  381. const retryTimeout = getJitterDelay(this._resumeRetryN, 1500, 3);
  382. logger.info(`Will try to resume the XMPP connection in ${retryTimeout}ms`);
  383. this._resumeTimeout = setTimeout(() => {
  384. logger.info('Trying to resume the XMPP connection');
  385. const url = new URL(this._stropheConn.service);
  386. url.searchParams.set('previd', resumeToken);
  387. this._stropheConn.service = url.toString();
  388. streamManagement.resume();
  389. }, retryTimeout);
  390. return true;
  391. }
  392. return false;
  393. }
  394. }