capybara/frontend/src/Connection.js

62 lines
1.7 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;
}
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.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.log("Closed - attempting to reconnect in 4000ms");
this.isReady = false;
setTimeout(() => this.connect(), 4000);
}
}
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;