2023-10-27 15:54:11 +01:00
|
|
|
import { Point } from "@influxdata/influxdb-client";
|
2023-10-27 16:30:30 +01:00
|
|
|
import axios from "axios";
|
2023-10-27 15:54:11 +01:00
|
|
|
import { w3cwebsocket as WebsocketClient } from "websocket";
|
|
|
|
import { InfluxWriteAPI } from "..";
|
|
|
|
import { connectMongo } from "../db/mongo";
|
|
|
|
import { LeaderboardSchema } from "../db/schemas/leaderboard";
|
|
|
|
|
|
|
|
async function update() {
|
2023-10-27 16:30:30 +01:00
|
|
|
const response = await axios.get("https://scoresaber.com/api/players/count");
|
|
|
|
const count = response.data;
|
2023-10-27 15:54:11 +01:00
|
|
|
|
|
|
|
const point = new Point("scoresaber")
|
|
|
|
.tag("type", "player_count")
|
|
|
|
.intField("value", parseInt(count))
|
|
|
|
.timestamp(new Date());
|
|
|
|
InfluxWriteAPI.writePoint(point);
|
|
|
|
|
|
|
|
console.log(`Updated player count to ${count}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
async function connectWebsocket() {
|
|
|
|
await connectMongo();
|
|
|
|
const leaderboard = await LeaderboardSchema.findOne({ _id: "scoresaber" });
|
|
|
|
if (!leaderboard) {
|
|
|
|
await LeaderboardSchema.create({ _id: "scoresaber", totalPlays: 0 });
|
|
|
|
}
|
|
|
|
let totalScores = leaderboard?.totalPlays || 0;
|
|
|
|
|
|
|
|
const socket = new WebsocketClient("wss://scoresaber.com/ws");
|
|
|
|
socket.onopen = () => {
|
|
|
|
console.log("Connected to websocket");
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.onclose = () => {
|
|
|
|
console.log("Disconnected from websocket");
|
|
|
|
setTimeout(connectWebsocket, 5000);
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.onerror = (error) => {
|
|
|
|
console.error("Websocket error:", error);
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.onmessage = (message) => {
|
|
|
|
const data = message.data;
|
|
|
|
let json;
|
|
|
|
try {
|
|
|
|
json = JSON.parse(data.toString());
|
|
|
|
} catch (e) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const commandName = json.commandName;
|
|
|
|
const commandData = json.commandData;
|
|
|
|
if (commandName == "score") {
|
|
|
|
totalScores++;
|
|
|
|
LeaderboardSchema.updateOne(
|
|
|
|
{ _id: "scoresaber" },
|
|
|
|
{ totalPlays: totalScores }
|
|
|
|
).exec();
|
|
|
|
const point = new Point("scoresaber")
|
|
|
|
.tag("type", "score_count")
|
|
|
|
.intField("value", totalScores)
|
|
|
|
.timestamp(new Date());
|
|
|
|
InfluxWriteAPI.writePoint(point);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
update();
|
|
|
|
connectWebsocket();
|
|
|
|
setInterval(update, 60_000); // 1 minute
|