capybara/frontend/src/Connection.js

67 lines
2 KiB
JavaScript
Raw Normal View History

import Logger from "./common/Logger";
class Connection {
constructor(url) {
this.ws = null;
this.log = Logger(["Connection"], ["log"]).log;
this.messageLog = Logger(["Connection", "Message"], ["log"]).log;
this.url = url;
this.isReady = false;
this.reconnectTimeout = 0;
}
formatAuthString(password) {
return `%auth%${btoa(password)}`;
}
connect(password) {
this.ws = new WebSocket(this.url);
this.ws.onerror = (e) => this.log("Error", e);
this.ws.onopen = () => {
this.log("Open");
this.reconnectTimeout = 0;
this.log("Sending authentication packet");
this.ws.send(`0${this.formatAuthString(password)}`); // send auth packet
};
this.ws.onmessage = ({ data }) => {
if (data === "1") {
if (this.onHandshakeCompleted)
this.onHandshakeCompleted();
this.isReady = true;
this.log("Handshake complete");
}
};
this.ws.onclose = ({ code }) => {
if (code === 4001) {// code for bad auth
this.log("Closed due to bad auth - skipping reconnect");
return;
}
this.isReady = false;
this.reconnectTimeout += 400;
if (this.reconnectTimeout >= 30000)
this.reconnectTimeout = 30000;
this.log(`Closed - will reconnect in ${this.reconnectTimeout}ms`);
setTimeout(() => this.connect(password), this.reconnectTimeout);
}
}
sendMessage(code, params=[]) {
let message = code;
2021-11-08 17:02:05 +02:00
for (let i = 0; i < params.length; i++) {
const param = params[i];
if (i == params.length - 1)
message += param;
else
message += param + ";";
2021-11-08 17:02:05 +02:00
}
this.ws.send(message);
}
disconnect() {
this.ws.close();
}
}
export default Connection;