aboutsummaryrefslogtreecommitdiff
path: root/build
diff options
context:
space:
mode:
authormat <27899617+mat-1@users.noreply.github.com>2021-05-27 16:56:50 -0500
committerGitHub <noreply@github.com>2021-05-27 16:56:50 -0500
commitc9097dc2d0749fa63fd731423bc87a5452f0444d (patch)
tree50afe6b99cf3ed6bd7369e804316c05c7407b5ca /build
parenta3662fb5888bd031b27cc81028ba86b0271eb442 (diff)
downloadskyblock-api-c9097dc2d0749fa63fd731423bc87a5452f0444d.tar.gz
skyblock-api-c9097dc2d0749fa63fd731423bc87a5452f0444d.tar.bz2
skyblock-api-c9097dc2d0749fa63fd731423bc87a5452f0444d.zip
Profile customization (#45)
* add basic discord auth * add uuid dependency * add lastUpdated to sessions * add route to get session from id * add accounts collection * update build * add gm rank * add `customization` url parameter * add customization parameter to /player/:user * add route to get info from discord id * remove a console.log * Update database.js * Update package.json * fix tests
Diffstat (limited to 'build')
-rw-r--r--build/cleaners/rank.js2
-rw-r--r--build/database.js41
-rw-r--r--build/discord.js42
-rw-r--r--build/hypixel.js28
-rw-r--r--build/hypixelApi.js2
-rw-r--r--build/index.js50
6 files changed, 151 insertions, 14 deletions
diff --git a/build/cleaners/rank.js b/build/cleaners/rank.js
index de2309e..38965e2 100644
--- a/build/cleaners/rank.js
+++ b/build/cleaners/rank.js
@@ -33,8 +33,8 @@ function cleanRank({ packageRank, newPackageRank, monthlyPackageRank, rankPlusCo
name = rank;
else
name = (_a = newPackageRank === null || newPackageRank === void 0 ? void 0 : newPackageRank.replace('_PLUS', '+')) !== null && _a !== void 0 ? _a : packageRank === null || packageRank === void 0 ? void 0 : packageRank.replace('_PLUS', '+');
- // MVP++ is called Superstar for some reason
switch (name) {
+ // MVP++ is called Superstar for some reason
case 'SUPERSTAR':
name = 'MVP++';
break;
diff --git a/build/database.js b/build/database.js
index 55867ce..2d1f5e9 100644
--- a/build/database.js
+++ b/build/database.js
@@ -25,8 +25,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
-exports.queueUpdateDatabaseProfile = exports.queueUpdateDatabaseMember = exports.updateDatabaseProfile = exports.updateDatabaseMember = exports.fetchMemberLeaderboardSpots = exports.fetchLeaderboard = exports.fetchProfileLeaderboard = exports.fetchMemberLeaderboard = exports.fetchAllMemberLeaderboardAttributes = exports.fetchSlayerLeaderboards = exports.fetchAllLeaderboardsCategorized = exports.cachedRawLeaderboards = void 0;
+exports.updateAccount = exports.fetchAccountFromDiscord = exports.fetchAccount = exports.fetchSession = exports.createSession = exports.queueUpdateDatabaseProfile = exports.queueUpdateDatabaseMember = exports.updateDatabaseProfile = exports.updateDatabaseMember = exports.fetchMemberLeaderboardSpots = exports.fetchLeaderboard = exports.fetchProfileLeaderboard = exports.fetchMemberLeaderboard = exports.fetchAllMemberLeaderboardAttributes = exports.fetchSlayerLeaderboards = exports.fetchAllLeaderboardsCategorized = exports.cachedRawLeaderboards = void 0;
const stats_1 = require("./cleaners/skyblock/stats");
+const slayers_1 = require("./cleaners/skyblock/slayers");
const mongodb_1 = require("mongodb");
const cached = __importStar(require("./hypixelCached"));
const constants = __importStar(require("./constants"));
@@ -34,7 +35,7 @@ const util_1 = require("./util");
const node_cache_1 = __importDefault(require("node-cache"));
const queue_promise_1 = __importDefault(require("queue-promise"));
const _1 = require(".");
-const slayers_1 = require("./cleaners/skyblock/slayers");
+const uuid_1 = require("uuid");
// don't update the user for 3 minutes
const recentlyUpdated = new node_cache_1.default({
stdTTL: 60 * 3,
@@ -51,6 +52,8 @@ let client;
let database;
let memberLeaderboardsCollection;
let profileLeaderboardsCollection;
+let sessionsCollection;
+let accountsCollection;
async function connect() {
if (!process.env.db_uri)
return console.warn('Warning: db_uri was not found in .env. Features that utilize the database such as leaderboards won\'t work.');
@@ -60,6 +63,8 @@ async function connect() {
database = client.db(process.env.db_name);
memberLeaderboardsCollection = database.collection('member-leaderboards');
profileLeaderboardsCollection = database.collection('profile-leaderboards');
+ sessionsCollection = database.collection('sessions');
+ accountsCollection = database.collection('accounts');
}
function getMemberCollectionAttributes(member) {
const collectionAttributes = {};
@@ -512,6 +517,38 @@ async function fetchAllLeaderboards(fast) {
if (_1.debug)
console.debug('Finished caching leaderboards!');
}
+async function createSession(refreshToken, userData) {
+ const sessionId = uuid_1.v4();
+ await sessionsCollection.insertOne({
+ _id: sessionId,
+ refresh_token: refreshToken,
+ discord_user: {
+ id: userData.id,
+ name: userData.username + '#' + userData.discriminator
+ },
+ lastUpdated: new Date()
+ });
+ return sessionId;
+}
+exports.createSession = createSession;
+async function fetchSession(sessionId) {
+ return await sessionsCollection.findOne({ _id: sessionId });
+}
+exports.fetchSession = fetchSession;
+async function fetchAccount(minecraftUuid) {
+ return await accountsCollection.findOne({ minecraftUuid });
+}
+exports.fetchAccount = fetchAccount;
+async function fetchAccountFromDiscord(discordId) {
+ return await accountsCollection.findOne({ discordId });
+}
+exports.fetchAccountFromDiscord = fetchAccountFromDiscord;
+async function updateAccount(discordId, schema) {
+ await accountsCollection.updateOne({
+ discordId
+ }, { $set: schema }, { upsert: true });
+}
+exports.updateAccount = updateAccount;
// make sure it's not in a test
if (!globalThis.isTest) {
connect().then(() => {
diff --git a/build/discord.js b/build/discord.js
new file mode 100644
index 0000000..be085bb
--- /dev/null
+++ b/build/discord.js
@@ -0,0 +1,42 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.getUser = exports.exchangeCode = void 0;
+const node_fetch_1 = __importDefault(require("node-fetch"));
+const https_1 = require("https");
+const DISCORD_CLIENT_ID = '656634948148527107';
+const httpsAgent = new https_1.Agent({
+ keepAlive: true
+});
+async function exchangeCode(redirectUri, code) {
+ const API_ENDPOINT = 'https://discord.com/api/v6';
+ const CLIENT_SECRET = process.env.discord_client_secret;
+ const data = {
+ 'client_id': DISCORD_CLIENT_ID,
+ 'client_secret': CLIENT_SECRET,
+ 'grant_type': 'authorization_code',
+ 'code': code,
+ 'redirect_uri': redirectUri,
+ 'scope': 'identify'
+ };
+ console.log(new URLSearchParams(data).toString());
+ const fetchResponse = await node_fetch_1.default(API_ENDPOINT + '/oauth2/token', {
+ method: 'POST',
+ agent: () => httpsAgent,
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams(data).toString()
+ });
+ return await fetchResponse.json();
+}
+exports.exchangeCode = exchangeCode;
+async function getUser(accessToken) {
+ const API_ENDPOINT = 'https://discord.com/api/v6';
+ const response = await node_fetch_1.default(API_ENDPOINT + '/users/@me', {
+ headers: { 'Authorization': 'Bearer ' + accessToken },
+ agent: () => httpsAgent,
+ });
+ return response.json();
+}
+exports.getUser = getUser;
diff --git a/build/hypixel.js b/build/hypixel.js
index ea61e4e..8e58ffc 100644
--- a/build/hypixel.js
+++ b/build/hypixel.js
@@ -23,13 +23,13 @@ var __importStar = (this && this.__importStar) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchMemberProfilesUncached = exports.fetchBasicProfileFromUuidUncached = exports.fetchMemberProfileUncached = exports.fetchMemberProfile = exports.fetchUser = exports.sendCleanApiRequest = exports.maxMinion = exports.saveInterval = void 0;
-const player_1 = require("./cleaners/player");
-const hypixelApi_1 = require("./hypixelApi");
-const cached = __importStar(require("./hypixelCached"));
const profile_1 = require("./cleaners/skyblock/profile");
+const database_1 = require("./database");
+const hypixelApi_1 = require("./hypixelApi");
const profiles_1 = require("./cleaners/skyblock/profiles");
+const player_1 = require("./cleaners/player");
+const cached = __importStar(require("./hypixelCached"));
const _1 = require(".");
-const database_1 = require("./database");
// the interval at which the "last_save" parameter updates in the hypixel api, this is 3 minutes
exports.saveInterval = 60 * 3 * 1000;
// the highest level a minion can be
@@ -61,11 +61,12 @@ async function cleanResponse({ path, data }, options) {
* @param included lets you choose what is returned, so there's less processing required on the backend
* used inclusions: player, profiles
*/
-async function fetchUser({ user, uuid, username }, included = ['player']) {
+async function fetchUser({ user, uuid, username }, included = ['player'], customization) {
if (!uuid) {
// If the uuid isn't provided, get it
uuid = await cached.uuidFromUser(user || username);
}
+ const websiteAccountPromise = customization ? database_1.fetchAccount(uuid) : null;
if (!uuid) {
// the user doesn't exist.
if (_1.debug)
@@ -99,11 +100,15 @@ async function fetchUser({ user, uuid, username }, included = ['player']) {
}
}
}
+ let websiteAccount = undefined;
+ if (websiteAccountPromise)
+ websiteAccount = await websiteAccountPromise;
return {
player: playerData !== null && playerData !== void 0 ? playerData : null,
profiles: profilesData !== null && profilesData !== void 0 ? profilesData : basicProfilesData,
activeProfile: includeProfiles ? activeProfile === null || activeProfile === void 0 ? void 0 : activeProfile.uuid : undefined,
- online: includeProfiles ? lastOnline > (Date.now() - exports.saveInterval) : undefined
+ online: includeProfiles ? lastOnline > (Date.now() - exports.saveInterval) : undefined,
+ customization: websiteAccount === null || websiteAccount === void 0 ? void 0 : websiteAccount.customization
};
}
exports.fetchUser = fetchUser;
@@ -112,9 +117,12 @@ exports.fetchUser = fetchUser;
* This is safe to use many times as the results are cached!
* @param user A username or uuid
* @param profile A profile name or profile uuid
+ * @param customization Whether stuff like the user's custom background will be returned
*/
-async function fetchMemberProfile(user, profile) {
+async function fetchMemberProfile(user, profile, customization) {
const playerUuid = await cached.uuidFromUser(user);
+ // we don't await the promise immediately so it can load while we do other stuff
+ const websiteAccountPromise = customization ? database_1.fetchAccount(playerUuid) : null;
const profileUuid = await cached.fetchProfileUuid(user, profile);
// if the profile doesn't have an id, just return
if (!profileUuid)
@@ -133,6 +141,9 @@ async function fetchMemberProfile(user, profile) {
};
});
cleanProfile.members = simpleMembers;
+ let websiteAccount = undefined;
+ if (websiteAccountPromise)
+ websiteAccount = await websiteAccountPromise;
return {
member: {
// the profile name is in member rather than profile since they sometimes differ for each member
@@ -142,7 +153,8 @@ async function fetchMemberProfile(user, profile) {
// add all other data relating to the hypixel player, such as username, rank, etc
...player
},
- profile: cleanProfile
+ profile: cleanProfile,
+ customization: websiteAccount === null || websiteAccount === void 0 ? void 0 : websiteAccount.customization
};
}
exports.fetchMemberProfile = fetchMemberProfile;
diff --git a/build/hypixelApi.js b/build/hypixelApi.js
index ccae09b..9f54ef2 100644
--- a/build/hypixelApi.js
+++ b/build/hypixelApi.js
@@ -36,7 +36,7 @@ function chooseApiKey() {
if (Date.now() > keyUsage.reset)
keyUsage.remaining = keyUsage.limit;
// if this key has more uses remaining than the current known best one, save it
- if (!bestKeyUsage || keyUsage.remaining > bestKeyUsage.remaining) {
+ if (bestKeyUsage === null || keyUsage.remaining > bestKeyUsage.remaining) {
bestKeyUsage = keyUsage;
bestKey = key;
}
diff --git a/build/index.js b/build/index.js
index c7f1385..09ca7d7 100644
--- a/build/index.js
+++ b/build/index.js
@@ -27,9 +27,11 @@ const database_1 = require("./database");
const hypixel_1 = require("./hypixel");
const express_rate_limit_1 = __importDefault(require("express-rate-limit"));
const constants = __importStar(require("./constants"));
+const discord = __importStar(require("./discord"));
const express_1 = __importDefault(require("express"));
const app = express_1.default();
exports.debug = false;
+const mainSiteUrl = 'http://localhost:8081';
// 200 requests over 5 minutes
const limiter = express_rate_limit_1.default({
windowMs: 60 * 1000 * 5,
@@ -43,6 +45,7 @@ const limiter = express_rate_limit_1.default({
}
});
app.use(limiter);
+app.use(express_1.default.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
@@ -51,10 +54,13 @@ app.get('/', async (req, res) => {
res.json({ ok: true });
});
app.get('/player/:user', async (req, res) => {
- res.json(await hypixel_1.fetchUser({ user: req.params.user }, [req.query.basic === 'true' ? undefined : 'profiles', 'player']));
+ res.json(await hypixel_1.fetchUser({ user: req.params.user }, [req.query.basic === 'true' ? undefined : 'profiles', 'player'], req.query.customization === 'true'));
+});
+app.get('/discord/:id', async (req, res) => {
+ res.json(await database_1.fetchAccountFromDiscord(req.params.id));
});
app.get('/player/:user/:profile', async (req, res) => {
- res.json(await hypixel_1.fetchMemberProfile(req.params.user, req.params.profile));
+ res.json(await hypixel_1.fetchMemberProfile(req.params.user, req.params.profile, req.query.customization === 'true'));
});
app.get('/player/:user/:profile/leaderboards', async (req, res) => {
res.json(await database_1.fetchMemberLeaderboardSpots(req.params.user, req.params.profile));
@@ -74,6 +80,46 @@ app.get('/leaderboards', async (req, res) => {
app.get('/constants', async (req, res) => {
res.json(await constants.fetchConstantValues());
});
+app.post('/accounts/createsession', async (req, res) => {
+ try {
+ const { code } = req.body;
+ const { access_token: accessToken, refresh_token: refreshToken } = await discord.exchangeCode(`${mainSiteUrl}/loggedin`, code);
+ if (!accessToken)
+ // access token is invalid :(
+ return res.json({ ok: false });
+ const userData = await discord.getUser(accessToken);
+ const sessionId = await database_1.createSession(refreshToken, userData);
+ res.json({ ok: true, session_id: sessionId });
+ }
+ catch (err) {
+ res.json({ ok: false });
+ }
+});
+app.post('/accounts/session', async (req, res) => {
+ try {
+ const { uuid } = req.body;
+ const session = await database_1.fetchSession(uuid);
+ const account = await database_1.fetchAccountFromDiscord(session.discord_user.id);
+ res.json({ session, account });
+ }
+ catch (err) {
+ console.error(err);
+ res.json({ ok: false });
+ }
+});
+app.post('/accounts/update', async (req, res) => {
+ // it checks against the key, so it's kind of secure
+ if (req.headers.key !== process.env.key)
+ return console.log('bad key!');
+ try {
+ await database_1.updateAccount(req.body.discordId, req.body);
+ res.json({ ok: true });
+ }
+ catch (err) {
+ console.error(err);
+ res.json({ ok: false });
+ }
+});
// only run the server if it's not doing tests
if (!globalThis.isTest)
app.listen(8080, () => console.log('App started :)'));