2023-12-15 14:32:43 -05:00
|
|
|
import {Message} from "./message.js"
|
|
|
|
|
2023-12-12 04:04:46 -05:00
|
|
|
class Channel {
|
2023-12-15 14:32:43 -05:00
|
|
|
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);
|
2023-12-12 04:04:46 -05:00
|
|
|
}
|
2023-12-15 14:32:43 -05:00
|
|
|
|
|
|
|
// reload = function to use when we receive a message
|
|
|
|
async connect(reload) {
|
|
|
|
let url = `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;
|
|
|
|
}
|
|
|
|
|
2023-12-20 17:48:52 -05:00
|
|
|
async sendMessageChannel(message, receivers_id) {
|
2023-12-15 14:32:43 -05:00
|
|
|
|
|
|
|
if (this.chatSocket == undefined)
|
|
|
|
return;
|
|
|
|
|
|
|
|
this.chatSocket.send(JSON.stringify({
|
2023-12-20 17:48:52 -05:00
|
|
|
'message':message,
|
|
|
|
'receivers_id':receivers_id,
|
2023-12-15 14:32:43 -05:00
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
async deleteChannel() {
|
|
|
|
let response = await this.client._delete("/api/chat/" + this.channel_id, {
|
|
|
|
});
|
|
|
|
|
|
|
|
let data = await response.json();
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
2023-12-12 04:04:46 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export {Channel}
|