From 745af7af5df94af962ec38c1cdc562bfc5983eb0 Mon Sep 17 00:00:00 2001 From: Midgard Date: Wed, 17 Feb 2021 17:13:28 +0100 Subject: [PATCH] Add websocket support, messages appear in realtime now --- js/mm_client.js | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/js/mm_client.js b/js/mm_client.js index 81fe9c1..33c7dd3 100644 --- a/js/mm_client.js +++ b/js/mm_client.js @@ -9,6 +9,10 @@ class MattermostClient { const creds = this.credentials.get(this.endpoint); this.token = creds ? creds.token : null; console.info(`Created MattermostClient for ${this.endpoint}, ${this.token ? "found token" : "did not find token"}`); + + if (this.token) { + this.websocket(); + } } async get(path, token, queryParams) { @@ -89,12 +93,19 @@ class MattermostClient { this.credentials.store(this.endpoint, login_id, token); this.token = token; let _ = this.getUsers(); + this.websocket(); return response.responseJson; } async logOut() { + console.log(this); + console.log(this.token); assert(this.token, "logged in"); - const response = await this.post("/users/logout", this.token); + try { + const response = await this.post("/users/logout", this.token); + } catch (e) { + console.warn(e); + } // Verify that the token is now invalidated if (await this.loggedIn()) { @@ -145,6 +156,40 @@ class MattermostClient { const response = await this.authedGet(`/files/${file_id}/link`, {}); return response.link; } + + websocket() { + assert(this.token, "logged in"); + + const endpoint_destructuring = this.endpoint.match(/^([^:]+)(:\/\/.*)/); + const protocol = endpoint_destructuring[1] === "https" ? "wss" : "ws"; + const endpoint = protocol + endpoint_destructuring[2] + "/websocket"; + + const socket = new WebSocket(endpoint); + + socket.addEventListener("error", event => { + console.error("Websocket errored", event.data); + }); + + socket.addEventListener("close", event => { + console.info("Websocket closed", event.data); + }); + + socket.addEventListener("open", event => { + console.log(`Opened websocket connection to ${endpoint}`); + socket.send(`{"seq": 1, "action": "authentication_challenge", "data": {"token": "${this.token}"}}`); + }); + + socket.addEventListener("message", event => { + console.log("Message from server ", event.data); + const data = JSON.parse(event.data); + + if (data.event === "posted") { + const post = JSON.parse(data.data.post); + pubsub.publish("MESSAGES_NEW", {...post, endpoint: this.endpoint}); + } + }); + + } }