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; for (let i = 0; i < params.length; i++) { const param = params[i]; if (i == params.length - 1) message += param; else message += param + ";"; } this.ws.send(message); } disconnect() { this.ws.close(); } } export default Connection;