2021-11-03 04:21:58 +02:00
|
|
|
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;
|
2021-11-08 00:25:27 +02:00
|
|
|
this.isReady = false;
|
2021-11-03 04:21:58 +02:00
|
|
|
}
|
|
|
|
|
2021-11-08 00:25:27 +02:00
|
|
|
formatAuthString(password) {
|
|
|
|
return `%auth%${btoa(password)}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(password) {
|
2021-11-03 04:21:58 +02:00
|
|
|
this.ws = new WebSocket(this.url);
|
|
|
|
this.ws.onerror = (e) => this.log("Error", e);
|
|
|
|
this.ws.onopen = () => {
|
|
|
|
this.log("Open");
|
2021-11-08 00:25:27 +02:00
|
|
|
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");
|
|
|
|
}
|
2021-11-03 04:21:58 +02:00
|
|
|
};
|
2021-11-08 00:25:27 +02:00
|
|
|
this.ws.onclose = ({ code }) => {
|
|
|
|
if (code === 4001) {// code for bad auth
|
|
|
|
this.log("Closed due to bad auth - skipping reconnect");
|
|
|
|
return;
|
|
|
|
}
|
2021-11-03 04:21:58 +02:00
|
|
|
this.log("Closed - attempting to reconnect in 4000ms");
|
2021-11-08 00:25:27 +02:00
|
|
|
this.isReady = false;
|
2021-11-03 04:21:58 +02:00
|
|
|
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];
|
2021-11-03 04:21:58 +02:00
|
|
|
if (i == params.length - 1)
|
|
|
|
message += param;
|
|
|
|
else
|
|
|
|
message += param + ";";
|
2021-11-08 17:02:05 +02:00
|
|
|
}
|
2021-11-03 04:21:58 +02:00
|
|
|
|
|
|
|
this.ws.send(message);
|
|
|
|
}
|
|
|
|
|
|
|
|
disconnect() {
|
|
|
|
this.ws.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Connection;
|