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.

StropheLastSuccess.ts 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * Attaches to the {@link Strophe.Connection.rawInput} which is called whenever any data is received from the server.
  3. */
  4. import { Strophe } from 'strophe.js';
  5. import XmppConnection from './XmppConnection';
  6. export default class LastRequestTracker {
  7. private _lastSuccess: number | null;
  8. private _lastFailedMessage: string | null;
  9. /**
  10. * Initializes new instance.
  11. */
  12. constructor() {
  13. this._lastSuccess = null;
  14. this._lastFailedMessage = null;
  15. }
  16. /**
  17. * Starts tracking requests on the given connection.
  18. *
  19. * @param {XmppConnection} xmppConnection - The XMPP connection which manages the given {@code stropheConnection}.
  20. * @param {Strophe.Connection} stropheConnection - Strophe connection instance.
  21. */
  22. startTracking(xmppConnection: XmppConnection, stropheConnection: Strophe.Connection): void {
  23. const originalRawInput = stropheConnection.rawInput;
  24. stropheConnection.rawInput = (...args: any[]): void => {
  25. const rawMessage = args[0];
  26. if (rawMessage.includes('failure')) {
  27. this._lastFailedMessage = rawMessage;
  28. }
  29. // It's okay to use rawInput callback only once the connection has been established, otherwise it will
  30. // treat 'item-not-found' or other connection error on websocket reconnect as successful stanza received.
  31. if (xmppConnection.connected) {
  32. this._lastSuccess = Date.now();
  33. }
  34. originalRawInput.apply(stropheConnection, args);
  35. };
  36. }
  37. /**
  38. * Returns the last raw failed incoming message on the xmpp connection.
  39. *
  40. * @returns {string|null}
  41. */
  42. getLastFailedMessage(): string | null {
  43. return this._lastFailedMessage;
  44. }
  45. /**
  46. * Returns how many milliseconds have passed since the last successful BOSH request.
  47. *
  48. * @returns {number|null}
  49. */
  50. getTimeSinceLastSuccess(): number | null {
  51. return this._lastSuccess
  52. ? Date.now() - this._lastSuccess
  53. : null;
  54. }
  55. }