import { Account } from "./account.js"; import { MatchMaking } from "./matchmaking.js"; import { Profiles } from "./profiles.js"; import { Channels } from './chat/channels.js'; import { MyProfile } from "./MyProfile.js"; function getCookie(name) { let cookie = {}; document.cookie.split(';').forEach(function(el) { let split = el.split('='); cookie[split[0].trim()] = split.slice(1).join("="); }) return cookie[name]; } class Client { constructor(url) { this._url = url; this.account = new Account(this); this.profiles = new Profiles(this); this.matchmaking = new MatchMaking(this); this._logged = undefined; this.channels = new Channels(this); this.channel = undefined; } async isAuthentificate() { if (this._logged == undefined) this.logged = await this._test_logged(); return this.logged; } async _get(uri) { let response = await fetch(this._url + uri, { method: "GET", }); return response; } async _post(uri, data) { let response = await fetch(this._url + uri, { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify(data), }); return response; } async _delete(uri, data) { let response = await fetch(this._url + uri, { method: "DELETE", headers: { "Content-Type": "application/json", "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify(data), }); return response; } async _patch_json(uri, data) { let response = await fetch(this._url + uri, { method: "PATCH", headers: { "X-CSRFToken": getCookie("csrftoken"), "Content-Type": "application/json", }, body: JSON.stringify(data), }); return response; } async _patch_file(uri, file) { let response = await fetch(this._url + uri, { method: "PATCH", headers: { "X-CSRFToken": getCookie("csrftoken"), }, body: file, }); return response; } async _update_logged(state) { if (!this.logged && state) { this.me = new MyProfile(this); await this.me.init(); } this.logged = state; } async login(username, password) { let response = await this._post("/api/accounts/login", {username: username, password: password}) let data = await response.json(); if (data.id != undefined) { await this._update_logged(true); return null; } return data; } async logout() { await this._get("/api/accounts/logout"); await this._update_logged(false); } async _test_logged() { let response = await this._get("/api/accounts/logged"); let data = await response.json(); if (data.id !== undefined) await this._update_logged(true); return data.id !== undefined; } } export {Client}