78 lines
1.5 KiB
JavaScript
78 lines
1.5 KiB
JavaScript
import {Message} from "./message.js"
|
|
|
|
class Channel {
|
|
constructor(client, channel_id, members_id, messages, reload) {
|
|
this.client = client;
|
|
this.channel_id = channel_id;
|
|
this.members_id = members_id;
|
|
this.messages = [];
|
|
if (messages != undefined)
|
|
this.updateMessages(messages);
|
|
|
|
this.connect(reload);
|
|
}
|
|
|
|
// reload = function to use when we receive a message
|
|
async connect(reload) {
|
|
let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/chat/${this.channel_id}`;
|
|
|
|
this.chatSocket = new WebSocket(url);
|
|
this.chatSocket.onmessage = (event) =>{
|
|
let data = JSON.parse(event.data)
|
|
|
|
this.messages.push(new Message(
|
|
this.channel_id,
|
|
data.author_id,
|
|
data.content,
|
|
data.time,
|
|
));
|
|
|
|
reload();
|
|
};
|
|
}
|
|
|
|
async disconnect() {
|
|
this.chatSocket.close();
|
|
}
|
|
|
|
updateMessages(messages) {
|
|
messages = JSON.parse(messages);
|
|
let new_messages = [];
|
|
|
|
messages.forEach((message) => {
|
|
message = message["fields"];
|
|
new_messages.push(new Message(
|
|
message["channel_id"],
|
|
message["author_id"],
|
|
message["content"],
|
|
message["time"],
|
|
));
|
|
});
|
|
|
|
//console.log(new_messages);
|
|
this.messages = new_messages;
|
|
return new_messages;
|
|
}
|
|
|
|
async sendMessageChannel(message) {
|
|
|
|
if (this.chatSocket == undefined)
|
|
return;
|
|
|
|
this.chatSocket.send(JSON.stringify({
|
|
'message':message
|
|
}));
|
|
}
|
|
|
|
async deleteChannel() {
|
|
let response = await this.client._delete("/api/chat/" + this.channel_id, {
|
|
});
|
|
|
|
let data = await response.json();
|
|
return data;
|
|
}
|
|
|
|
}
|
|
|
|
export {Channel}
|