many many many many changes

This commit is contained in:
Lee
2023-10-19 14:17:55 +01:00
parent 6acf6e8635
commit a031451fa3
36 changed files with 2743 additions and 174 deletions

View File

@ -0,0 +1,90 @@
import { connectMongo } from "@/database/mongo";
import { PlayerSchema } from "@/database/schemas/player";
import { ScoresaberScore } from "@/database/schemas/scoresaberScore";
import { triggerClient } from "@/trigger";
import { fetchScores } from "@/utils/scoresaber/api";
import { createScore, updateScore } from "@/utils/scoresaber/db";
import { cronTrigger } from "@trigger.dev/sdk";
triggerClient.defineJob({
id: "fetch-new-scores",
name: "Scores: Fetch all new scores for players",
version: "0.0.1",
trigger: cronTrigger({
cron: "*/15 * * * *", // Fetch new scores every 15 minutes
}),
// trigger: eventTrigger({
// name: "user.add",
// }),
run: async (payload, io, ctx) => {
await io.logger.info("Scores: Fetching all new scores for players");
// Ensure we're connected to the database
await connectMongo();
const players = await PlayerSchema.find().select("_id"); // Get all players
for (const player of players) {
// Loop through all players
await io.logger.info(
`Scores: Fetching new scores for player: "${player._id}"`,
);
// Get the old scores for the player
const oldScores = await ScoresaberScore.find({ playerId: player._id })
.select("_id")
.select("timeSet")
.sort("-timeSet")
.limit(100) // Limit to 100 scores so we don't violate the db
.exec();
const mostRecentScore = oldScores[0];
console.log(mostRecentScore);
let search = true;
let page = 0;
let newScoresCount = 0;
while (search === true) {
const newScores = await fetchScores(player._id, page++);
if (newScores === undefined) {
search = false;
io.logger.warn(
`Scores: Failed to fetch scores for player: "${player._id}"`,
);
break;
}
// Check if any scores were returned
if (newScores.length === 0) {
search = false;
break;
}
// Loop through the page of scores
for (const scoreData of newScores) {
const score = scoreData.score;
const leaderboard = scoreData.leaderboard;
// Check if the latest score is the same as the most recent score
// If it is, we've reached the end of the new scores
if (score.id == mostRecentScore._id) {
search = false;
break;
}
const hasScoreOnLeaderboard = await ScoresaberScore.exists({
leaderboardId: leaderboard.id,
});
if (!hasScoreOnLeaderboard) {
await createScore(player.id, scoreData);
} else {
await updateScore(player.id, scoreData);
}
newScoresCount++;
}
}
io.logger.info(
`Scores: Fetched ${newScoresCount} new scores for player: "${player._id}"`,
);
}
},
});

View File

@ -1,3 +1,4 @@
// export all your job files here
export * from "./fetchNewScores";
export * from "./setupUser";

View File

@ -1,4 +1,11 @@
import { connectMongo } from "@/database/mongo";
import { PlayerSchema } from "@/database/schemas/player";
import { ScoresaberError } from "@/schemas/scoresaber/error";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { triggerClient } from "@/trigger";
import * as Utils from "@/utils/numberUtils";
import { fetchAllScores } from "@/utils/scoresaber/api";
import { createScore } from "@/utils/scoresaber/db";
import { eventTrigger } from "@trigger.dev/sdk";
triggerClient.defineJob({
@ -10,7 +17,69 @@ triggerClient.defineJob({
}),
run: async (payload, io, ctx) => {
const { id } = payload;
const isNumber = Utils.isNumber(id);
if (!isNumber) {
await io.logger.warn(`Setup User: Failed - Invalid account id: "${id}"`);
return;
}
await io.logger.info(`Setup User: Running for ${id}`);
await io.logger.info(`Setup User: Running for account: "${id}"`);
const resposnse = await io.backgroundFetch<
ScoresaberPlayer | ScoresaberError
>("fetch-user-data", `https://scoresaber.com/api/player/${id}/full`);
// Check if there was an error fetching the user data
const error = resposnse as ScoresaberError;
if (error.message !== undefined) {
await io.logger.error(
`Setup User: Failed - Error fetching user data: "${error.message}"`,
);
return;
}
const user = resposnse as ScoresaberPlayer;
await connectMongo(); // Ensure we're connected to the database
const player = await PlayerSchema.findOne({ id: user.id });
if (player !== null) {
await io.logger.info(
`Setup User: Failed - Player already exists: "${player.id}"`,
);
return;
}
await io.logger.info(`Setup User: Creating player: "${user.id}"`);
const newPlayer = await PlayerSchema.create({
_id: user.id,
avatar: user.profilePicture,
name: user.name,
country: user.country,
scoresaber: {
pp: user.pp,
rank: user.rank,
countryRank: user.countryRank,
role: user.role,
badges: user.badges,
histories: user.histories,
scoreStats: user.scoreStats,
permissions: user.permissions,
inactive: user.inactive,
},
}); // Save the player to the database
io.logger.info(`Setup User: Created player: "${user.id}"`);
io.logger.info(`Setup User: Fetching scores for player: "${user.id}"`);
const scores = await fetchAllScores(newPlayer.id, "recent");
if (scores == undefined) {
await io.logger.error(`Setup User: Failed - Error fetching scores`);
return;
}
for (const scoreSaberScore of scores) {
createScore(user.id, scoreSaberScore);
}
io.logger.info(`Setup User: Fetched scores for player: "${user.id}"`);
},
});