switch to store client

This commit is contained in:
Luna 2025-05-24 02:08:25 +02:00
parent 0088a48fee
commit f220d135ff
9 changed files with 125 additions and 129 deletions

View file

@ -6,7 +6,7 @@
*/ */
export function bufferToImageUrl(imageBuffer: Uint8Array, mimeType: string = 'image/png'): string { export function bufferToImageUrl(imageBuffer: Uint8Array, mimeType: string = 'image/png'): string {
if(imageBuffer.length == 1) { if(imageBuffer.length == 1) {
throw new Error("This is the default logo.") return '/talogo.png'
} }
// Method 1: Create a data URL // Method 1: Create a data URL
const base64String = arrayBufferToBase64(imageBuffer); const base64String = arrayBufferToBase64(imageBuffer);

View file

@ -25,3 +25,6 @@ export const TABotTokenStore = createPersistedStore('TABotTokenTAUI', null);
export const TAServerUrl = createPersistedStore('TAServerUrl', "server.tournamentassistant.net"); export const TAServerUrl = createPersistedStore('TAServerUrl', "server.tournamentassistant.net");
export const TAServerPort = createPersistedStore('TAServerPort', "8676"); export const TAServerPort = createPersistedStore('TAServerPort', "8676");
// In the future, use a store for TAClient, since svelte is neat :)))
export const client = new TAClient();

View file

@ -2,7 +2,7 @@
import { onMount, onDestroy } from 'svelte'; import { onMount, onDestroy } from 'svelte';
import Notification from '$lib/components/notifications/Popup.svelte'; import Notification from '$lib/components/notifications/Popup.svelte';
import { discordAuthUrl } from '$lib/config.json'; import { discordAuthUrl } from '$lib/config.json';
import { discordDataStore, discordTokenStore, authTokenStore, TAServerPort, TAServerUrl } from '$lib/stores'; import { discordDataStore, discordTokenStore, authTokenStore, TAServerPort, TAServerUrl, client } from '$lib/stores';
import { TAClient, Response_ResponseType } from 'moons-ta-client'; import { TAClient, Response_ResponseType } from 'moons-ta-client';
import { v4 as uuidv4 } from "uuid"; import { v4 as uuidv4 } from "uuid";
@ -20,9 +20,6 @@
// Change to an object for better reactivity // Change to an object for better reactivity
let copyClicked: Record<string, boolean> = {}; let copyClicked: Record<string, boolean> = {};
// Declare client at component level so we can access it in onDestroy
let client: TAClient = new TAClient();
// Remove 'Bearer ' from the token // Remove 'Bearer ' from the token
if ($authTokenStore) { if ($authTokenStore) {
const cleanToken = $authTokenStore.replace('Bearer ', ''); const cleanToken = $authTokenStore.replace('Bearer ', '');
@ -41,12 +38,13 @@
} }
try { try {
if(!client.isConnected) {
const connectResult = await client.connect($TAServerUrl, $TAServerPort); const connectResult = await client.connect($TAServerUrl, $TAServerPort);
if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) { if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
error = "Failed to connect to server"; error = "Failed to connect to server";
loading = false; loading = false;
return; }
} }
const tokens = await client.getBotTokensForUser($discordDataStore.id); const tokens = await client.getBotTokensForUser($discordDataStore.id);
@ -64,13 +62,6 @@
} }
}); });
onDestroy(() => {
if (client) {
// Properly disconnect and clean up any listeners
client.disconnect();
}
});
function closeNotification() { function closeNotification() {
showLoginNotification = false; showLoginNotification = false;
} }

View file

@ -3,7 +3,7 @@
import { onMount, onDestroy } from 'svelte'; import { onMount, onDestroy } from 'svelte';
import Notification from '$lib/components/notifications/Popup.svelte'; import Notification from '$lib/components/notifications/Popup.svelte';
import { discordAuthUrl } from '$lib/config.json'; import { discordAuthUrl } from '$lib/config.json';
import { discordDataStore, discordTokenStore, authTokenStore, TAServerPort, TAServerUrl } from '$lib/stores'; import { discordDataStore, discordTokenStore, authTokenStore, TAServerPort, TAServerUrl, client } from '$lib/stores';
import { TAClient, Response_ResponseType, Tournament } from 'moons-ta-client'; import { TAClient, Response_ResponseType, Tournament } from 'moons-ta-client';
import { bufferToImageUrl } from '$lib/services/taImages'; import { bufferToImageUrl } from '$lib/services/taImages';
import { v4 as uuidv4 } from "uuid"; import { v4 as uuidv4 } from "uuid";
@ -34,9 +34,6 @@
let nameError = ''; let nameError = '';
let creating = false; let creating = false;
// Declare client at component level so we can access it in onDestroy
let client: TAClient = new TAClient();
// Remove 'Bearer ' from the token // Remove 'Bearer ' from the token
if($authTokenStore) { if($authTokenStore) {
const cleanToken = $authTokenStore.replace('Bearer ', ''); const cleanToken = $authTokenStore.replace('Bearer ', '');
@ -66,6 +63,7 @@
} }
try { try {
if(!client.isConnected) {
const connectResult = await client.connect($TAServerUrl, $TAServerPort); const connectResult = await client.connect($TAServerUrl, $TAServerPort);
if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) { if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
@ -73,6 +71,7 @@
loading = false; loading = false;
return; return;
} }
}
// Get tournaments from the client // Get tournaments from the client
const tournamentsList = client.stateManager.getTournaments(); const tournamentsList = client.stateManager.getTournaments();
@ -103,14 +102,14 @@
// Fetch authorized users for this tournament // Fetch authorized users for this tournament
// This initiates the API call immediately but doesn't block the map function // This initiates the API call immediately but doesn't block the map function
// const authorisedUsersPromise = fetchTournamentAuthorisedUsers(t.guid); // const authorisedUsersPromise = await fetchTournamentAuthorisedUsers(t.guid);
return { return {
id: t.guid.substring(0, 8), // Short ID for display id: t.guid.substring(0, 8), // Short ID for display
name: t.settings?.tournamentName || 'Unnamed Tournament', name: t.settings?.tournamentName || 'Unnamed Tournament',
image: imageUrl, image: imageUrl,
guid: t.guid, guid: t.guid,
// authorisedUsers: await authorisedUsersPromise // Wait for the promise to resolve // authorisedUsers: authorisedUsersPromise // Wait for the promise to resolve
}; };
})); }));
} catch (connErr) { } catch (connErr) {
@ -127,10 +126,10 @@
}); });
onDestroy(() => { onDestroy(() => {
if (client.isConnected == true) { // if (client.isConnected == true) {
// Properly disconnect and clean up any listeners // // Properly disconnect and clean up any listeners
client.disconnect(); // client.disconnect();
} // }
}); });
async function fetchTournamentAuthorisedUsers(tournamentGuid: string) { async function fetchTournamentAuthorisedUsers(tournamentGuid: string) {

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore } from "$lib/stores"; import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, client } from "$lib/stores";
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
import { bkAPIUrl } from '$lib/config.json'; import { bkAPIUrl } from '$lib/config.json';
//@ts-ignore //@ts-ignore
@ -33,8 +33,6 @@
In_Game = 2 In_Game = 2
} }
const client = new TAClient();
// Remove 'Bearer ' from the token // Remove 'Bearer ' from the token
if($authTokenStore) { if($authTokenStore) {
const cleanToken = $authTokenStore.replace('Bearer ', ''); const cleanToken = $authTokenStore.replace('Bearer ', '');
@ -63,8 +61,8 @@
} }
// Handle match status changes // Handle match status changes
const handleMatchUpdated = (params: any) => { function handleMatchUpdated(params: any) {
console.log(params); console.log("matchUpdate", params);
if (params.guid === tournamentGuid) { if (params.guid === tournamentGuid) {
// Update matches list // Update matches list
fetchTournamentData(); fetchTournamentData();
@ -72,7 +70,7 @@
}; };
// Handle match deletion // Handle match deletion
const handleMatchDeleted = (matchInfo: [Match, Tournament]) => { function handleMatchDeleted(matchInfo: any) {
if (matchInfo[1].guid === tournamentGuid) { if (matchInfo[1].guid === tournamentGuid) {
// Update matches list // Update matches list
fetchTournamentData(); fetchTournamentData();
@ -95,16 +93,21 @@
if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) { if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
throw new Error(connectResult.details.connect.message); throw new Error(connectResult.details.connect.message);
} }
}
tournament = client.stateManager.getTournament(tournamentGuid);
if(!tournament?.users.some(user => user.guid == client.stateManager.getSelfGuid())) {
const joinResult = await client.joinTournament(tournamentGuid); const joinResult = await client.joinTournament(tournamentGuid);
if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) { if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) {
throw new Error('Could not join tournament'); throw new Error('Could not join tournament');
} }
tournament = joinResult.details.join.state?.tournaments.find((x: Tournament) => x.guid === tournamentGuid); tournament = joinResult.details.join.state?.tournaments.find((x: Tournament) => x.guid === tournamentGuid);
console.log("tournament", tournament)
} }
if(client.stateManager.getTournaments().some(tournament => tournament.users.some(user => user.guid == client.stateManager.getSelfGuid() && user.clientType == 1))) {
}
// Wait for state to be fully initialized // Wait for state to be fully initialized
await new Promise(resolve => setTimeout(resolve, 1000)); await new Promise(resolve => setTimeout(resolve, 1000));
@ -113,7 +116,7 @@
matches = client.stateManager.getMatches(tournamentGuid) || []; matches = client.stateManager.getMatches(tournamentGuid) || [];
// Get all users for this tournament // Get all users for this tournament
const allUsers = client.stateManager.getUsers(tournamentGuid)!.filter(x => x.clientType === 0) || []; const allUsers = tournament!.users.filter(x => x.clientType === 0) || [];
// Get users not in matches // Get users not in matches
let allUsersGuidArray = allUsers.map(user => user.guid); let allUsersGuidArray = allUsers.map(user => user.guid);
@ -121,16 +124,22 @@
matches.forEach(match => { matches.forEach(match => {
match.associatedUsers.forEach(async(userGuid) => { match.associatedUsers.forEach(async(userGuid) => {
if(allUsersGuidArray.includes(userGuid)){ if(allUsersGuidArray.includes(userGuid)){
let discordInfo = await client.getDiscordInfo(tournamentGuid, userGuid);
console.log("discordInfo", discordInfo)
console.log(await client.stateManager.getUser(tournamentGuid, (discordInfo as any).details.getDiscordInfo.discordId))
usersInMatches.add(userGuid); usersInMatches.add(userGuid);
} }
}); });
}); });
availablePlayers = allUsers.filter(user => !usersInMatches.has(user.guid)); availablePlayers = allUsers.filter(user => !matches.some(match => match.associatedUsers.includes(user.guid)));
client.on('createdMatch', (params) => {
console.log("paramsUpdate", params)
});
client.on('updatedMatch', (params) => {
console.log("paramsUpdate", params)
})
client.on('deletedMatch', handleMatchDeleted);
} catch (err) { } catch (err) {
console.error('Error fetching tournament data:', err); console.error('Error fetching tournament data:', err);
error = err instanceof Error ? err.message : 'An unknown error occurred'; error = err instanceof Error ? err.message : 'An unknown error occurred';
@ -141,22 +150,29 @@
} }
} }
async function createMatch() {
const response = await client.createMatch(tournament!.guid, {
guid: '00000000-0000-4000-00000000',
leader: client.stateManager.getSelfGuid(),
associatedUsers: $selectedPlayerGuids
});
console.log(response)
}
onMount(async() => { onMount(async() => {
if ($authTokenStore) { if ($authTokenStore) {
await fetchTournamentData(); await fetchTournamentData();
} else { } else {
window.location.href = "/discordAuth" window.location.href = "/discordAuth"
} }
client.on('createdMatch', handleMatchUpdated);
// client.on('deletedMatch', handleMatchDeleted);
}); });
onDestroy(() => { onDestroy(() => {
// client.stateManager.removeListener('matchUpdated', handleMatchUpdated); client.stateManager.removeListener('matchUpdated', handleMatchUpdated);
// client.stateManager.removeListener('matchDeleted', handleMatchDeleted); client.stateManager.removeListener('matchDeleted', handleMatchDeleted);
client.removeListener('createdMatch', handleMatchUpdated) client.removeListener('createdMatch', handleMatchUpdated)
client.disconnect(); // client.disconnect();
}); });
</script> </script>
@ -200,20 +216,19 @@
<div class="match-card"> <div class="match-card">
<div class="match-header"> <div class="match-header">
<div class="match-status" style="background-color: {match.selectedMap ? 'var(--danger-color)' : '#FCD34D'}"></div> <div class="match-status" style="background-color: {match.selectedMap ? 'var(--danger-color)' : '#FCD34D'}"></div>
<h4>{'Unnamed Match'}</h4> <h4>
<!-- <img
src={tournament?.users.find(x => x.guid == match.leader)?.discordInfo?.avatarUrl || "https://api.dicebear.com/7.x/identicon/svg?seed=" + tournament?.users.find(x => x.guid == match.leader)?.guid}
alt="Player"
FIX THIS class="player-avatar"
/>
{tournament?.users.find(x => x.guid == match.leader)?.discordInfo?.username}'s Match
</h4>
-->
</div> </div>
<div class="match-players"> <div class="match-players">
{#if match.associatedUsers && match.associatedUsers.length > 0} {#if match.associatedUsers && match.associatedUsers.length > 0}
{#each match.associatedUsers as userGuid} {#each match.associatedUsers as userGuid}
{#if client.stateManager.getUser(tournamentGuid, userGuid)} {#if client.stateManager.getUser(tournamentGuid, userGuid) && client.stateManager.getUser(tournamentGuid, userGuid)?.clientType == 0}
<div class="player-chip"> <div class="player-chip">
<img src={client.stateManager.getUser(tournamentGuid, userGuid)?.discordInfo?.avatarUrl || "https://api.dicebear.com/7.x/identicon/svg?seed=" + userGuid} <img src={client.stateManager.getUser(tournamentGuid, userGuid)?.discordInfo?.avatarUrl || "https://api.dicebear.com/7.x/identicon/svg?seed=" + userGuid}
alt="Player" alt="Player"
@ -262,7 +277,7 @@
alt="Player" alt="Player"
class="player-avatar"> class="player-avatar">
<div class="player-info"> <div class="player-info">
<h4>{player.discordInfo.username}</h4> <h4>{player.name} ({player.discordInfo.username})</h4>
<p>{PlayerPlayState[player.playState]}</p> <p>{PlayerPlayState[player.playState]}</p>
</div> </div>
</div> </div>
@ -276,7 +291,7 @@
<div class="selection-bar"> <div class="selection-bar">
<p>{$selectedPlayerGuids.length} players selected</p> <p>{$selectedPlayerGuids.length} players selected</p>
<div class="selection-actions"> <div class="selection-actions">
<button class="action-button create-match"> <button class="action-button create-match" on:click={createMatch}>
<span class="material-icons">add</span> <span class="material-icons">add</span>
Create Match with Selection Create Match with Selection
</button> </button>

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore } from "$lib/stores"; import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore, client } from "$lib/stores";
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
//@ts-ignore //@ts-ignore
import { Match, Tournament, TAClient, Response_ResponseType, Map } from 'moons-ta-client'; import { Match, Tournament, TAClient, Response_ResponseType, Map } from 'moons-ta-client';
@ -50,8 +50,6 @@
let mapPoolToDelete: string | null = null; let mapPoolToDelete: string | null = null;
let mapPoolNameToDelete: string = ""; let mapPoolNameToDelete: string = "";
const client = new TAClient();
// Remove 'Bearer ' from the token // Remove 'Bearer ' from the token
if ($authTokenStore) { if ($authTokenStore) {
const cleanToken = $authTokenStore.replace('Bearer ', ''); const cleanToken = $authTokenStore.replace('Bearer ', '');
@ -144,18 +142,22 @@
error = null; error = null;
try { try {
if(!client.isConnected) {
const connectResult = await client.connect($TAServerUrl, $TAServerPort); const connectResult = await client.connect($TAServerUrl, $TAServerPort);
if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) { if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
throw new Error(connectResult.details.connect.message); throw new Error(connectResult.details.connect.message);
} }
}
if(!client.stateManager.getTournament(tournamentGuid)!.users.some(user => user.guid == client.stateManager.getSelfGuid())) {
const joinResult = await client.joinTournament(tournamentGuid); const joinResult = await client.joinTournament(tournamentGuid);
if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) { if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) {
throw new Error('Could not join tournament'); throw new Error('Could not join tournament');
} }
}
tournament = joinResult.details.join.state?.tournaments.find((x: Tournament) => x.guid === tournamentGuid); tournament = client.stateManager.getTournament(tournamentGuid)!;
if(tournament?.settings?.enablePools == false) { if(tournament?.settings?.enablePools == false) {
error = "The map pools feature is not enabled for this tournament. Please enable it in the Settings section."; error = "The map pools feature is not enabled for this tournament. Please enable it in the Settings section.";
@ -194,10 +196,6 @@
window.location.href = "/discordAuth" window.location.href = "/discordAuth"
} }
}); });
onDestroy(() => {
client.disconnect();
});
</script> </script>
<div class="layout"> <div class="layout">

View file

@ -2,7 +2,7 @@
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
//@ts-ignore //@ts-ignore
import { TAClient, Response_ResponseType, Map, Tournament, GameplayModifiers_GameOptions } from 'moons-ta-client'; import { TAClient, Response_ResponseType, Map, Tournament, GameplayModifiers_GameOptions } from 'moons-ta-client';
import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore } from "$lib/stores"; import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, client } from "$lib/stores";
import { bufferToImageUrl } from "$lib/services/taImages.js"; import { bufferToImageUrl } from "$lib/services/taImages.js";
import SideMenu from "$lib/components/menus/SideMenuTournaments.svelte"; import SideMenu from "$lib/components/menus/SideMenuTournaments.svelte";
import Popup from "$lib/components/notifications/Popup.svelte"; import Popup from "$lib/components/notifications/Popup.svelte";
@ -108,8 +108,6 @@
let showSuccessNotification = false; let showSuccessNotification = false;
let successMessage = ""; let successMessage = "";
const client = new TAClient();
// Remove 'Bearer ' from the token // Remove 'Bearer ' from the token
if ($authTokenStore) { if ($authTokenStore) {
const cleanToken = $authTokenStore.replace('Bearer ', ''); const cleanToken = $authTokenStore.replace('Bearer ', '');
@ -206,17 +204,17 @@
if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) { if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
throw new Error(connectResult.details.connect.message); throw new Error(connectResult.details.connect.message);
} }
}
if(!client.stateManager.getTournament(tournamentGuid)!.users.some(user => user.guid == client.stateManager.getSelfGuid())) {
const joinResult = await client.joinTournament(tournamentGuid); const joinResult = await client.joinTournament(tournamentGuid);
if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) { if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) {
throw new Error('Could not join tournament'); throw new Error('Could not join tournament');
} }
tournament = await joinResult.details.join.state?.tournaments.find((x: Tournament) => x.guid === tournamentGuid);
} else {
tournament = await client.stateManager.getTournament(tournamentGuid)!;
} }
tournament = client.stateManager.getTournament(tournamentGuid)!;
// Find the map pool with the specified GUID // Find the map pool with the specified GUID
const pool = await tournament?.settings?.pools.find(p => p.guid === poolGuid); const pool = await tournament?.settings?.pools.find(p => p.guid === poolGuid);
@ -265,10 +263,6 @@
window.location.href = "/discordAuth"; window.location.href = "/discordAuth";
} }
}); });
onDestroy(() => {
client.disconnect();
});
</script> </script>
<div class="layout"> <div class="layout">

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore } from "$lib/stores"; import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore, client } from "$lib/stores";
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
import { bkAPIUrl } from '$lib/config.json'; import { bkAPIUrl } from '$lib/config.json';
import AddNewAuthorisedUser from "$lib/components/popups/AddNewAuthorisedUser.svelte"; import AddNewAuthorisedUser from "$lib/components/popups/AddNewAuthorisedUser.svelte";
@ -61,8 +61,6 @@
"View and Administrator" = 3 "View and Administrator" = 3
} }
const client = new TAClient();
// Remove 'Bearer ' from the token // Remove 'Bearer ' from the token
if($authTokenStore) { if($authTokenStore) {
const cleanToken = $authTokenStore.replace('Bearer ', ''); const cleanToken = $authTokenStore.replace('Bearer ', '');
@ -218,18 +216,22 @@
error = null; error = null;
try { try {
if(!client.isConnected) {
const connectResult = await client.connect($TAServerUrl, $TAServerPort); const connectResult = await client.connect($TAServerUrl, $TAServerPort);
if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) { if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
throw new Error(connectResult.details.connect.message); throw new Error(connectResult.details.connect.message);
} }
}
if(!client.stateManager.getTournament(tournamentGuid)!.users.some(user => user.guid == client.stateManager.getSelfGuid())) {
const joinResult = await client.joinTournament(tournamentGuid); const joinResult = await client.joinTournament(tournamentGuid);
if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) { if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) {
throw new Error('Could not join tournament'); throw new Error('Could not join tournament');
} }
}
tournament = joinResult.details.join.state?.tournaments.find((x: Tournament) => x.guid === tournamentGuid); tournament = client.stateManager.getTournament(tournamentGuid)!;
// Set initial values from tournament data // Set initial values from tournament data
if (tournament) { if (tournament) {
@ -284,10 +286,6 @@
window.location.href = "/discordAuth" window.location.href = "/discordAuth"
} }
}); });
onDestroy(() => {
client.disconnect();
});
</script> </script>
<div class="layout"> <div class="layout">

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore } from "$lib/stores"; import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore, client } from "$lib/stores";
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
//@ts-ignore //@ts-ignore
import { Match, Tournament, TAClient, Response_ResponseType } from 'moons-ta-client'; import { Match, Tournament, TAClient, Response_ResponseType } from 'moons-ta-client';
@ -50,8 +50,6 @@
// File upload // File upload
let fileInput: HTMLInputElement; let fileInput: HTMLInputElement;
const client = new TAClient();
// Remove 'Bearer ' from the token // Remove 'Bearer ' from the token
if ($authTokenStore) { if ($authTokenStore) {
const cleanToken = $authTokenStore.replace('Bearer ', ''); const cleanToken = $authTokenStore.replace('Bearer ', '');
@ -165,18 +163,22 @@
error = null; error = null;
try { try {
if(!client.isConnected) {
const connectResult = await client.connect($TAServerUrl, $TAServerPort); const connectResult = await client.connect($TAServerUrl, $TAServerPort);
if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) { if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
throw new Error(connectResult.details.connect.message); throw new Error(connectResult.details.connect.message);
} }
}
if(!client.stateManager.getTournament(tournamentGuid)!.users.some(user => user.guid == client.stateManager.getSelfGuid())) {
const joinResult = await client.joinTournament(tournamentGuid); const joinResult = await client.joinTournament(tournamentGuid);
if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) { if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) {
throw new Error('Could not join tournament'); throw new Error('Could not join tournament');
} }
}
tournament = joinResult.details.join.state?.tournaments.find((x: Tournament) => x.guid === tournamentGuid); tournament = client.stateManager.getTournament(tournamentGuid)!;
if(tournament?.settings?.enableTeams == false) { if(tournament?.settings?.enableTeams == false) {
error = "The teams feature is not enabled for this tournament. Please enable it in the Settings section."; error = "The teams feature is not enabled for this tournament. Please enable it in the Settings section.";
@ -216,10 +218,6 @@
window.location.href = "/discordAuth" window.location.href = "/discordAuth"
} }
}); });
onDestroy(() => {
client.disconnect();
});
</script> </script>
<div class="layout"> <div class="layout">