git » sdk » commit 4270b3e

Event for when connection goes offline

author Stephen Paul Weber
2024-07-09 16:24:35 UTC
committer Stephen Paul Weber
2024-07-09 16:24:35 UTC
parent d207e4932b6393d96cb3be77c2d25d03e4925d7e

Event for when connection goes offline

snikket/Client.hx +15 -0
snikket/streams/XmppJsStream.hx +9 -1

diff --git a/snikket/Client.hx b/snikket/Client.hx
index 356d65e..9fadc86 100644
--- a/snikket/Client.hx
+++ b/snikket/Client.hx
@@ -86,6 +86,9 @@ class Client extends EventEmitter {
 		this.persistence = persistence;
 		stream = new Stream();
 		stream.on("status/online", this.onConnected);
+		stream.on("status/offline", (data) -> {
+			this.trigger("status/offline", {});
+		});
 
 		stream.on("fast-token", (data) -> {
 			persistence.storeLogin(this.jid.asBare().asString(), stream.clientId ?? this.jid.resource, displayName(), data.token);
@@ -833,6 +836,18 @@ class Client extends EventEmitter {
 		});
 	}
 
+	/**
+		Event fired when client is disconnected
+
+		@param handler takes no arguments
+	**/
+	public function addStatusOfflineListener(handler:()->Void):Void {
+		this.on("status/offline", (data) -> {
+			handler();
+			return EventHandled;
+		});
+	}
+
 	/**
 		Event fired when a new ChatMessage comes in on any Chat
 		Also fires when status of a ChatMessage changes,
diff --git a/snikket/streams/XmppJsStream.hx b/snikket/streams/XmppJsStream.hx
index 5572921..017f51b 100644
--- a/snikket/streams/XmppJsStream.hx
+++ b/snikket/streams/XmppJsStream.hx
@@ -229,9 +229,17 @@ class XmppJsStream extends GenericStream {
 			this.trigger("fast-token", tokenEl.attrs);
 		});
 
+		xmpp.on("status", (status) -> {
+			if (status == "disconnect") {
+				if (this.state.can("connection-closed")) this.state.event("connection-closed");
+			} else if(status == "connecting") {
+				if (this.state.can("connect-requested")) this.state.event("connect-requested");
+			}
+		});
+
 		resumed = false;
 		xmpp.start().catchError(function (err) {
-			this.state.event("connection-error");
+			if (this.state.can("connection-error")) this.state.event("connection-error");
 			final xmppError = Std.downcast(err, XmppJsError);
 			if (xmppError?.name == "SASLError") {
 				this.trigger("auth/fail", xmppError);