2024-04-02 15:57:41 +00:00
|
|
|
export default class WetSockClient {
|
|
|
|
|
constructor(url) {
|
|
|
|
|
this.socket = new WebSocket(url);
|
|
|
|
|
this.listeners = new Map();
|
|
|
|
|
this.plugins = new Map();
|
|
|
|
|
|
2024-04-07 20:08:40 +01:00
|
|
|
this.socket.addEventListener('open', () => {
|
2024-04-02 15:57:41 +00:00
|
|
|
console.log('Connected to WetSock server');
|
2024-04-07 20:08:40 +01:00
|
|
|
});
|
2024-04-02 15:57:41 +00:00
|
|
|
|
2024-04-07 20:08:40 +01:00
|
|
|
this.socket.addEventListener('message', (event) => {
|
2024-04-02 15:57:41 +00:00
|
|
|
const message = JSON.parse(event.data);
|
|
|
|
|
this.handleMessage(message);
|
2024-04-07 20:08:40 +01:00
|
|
|
});
|
2024-04-02 15:57:41 +00:00
|
|
|
|
2024-04-07 20:08:40 +01:00
|
|
|
this.socket.addEventListener('close', () => {
|
2024-04-02 15:57:41 +00:00
|
|
|
console.log('Disconnected from WetSock server');
|
2024-04-07 20:08:40 +01:00
|
|
|
});
|
2024-04-02 15:57:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
on(event, callback) {
|
|
|
|
|
if (!this.listeners.has(event)) {
|
|
|
|
|
this.listeners.set(event, []);
|
|
|
|
|
}
|
|
|
|
|
this.listeners.get(event).push(callback);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
emit(event, ...args) {
|
|
|
|
|
const listeners = this.listeners.get(event);
|
|
|
|
|
if (listeners) {
|
|
|
|
|
listeners.forEach((listener) => listener(...args));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
handleMessage(message) {
|
2024-04-07 20:08:40 +01:00
|
|
|
this.emit('message', message);
|
|
|
|
|
const { event, data, ...rest } = message;
|
|
|
|
|
switch (event) {
|
|
|
|
|
case 'plugins':
|
|
|
|
|
this.updatePlugins(data);
|
|
|
|
|
break;
|
2024-04-02 15:57:41 +00:00
|
|
|
}
|
2024-04-07 20:08:40 +01:00
|
|
|
this.emit(event, data);
|
2024-04-02 15:57:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
updatePlugins(plugins) {
|
|
|
|
|
plugins.forEach((plugin) => {
|
|
|
|
|
this.plugins.set(plugin.identifier, plugin.actions);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
send(message) {
|
2024-04-07 20:08:40 +01:00
|
|
|
if(typeof(message) != 'string') throw new TypeError('message needs to be a string');
|
|
|
|
|
if(message.startsWith('/')) {
|
|
|
|
|
const [command, ...rest] = message.split(' ');
|
|
|
|
|
|
|
|
|
|
message = {
|
|
|
|
|
action: command.substring(1),
|
|
|
|
|
message: rest.join(' ')
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-04-02 15:57:41 +00:00
|
|
|
this.socket.send(JSON.stringify(message));
|
|
|
|
|
}
|
|
|
|
|
}
|