45 lines
1.3 KiB
JavaScript
45 lines
1.3 KiB
JavaScript
const tavern = {
|
|
socket: socket = new WebSocket('ws:/' + window.location.host + '/ws'),
|
|
connected: false,
|
|
loggedIn: false,
|
|
call: (f, ...args) => {
|
|
if(typeof(f) == "function") {
|
|
f(...args);
|
|
}
|
|
}
|
|
};
|
|
|
|
tavern.socket.onopen = () => tavern.connected = true;
|
|
tavern.socket.onmessage = (m) => {
|
|
m = JSON.parse(m.data);
|
|
console.log(m);
|
|
if(m.login) {
|
|
tavern.socket.loggedIn = m.login.success;
|
|
tavern.call(tavern.onlogin, tavern.socket.loggedIn);
|
|
}
|
|
if(m.message) {
|
|
tavern.call(tavern.onmessage, m.message)
|
|
}
|
|
if(m.get_chat_history) {
|
|
m.get_chat_history.forEach(msg => {
|
|
tavern.call(tavern.onmessage, msg);
|
|
});
|
|
}
|
|
}
|
|
tavern.login = (username, password) => {
|
|
if(!tavern.connected || tavern.loggedIn) { return false; }
|
|
tavern.socket.send(JSON.stringify({ login: { username, password }}));
|
|
}
|
|
tavern.simple_msg = (msg, token) => {
|
|
if(!tavern.connected || tavern.loggedIn) { return false; }
|
|
tavern.socket.send(JSON.stringify({ message: { text: msg, source: token ?? "" } }));
|
|
}
|
|
tavern.get_chat_history = (from, amount) => {
|
|
if(!tavern.connected || tavern.loggedIn) { return false; }
|
|
tavern.socket.send(JSON.stringify({ get_chat_history: { from: from, amount: amount } }))
|
|
}
|
|
tavern.get_last_msgs = (amount) => {
|
|
if(!tavern.connected || tavern.loggedIn) { return false; }
|
|
tavern.socket.send(JSON.stringify({ get_last_messages: { amount: amount } }))
|
|
}
|