import { navigateTo } from "../../index.js"; import {create_popup} from "../../utils/noticeUtils.js"; class Notice { constructor(client) { this.client = client; this.data = {}; // users online, invited by, asked friend by, let data_variable = ["online", "invited", "asked"]; for (let i in data_variable) this.data[data_variable[i]] = []; this.connect(); } async connect() { let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/chat/notice`; this.chatSocket = new WebSocket(url); this.chatSocket.onmessage = (event) =>{ let send = JSON.parse(event.data); console.log("notice: ", send); if (send.type == "invite") this.receiveInvite(send); else if (send.type == "online_users" || send.type == "disconnect") this.receiveOnlineUser(send); else if (send.type == "accept_invite") this.receiveAcceptInvite(send); } this.chatSocket.onopen = (event) => { this.getOnlineUser(); } } async disconnect() { if (this.chatSocket == undefined) return ; this.chatSocket.close(); } async acceptInvite(invitedBy) { this.sendRequest({ type: "accept_invite", targets: [invitedBy], }); } async receiveAcceptInvite(send) { let id_game = send["result"]; navigateTo("/game/" + id_game); } async refuseInvite(invitedBy) { this.sendRequest({ type: "refuse_invite", targets: [invitedBy], }); } async sendInvite(id_inviteds) { this.sendRequest({ type: "invite", targets: id_inviteds, time: new Date().getTime(), }); } async receiveInvite(send) { if (this.client.me == undefined) return ; let content = send.content; if (send.author_id == this.client.me.id) { if (send.status == 200) { for (let target in send.targets) return create_popup("Invitation send"); } else if (send.status == 404) return create_popup("User not connected"); else if (send.status == 409) return create_popup("Already invited"); } else { if (!content.includes(send.author_id) || this.data["invited"].includes(send.author_id)) return; this.data["invited"] = content; let sender = await this.client.profiles.getProfile(send.author_id); create_popup("Invitation received by " + sender.username); if (this.rewrite_invite !== undefined) this.rewrite_invite(); // Géré la reception de l'invitation } } async getOnlineUser() { this.online_users = {}; this.sendRequest({ type: "online_users", targets: [], time: new Date().getTime(), }); } async receiveOnlineUser(send) { let content = send.content; if (content !== undefined) { if (this.data["online"].length > 0) { // get all disconnect user let disconnects = this.data["online"].filter(id => !Object.keys(content).includes(id)); // delete invite this.data["invited"] = this.data["invited"].filter(id => !disconnects.includes(id)); //console.log(this.data["invited"]); } this.data["online"] = Object.keys(content); if (this.rewrite_usernames !== undefined) this.rewrite_usernames(); } } async sendRequest(content) { if (this.chatSocket == undefined) return; this.chatSocket.send(JSON.stringify(content)); } } export {Notice}