try restore

This commit is contained in:
2024-01-02 15:23:29 +01:00
47 changed files with 1132 additions and 79 deletions

View File

@ -33,7 +33,7 @@ class Account
if (JSON.stringify(response_data) == JSON.stringify({'detail': 'Authentication credentials were not provided.'}))
{
this.client._logged = false;
this.client._update_logged(false);
return null;
}
if (response_data == "user deleted")

View File

@ -35,7 +35,9 @@ class Channel {
this.chatSocket.close();
}
updateMessages(messages) {
updateMessages(messages)
{
console.log(messages);
messages = JSON.parse(messages);
let new_messages = [];

View File

@ -9,8 +9,8 @@ class Channels {
async createChannel(members_id, reload) {
let null_id = false;
members_id.forEach(user_id => {
if (user_id == null)
members_id.forEach(member_id => {
if (member_id == null)
null_id = true;
});
if (null_id)
@ -28,6 +28,7 @@ class Channels {
let messages = undefined;
if (exit_code == 200)
messages = data.messages;
return new Channel(this.client, data.channel_id, members_id, messages, reload);
}

View File

@ -3,6 +3,8 @@ import { MatchMaking } from "./matchmaking.js";
import { Profiles } from "./profiles.js";
import { Channels } from './chat/channels.js';
import { MyProfile } from "./MyProfile.js";
import { navigateTo } from "../index.js"
import { Tourmanents } from "./tournament/tournaments.js";
function getCookie(name)
{
@ -22,6 +24,7 @@ class Client
this.account = new Account(this);
this.profiles = new Profiles(this);
this.matchmaking = new MatchMaking(this);
this.tournaments = new Tourmanents(this);
this._logged = undefined;
this.channels = new Channels(this);
@ -102,6 +105,10 @@ class Client
this.me = new MyProfile(this);
await this.me.init();
}
if (this.logged && !state)
{
navigateTo("/login");
}
this.logged = state;
}

View File

@ -8,30 +8,45 @@ class MatchMaking
constructor(client)
{
/**
* @type {client}
* @type {Client}
*/
this.client = client
this.searching = false;
}
async start(func)
async start(receive_func, disconnect_func, mode)
{
if (!await this.client.isAuthentificate())
return null;
let url = `wss://${window.location.host}/ws/matchmaking/`;
let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/matchmaking/${mode}`;
this._socket = new WebSocket(url);
this._chatSocket = new WebSocket(url);
this._chatSocket.onmessage = function (event) {
this.searching = true;
this.receive_func = receive_func;
this.disconnect_func = disconnect_func;
this._socket.onmessage = function (event) {
const data = JSON.parse(event.data);
func(data.game_id)
receive_func(data);
};
this._socket.onclose = this.onclose.bind(this);
}
onclose(event)
{
this.stop();
this.disconnect_func(event);
}
async stop()
{
this._chatSocket.close()
this.searching = false;
this._socket.close()
}
}
export {MatchMaking}
export {MatchMaking}

View File

@ -20,6 +20,10 @@ class Profile
async init(user_id)
{
let response = await this.client._get(`/api/profiles/${user_id}`);
if (response.status === 404)
return 1;
let response_data = await response.json();
this.user_id = response_data.user_id;

View File

@ -28,7 +28,8 @@ class Profiles
async getProfile(user_id)
{
let profile = new Profile(this.client);
await profile.init(user_id);
if (await profile.init(user_id))
return null;
return profile;
}

View File

@ -0,0 +1,98 @@
import { Client } from "../client.js";
class Tourmanent
{
/**
* @param {Client} client
*/
constructor(client, name = undefined, nb_players = undefined, nb_players_by_game = undefined, level = undefined, started = undefined, finished = undefined, levels = undefined, id = undefined)
{
/**
* @type {Client}
*/
this.client = client;
this.name = name || `${nb_players_by_game}x1, ${nb_players} players`;
this.nb_players = nb_players;
this.nb_players_by_game = nb_players_by_game;
this.level = level;
this.started = started;
this.finished = finished;
this.levels = levels;
this.state = this.get_state();
this.id = id
this.connected = false;
}
get_state()
{
if (this.finished)
return "finished";
if (this.started)
return "started";
else
return "waiting";
}
async init(id)
{
let response = await this.client._get(`/api/tournaments/${id}`);
if (response.status === 404)
return 1;
let response_data = await response.json();
this.name = response_data.name || `${response_data.nb_players_by_game}x1, ${response_data.nb_players} players`;
this.nb_players = response_data.nb_players;
this.nb_players_by_game = response_data.nb_players_by_game;
this.level = response_data.level;
this.started = response_data.started;
this.finished = response_data.finished;
this.levels = response_data.levels;
this.id = response_data.id
this.state = this.get_state();
}
leave(event)
{
if (this.connected == false)
return
this.connected = false;
this._socket.close()
this.disconnect_func(event);
}
toggle_participation()
{
if (!this.connected)
return
this._socket.send(JSON.stringify({participate: ""}));
}
async join(receive_func, disconnect_func)
{
if (!await this.client.isAuthentificate())
return null;
let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/tournaments/${this.id}`;
this._socket = new WebSocket(url);
this.connected = true;
this.isParticipating = false;
this.receive_func = receive_func;
this.disconnect_func = disconnect_func;
this._socket.onmessage = function (event) {
const data = JSON.parse(event.data);
receive_func(data);
};
this._socket.onclose = this.leave.bind(this);
}
}
export { Tourmanent }

View File

@ -0,0 +1,78 @@
import { Client } from "../client.js";
import { Tourmanent } from "./tournament.js";
class Tourmanents
{
/**
* @param {Client} client
*/
constructor(client)
{
/**
* @type {Client}
*/
this.client = client
}
async getTournament(id)
{
let tournament = new Tourmanent(this.client);
if (await tournament.init(id))
return null;
return tournament;
}
async createTournament(nb_players, nb_players_by_game, name = "")
{
let response = await this.client._post("/api/tournaments/", {nb_players: nb_players, nb_players_by_game: nb_players_by_game, name: name});
if (response.status === 403)
{
this.client._update_logged(false);
return null;
}
let response_data = await response.json();
return response_data;
}
/**
* @param {string} state must be "finished", or "started", or "waiting". Any other return all elements
*/
async search(state)
{
let response = await this.client._get(`/api/tournaments/search/${state}`);
let response_data = await response.json()
if (response.status === 404)
{
this.client._update_logged(false);
return null;
}
let tournaments = [];
response_data.forEach(tournament_data => {
tournaments.push(new Tourmanent(this.client,
tournament_data.name,
tournament_data.nb_players,
tournament_data.nb_players_by_game,
tournament_data.level,
tournament_data.started,
tournament_data.finished,
tournament_data.levels,
tournament_data.id));
});
return tournaments;
}
async all()
{
return await this.search("");
}
}
export { Tourmanents }

View File

@ -14,6 +14,9 @@ import AbstractRedirectView from "./views/abstracts/AbstractRedirectView.js";
import MeView from "./views/MeView.js";
import ProfilePageView from "./views/ProfilePageView.js";
import MatchMakingView from "./views/MatchMakingView.js";
import TournamentPageView from "./views/TournamentPageView.js";
import TournamentsView from "./views/TournamentsListView.js";
import TournamentCreateView from "./views/TournamentCreateView.js";
let client = new Client(location.protocol + "//" + location.host)
@ -35,10 +38,26 @@ const navigateTo = async (uri) => {
history.pushState(null, null, uri);
};
async function renderView(view)
{
let content = await view.getHtml();
if (content == null)
return 1;
view.setTitle();
document.querySelector("#app").innerHTML = content
if (await view.postInit())
renderView(new PageNotFoundView());
}
const router = async (uri) => {
const routes = [
{ path: "/", view: Dashboard },
{ path: "/profiles/:id", view: ProfilePageView },
{ path: "/tournaments/create", view: TournamentCreateView },
{ path: "/tournaments/:id", view: TournamentPageView },
{ path: "/tournaments/", view: TournamentsView },
{ path: "/login", view: LoginView },
{ path: "/logout", view: LogoutView },
{ path: "/register", view: RegisterView },
@ -80,14 +99,7 @@ const router = async (uri) => {
lastView = view;
await client.isAuthentificate();
let content = await view.getHtml();
if (content == null)
return 1;
view.setTitle();
document.querySelector("#app").innerHTML = content
await view.postInit();
renderView(view);
return 0;
};

View File

@ -1,24 +1,64 @@
import { client, navigateTo } from "../index.js";
import AbstractView from "./abstracts/AbstractView.js";
import { clear, fill_errors } from "../utils/formUtils.js";
import AbstractAuthentifiedView from "./abstracts/AbstractAuthentifiedView.js";
function game_found(game_id)
{
navigateTo(`/games/${game_id}`)
}
export default class extends AbstractAuthentifiedView {
constructor(params)
{
super(params, "Matchmaking");
}
export default class extends AbstractView {
constructor(params) {
super(params, "Dashboard");
async press_button()
{
if (client.matchmaking.searching)
{
client.matchmaking.stop();
document.getElementById("button").value = "Find a game"
}
else
{
let nb_players = document.getElementById("nb_players-input").value
await client.matchmaking.start(this.onreceive.bind(this), this.ondisconnect.bind(this), nb_players);
document.getElementById("button").value = "Stop matchmaking"
}
}
ondisconnect(event)
{
if (event.code === 1000)
clear("innerText", ["detail"])
document.getElementById("button").value = "Find a game"
}
onreceive(data)
{
if (data.detail === "game_found")
{
navigateTo(`/games/${data.game_id}`);
return;
}
this.display_data(data)
}
display_data(data)
{
clear("innerText", ["detail"]);
fill_errors(data, "innerText");
}
async postInit()
{
await client.matchmaking.start(game_found)
document.getElementById("button").onclick = this.press_button.bind(this)
}
async getHtml() {
return `
<h1>finding<h1>
<h1>Select mode</h1>
<input type="number" value="2" id="nb_players-input">
<input type="button" value="Find a game" id="button">
<span id="detail"></span>
`;
}

View File

@ -9,6 +9,11 @@ export default class extends AbstractView {
async postInit()
{
let profile = await client.profiles.getProfile(this.user_id);
if (profile === null)
return 1;
this.profile = await client.profiles.getProfile(this.user_id);
this.info = document.getElementById("info");

View File

@ -0,0 +1,52 @@
import {client, navigateTo} from "../index.js";
import { clear, fill_errors } from "../utils/formUtils.js";
import AbstractAuthentifiedView from "./abstracts/AbstractAuthentifiedView.js";
export default class extends AbstractAuthentifiedView
{
constructor(params)
{
super(params, "Create tournament");
this.id = params.id;
}
async create()
{
let name = document.getElementById("name-input").value;
let nb_players = document.getElementById("nb_players-input").value;
let nb_players_by_game = document.getElementById("nb_players_by_game-input").value
let response_data = await client.tournaments.createTournament(nb_players, nb_players_by_game, name);
if (response_data === null)
return;
let id = response_data["id"]
if (id !== undefined)
{
navigateTo(`/tournaments/${id}`);
return;
}
clear("innerHTML", ["name", "nb_players", "nb_players_by_game"]);
fill_errors(response_data, "innerHTML");
}
async postInit()
{
document.getElementById("create-button").onclick = this.create;
}
async getHtml()
{
return `
<input type="text" id="name-input" placeholder="Tournament name">
<span id="name"></span>
<input type="number" id="nb_players-input" placeholder="Number of players in tournament">
<span id="nb_players"></span>
<input type="number" id="nb_players_by_game-input" placeholder="Number of players by game">
<span id="nb_players_by_game"></span>
<input type="button" id="create-button" value="Create tournament">
`
}
}

View File

@ -0,0 +1,98 @@
import {client, navigateTo} from "../index.js";
import AbstractAuthentifiedView from "./abstracts/AbstractAuthentifiedView.js";
export default class extends AbstractAuthentifiedView
{
constructor(params)
{
super(params, "Tournament");
this.id = params.id;
}
pressButton()
{
this.tournament.toggle_participation();
}
async receive(data)
{
if (data.detail === "nb_participants" || data.detail === "update_participants")
document.getElementById("nb_participants").innerText = `${data.nb_participants} / ${this.tournament.nb_players}`
if (data.detail === "go_to")
navigateTo(data.url);
if (data.detail === "is_participant")
this.updateParticipating(data.is_participant)
if (data.detail === "error")
document.getElementById("display").innerText = data.error_message
}
async updateParticipating(state)
{
document.getElementById("button").value = state ? `Leave ${this.tournament.name}` : `Join ${this.tournament.name}`;
document.getElementById("display").innerText = state ? "You are a particpant" : "You are not a participant";
}
async ondisconnect(event)
{
}
async postInit()
{
this.tournament = await client.tournaments.getTournament(this.id);
if (this.tournament === null)
return 1;
this.tournament.join(this.receive.bind(this), this.ondisconnect.bind(this));
let button = document.getElementById("button")
button.onclick = this.pressButton.bind(this);
document.getElementById("name").innerText = this.tournament.name;
document.getElementById("nb_players").innerText = this.tournament.nb_players;
document.getElementById("nb_players_by_game").innerText = this.tournament.nb_players_by_game;
document.getElementById("level").innerText = this.tournament.level;
document.getElementById("state").innerText = this.tournament.state;
if (this.tournament.state === "waiting")
button.disabled = false;
}
async getHtml()
{
return `
<table>
<thead>
<tr>
<th id="name">Loading...</th>
</tr>
</thead>
<tbody>
<tr>
<td>Number of players</td>
<td id="nb_players">Loading...</td>
</tr>
<tr>
<td>Number of players by game</td>
<td id="nb_players_by_game">Loading...</td>
</tr>
<tr>
<td>Number of round</td>
<td id="level">Loading...</td>
</tr>
<tr>
<td>Number of player</td>
<td id="nb_participants">Loading...</td>
</tr>
<tr>
<td>status</td>
<td id="state">Loading...</td>
</tr>
</tbody>
</table>
<input type="button" id="button" value="Join tournament" disabled>
<span id="display"></span>
`
}
}

View File

@ -0,0 +1,133 @@
import {client} from "../index.js";
import AbstractAuthentifiedView from "./abstracts/AbstractAuthentifiedView.js";
export default class extends AbstractAuthentifiedView
{
constructor(params)
{
super(params, "Tournament");
this.id = params.id;
}
async external_search()
{
let state = document.getElementById("state-select").value;
this.tournaments = await client.tournaments.search(state);
}
add_nb_player_by_game_selector()
{
let nb_players_by_game_list = new Set()
this.tournaments.forEach(tournament => {
nb_players_by_game_list.add(tournament.nb_players_by_game);
});
let select = document.getElementById("nb-players-by-game-select");
let new_children = []
const opt = document.createElement("option");
opt.value = "all";
opt.text = "All";
new_children.push(opt);
nb_players_by_game_list.forEach(nb_players_by_game => {
const opt = document.createElement("option");
opt.value = nb_players_by_game;
opt.text = nb_players_by_game;
new_children.push(opt);
})
select.replaceChildren(...new_children);
}
internal_search()
{
let nb_players_by_game = document.getElementById("nb-players-by-game-select").value;
this.display_tournaments = [];
this.tournaments.forEach(tournament => {
if (nb_players_by_game === "all" || nb_players_by_game == tournament.nb_players_by_game)
this.display_tournaments.push(tournament);
});
}
display_result()
{
const tournaments_list = document.getElementById("tournaments-list");
const new_children = []
this.display_tournaments.forEach(tournament => {
let tr = document.createElement("tr");
// name
let td = document.createElement("td");
td.innerText = tournament.name;
tr.appendChild(td);
// state
td = document.createElement("td");
td.innerText = tournament.state;
tr.appendChild(td);
// nb_players
td = document.createElement("td");
td.innerText = tournament.nb_players;
tr.appendChild(td);
// nb_players_by_game
td = document.createElement("td");
td.innerText = tournament.nb_players_by_game;
tr.appendChild(td);
new_children.push(tr);
});
tournaments_list.replaceChildren(...new_children);
}
async update_query()
{
this.internal_search();
this.display_result();
}
async update_search()
{
await this.external_search();
this.add_nb_player_by_game_selector();
this.update_query();
}
async postInit()
{
await this.update_search()
document.getElementById("state-select").onchange = this.update_search.bind(this);
document.getElementById("nb-players-by-game-select").onchange = this.update_query.bind(this);
}
async getHtml()
{
return `
<select id="state-select">
<option value="waiting">Waiting</option>
<option value="started">Started</option>
<option value="finished">Finished</option>
<option value="all">All</option>
</select>
<select id="nb-players-by-game-select">
</select>
<table>
<thead>
<td>Name</td>
<td>Status</td>
<td>Max numbers of players</td>
<td>Max numbers of players by game</td>
</thead>
<tbody id="tournaments-list">
</tbody>
</table>
`
}
}