fetch() changes in all svelte

+ miscs front refactoring
This commit is contained in:
LuckyLaszlo
2023-01-16 18:03:08 +01:00
parent 36f13cb5af
commit 314fa10cff
9 changed files with 522 additions and 424 deletions

View File

@@ -1,30 +1,36 @@
<script lang="ts">
import Canvas from "../pieces/Canvas.svelte";
import { push } from "svelte-spa-router";
import { onMount } from 'svelte';
import { push } from "svelte-spa-router";
import { onMount } from 'svelte';
let user;
import { fetchUser } from "../pieces/utils";
let user;
onMount(async () => {
user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`)
.then((resp) => resp.json())
if (user && user.statusCode && user.statusCode === 403) {
console.log('on mount no user, returned status code 403 so logging out of userStore')
}
user = await fetchUser();
});
const login = async() => {
window.location.href = `http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth`;
console.log('you are now logged in');
}
const login = async() => {
window.location.href = `http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth`;
console.log('you are now logged in');
}
const logout = async() => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth/logout`, {
method: 'POST',
});
user = undefined;
const logout = async() => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth/logout`,
{
method: 'POST'
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch logout: ", error);
});
user = null;
};
</script>

View File

@@ -1,44 +1,59 @@
<script lang="ts">
import { onMount } from "svelte";
import { push } from "svelte-spa-router";
import { onMount } from "svelte";
import { push } from "svelte-spa-router";
let qrCodeImg;
let qrCode = "";
let wrongCode = "";
const fetchQrCodeImg = (async () => {
qrCodeImg = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth/2fa/generate`,
{
method: "POST",
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.blob();
})
.then((blob) => {
return URL.createObjectURL(blob);
})
.catch((error) => {
console.log("catch fetchQrCodeImg: ", error);
});
let qrCodeImg;
let qrCode = "";
let wrongCode = "";
const fetchQrCodeImg = (async() => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth/2fa/generate`,
{
method: 'POST',
})
.then(response => {return response.blob()})
.then(blob => {
const url = URL.createObjectURL(blob);
qrCodeImg = url;
});
})()
})();
const submitCode = async() => {
const response = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth/2fa/check`,
{
method : 'POST',
headers : {
"Content-Type": "application/json",
},
body : JSON.stringify({
"twoFaCode" : qrCode,
}),
});
if (response.status === 401) {
qrCode = "";
wrongCode = `Wrong code`;
}
if (response.status === 200) {
push('/profile');
console.log('valid Code for 2FA')
}
};
const submitCode = async () => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth/2fa/check`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
twoFaCode: qrCode,
}),
}
)
.then((response) => {
if (!response.ok) {
if (response.status === 401) {
qrCode = "";
wrongCode = `Wrong code`;
}
throw new Error("HTTP " + response.status);
}
push("/profile");
console.log("valid Code for 2FA");
})
.catch((error) => {
console.log("catch submitCode: ", error);
});
};
</script>

View File

@@ -1,28 +1,37 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { fetchUser } from "../../pieces/utils";
let user;
let allUsersRanking = [];
let fetchScoresInterval;
//user's stuff
let currentUser;
let allUsers = [];
let idInterval;
onMount( async() => {
currentUser = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`)
.then( x => x.json() );
allUsers = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/ranking`)
.then( x => x.json() );
idInterval = setInterval(fetchScores, 10000);
user = await fetchUser();
allUsersRanking = await fetchScores();
fetchScoresInterval = setInterval(fetchScores, 10000);
})
onDestroy( async() => {
clearInterval(idInterval);
clearInterval(fetchScoresInterval);
})
function fetchScores() {
fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/ranking`)
.then( x => x.json() )
.then( x => allUsers = x );
async function fetchScores()
{
return fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/ranking`)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
})
.catch((error) => {
console.log("catch fetchScores: ", error);
return [];
});
}
</script>
@@ -41,18 +50,18 @@
</tr>
</thead>
<tbody>
{#each allUsers as user, i}
{#each allUsersRanking as userRanking, i}
<tr>
<th>{i + 1}</th>
{#if user.username === currentUser.username}
<td><b>{user.username} [You]</b></td>
{#if userRanking.username === user.username}
<td><b>{userRanking.username} [You]</b></td>
{:else}
<td>{user.username}</td>
<td>{userRanking.username}</td>
{/if}
<td>{user.stats.winGame}</td>
<td>{user.stats.loseGame}</td>
<td>{user.stats.drawGame}</td>
<td>{user.stats.totalGame}</td>
<td>{userRanking.stats.winGame}</td>
<td>{userRanking.stats.loseGame}</td>
<td>{userRanking.stats.drawGame}</td>
<td>{userRanking.stats.totalGame}</td>
</tr>
{/each}
</tbody>

View File

@@ -1,19 +1,17 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount } from 'svelte';
import GenerateUserDisplay from '../../pieces/GenerateUserDisplay.svelte';
import { push } from 'svelte-spa-router';
import { push } from 'svelte-spa-router';
import Chat from '../../pieces/chat/Chat.svelte';
import { fetchUser } from "../../pieces/utils";
let user;
onMount( async() => {
// console.log('mounting profile display')
user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`)
.then( (x) => x.json() );
})
let user;
onMount( async() => {
user = await fetchUser();
})
</script>
@@ -21,7 +19,7 @@
<div class="background-pages">
<div class="outer">
{#if user !== undefined}
{#if user}
<GenerateUserDisplay user={user}/>
<button on:click={() => (push('/profile/settings'))}>Profile Settings</button>
{:else}

View File

@@ -1,32 +1,25 @@
<script lang="ts">
/* ProfileDisplayOneUser is the same as DisplayAUser except sources the username from params from router rather than
from a regular var. But yea it's functionally identical, seemed easier to just have a duplicate rather than figuring
out how to get a more complicated things to do 2 jobs.*/
/* ProfileDisplayOneUser is the same as DisplayAUser except sources the username from params from router rather than
from a regular var. But yea it's functionally identical, seemed easier to just have a duplicate rather than figuring
out how to get a more complicated things to do 2 jobs.*/
import { onMount } from 'svelte';
import GenerateUserDisplay from '../../pieces/GenerateUserDisplay.svelte';
import { fetchUser } from "../../pieces/utils";
import { onMount } from 'svelte';
import GenerateUserDisplay from '../../pieces/GenerateUserDisplay.svelte';
export let params;
let oneUser;
export let params;
let user;
onMount( async() => {
oneUser = await fetchUser(params.username);
})
onMount( async() => {
// console.log('Display One User username: '+ params.username)
user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user?username=${params.username}`)
.then( (x) => x.json() );
console.log('in display ONE user')
console.log({...user})
})
</script>
<div class="background-pages">
{#if user !== undefined}
<GenerateUserDisplay user={user}/>
{#if oneUser}
<GenerateUserDisplay user={oneUser}/>
{:else}
<h2>Sorry</h2>
<div>Failed to load user {params.username}</div>
@@ -35,4 +28,3 @@
<!-- This is where i might toss in an Invite to Game button ? -->
</div>

View File

@@ -1,81 +1,89 @@
<script lang="ts">
import Card from '../../pieces/Card.svelte';
import {onMount} from 'svelte';
import { push } from 'svelte-spa-router';
import Button from '../../pieces/Button.svelte';
import { fetchAvatar } from "../../pieces/utils";
import Card from '../../pieces/Card.svelte';
import {onMount} from 'svelte';
import { push } from 'svelte-spa-router';
import Button from '../../pieces/Button.svelte';
import { fetchUser, fetchAvatar } from "../../pieces/utils";
let user;
let avatar, newAvatar;
let uploadAvatarSuccess = false;
let user;
let avatar, newAvatar;
let uploadAvatarSuccess = false;
// tbh i might not need this...
let set = { username: '', tfa: false };
let nameTmp; // annoying...
const errors = { username: '', checkbox: '', avatar: ''};
let success = {username: '', avatar: '' };
// tbh i might not need this...
let set = { username: '', tfa: false };
let nameTmp; // annoying...
const errors = { username: '', checkbox: '', avatar: ''};
let success = {username: '', avatar: '' };
onMount( async() => {
user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`)
.then( (x) => x.json() );
// do a .catch?
user = await fetchUser();
avatar = await fetchAvatar();
if (user === undefined) {
if (!user) {
console.log('User did not load, something more official should prolly happen')
}
// i don't unerstand why this is necessary but it really doesn't like it otherwise
nameTmp = user.username;
set.tfa = user.isEnabledTwoFactorAuth;
avatar = await fetchAvatar(user.username);
})
const settingsHandler = async() => {
// I don't really care which i use at this point...
// if (set.username === nameTmp) {
if ((set.username.trim() === '') && set.tfa === user.isEnabledTwoFactorAuth) {
errors.username = 'Invalid new username';
return;
}
else if ((set.username.trim() === '') && set.tfa !== user.isEnabledTwoFactorAuth) {
set.username = user.username
}
else {
errors.username = '';
}
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"username": set.username,
"isEnabledTwoFactorAuth": set.tfa
})
})
.then((response) => {
if (response.status === 200)
success.username = "Your changes have been saved"
else if (response.status === 201)
push("/2fa");
else if (response.status === 409)
errors.username = `${set.username} is already in use, pick a different one.`;
else
errors.username = "Something went wrong";
const settingsHandler = async() =>
{
// TODO Luke <--> Eric : Explications
// I don't really care which i use at this point...
// if (set.username === nameTmp) {
if ((set.username.trim() === '') && set.tfa === user.isEnabledTwoFactorAuth) {
errors.username = 'Invalid new username';
return;
}
else if ((set.username.trim() === '') && set.tfa !== user.isEnabledTwoFactorAuth) {
set.username = user.username
}
else {
errors.username = '';
}
)
.catch((err) => errors.username = err)
// .then((result) => console.log(result))
// .then(() => console.log('successful sub of new settings'))
};
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`,
{
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"username": set.username,
"isEnabledTwoFactorAuth": set.tfa
})
}
)
.then((response) => {
if (!response.ok) {
errors.username = "Something went wrong";
if (response.status === 409) {
errors.username = `${set.username} is already in use, pick a different one.`;
}
throw new Error("HTTP " + response.status);
}
else {
if (response.status === 200) {
success.username = "Your changes have been saved";
}
else if (response.status === 201) {
push("/2fa");
}
}
})
.catch((error) => {
console.log("catch settingsHandler: ", error);
});
}
const uploadAvatar = async() => {
errors.avatar = '';
if (newAvatar === undefined) {
if (!newAvatar) {
errors.avatar = 'You need to pick a file.'
return;
}
@@ -85,19 +93,23 @@
// tmp
console.log(data);
const responseWhenChangeAvatar = fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user/avatar`,
{
method : 'POST',
body : data,
})
const responseFromServer = await responseWhenChangeAvatar;
if (responseFromServer.ok === true) {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user/avatar`,
{
method : 'POST',
body : data,
}
)
.then((response) => {
if (!response.ok) {
errors.avatar = response.statusText;
throw new Error("HTTP " + response.status);
}
uploadAvatarSuccess = true;
success.avatar = 'Your avatar has been updated';
}
else {
errors.avatar = responseFromServer.statusText;
}
})
.catch((error) => {
console.log("catch uploadAvatar: ", error);
});
avatar = await fetchAvatar(user.username);
}
@@ -130,7 +142,7 @@
<Card>
<!-- ok so it can't actually show us the file we upload until we've uploaded it... -->
{#if avatar !== undefined}
{#if avatar}
<img class="avatar" src={avatar} alt="your avatar"/>
{/if}
<form on:submit|preventDefault={uploadAvatar}>
@@ -141,7 +153,7 @@
<input type="file" bind:files={newAvatar}/>
<div class="error">{errors.avatar}</div>
</div>
<Button type={newAvatar === undefined ? "primary" : "secondary"}>Upload Avatar</Button>
<Button type={!newAvatar ? "primary" : "secondary"}>Upload Avatar</Button>
</form>
</Card>
</div>

View File

@@ -1,232 +1,294 @@
<script lang="ts">
import { onMount } from "svelte";
import Button from "../../pieces/Button.svelte";
import DisplayAUser from "../../pieces/DisplayAUser.svelte";
import Tabs from "../../pieces/Tabs.svelte";
import { fetchUser, fetchAllUsers, fetchAvatar } from "../../pieces/utils";
import { onMount } from "svelte";
import Button from "../../pieces/Button.svelte";
import DisplayAUser from "../../pieces/DisplayAUser.svelte";
import Tabs from "../../pieces/Tabs.svelte";
let user;
let allUsers = [];
let myFriendships = [];
let requestsMade, requestsRecieved;
let blockedUsers = [];
let usernameBeingViewed;
let friendshipStatusFull; // date, reveiverUsername, status
let user;
let allUsers;
let myFriendships;
let requestsMade, requestsRecieved;
let blockedUsers;
let usernameBeingViewed;
let friendshipStatusFull; // date, reveiverUsername, status
/**** Layout variables ****/
let tabItems: string[] = [
"All Users",
"My Friends",
"Friend Requests",
"Blocked Users",
];
let activeTabItem: string = "All Users";
/**** Layout variables ****/
let tabItems: string[] = ['All Users', 'My Friends', 'Friend Requests', 'Blocked Users']
let activeTabItem: string = 'All Users';
onMount(async () => {
user = await fetchUser();
fetchAll();
});
onMount( async() => {
user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`)
.then( (x) => x.json() );
const fetchAll = async () => {
// no need to await i think it can load in the background
fetchAllUsers_Wrapper();
fetchMyFriendships();
fetchRequestsMade();
fetchRequestsReceived();
fetchBlockedUsers();
};
fetchAll();
});
/***** Fetch basic things *****/
const fetchAllUsers_Wrapper = async () => {
allUsers = await fetchAllUsers();
if (usernameBeingViewed) {
let found = allUsers.find(
(e) => e.username === usernameBeingViewed
);
if (!found) {
usernameBeingViewed = null;
friendshipStatusFull = null;
}
}
};
const fetchAll = async() => {
// no need to await i think it can load in the background
fetchAllUsers();
fetchMyFriendships();
fetchRequestsMade();
fetchRequestsReceived();
fetchBlockedUsers();
}
// it's more like fetch friendships
// then i need to extract the users
const fetchMyFriendships = async () => {
myFriendships = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/myfriends`)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
})
.catch((error) => {
console.log("catch fetchMyFriendships: ", error);
return [];
});
};
/***** Fetch basic things *****/
const fetchAllUsers = async() => {
allUsers = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user/all`)
.then( x => x.json() );
console.log('got all users ')
console.log({...allUsers})
if (usernameBeingViewed !== undefined) {
let found = allUsers.find(e => e.username === usernameBeingViewed);
// console.log("SEARCHING ALL USERS: ")
// console.log({...found})
if (found === undefined) {
// console.log('none found')
usernameBeingViewed = undefined;
friendshipStatusFull = undefined;
}
}
};
const fetchRequestsMade = async () => {
requestsMade = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/pending`)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
})
.catch((error) => {
console.log("catch fetchRequestsMade: ", error);
return [];
});
};
// it's more like fetch friendships
// then i need to extract the users
const fetchMyFriendships = async() => {
myFriendships = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/myfriends`)
.then( x => x.json() );
const fetchRequestsReceived = async () => {
requestsRecieved = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/received`)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
})
.catch((error) => {
console.log("catch fetchRequestsReceived: ", error);
return [];
});
};
console.log('got my friends ')
console.log({...myFriendships})
};
const fetchBlockedUsers = async () => {
blockedUsers = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/blocked`)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
})
.catch((error) => {
console.log("catch fetchBlockedUsers: ", error);
return [];
});
};
/**** END OF MAIN FETCH ****/
const fetchRequestsMade = async() => {
requestsMade = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/pending`)
.then( x => x.json() );
// returns everything but BLOCKED
const fetchFriendshipFull = async (aUsername) => {
friendshipStatusFull = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/myfriends?username=${aUsername}`)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
})
.catch((error) => {
console.log("catch fetchFriendshipFull: ", error);
return [];
});
};
console.log('got requests made ')
console.log({...requestsMade})
};
const sendFriendRequest = async (aUsername) => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
receiverUsername: aUsername,
status: "R",
}),
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch sendFriendRequest: ", error);
});
const fetchRequestsReceived = async() => {
requestsRecieved = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/received`)
.then( x => x.json() );
await fetchFriendshipFull(aUsername);
await fetchAll();
};
console.log('got requests received ')
console.log({...requestsRecieved})
};
const viewAUser = async (aUsername) => {
usernameBeingViewed = aUsername;
await fetchFriendshipFull(aUsername);
};
const fetchBlockedUsers = async() => {
blockedUsers = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/blocked`)
.then( x => x.json() );
const acceptFriendRequest = async (relationshipId) => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations/${relationshipId}/accept`,
{
method: "PATCH",
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch acceptFriendRequest: ", error);
});
console.log('got blocked users, is it empty?')
console.log({...blockedUsers})
console.log(Object.keys(blockedUsers))
};
/**** END OF MAIN FETCH ****/
await fetchFriendshipFull(usernameBeingViewed);
await fetchAll();
activeTabItem = activeTabItem;
};
// returns everything but BLOCKED
const fetchFriendshipFull = async(aUsername) => {
console.log('fetch friendship from a username')
console.log(aUsername)
const declineFriendRequest = async (relationshipId) => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations/${relationshipId}/decline`,
{
method: "PATCH",
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch declineFriendRequest: ", error);
});
friendshipStatusFull = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/myfriends?username=${aUsername}`)
.then( x => x.json());
await fetchFriendshipFull(usernameBeingViewed);
await fetchAll();
activeTabItem = activeTabItem;
};
console.log({...friendshipStatusFull})
};
const unfriend = async (relationshipId) => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations/${relationshipId}`,
{
method: "DELETE",
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch unfriend: ", error);
});
const sendFriendRequest = async(aUsername) => {
console.log('sending a friend request')
console.log(aUsername)
await fetchFriendshipFull(usernameBeingViewed);
if (Object.keys(friendshipStatusFull).length === 0) {
friendshipStatusFull = null;
}
const resp = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations`, {
method : "POST",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
"receiverUsername": aUsername,
"status": "R"
})
})
.then( x => x.json())
// .catch( x => console.log({...x}))
await fetchFriendshipFull(aUsername);
await fetchAll();
};
await fetchAll();
activeTabItem = activeTabItem;
};
const viewAUser = async(aUsername) => {
console.log('Profile Friend updating userBeingViewed')
const blockANonFriendUser = async (aUsername) => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
receiverUsername: aUsername,
status: "B",
}),
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch blockANonFriendUser: ", error);
});
usernameBeingViewed = aUsername;
await fetchFriendshipFull(aUsername);
await fetchAll();
usernameBeingViewed = null;
friendshipStatusFull = null;
console.log('Friendship Status Full')
console.log({...friendshipStatusFull})
};
activeTabItem = activeTabItem;
};
const acceptFriendRequest = async(relationshipId) => {
console.log('accept friend request')
const blockAFriend = async (relationshipId) => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations/${relationshipId}/block`,
{
method: "PATCH"
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch blockAFriend: ", error);
});
const resp = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations/${relationshipId}/accept`, {
method: "PATCH"})
.then( x => x.json());
await fetchFriendshipFull(usernameBeingViewed);
await fetchAll();
activeTabItem = activeTabItem;
};
await fetchAll();
usernameBeingViewed = null;
friendshipStatusFull = null;
const declineFriendRequest = async(relationshipId) => {
console.log('decline friend request')
// reloads active tab so you get blocked users for example
activeTabItem = activeTabItem;
};
const resp = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations/${relationshipId}/decline`, {
method: "PATCH"})
.then( x => x.json());
await fetchFriendshipFull(usernameBeingViewed);
await fetchAll();
activeTabItem = activeTabItem;
};
const unfriend = async(relationshipId) => {
console.log('Unfriend')
const resp = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations/${relationshipId}`, {
method: "DELETE"})
.then( x => x.json());
await fetchFriendshipFull(usernameBeingViewed);
if (Object.keys(friendshipStatusFull).length === 0)
friendshipStatusFull = undefined;
await fetchAll();
activeTabItem = activeTabItem;
};
const blockANonFriendUser = async(aUsername) => {
console.log('Block a non friend user, their username')
console.log(aUsername)
let sentFriendRequest = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations`, {
method : "POST",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
"receiverUsername": aUsername,
"status": "B"
})
})
.then( x => x.json())
// await fetchBlockedUsers();
// await fetchAllUsers();
await fetchAll();
usernameBeingViewed = undefined;
friendshipStatusFull = undefined;
activeTabItem = activeTabItem;
};
const blockAFriend = async(relationshipId) => {
console.log('blocking a friend, the relationshipID')
console.log(relationshipId)
const resp = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/network/relations/${relationshipId}/block`, {method: "PATCH"})
.then( x => x.json() );
console.log('blocked a user response')
console.log({...resp})
// await fetchBlockedUsers();
// await fetchAllUsers();
await fetchAll();
usernameBeingViewed = undefined;
friendshipStatusFull = undefined;
// reloads active tab so you get blocked users for example
activeTabItem = activeTabItem;
};
const unblockAUser = async(relationshipId) => {
// it's basically the same as unfriending someone cuz unfriending them means the relationship is deleted
await unfriend(relationshipId);
activeTabItem = activeTabItem;
};
const switchTab = async(e) => {
activeTabItem = e.detail;
if (activeTabItem === 'All Users') {
await fetchAllUsers();
} else if (activeTabItem === 'My Friends') {
await fetchMyFriendships();
} else if (activeTabItem === 'Friend Requests') {
await fetchRequestsReceived();
} else if (activeTabItem === 'Blocked Users') {
await fetchBlockedUsers();
console.log('fetching blocked users')
}
if (usernameBeingViewed !== undefined)
fetchFriendshipFull(usernameBeingViewed);
};
const unblockAUser = async (relationshipId) => {
// it's basically the same as unfriending someone cuz unfriending them means the relationship is deleted
await unfriend(relationshipId);
activeTabItem = activeTabItem;
};
const switchTab = async (e) => {
activeTabItem = e.detail;
if (activeTabItem === "All Users") {
await fetchAllUsers_Wrapper();
} else if (activeTabItem === "My Friends") {
await fetchMyFriendships();
} else if (activeTabItem === "Friend Requests") {
await fetchRequestsReceived();
} else if (activeTabItem === "Blocked Users") {
await fetchBlockedUsers();
console.log("fetching blocked users");
}
if (usernameBeingViewed)
fetchFriendshipFull(usernameBeingViewed);
};
</script>
@@ -239,7 +301,7 @@
<div class="sidebar-list">
<Tabs items={tabItems} activeItem={activeTabItem} size="small" on:tabChange={switchTab}/>
{#if activeTabItem === 'All Users' && allUsers !== undefined}
{#if activeTabItem === 'All Users' && allUsers}
<h3>{activeTabItem}</h3>
{#if Object.keys(allUsers).length === 0}
<div class="tip">You are alone on this platform...</div>
@@ -255,7 +317,7 @@
<div class="status sidebar-item">{aUser.status}</div>
<br>
{/each}
{:else if activeTabItem === 'My Friends' && myFriendships !== undefined}
{:else if activeTabItem === 'My Friends' && myFriendships}
<h3>{activeTabItem}</h3>
{#if Object.keys(myFriendships).length === 0}
<div class="tip">You don't have any Friends... Yet!</div>
@@ -268,7 +330,7 @@
{/if}
<br>
{/each}
{:else if activeTabItem === 'Friend Requests' && requestsRecieved !== undefined}
{:else if activeTabItem === 'Friend Requests' && requestsRecieved}
<h3>{activeTabItem}</h3>
{#if Object.keys(requestsRecieved).length === 0}
<div class="tip">You don't have any Friend Requests</div>
@@ -278,7 +340,7 @@
<div class="status sidebar-item">{aUser.status}</div>
<br>
{/each}
{:else if activeTabItem === 'Blocked Users' && blockedUsers !== undefined}
{:else if activeTabItem === 'Blocked Users' && blockedUsers}
<h3>{activeTabItem}</h3>
<!-- seems a little excessive... maybe a lighter way of doing this? doesn't seem like it, i hate it but at least only happens sometimes.default... -->
{#if Object.keys(blockedUsers).length === 0}
@@ -294,7 +356,7 @@
<div class="main-display">
{#if usernameBeingViewed !== undefined}
{#if usernameBeingViewed}
<DisplayAUser aUsername={usernameBeingViewed}/>
<div class="buttons-area">

View File

@@ -1,30 +1,23 @@
<script lang="ts">
import { onMount } from 'svelte';
import GenerateUserDisplay from './GenerateUserDisplay.svelte';
import { onMount } from 'svelte';
import GenerateUserDisplay from './GenerateUserDisplay.svelte';
import { fetchUser } from "../pieces/utils";
export let aUsername;
let user;
export let aUsername;
let aUser;
onMount( async() => {
// console.log('Display aUser username: '+ aUsername)
onMount( async() => {
aUser = await fetchUser(aUsername);
})
user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user?username=${aUsername}`)
.then( (x) => x.json() );
})
export const updateUser = async() => {
user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user?username=${aUsername}`)
.then( (x) => x.json() );
};
$: aUsername, updateUser();
$: aUsername, fetchUser(aUsername);
</script>
<div class="background-pages">
{#if user !== undefined}
<GenerateUserDisplay user={user}/>
{#if aUser}
<GenerateUserDisplay user={aUser}/>
{:else}
<h2>Sorry</h2>
<div>Failed to load user {aUsername}</div>

View File

@@ -1,36 +1,47 @@
<script lang="ts">
import { push } from "svelte-spa-router";
import { location } from 'svelte-spa-router';
import { push } from "svelte-spa-router";
import { location } from 'svelte-spa-router';
// no need, it's just for links
import active from 'svelte-spa-router/active'
// or i could leave them all and not display if they're active?
// no need, it's just for links
import active from 'svelte-spa-router/active'
// or i could leave them all and not display if they're active?
$: current = $location;
$: current = $location;
let handleClickLogout = async () => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth/logout`, {
method: 'POST',
})
.then( () => push('/') )
console.log('clicked logout header')
};
let handleClickLogout = async () =>
{
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/auth/logout`,
{
method: 'POST',
}
)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch handleClickLogout: ", error);
});
push('/');
};
</script>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<div class="header">
<img src="/img/logo_potato.png" alt="Potato Pong Logo" on:click={() => (push('/'))}>
<div class="center">
<button class:selected="{current === '/game'}" on:click={() => (push('/game'))}>Play</button>
<button class:selected="{current === '/spectator'}" on:click={() => (push('/spectator'))}>Spectate</button>
<button class:selected="{current === '/ranking'}" on:click={() => (push('/ranking'))}>Ranking</button>
<button class:selected="{current === '/profile'}" on:click={() => (push('/profile'))}>My Profile</button>
<button class:selected="{current === '/profile/users'}" on:click={() => (push('/profile/users'))}>Users</button>
</div>
<button class="logout" on:click={handleClickLogout}>Log Out</button>
<img src="/img/logo_potato.png" alt="Potato Pong Logo" on:click={() => (push('/'))}>
<div class="center">
<button class:selected="{current === '/game'}" on:click={() => (push('/game'))}>Play</button>
<button class:selected="{current === '/spectator'}" on:click={() => (push('/spectator'))}>Spectate</button>
<button class:selected="{current === '/ranking'}" on:click={() => (push('/ranking'))}>Ranking</button>
<button class:selected="{current === '/profile'}" on:click={() => (push('/profile'))}>My Profile</button>
<button class:selected="{current === '/profile/users'}" on:click={() => (push('/profile/users'))}>Users</button>
</div>
<button class="logout" on:click={handleClickLogout}>Log Out</button>
</div>
<style>