Add websocket support, messages appear in realtime now
This commit is contained in:
parent
023d95d725
commit
745af7af5d
1 changed files with 46 additions and 1 deletions
|
@ -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");
|
||||
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});
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
Loading…
Reference in a new issue