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

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

@ -189,3 +189,13 @@ export function getAveragePp(playerId: string, limit: number = 20) {
return getTotalPpFromSortedPps(rankedScorePps, 0) / limit; 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;
}