fix proxy

This commit is contained in:
Lee 2023-10-31 11:44:27 +00:00
parent 918da6f88b
commit 47a255e48a
7 changed files with 314 additions and 341 deletions

@ -5,17 +5,17 @@ import { BeatSaverMapData } from "../types/BeatSaverMapData";
import { getValue, setValue, valueExists } from "../utils/redisUtils"; import { getValue, setValue, valueExists } from "../utils/redisUtils";
const BEATSAVER_MAP_API = const BEATSAVER_MAP_API =
env(VARS.HTTP_PROXY) + "/https://api.beatsaver.com/maps/hash/%s"; env(VARS.HTTP_PROXY) + "/https://api.beatsaver.com/maps/hash/%s";
const KEY = "BS_MAP_DATA_"; const KEY = "BS_MAP_DATA_";
function getLatestMapArt(data: BeatSaverMapData) { function getLatestMapArt(data: BeatSaverMapData) {
return data.versions[data.versions.length - 1].coverURL; return data.versions[data.versions.length - 1].coverURL;
} }
type MapData = { type MapData = {
bsr: string; bsr: string;
mapArt: string | undefined; mapArt: string | undefined;
}; };
/** /**
@ -25,34 +25,30 @@ type MapData = {
* @returns The map data * @returns The map data
*/ */
export async function getMapData(hash: string): Promise<MapData | undefined> { export async function getMapData(hash: string): Promise<MapData | undefined> {
const mapHash = hash.replace("custom_level_", "").toLowerCase(); const mapHash = hash.replace("custom_level_", "").toLowerCase();
const key = `${KEY}${mapHash}`; const key = `${KEY}${mapHash}`;
const exists = await valueExists(key); const exists = await valueExists(key);
if (exists) { if (exists) {
const data = await getValue(key); const data = await getValue(key);
return JSON.parse(data); return JSON.parse(data);
} }
const before = Date.now(); const before = Date.now();
const response = await axios.get(BEATSAVER_MAP_API.replace("%s", mapHash), { const response = await axios.get(BEATSAVER_MAP_API.replace("%s", mapHash));
headers: { if (response.status === 404) {
"X-Requested-With": "BeatSaber Overlay", return undefined;
}, }
}); const jsonResponse = response.data;
if (response.status === 404) { const json = {
return undefined; bsr: jsonResponse.id,
} mapArt: getLatestMapArt(jsonResponse),
const jsonResponse = response.data; };
const json = { await setValue(key, JSON.stringify(json), 86400 * 7); // Expire in a week
bsr: jsonResponse.id, console.log(
mapArt: getLatestMapArt(jsonResponse), `[Cache]: Cached BS Map Data for hash ${mapHash} in ${
}; Date.now() - before
await setValue(key, JSON.stringify(json), 86400 * 7); // Expire in a week }ms`
console.log( );
`[Cache]: Cached BS Map Data for hash ${mapHash} in ${ return json;
Date.now() - before
}ms`
);
return json;
} }

@ -2,13 +2,8 @@ import axios from "axios";
import LeaderboardType from "../../consts/LeaderboardType"; import LeaderboardType from "../../consts/LeaderboardType";
export async function getPlayerData(leaderboardType, playerId) { export async function getPlayerData(leaderboardType, playerId) {
const data = await axios.get( const data = await axios.get(
LeaderboardType[leaderboardType].ApiUrl.PlayerData.replace("%s", playerId), LeaderboardType[leaderboardType].ApiUrl.PlayerData.replace("%s", playerId)
{ );
headers: { return data;
"x-requested-with": "BeatSaber Overlay",
},
}
);
return data;
} }

@ -11,97 +11,92 @@ const KEY = "BL_MAP_DATA_";
* @returns * @returns
*/ */
export default async function handler(req, res) { export default async function handler(req, res) {
if (!req.query.hash || !req.query.difficulty || !req.query.characteristic) { if (!req.query.hash || !req.query.difficulty || !req.query.characteristic) {
return res.status(404).json({ return res.status(404).json({
status: 404, status: 404,
message: "Invalid request", message: "Invalid request",
}); });
} }
const mapHash = req.query.hash.replace("custom_level_", "").toLowerCase(); const mapHash = req.query.hash.replace("custom_level_", "").toLowerCase();
const difficulty = req.query.difficulty.replace(" ", ""); const difficulty = req.query.difficulty.replace(" ", "");
const characteristic = req.query.characteristic; const characteristic = req.query.characteristic;
const key = `${KEY}${difficulty}-${characteristic}-${mapHash}`; const key = `${KEY}${difficulty}-${characteristic}-${mapHash}`;
const exists = await valueExists(key); const exists = await valueExists(key);
if (exists) { if (exists) {
const data = await getValue(key); const data = await getValue(key);
const json = JSON.parse(data); const json = JSON.parse(data);
res.setHeader("Cache-Status", "hit"); res.setHeader("Cache-Status", "hit");
return res.status(200).json({ return res.status(200).json({
status: "OK", status: "OK",
difficulty: difficulty, difficulty: difficulty,
stars: json.stars, stars: json.stars,
modifiers: json.modifiers, modifiers: json.modifiers,
passRating: json.passRating, passRating: json.passRating,
accRating: json.accRating, accRating: json.accRating,
techRating: json.techRating, techRating: json.techRating,
}); });
} }
const before = Date.now(); const before = Date.now();
const reesponse = await axios.get( const reesponse = await axios.get(
WebsiteTypes.BeatLeader.ApiUrl.MapData.replace("%h", mapHash), WebsiteTypes.BeatLeader.ApiUrl.MapData.replace("%h", mapHash)
{ );
headers: { if (reesponse.status === 404) {
"X-Requested-With": "BeatSaber Overlay", return res.status(404).json({
}, status: 404,
} message: "Unknown Map Hash",
); });
if (reesponse.status === 404) { }
return res.status(404).json({ const json = reesponse.data;
status: 404, let starCount = undefined;
message: "Unknown Map Hash", let modifiers = undefined;
}); let passRating = undefined;
} let accRating = undefined;
const json = reesponse.data; let techRating = undefined;
let starCount = undefined;
let modifiers = undefined;
let passRating = undefined;
let accRating = undefined;
let techRating = undefined;
for (const diff of json.difficulties) { for (const diff of json.difficulties) {
if ( if (
diff.difficultyName === difficulty && diff.difficultyName === difficulty &&
diff.modeName === characteristic diff.modeName === characteristic
) { ) {
starCount = diff.stars; starCount = diff.stars;
modifiers = diff.modifierValues; modifiers = diff.modifierValues;
passRating = diff.passRating; passRating = diff.passRating;
accRating = diff.accRating; accRating = diff.accRating;
techRating = diff.techRating; techRating = diff.techRating;
} }
} }
if (starCount === undefined) { if (starCount === undefined) {
return res.status(404).json({ return res.status(404).json({
status: 404, status: 404,
message: "Unknown Map Hash", message: "Unknown Map Hash",
}); });
} }
await setValue( await setValue(
key, key,
JSON.stringify({ JSON.stringify({
stars: starCount, stars: starCount,
modifiers: modifiers, modifiers: modifiers,
passRating: passRating, passRating: passRating,
accRating: accRating, accRating: accRating,
techRating: techRating, techRating: techRating,
}) })
); );
console.log( console.log(
`[Cache]: Cached BL Star Count for hash ${mapHash} in ${ `[Cache]: Cached BL Star Count for hash ${mapHash} in ${
Date.now() - before Date.now() - before
}ms` }ms`
); );
res.setHeader("Cache-Status", "miss"); res.setHeader("Cache-Status", "miss");
return res.status(200).json({ return res.status(200).json({
status: "OK", status: "OK",
difficulty: difficulty, difficulty: difficulty,
stars: starCount, stars: starCount,
modifiers: modifiers, modifiers: modifiers,
passRating: passRating, passRating: passRating,
accRating: accRating, accRating: accRating,
techRating: techRating, techRating: techRating,
}); });
} }

@ -12,65 +12,60 @@ const KEY = "SS_MAP_STAR_";
* @returns * @returns
*/ */
export default async function handler(req, res) { export default async function handler(req, res) {
if (!req.query.hash) { if (!req.query.hash) {
return res.status(404).json({ return res.status(404).json({
status: 404, status: 404,
message: "Invalid request", message: "Invalid request",
}); });
} }
const mapHash = req.query.hash.replace("custom_level_", "").toLowerCase(); const mapHash = req.query.hash.replace("custom_level_", "").toLowerCase();
const difficulty = req.query.difficulty.replace(" ", ""); const difficulty = req.query.difficulty.replace(" ", "");
const characteristic = req.query.characteristic; const characteristic = req.query.characteristic;
const key = `${KEY}${difficulty}-${characteristic}-${mapHash}`; const key = `${KEY}${difficulty}-${characteristic}-${mapHash}`;
const exists = await valueExists(key); const exists = await valueExists(key);
if (exists) { if (exists) {
const data = await getValue(key); const data = await getValue(key);
res.setHeader("Cache-Status", "hit"); res.setHeader("Cache-Status", "hit");
return res.status(200).json({ return res.status(200).json({
status: "OK", status: "OK",
difficulty: difficulty, difficulty: difficulty,
stars: Number.parseFloat(data), stars: Number.parseFloat(data),
}); });
} }
const before = Date.now(); const before = Date.now();
const response = await axios.get( const response = await axios.get(
WebsiteTypes.ScoreSaber.ApiUrl.MapData.replace("%h", mapHash).replace( WebsiteTypes.ScoreSaber.ApiUrl.MapData.replace("%h", mapHash).replace(
"%d", "%d",
diffToScoreSaberDiff(difficulty) diffToScoreSaberDiff(difficulty)
), )
{ );
headers: { if (response.status === 404) {
"X-Requested-With": "BeatSaber Overlay", return res.status(404).json({
}, status: 404,
} message: "Unknown Map Hash",
); });
if (response.status === 404) { }
return res.status(404).json({ const json = response.data;
status: 404, let starCount = json.stars;
message: "Unknown Map Hash", if (starCount === undefined) {
}); return res.status(404).json({
} status: 404,
const json = response.data; message: "Unknown Map Hash",
let starCount = json.stars; });
if (starCount === undefined) { }
return res.status(404).json({ await setValue(key, starCount);
status: 404, console.log(
message: "Unknown Map Hash", `[Cache]: Cached SS Star Count for hash ${mapHash} in ${
}); Date.now() - before
} }ms`
await setValue(key, starCount); );
console.log( res.setHeader("Cache-Status", "miss");
`[Cache]: Cached SS Star Count for hash ${mapHash} in ${ return res.status(200).json({
Date.now() - before status: "OK",
}ms` difficulty: difficulty,
); stars: starCount,
res.setHeader("Cache-Status", "miss"); });
return res.status(200).json({
status: "OK",
difficulty: difficulty,
stars: starCount,
});
} }

@ -4,52 +4,48 @@ import Utils from "../utils/utils";
import { useSettingsStore } from "./overlaySettingsStore"; import { useSettingsStore } from "./overlaySettingsStore";
interface PlayerDataState { interface PlayerDataState {
isLoading: boolean; isLoading: boolean;
id: string; id: string;
pp: number; pp: number;
avatar: string; avatar: string;
globalPos: number; globalPos: number;
countryRank: number; countryRank: number;
country: string; country: string;
updatePlayerData: () => void; updatePlayerData: () => void;
} }
export const usePlayerDataStore = create<PlayerDataState>()((set) => ({ export const usePlayerDataStore = create<PlayerDataState>()((set) => ({
isLoading: true, isLoading: true,
id: "", id: "",
pp: 0, pp: 0,
avatar: "", avatar: "",
globalPos: 0, globalPos: 0,
countryRank: 0, countryRank: 0,
country: "", country: "",
updatePlayerData: async () => { updatePlayerData: async () => {
const leaderboardType = useSettingsStore.getState().leaderboardType; const leaderboardType = useSettingsStore.getState().leaderboardType;
const playerId = useSettingsStore.getState().id; const playerId = useSettingsStore.getState().id;
const apiUrl = Utils.getWebsiteApi( const apiUrl = Utils.getWebsiteApi(
leaderboardType leaderboardType
).ApiUrl.PlayerData.replace("%s", playerId); ).ApiUrl.PlayerData.replace("%s", playerId);
const response = await axios.get(apiUrl, { const response = await axios.get(apiUrl);
headers: { if (response.status !== 200) {
"x-requested-with": "BeatSaber Overlay", return;
}, }
}); const data = response.data;
if (response.status !== 200) {
return;
}
const data = response.data;
console.log("Updated player data"); console.log("Updated player data");
set(() => ({ set(() => ({
id: playerId, id: playerId,
isLoading: false, isLoading: false,
pp: data.pp, pp: data.pp,
avatar: data.avatar || data.profilePicture, avatar: data.avatar || data.profilePicture,
globalPos: data.rank, globalPos: data.rank,
countryRank: data.countryRank, countryRank: data.countryRank,
country: data.country, country: data.country,
})); }));
}, },
})); }));

@ -5,134 +5,130 @@ import { getScoreSaberPP } from "../curve/ScoreSaberCurve";
import { useSongDataStore } from "../store/songDataStore"; import { useSongDataStore } from "../store/songDataStore";
export default class Utils { export default class Utils {
/** /**
* Returns the information for the given website type. * Returns the information for the given website type.
* *
* @param {string} website * @param {string} website
* @returns The website type's information. * @returns The website type's information.
*/ */
static getWebsiteApi(website) { static getWebsiteApi(website) {
return LeaderboardType[website]; return LeaderboardType[website];
} }
static openInNewTab(url) { static openInNewTab(url) {
window.open(url, "_blank"); window.open(url, "_blank");
} }
static async isLeaderboardValid(url, steamId) { static async isLeaderboardValid(url, steamId) {
const response = await axios.get(url.replace("%s", steamId), { const response = await axios.get(url.replace("%s", steamId));
headers: { if (response.status === 429) {
"X-Requested-With": "BeatSaber Overlay", return true; // Just assume it's true is we are rate limited
}, }
}); const json = response.data;
if (response.status === 429) { return !!json.pp;
return true; // Just assume it's true is we are rate limited }
}
const json = response.data;
return !!json.pp;
}
static calculatePP(stars, acc, type) { static calculatePP(stars, acc, type) {
if (stars <= 0) { if (stars <= 0) {
return undefined; return undefined;
} }
if (type === "BeatLeader") { if (type === "BeatLeader") {
const leaderboardData = const leaderboardData =
useSongDataStore.getState().mapLeaderboardData.beatLeader; useSongDataStore.getState().mapLeaderboardData.beatLeader;
return getBeatLeaderPP( return getBeatLeaderPP(
acc, acc,
leaderboardData.accRating, leaderboardData.accRating,
leaderboardData.passRating, leaderboardData.passRating,
leaderboardData.techRating leaderboardData.techRating
); );
} }
if (type === "ScoreSaber") { if (type === "ScoreSaber") {
return getScoreSaberPP(acc, stars); return getScoreSaberPP(acc, stars);
} }
return undefined; return undefined;
} }
static calculateModifierBonus() { static calculateModifierBonus() {
const songMods = useSongDataStore.getState().songModifiers; const songMods = useSongDataStore.getState().songModifiers;
const modifierMulipliers = const modifierMulipliers =
useSongDataStore.getState().mapLeaderboardData.beatLeader.modifiers; useSongDataStore.getState().mapLeaderboardData.beatLeader.modifiers;
let bonus = 1; let bonus = 1;
// No Fail // No Fail
if ( if (
songMods.noFail == true && songMods.noFail == true &&
modifierMulipliers.nf < 0 && modifierMulipliers.nf < 0 &&
useSongDataStore.getState().failed useSongDataStore.getState().failed
) { ) {
bonus -= modifierMulipliers.nf; bonus -= modifierMulipliers.nf;
} }
// Speed Modifiers // Speed Modifiers
if (songMods.songSpeed != "Normal") { if (songMods.songSpeed != "Normal") {
if (songMods.songSpeed == "SuperSlow" && modifierMulipliers.ss > 0) { if (songMods.songSpeed == "SuperSlow" && modifierMulipliers.ss > 0) {
bonus -= modifierMulipliers.ss; bonus -= modifierMulipliers.ss;
} }
if (songMods.songSpeed == "Faster" && modifierMulipliers.fs > 0) { if (songMods.songSpeed == "Faster" && modifierMulipliers.fs > 0) {
bonus += modifierMulipliers.fs; bonus += modifierMulipliers.fs;
} }
if (songMods.songSpeed == "SuperFast" && modifierMulipliers.sf > 0) { if (songMods.songSpeed == "SuperFast" && modifierMulipliers.sf > 0) {
bonus += modifierMulipliers.sf; bonus += modifierMulipliers.sf;
} }
} }
// Disappearing Arrows // Disappearing Arrows
if (songMods.disappearingArrows == true && modifierMulipliers.da > 0) { if (songMods.disappearingArrows == true && modifierMulipliers.da > 0) {
bonus += modifierMulipliers.da; bonus += modifierMulipliers.da;
} }
// Ghost Notes // Ghost Notes
if (songMods.ghostNotes == true && modifierMulipliers.gn > 0) { if (songMods.ghostNotes == true && modifierMulipliers.gn > 0) {
toAdd += modifierMulipliers.gn; toAdd += modifierMulipliers.gn;
} }
// No Arrows // No Arrows
if (songMods.noArrows == true && modifierMulipliers.na < 0) { if (songMods.noArrows == true && modifierMulipliers.na < 0) {
bonus -= modifierMulipliers.na; bonus -= modifierMulipliers.na;
} }
// No Bombs // No Bombs
if (songMods.noBombs == true && modifierMulipliers.nb < 0) { if (songMods.noBombs == true && modifierMulipliers.nb < 0) {
bonus -= modifierMulipliers.nb; bonus -= modifierMulipliers.nb;
} }
// No Obstacles // No Obstacles
if (songMods.obstacles == false && modifierMulipliers.no < 0) { if (songMods.obstacles == false && modifierMulipliers.no < 0) {
bonus -= modifierMulipliers.no; bonus -= modifierMulipliers.no;
} }
return bonus; return bonus;
} }
static base64ToArrayBuffer(base64) { static base64ToArrayBuffer(base64) {
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
} }
static stringToBoolean = (stringValue) => { static stringToBoolean = (stringValue) => {
switch (stringValue?.toLowerCase()?.trim()) { switch (stringValue?.toLowerCase()?.trim()) {
case "true": case "true":
case "yes": case "yes":
case "1": case "1":
return true; return true;
case "false": case "false":
case "no": case "no":
case "0": case "0":
case null: case null:
case undefined: case undefined:
return false; return false;
default: default:
return JSON.parse(stringValue); return JSON.parse(stringValue);
} }
}; };
static capitalizeFirstLetter(string) { static capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1); return string.charAt(0).toUpperCase() + string.slice(1);
} }
} }