cleanup and added total scores label
All checks were successful
deploy / deploy (push) Successful in 57s

This commit is contained in:
Lee 2023-10-23 10:36:48 +01:00
parent 9494fe599b
commit 05e257f8be
3 changed files with 118 additions and 147 deletions

@ -6,6 +6,7 @@ import {
calcPpBoundary,
getAveragePp,
getHighestPpPlay,
getTotalScores,
} from "@/utils/scoresaber/scores";
import {
GlobeAsiaAustraliaIcon,
@ -53,7 +54,7 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
async function addProfile(isFriend: boolean) {
if (!useScoresaberScoresStore.getState().exists(playerId)) {
const reponse = await playerScoreStore?.addPlayer(
const reponse = await playerScoreStore?.addOrUpdatePlayer(
playerId,
(page, totalPages) => {
const autoClose = page == totalPages ? 5000 : false;
@ -192,6 +193,12 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
{hasLocalScores && (
<>
<Label
title="Total Scores"
className="bg-blue-500"
hoverValue="Total amount of scores set"
value={`${formatNumber(getTotalScores(playerId))}`}
/>
<Label
title="Top PP"
className="bg-[#8992e8]"

@ -11,6 +11,7 @@ import { useSettingsStore } from "./settingsStore";
type Player = {
id: string;
lastUpdated: number;
scores: ScoresaberSmallerPlayerScore[];
};
@ -48,7 +49,7 @@ interface ScoreSaberScoresStore {
* @param callback a callback to call when a score page is fetched
* @returns if the player was added successfully
*/
addPlayer: (
addOrUpdatePlayer: (
playerId: string,
callback?: (page: number, totalPages: number) => void,
) => Promise<{
@ -84,10 +85,13 @@ export const useScoresaberScoresStore = create<ScoreSaberScoresStore>()(
return players.find((player) => player.id == playerId);
},
addPlayer: async (
addOrUpdatePlayer: async (
playerId: string,
callback?: (page: number, totalPages: number) => void,
) => {
): Promise<{
error: boolean;
message: string;
}> => {
const players: Player[] = get().players;
// Check if the player already exists
@ -98,134 +102,19 @@ export const useScoresaberScoresStore = create<ScoreSaberScoresStore>()(
};
}
// Get all of the players scores
let scores = await ScoreSaberAPI.fetchAllScores(
playerId,
"recent",
(page, totalPages) => {
if (callback) callback(page, totalPages);
},
);
if (scores == undefined) {
if (playerId == undefined) {
return {
error: true,
message: "Could not fetch scores for player",
message: "Player id is undefined",
};
}
let smallerScores = new Array<ScoresaberSmallerPlayerScore>();
for (const score of scores) {
smallerScores.push({
score: {
id: score.score.id,
rank: score.score.rank,
baseScore: score.score.baseScore,
modifiedScore: score.score.modifiedScore,
pp: score.score.pp,
weight: score.score.weight,
modifiers: score.score.modifiers,
multiplier: score.score.multiplier,
badCuts: score.score.badCuts,
missedNotes: score.score.missedNotes,
maxCombo: score.score.maxCombo,
fullCombo: score.score.fullCombo,
hmd: score.score.hmd,
timeSet: score.score.timeSet,
},
leaderboard: {
id: score.leaderboard.id,
songHash: score.leaderboard.songHash,
difficulty: score.leaderboard.difficulty,
maxScore: score.leaderboard.maxScore,
createdDate: score.leaderboard.createdDate,
stars: score.leaderboard.stars,
plays: score.leaderboard.plays,
coverImage: score.leaderboard.coverImage,
},
});
}
console.log(`Updating scores for ${playerId}...`);
// Remove scores that are already in the database
const player = get().get(playerId);
if (player) {
scores = scores.filter(
(score) =>
player.scores.findIndex((s) => s.score.id == score.score.id) ==
-1,
);
}
const player = players.find((player) => player.id == playerId);
set({
players: [
...players,
{
id: playerId,
scores: scores,
},
],
});
return {
error: false,
message: "Player added successfully",
};
},
updatePlayerScores: async () => {
const players = get().players;
const friends = useSettingsStore.getState().friends;
let allPlayers = new Array<ScoresaberPlayer>();
for (const friend of friends) {
allPlayers.push(friend);
}
const localPlayer = useSettingsStore.getState().player;
if (localPlayer) {
allPlayers.push(localPlayer);
}
// add local player and friends if they don't exist
for (const player of allPlayers) {
if (get().lastUpdated == 0) {
set({ lastUpdated: Date.now() });
}
if (get().get(player.id) == undefined) {
toast.info(
`${
player.id == localPlayer?.id
? `You were`
: `Friend ${player.name} was`
} missing from the ScoreSaber scores database, adding...`,
);
await get().addPlayer(player.id);
toast.success(
`${
player.id == useSettingsStore.getState().player?.id
? `You were`
: `Friend ${player.name} was`
} added to the ScoreSaber scores database`,
);
}
}
// Skip if we refreshed the scores recently
const timeUntilRefreshMs =
UPDATE_INTERVAL - (Date.now() - get().lastUpdated);
if (timeUntilRefreshMs > 0) {
console.log(
"Waiting",
timeUntilRefreshMs / 1000,
"seconds to refresh scores for players",
);
setTimeout(() => get().updatePlayerScores(), timeUntilRefreshMs);
return;
}
// loop through all of the players and update their scores
for (const player of players) {
if (player == undefined) continue;
console.log(`Updating scores for ${player.id}...`);
let oldScores: ScoresaberSmallerPlayerScore[] = player.scores;
let oldScores: ScoresaberSmallerPlayerScore[] = player
? player.scores
: [];
// Sort the scores by date (newset to oldest), so we know when to stop searching for new scores
oldScores = oldScores.sort((a, b) => {
@ -233,24 +122,26 @@ export const useScoresaberScoresStore = create<ScoreSaberScoresStore>()(
const bDate = new Date(b.score.timeSet);
return bDate.getTime() - aDate.getTime();
});
if (!oldScores.length) continue;
const mostRecentScore = oldScores[0].score;
const mostRecentScoreId =
oldScores.length > 0 ? oldScores[0].score.id : undefined;
let search = true;
let page = 0;
let newScoresCount = 0;
while (search) {
page++;
const newScores = await ScoreSaberAPI.fetchScores(player.id, page);
if (newScores == undefined) continue;
const newScores = await ScoreSaberAPI.fetchScores(playerId, page);
console.log("scanning page", page, "for", playerId);
if (newScores?.scores.length == 0 || newScores == undefined) break;
for (const score of newScores.scores) {
if (mostRecentScore && score.score.id == mostRecentScore.id) {
if (score.score.id == mostRecentScoreId) {
search = false;
break;
}
if (mostRecentScoreId) {
// remove the old score
const oldScoreIndex = oldScores.findIndex(
(score) => score.score.id == score.score.id,
@ -258,6 +149,7 @@ export const useScoresaberScoresStore = create<ScoreSaberScoresStore>()(
if (oldScoreIndex != -1) {
oldScores = oldScores.splice(oldScoreIndex, 1);
}
}
oldScores.push({
score: {
id: score.score.id,
@ -291,24 +183,86 @@ export const useScoresaberScoresStore = create<ScoreSaberScoresStore>()(
}
let newPlayers = players;
// Remove the player if it already exists
// Remove the player if they already exists
newPlayers = newPlayers.filter(
(playerr: Player) => playerr.id != player.id,
(playerr: Player) => playerr.id != playerId,
);
// Add the player
newPlayers.push({
id: player.id,
id: playerId,
scores: oldScores,
lastUpdated: Date.now(),
});
console.log(oldScores);
if (newScoresCount > 0) {
console.log(`Found ${newScoresCount} new scores for ${player.id}`);
console.log(`Found ${newScoresCount} new scores for ${playerId}`);
}
set({
players: newPlayers,
lastUpdated: Date.now(),
});
return {
error: false,
message: "Player added successfully",
};
},
updatePlayerScores: async () => {
const players = get().players;
const friends = useSettingsStore.getState().friends;
let allPlayers = new Array<ScoresaberPlayer>();
for (const friend of friends) {
allPlayers.push(friend);
}
const localPlayer = useSettingsStore.getState().player;
if (localPlayer) {
allPlayers.push(localPlayer);
}
// add local player and friends if they don't exist
for (const player of allPlayers) {
if (get().lastUpdated == 0) {
set({ lastUpdated: Date.now() });
}
if (get().get(player.id) == undefined) {
toast.info(
`${
player.id == localPlayer?.id
? `You were`
: `Friend ${player.name} was`
} missing from the ScoreSaber scores database, adding...`,
);
await get().addOrUpdatePlayer(player.id);
toast.success(
`${
player.id == useSettingsStore.getState().player?.id
? `You were`
: `Friend ${player.name} was`
} added to the ScoreSaber scores database`,
);
}
}
// Skip if we refreshed the scores recently
const timeUntilRefreshMs =
UPDATE_INTERVAL - (Date.now() - get().lastUpdated);
if (timeUntilRefreshMs > 0) {
console.log(
"Waiting",
timeUntilRefreshMs / 1000,
"seconds to refresh scores for players",
);
setTimeout(() => get().updatePlayerScores(), timeUntilRefreshMs);
return;
}
// loop through all of the players and update their scores
for (const player of players) {
get().addOrUpdatePlayer(player.id);
}
},
}),

@ -189,3 +189,13 @@ export function getAveragePp(playerId: string, limit: number = 20) {
return getTotalPpFromSortedPps(rankedScorePps, 0) / limit;
}
/**
* Returns the total amount of scores for the given player
*
* @param playerId the player id
* @returns the total amount of scores
*/
export function getTotalScores(playerId: string) {
return useScoresaberScoresStore.getState().get(playerId)?.scores?.length;
}