Skip to content

Commit

Permalink
feat(api): tracking
Browse files Browse the repository at this point in the history
  • Loading branch information
GalvinPython committed Sep 1, 2024
1 parent e5923ae commit 78122dd
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 9 deletions.
73 changes: 70 additions & 3 deletions api/src/db/queries/tracking.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// TODO: Move this file to a utils folder or something - this is NOT queries

import { CronJob } from "cron";
import { pool } from "..";
import type { QueryError } from "mysql2";

let usersToUpdate: Record<string, string[]> = {};
let timestamp: string

export async function addUserToTrackingData(userId: string, guildId: string) : Promise<void> {
console.log("Adding user to tracking data:", userId, guildId);
Expand All @@ -9,25 +14,87 @@ export async function addUserToTrackingData(userId: string, guildId: string) : P
}
if (!usersToUpdate[guildId].includes(userId)) {
usersToUpdate[guildId].push(userId);
return;
}
return;
}

async function doTrackingJob() {
timestamp = new Date().toISOString().slice(0, 19).replace('T', ' ');
const usersToUpdateTemp = { ...usersToUpdate };
usersToUpdate = {};
console.log("Updating users:", usersToUpdateTemp);
if (!Object.keys(usersToUpdateTemp).length) {
console.log("No users to update!");
return;
}
const guildIds = Object.keys(usersToUpdateTemp);
for (const guildId of guildIds) {
const userIds = usersToUpdateTemp[guildId];
for (const userId of userIds) {
console.log(userId, guildId);
const userIdsString = userIds.join(",");
const [err, results] = await getUsersXp(userIdsString, guildId);
if (err) {
console.error("Error getting users:", err);
return;
}
console.log("Results:", results);
for (const result of results) {
const { id, guild_id, xp } = result;
await insertUserDataToTracking(id, guild_id, xp);
}
}
}

const trackingJob = new CronJob("*/5 * * * * *", doTrackingJob);
trackingJob.start();
trackingJob.start();

export async function getUsersTrackingData(userId: string, guildId: string): Promise<[QueryError | null, any]> {
return new Promise((resolve, reject) => {
pool.query("SELECT * FROM tracking WHERE user_id = ? AND guild_id = ?", [userId, guildId], (err, results) => {
if (err) {
reject([err, null]);
} else {
resolve([null, results]);
}
});
});
}

export async function getGuildTrackingData(guildId: string, override: number | null): Promise<[QueryError | null, null] | [null, any]> {
const topNumber: number = override || 10;

return new Promise((resolve, reject) => {
pool.query("SELECT * FROM tracking WHERE guild_id = ? ORDER BY xp DESC, time ASC LIMIT ?", [guildId, topNumber], (err, results) => {
if (err) {
reject([err, null]);
} else {
resolve([null, results]);
}
});
});
}

async function getUsersXp(userString: string, guildId: string): Promise<[QueryError | null, any]> {
return new Promise((resolve, reject) => {
pool.query("SELECT * FROM users WHERE id IN (?) AND guild_id = ?", [userString, guildId], (err, results) => {
if (err) {
reject([err, null]);
} else {
resolve([null, results]);
}
});
});
}

async function insertUserDataToTracking(userId: string, guildId: string, xp: number): Promise<[QueryError | null, null]> {
const time = timestamp;
return new Promise((resolve, reject) => {
pool.query("INSERT INTO tracking (user_id, guild_id, xp, time) VALUES (?, ?, ?, ?)", [userId, guildId, xp, time], (err) => {
if (err) {
reject([err, null]);
} else {
resolve([null, null]);
}
});
});
}
34 changes: 28 additions & 6 deletions api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express, { type NextFunction, type Request, type Response } from "express";
import cors from "cors";
import { getBotInfo, getGuild, getUser, getUsers, initTables, pool, updateGuild, enableUpdates, disableUpdates, setCooldown, setUpdatesChannel, setXP, setLevel, removeGuild, removeUser, getAllServersWithUpdatesEnabled, addUserToTrackingData } from "./db";
import { getBotInfo, getGuild, getUser, getUsers, initTables, pool, updateGuild, enableUpdates, disableUpdates, setCooldown, setUpdatesChannel, setXP, setLevel, removeGuild, removeUser, getAllServersWithUpdatesEnabled, addUserToTrackingData, getGuildTrackingData, getUsersTrackingData } from "./db";

const app = express();
const PORT = 18103;
Expand Down Expand Up @@ -197,6 +197,32 @@ app.get('/get/dbusage', (_req, res) => {
})
});

app.get('/get/tracking/:guild', async (req, res) => {
const { guild } = req.params;

const [err, data] = await getGuildTrackingData(guild, null);

if (err) {
console.error("Error fetching tracking data:", err);
return res.status(500).json({ message: "Internal server error" });
}

return res.status(200).json(data);
});

app.get('/get/tracking/:guild/:user', async (req, res) => {
const { guild, user } = req.params;

const [err, data] = await getUsersTrackingData(user, guild);

if (err) {
console.error("Error fetching tracking data:", err);
return res.status(500).json({ message: "Internal server error" });
}

return res.status(200).json(data);
});

app.get("/get/:guild/:user", async (req, res) => {
const { guild, user } = req.params;

Expand Down Expand Up @@ -492,7 +518,7 @@ app.get("/invite", (_req, res) => res.status(308).redirect("https://discord.com/
app.get('/support', (_req, res) => res.status(308).redirect('https://discord.gg/fpJVTkVngm'));

app.use((_req, res) => {
res.status(404).json({ message: "Not found" });
res.status(404).send()
});

app.listen(PORT, () => {
Expand Down Expand Up @@ -743,7 +769,3 @@ async function syncFromLurkr(guild: string) {
}
}
//#endregion

//#region Tracking

//#endregion

0 comments on commit 78122dd

Please sign in to comment.