ft_transcendence/frontend/static/js/api/chat/channel.js

78 lines
1.5 KiB
JavaScript
Raw Normal View History

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) {
2023-12-26 08:28:04 -05:00
let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/chat/${this.channel_id}`;
2023-12-15 14:32:43 -05:00
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;
}
2023-12-12 04:04:46 -05:00
}
export {Channel}