2022-10-19 16:44:21 +00:00
|
|
|
import fetch from "node-fetch";
|
|
|
|
import sharp from "sharp";
|
2022-10-20 17:00:27 +00:00
|
|
|
import { isValidSteamId } from "../../src/helpers/validateSteamId";
|
|
|
|
import RedisUtils from "../../src/utils/redisUtils";
|
2022-10-19 16:44:21 +00:00
|
|
|
|
2022-10-20 17:00:27 +00:00
|
|
|
const KEY = "STEAM_AVATAR_";
|
|
|
|
const ext = "jpg";
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {Request} req
|
|
|
|
* @param {Response} res
|
|
|
|
* @returns
|
|
|
|
*/
|
2022-10-19 16:44:21 +00:00
|
|
|
export default async function handler(req, res) {
|
|
|
|
const steamId = req.query.steamid;
|
2022-10-20 17:00:27 +00:00
|
|
|
const isValid = await isValidSteamId(steamId);
|
|
|
|
if (isValid == false) {
|
|
|
|
return res.status(404).json({
|
|
|
|
status: 404,
|
|
|
|
message: "Unknown Steam Avatar",
|
2022-10-19 16:44:21 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-10-20 17:00:27 +00:00
|
|
|
const exists = await RedisUtils.exists(`${KEY}${steamId}`);
|
|
|
|
if (exists) {
|
|
|
|
const data = await RedisUtils.getValue(`${KEY}${steamId}`);
|
|
|
|
const buffer = Buffer.from(data, "base64");
|
|
|
|
res.writeHead(200, {
|
|
|
|
"Content-Type": "image/" + ext,
|
|
|
|
"Content-Length": buffer.length,
|
|
|
|
"Cache-Status": "hit",
|
|
|
|
});
|
|
|
|
return res.end(buffer);
|
2022-10-19 16:44:21 +00:00
|
|
|
}
|
2022-10-20 17:00:27 +00:00
|
|
|
|
2022-10-21 13:51:29 +00:00
|
|
|
const before = Date.now();
|
2022-10-20 17:00:27 +00:00
|
|
|
const data = await fetch(
|
|
|
|
`https://cdn.scoresaber.com/avatars/${steamId}.${ext}`
|
|
|
|
);
|
|
|
|
if (data.status === 404) {
|
|
|
|
return res.status(404).json({
|
|
|
|
status: 404,
|
|
|
|
message: "Unknown Steam Avatar",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
let buffer = await data.buffer(); // Change to arrayBuffer at some point to make it shush
|
|
|
|
buffer = await sharp(buffer).resize(150, 150).toBuffer();
|
|
|
|
const bytes = buffer.toString("base64");
|
|
|
|
|
|
|
|
await RedisUtils.setValue(`${KEY}${steamId}`, bytes);
|
2022-10-21 13:51:29 +00:00
|
|
|
console.log(
|
|
|
|
`[Cache]: Cached Avatar for id ${steamId} in ${Date.now() - before}ms`
|
|
|
|
);
|
2022-10-20 17:00:27 +00:00
|
|
|
res.setHeader("Cache-Status", "miss");
|
|
|
|
res.setHeader("Content-Type", "image/" + ext);
|
|
|
|
res.status(200).send(buffer);
|
2022-10-19 16:44:21 +00:00
|
|
|
}
|