fix data fetching and auto refresh data
All checks were successful
deploy / deploy (push) Successful in 58s

This commit is contained in:
Lee 2023-10-22 05:14:37 +01:00
parent f03ac7809d
commit e54d106a53
7 changed files with 229 additions and 83 deletions

@ -1,19 +1,9 @@
"use client"; "use client";
import { usePlayerScoresStore } from "@/store/playerScoresStore";
type AppProviderProps = { type AppProviderProps = {
children: React.ReactNode; children: React.ReactNode;
}; };
usePlayerScoresStore.getState().updatePlayerScores();
setTimeout(
() => {
usePlayerScoresStore.getState().updatePlayerScores();
},
1000 * 60 * 10,
); // fetch new scores every 10 minutes
export default function AppProvider({ children }: AppProviderProps) { export default function AppProvider({ children }: AppProviderProps) {
return <>{children}</>; return <>{children}</>;
} }

@ -1,7 +1,7 @@
import clsx from "clsx"; import clsx from "clsx";
interface ButtonProps { interface ButtonProps {
text: string; text: JSX.Element | string;
url: string; url: string;
icon?: JSX.Element; icon?: JSX.Element;
className?: string; className?: string;

@ -32,7 +32,7 @@ function NavbarButton({ text, icon, href, children }: ButtonProps) {
</a> </a>
{children && ( {children && (
<div className="absolute z-20 hidden divide-y rounded-md bg-neutral-600 shadow-sm group-hover:flex"> <div className="absolute z-20 hidden divide-y rounded-md bg-gray-600 opacity-[0.98] shadow-sm group-hover:flex">
<div className="p-2">{children}</div> <div className="p-2">{children}</div>
</div> </div>
)} )}
@ -61,7 +61,27 @@ export default function Navbar() {
)} )}
<NavbarButton text="Friends" icon={<UserIcon height={20} width={20} />}> <NavbarButton text="Friends" icon={<UserIcon height={20} width={20} />}>
{settingsStore?.friends.length == 0 ? (
<p className="text-sm font-bold">No friends, add someone!</p> <p className="text-sm font-bold">No friends, add someone!</p>
) : (
settingsStore?.friends.map((friend) => {
return (
<Button
key={friend.id}
className="mt-2 bg-gray-600"
text={friend.name}
url={`/player/${friend.id}`}
icon={
<Avatar
url={friend.profilePicture}
label={`${friend.name}'s avatar`}
size={20}
/>
}
/>
);
})
)}
<Button <Button
className="mt-2" className="mt-2"

@ -3,7 +3,11 @@ import { usePlayerScoresStore } from "@/store/playerScoresStore";
import { useSettingsStore } from "@/store/settingsStore"; import { useSettingsStore } from "@/store/settingsStore";
import { formatNumber } from "@/utils/number"; import { formatNumber } from "@/utils/number";
import { calcPpBoundary, getHighestPpPlay } from "@/utils/scoresaber/scores"; import { calcPpBoundary, getHighestPpPlay } from "@/utils/scoresaber/scores";
import { GlobeAsiaAustraliaIcon, HomeIcon } from "@heroicons/react/20/solid"; import {
GlobeAsiaAustraliaIcon,
HomeIcon,
UserIcon,
} from "@heroicons/react/20/solid";
import { useRef } from "react"; import { useRef } from "react";
import ReactCountryFlag from "react-country-flag"; import ReactCountryFlag from "react-country-flag";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
@ -29,8 +33,20 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
async function claimProfile() { async function claimProfile() {
settingsStore?.setUserId(playerId); settingsStore?.setUserId(playerId);
settingsStore?.refreshProfile(); addProfile(false);
}
async function addFriend() {
const friend = await settingsStore?.addFriend(playerData.id);
if (!friend) {
toast.error(`Failed to add ${playerData.name} as a friend`);
return;
}
addProfile(true);
}
async function addProfile(isFriend: boolean) {
if (!usePlayerScoresStore.getState().exists(playerId)) {
const reponse = await playerScoreStore?.addPlayer( const reponse = await playerScoreStore?.addPlayer(
playerId, playerId,
(page, totalPages) => { (page, totalPages) => {
@ -52,18 +68,27 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
}); });
} }
console.log(`Fetching scores for ${playerId} (${page}/${totalPages})`); console.log(
`Fetching scores for ${playerId} (${page}/${totalPages})`,
);
}, },
); );
if (reponse?.error) { if (reponse?.error) {
toast.error("Failed to claim profile"); toast.error("Failed to fetch scores");
console.log(reponse.message); console.log(reponse.message);
return; return;
} }
toast.success("Successfully claimed profile");
} }
if (!isFriend) {
toast.success(`Successfully set ${playerData.name} as your profile`);
} else {
toast.success(`Successfully added ${playerData.name} as a friend`);
}
}
const isOwnProfile = settingsStore?.userId == playerId;
return ( return (
<Card className="mt-2"> <Card className="mt-2">
{/* Player Info */} {/* Player Info */}
@ -76,14 +101,21 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
{/* Settings Buttons */} {/* Settings Buttons */}
<div className="absolute right-3 top-20 flex flex-col justify-end gap-2 md:relative md:right-0 md:top-0 md:mt-2 md:flex-row md:justify-center"> <div className="absolute right-3 top-20 flex flex-col justify-end gap-2 md:relative md:right-0 md:top-0 md:mt-2 md:flex-row md:justify-center">
{settingsStore?.userId !== playerId && ( {!isOwnProfile && (
<button> <button
<HomeIcon className="h-fit w-fit rounded-md bg-blue-500 p-1 hover:bg-blue-600"
title="Set as your Profile"
width={28}
height={28}
onClick={claimProfile} onClick={claimProfile}
/> >
<HomeIcon title="Set as your Profile" width={24} height={24} />
</button>
)}
{!settingsStore?.isFriend(playerId) && !isOwnProfile && (
<button
className="rounded-md bg-blue-500 p-1 hover:bg-blue-600"
onClick={addFriend}
>
<UserIcon title="Add as Friend" width={24} height={24} />
</button> </button>
)} )}
</div> </div>

@ -2,21 +2,23 @@
import { ScoresaberPlayerScore } from "@/schemas/scoresaber/playerScore"; import { ScoresaberPlayerScore } from "@/schemas/scoresaber/playerScore";
import { fetchAllScores, fetchScores } from "@/utils/scoresaber/api"; import { fetchAllScores, fetchScores } from "@/utils/scoresaber/api";
import moment from "moment";
import { create } from "zustand"; import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware"; import { createJSONStorage, persist } from "zustand/middleware";
import { useSettingsStore } from "./settingsStore";
type Player = { type Player = {
lastUpdated: number;
id: string; id: string;
scores: ScoresaberPlayerScore[]; scores: ScoresaberPlayerScore[];
}; };
interface PlayerScoresStore { interface PlayerScoresStore {
lastUpdated: number;
players: Player[]; players: Player[];
setLastUpdated: (lastUpdated: number) => void;
exists: (playerId: string) => boolean; exists: (playerId: string) => boolean;
get(playerId: string): Player | undefined; get(playerId: string): Player | undefined;
addPlayer: ( addPlayer: (
playerId: string, playerId: string,
callback?: (page: number, totalPages: number) => void, callback?: (page: number, totalPages: number) => void,
@ -27,13 +29,18 @@ interface PlayerScoresStore {
updatePlayerScores: () => void; updatePlayerScores: () => void;
} }
const UPDATE_INTERVAL = 1000 * 60 * 60; // 1 hour const UPDATE_INTERVAL = 1000 * 60 * 30; // 30 minutes
export const usePlayerScoresStore = create<PlayerScoresStore>()( export const usePlayerScoresStore = create<PlayerScoresStore>()(
persist( persist(
(set) => ({ (set) => ({
lastUpdated: 0,
players: [], players: [],
setLastUpdated: (lastUpdated: number) => {
set({ lastUpdated });
},
exists: (playerId: string) => { exists: (playerId: string) => {
const players: Player[] = usePlayerScoresStore.getState().players; const players: Player[] = usePlayerScoresStore.getState().players;
return players.some((player) => player.id == playerId); return players.some((player) => player.id == playerId);
@ -73,15 +80,11 @@ export const usePlayerScoresStore = create<PlayerScoresStore>()(
message: "Could not fetch scores for player", message: "Could not fetch scores for player",
}; };
} }
console.log(scores);
set({ set({
players: [ players: [
...players, ...players,
{ {
id: playerId, id: playerId,
lastUpdated: new Date().getTime(),
scores: scores, scores: scores,
}, },
], ],
@ -93,18 +96,34 @@ export const usePlayerScoresStore = create<PlayerScoresStore>()(
}, },
updatePlayerScores: async () => { updatePlayerScores: async () => {
// Skip if we refreshed the scores recently
const timeUntilRefreshMs =
UPDATE_INTERVAL -
(Date.now() - usePlayerScoresStore.getState().lastUpdated);
if (timeUntilRefreshMs > 0) {
console.log(
"Waiting",
moment.duration(timeUntilRefreshMs).humanize(),
"to refresh scores for players",
);
setTimeout(
() => usePlayerScoresStore.getState().updatePlayerScores(),
timeUntilRefreshMs,
);
return;
}
const players = usePlayerScoresStore.getState().players; const players = usePlayerScoresStore.getState().players;
const friends = useSettingsStore.getState().friends;
for (const friend of friends) {
players.push({
id: friend.id,
scores: [],
});
}
for (const player of players) { for (const player of players) {
if (player == undefined) continue; if (player == undefined) continue;
// Skip if the player was already updated recently
if (
player.lastUpdated >
new Date(Date.now() - UPDATE_INTERVAL).getTime()
)
continue;
console.log(`Updating scores for ${player.id}...`); console.log(`Updating scores for ${player.id}...`);
let oldScores = player.scores; let oldScores = player.scores;
@ -116,7 +135,9 @@ export const usePlayerScoresStore = create<PlayerScoresStore>()(
return bDate.getTime() - aDate.getTime(); return bDate.getTime() - aDate.getTime();
}); });
const mostRecentScore = oldScores?.[0].score; if (!oldScores || oldScores.length == 0) continue;
const mostRecentScore = oldScores[0].score;
if (mostRecentScore == undefined) continue; if (mostRecentScore == undefined) continue;
let search = true; let search = true;
@ -150,7 +171,6 @@ export const usePlayerScoresStore = create<PlayerScoresStore>()(
newPlayers = newPlayers.filter((playerr) => playerr.id != player.id); newPlayers = newPlayers.filter((playerr) => playerr.id != player.id);
// Add the player // Add the player
newPlayers.push({ newPlayers.push({
lastUpdated: new Date().getTime(),
id: player.id, id: player.id,
scores: oldScores, scores: oldScores,
}); });
@ -158,6 +178,11 @@ export const usePlayerScoresStore = create<PlayerScoresStore>()(
if (newScoresCount > 0) { if (newScoresCount > 0) {
console.log(`Found ${newScoresCount} new scores for ${player.id}`); console.log(`Found ${newScoresCount} new scores for ${player.id}`);
} }
set({
players: newPlayers,
lastUpdated: Date.now(),
});
} }
}, },
}), }),
@ -167,3 +192,8 @@ export const usePlayerScoresStore = create<PlayerScoresStore>()(
}, },
), ),
); );
usePlayerScoresStore.getState().updatePlayerScores();
setInterval(() => {
usePlayerScoresStore.getState().updatePlayerScores();
}, UPDATE_INTERVAL);

@ -1,7 +1,9 @@
"use client"; "use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { SortType, SortTypes } from "@/types/SortTypes"; import { SortType, SortTypes } from "@/types/SortTypes";
import { getPlayerInfo } from "@/utils/scoresaber/api"; import { getPlayerInfo } from "@/utils/scoresaber/api";
import moment from "moment";
import { create } from "zustand"; import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware"; import { createJSONStorage, persist } from "zustand/middleware";
@ -9,19 +11,30 @@ interface SettingsStore {
userId: string | undefined; userId: string | undefined;
profilePicture: string | undefined; profilePicture: string | undefined;
lastUsedSortType: SortType; lastUsedSortType: SortType;
friends: ScoresaberPlayer[];
profilesLastUpdated: number;
setUserId: (userId: string) => void; setUserId: (userId: string) => void;
setProfilePicture: (profilePicture: string) => void; setProfilePicture: (profilePicture: string) => void;
setLastUsedSortType: (sortType: SortType) => void; setLastUsedSortType: (sortType: SortType) => void;
refreshProfile: () => void; addFriend: (friendId: string) => Promise<boolean>;
removeFriend: (friendId: string) => void;
isFriend: (friendId: string) => boolean;
clearFriends: () => void;
setProfilesLastUpdated: (profilesLastUpdated: number) => void;
refreshProfiles: () => void;
} }
const UPDATE_INTERVAL = 1000 * 60 * 10; // 10 minutes
export const useSettingsStore = create<SettingsStore>()( export const useSettingsStore = create<SettingsStore>()(
persist( persist(
(set) => ({ (set) => ({
userId: undefined, userId: undefined,
profilePicture: undefined, profilePicture: undefined,
lastUsedSortType: SortTypes.top, lastUsedSortType: SortTypes.top,
friends: [],
profilesLastUpdated: 0,
setUserId: (userId: string) => { setUserId: (userId: string) => {
set({ userId }); set({ userId });
@ -32,18 +45,77 @@ export const useSettingsStore = create<SettingsStore>()(
setLastUsedSortType: (sortType: SortType) => setLastUsedSortType: (sortType: SortType) =>
set({ lastUsedSortType: sortType }), set({ lastUsedSortType: sortType }),
async refreshProfile() { async addFriend(friendId: string) {
const id = useSettingsStore.getState().userId; const friends = useSettingsStore.getState().friends;
if (!id) return; if (friends.some((friend) => friend.id == friendId)) {
return false;
}
const profile = await getPlayerInfo(id); const friend = await getPlayerInfo(friendId);
if (friend == undefined || friend == null) return false;
set({ friends: [...friends, friend] });
return true;
},
removeFriend: (friendId: string) => {
const friends = useSettingsStore.getState().friends;
set({ friends: friends.filter((friend) => friend.id != friendId) });
return friendId;
},
clearFriends: () => set({ friends: [] }),
isFriend: (friendId: string) => {
const friends: ScoresaberPlayer[] = useSettingsStore.getState().friends;
return friends.some((friend) => friend.id == friendId);
},
setProfilesLastUpdated: (profilesLastUpdated: number) =>
set({ profilesLastUpdated }),
async refreshProfiles() {
const timeUntilRefreshMs =
UPDATE_INTERVAL -
(Date.now() - useSettingsStore.getState().profilesLastUpdated);
if (timeUntilRefreshMs > 0) {
console.log(
"Waiting",
moment.duration(timeUntilRefreshMs).humanize(),
"to refresh profiles",
);
setTimeout(() => this.refreshProfiles(), timeUntilRefreshMs);
return;
}
const userId = useSettingsStore.getState().userId;
const profiles =
useSettingsStore.getState().friends.map((f) => f.id) ?? [];
if (userId) {
profiles.push(userId);
}
for (const profileId of profiles) {
const profile = await getPlayerInfo(profileId);
if (profile == undefined || profile == null) return; if (profile == undefined || profile == null) return;
useSettingsStore.setState({ if (this.isFriend(profileId)) {
userId: profile.id, const friends = useSettingsStore.getState().friends;
profilePicture: profile.profilePicture, const friendIndex = friends.findIndex(
}); (friend) => friend.id == profileId,
);
friends[friendIndex] = profile;
set({ friends });
} else {
this.setProfilePicture(profile.profilePicture);
set({ userId: profile.id });
}
console.log("Updated profile:", profile.id); console.log("Updated profile:", profile.id);
}
useSettingsStore.setState({ profilesLastUpdated: Date.now() });
}, },
}), }),
{ {
@ -53,4 +125,8 @@ export const useSettingsStore = create<SettingsStore>()(
), ),
); );
useSettingsStore.getState().refreshProfile(); useSettingsStore.getState().refreshProfiles();
setInterval(
() => useSettingsStore.getState().refreshProfiles(),
UPDATE_INTERVAL,
);

@ -145,8 +145,6 @@ export async function fetchAllScores(
page++; page++;
} while (!done); } while (!done);
console.log(scores);
return scores as ScoresaberPlayerScore[]; return scores as ScoresaberPlayerScore[];
} }