From c0c534dafb54ebf9f95a5054f576ad99de29f232 Mon Sep 17 00:00:00 2001 From: mat <27899617+mat-1@users.noreply.github.com> Date: Tue, 29 Jun 2021 17:52:00 -0500 Subject: enable strictNullChecks and fix all related issues (#65) --- src/cleaners/player.ts | 4 +- src/cleaners/skyblock/collections.ts | 2 +- src/cleaners/skyblock/inventory.ts | 4 +- src/cleaners/skyblock/member.ts | 13 +++--- src/cleaners/skyblock/minions.ts | 2 +- src/cleaners/skyblock/profile.ts | 8 ++-- src/cleaners/skyblock/profiles.ts | 11 ++++-- src/cleaners/skyblock/stats.ts | 11 +++--- src/constants.ts | 4 +- src/database.ts | 62 ++++++++++++++++++----------- src/discord.ts | 6 ++- src/hypixel.ts | 55 ++++++++++++++------------ src/hypixelApi.ts | 12 +++--- src/hypixelCached.ts | 77 ++++++++++++++++++++++-------------- src/index.ts | 9 ++++- src/mojang.ts | 7 ++-- src/util.ts | 2 +- 17 files changed, 171 insertions(+), 118 deletions(-) (limited to 'src') diff --git a/src/cleaners/player.ts b/src/cleaners/player.ts index 6ac1382..b2dfc77 100644 --- a/src/cleaners/player.ts +++ b/src/cleaners/player.ts @@ -17,10 +17,10 @@ export interface CleanPlayer extends CleanBasicPlayer { // first_join?: number } -export async function cleanPlayerResponse(data: HypixelPlayer): Promise { +export async function cleanPlayerResponse(data: HypixelPlayer): Promise { // Cleans up a 'player' api response if (!data) - return // bruh + return null // bruh return { uuid: undashUuid(data.uuid), username: data.displayname, diff --git a/src/cleaners/skyblock/collections.ts b/src/cleaners/skyblock/collections.ts index 708822b..99fdc27 100644 --- a/src/cleaners/skyblock/collections.ts +++ b/src/cleaners/skyblock/collections.ts @@ -84,7 +84,7 @@ export interface Collection { } // get a category name (farming) from a collection name (wheat) -function getCategory(collectionName): CollectionCategory { +function getCategory(collectionName): CollectionCategory | undefined { for (const categoryName in COLLECTIONS) { const categoryItems = COLLECTIONS[categoryName] if (categoryItems.includes(collectionName)) diff --git a/src/cleaners/skyblock/inventory.ts b/src/cleaners/skyblock/inventory.ts index 890937a..5ad6617 100644 --- a/src/cleaners/skyblock/inventory.ts +++ b/src/cleaners/skyblock/inventory.ts @@ -26,7 +26,7 @@ interface Item { export type Inventory = Item[] -function cleanItem(rawItem): Item { +function cleanItem(rawItem): Item | null { // if the item doesn't have an id, it isn't an item if (rawItem.id === undefined) return null @@ -35,7 +35,7 @@ function cleanItem(rawItem): Item { const damageValue = rawItem.Damage const itemTag = rawItem.tag const extraAttributes = itemTag?.ExtraAttributes ?? {} - let headId: string + let headId: string | undefined if (vanillaId === 397) { const headDataBase64 = itemTag?.SkullOwner?.Properties?.textures?.[0]?.Value diff --git a/src/cleaners/skyblock/member.ts b/src/cleaners/skyblock/member.ts index 4a2f8cc..cee1864 100644 --- a/src/cleaners/skyblock/member.ts +++ b/src/cleaners/skyblock/member.ts @@ -30,7 +30,7 @@ export interface CleanMember extends CleanBasicMember { rawHypixelStats?: { [ key: string ]: number } minions: CleanMinion[] fairy_souls: FairySouls - inventories: Inventories + inventories?: Inventories objectives: Objective[] skills: Skill[] visited_zones: Zone[] @@ -38,8 +38,9 @@ export interface CleanMember extends CleanBasicMember { slayers: SlayerData } -export async function cleanSkyBlockProfileMemberResponseBasic(member: any, included: Included[] = null): Promise { +export async function cleanSkyBlockProfileMemberResponseBasic(member: any): Promise { const player = await cached.fetchPlayer(member.uuid) + if (!player) return null return { uuid: member.uuid, username: player.username, @@ -50,11 +51,11 @@ export async function cleanSkyBlockProfileMemberResponseBasic(member: any, inclu } /** Cleans up a member (from skyblock/profile) */ -export async function cleanSkyBlockProfileMemberResponse(member, included: Included[] = null): Promise { +export async function cleanSkyBlockProfileMemberResponse(member, included: Included[] | undefined = undefined): Promise { // profiles.members[] - const inventoriesIncluded = included === null || included.includes('inventories') + const inventoriesIncluded = included === undefined || included.includes('inventories') const player = await cached.fetchPlayer(member.uuid) - if (!player) return + if (!player) return null const fairySouls = cleanFairySouls(member) const { max_fairy_souls: maxFairySouls } = await constants.fetchConstantValues() @@ -109,5 +110,5 @@ export interface CleanMemberProfilePlayer extends CleanPlayer { export interface CleanMemberProfile { member: CleanMemberProfilePlayer profile: CleanFullProfileBasicMembers - customization: AccountCustomization + customization?: AccountCustomization } diff --git a/src/cleaners/skyblock/minions.ts b/src/cleaners/skyblock/minions.ts index 21f7b66..d045a7e 100644 --- a/src/cleaners/skyblock/minions.ts +++ b/src/cleaners/skyblock/minions.ts @@ -80,7 +80,7 @@ export function combineMinionArrays(minions: CleanMinion[][]): CleanMinion[] { // This should never happen, but in case the length of `minion.levels` is longer than // `matchingMinionReference.levels`, then it should be extended to be equal length while (matchingMinionReference.levels.length < minion.levels.length) - matchingMinionReference.levels.push(null) + matchingMinionReference.levels.push(false) for (let i = 0; i < minion.levels.length; i++) { if (minion.levels[i]) diff --git a/src/cleaners/skyblock/profile.ts b/src/cleaners/skyblock/profile.ts index 0453ff3..5bcea4b 100644 --- a/src/cleaners/skyblock/profile.ts +++ b/src/cleaners/skyblock/profile.ts @@ -25,7 +25,7 @@ export interface CleanFullProfileBasicMembers extends CleanProfile { /** Return a `CleanProfile` instead of a `CleanFullProfile`, useful when we need to get members but don't want to waste much ram */ export async function cleanSkyblockProfileResponseLighter(data): Promise { // We use Promise.all so it can fetch all the usernames at once instead of waiting for the previous promise to complete - const promises: Promise[] = [] + const promises: Promise[] = [] for (const memberUUID in data.members) { const memberRaw = data.members[memberUUID] @@ -34,7 +34,7 @@ export async function cleanSkyblockProfileResponseLighter(data): Promise m) as CleanBasicMember[] return { uuid: data.profile_id, @@ -48,7 +48,7 @@ export async function cleanSkyblockProfileResponseLighter(data): Promise { // We use Promise.all so it can fetch all the users at once instead of waiting for the previous promise to complete - const promises: Promise[] = [] + const promises: Promise[] = [] for (const memberUUID in data.members) { const memberRaw = data.members[memberUUID] @@ -62,7 +62,7 @@ export async function cleanSkyblockProfileResponse(data: any, options?: ApiOptio )) } - const cleanedMembers: CleanMember[] = (await Promise.all(promises)).filter(m => m !== null && m !== undefined) + const cleanedMembers: CleanMember[] = (await Promise.all(promises)).filter(m => m !== null && m !== undefined) as CleanMember[] if (options?.basic) { return { diff --git a/src/cleaners/skyblock/profiles.ts b/src/cleaners/skyblock/profiles.ts index f12b5f6..a44fe48 100644 --- a/src/cleaners/skyblock/profiles.ts +++ b/src/cleaners/skyblock/profiles.ts @@ -1,5 +1,10 @@ -import { HypixelPlayerStatsSkyBlockProfiles } from "../../hypixelApi" -import { CleanBasicProfile, CleanProfile, cleanSkyblockProfileResponse, cleanSkyblockProfileResponseLighter } from "./profile" +import { HypixelPlayerStatsSkyBlockProfiles } from '../../hypixelApi' +import { + CleanBasicProfile, + CleanFullProfile, + CleanProfile, + cleanSkyblockProfileResponse +} from './profile' export function cleanPlayerSkyblockProfiles(rawProfiles: HypixelPlayerStatsSkyBlockProfiles): CleanBasicProfile[] { let profiles: CleanBasicProfile[] = [] @@ -14,7 +19,7 @@ export function cleanPlayerSkyblockProfiles(rawProfiles: HypixelPlayerStatsSkyBl /** Convert an array of raw profiles into clean profiles */ export async function cleanSkyblockProfilesResponse(data: any[]): Promise { - const promises = [] + const promises: Promise[] = [] for (const profile of data ?? []) { // let cleanedProfile = await cleanSkyblockProfileResponseLighter(profile) promises.push(cleanSkyblockProfileResponse(profile)) diff --git a/src/cleaners/skyblock/stats.ts b/src/cleaners/skyblock/stats.ts index 31a894c..a91ca74 100644 --- a/src/cleaners/skyblock/stats.ts +++ b/src/cleaners/skyblock/stats.ts @@ -14,8 +14,8 @@ const statCategories: { [ key: string ]: string[] | null } = { // sorted in orde } export interface StatCategory { - category: string, - name: string + category: string | null + name: string | null } export function categorizeStat(statNameRaw: string): StatCategory { @@ -71,11 +71,11 @@ export interface StatItem { rawName: string value: number categorizedName: string - category: string - unit: string + category: string | null + unit: string | null } -export function getStatUnit(name: string): string { +export function getStatUnit(name: string): string | null { for (const [ unitName, statMatchers ] of Object.entries(statUnits)) { for (const statMatch of statMatchers) { let trailingEnd = statMatch[0] === '_' @@ -88,6 +88,7 @@ export function getStatUnit(name: string): string { return unitName } } + return null } diff --git a/src/constants.ts b/src/constants.ts index 9699e57..dcb9acf 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -40,7 +40,7 @@ async function fetchGithubApi(method: string, route: string, headers?: any, json githubApiBase + route, { agent: () => httpsAgent, - body: json ? JSON.stringify(json) : null, + body: json ? JSON.stringify(json) : undefined, method, headers: Object.assign({ 'Authorization': `token ${process.env.github_token}` @@ -78,7 +78,7 @@ function fetchFile(path: string): Promise { return new Promise(resolve => { queue.enqueue(async() => { if (fileCache.has(path)) - return resolve(fileCache.get(path)) + return resolve(fileCache.get(path)!) const r = await fetchGithubApi( 'GET', diff --git a/src/database.ts b/src/database.ts index 60fbc7e..5d15954 100644 --- a/src/database.ts +++ b/src/database.ts @@ -59,7 +59,7 @@ interface profileRawLeaderboardItem { } interface MemberLeaderboardItem { - player: CleanPlayer + player: CleanPlayer | null profileUuid: string value: number } @@ -205,9 +205,11 @@ export async function fetchAllLeaderboardsCategorized(): Promise<{ [ category: s const categorizedLeaderboards: { [ category: string ]: string[] } = {} for (const leaderboard of [...memberLeaderboardAttributes, ...profileLeaderboardAttributes]) { const { category } = categorizeStat(leaderboard) - if (!categorizedLeaderboards[category]) - categorizedLeaderboards[category] = [] - categorizedLeaderboards[category].push(leaderboard) + if (category) { + if (!categorizedLeaderboards[category]) + categorizedLeaderboards[category] = [] + categorizedLeaderboards[category].push(leaderboard) + } } // move misc to end by removing and readding it @@ -366,14 +368,14 @@ async function fetchProfileLeaderboardRaw(name: string): Promise => { + const player = await cached.fetchBasicPlayer(i.uuid) return { - player: await cached.fetchBasicPlayer(i.uuid), + player, profileUuid: i.profile, value: i.value } @@ -408,9 +411,12 @@ export async function fetchProfileLeaderboard(name: string): Promise => { - const players = [] - for (const playerUuid of i.players) - players.push(await cached.fetchBasicPlayer(playerUuid)) + const players: CleanPlayer[] = [] + for (const playerUuid of i.players) { + const player = await cached.fetchBasicPlayer(playerUuid) + if (player) + players.push(player) + } return { players: players, profileUuid: i.uuid, @@ -445,17 +451,26 @@ export async function fetchLeaderboard(name: string): Promise { const fullProfile = await cached.fetchProfile(player, profile) + if (!fullProfile) return null const fullMember = fullProfile.members.find(m => m.username.toLowerCase() === player.toLowerCase() || m.uuid === player) + if (!fullMember) return null // update the leaderboard positions for the member await updateDatabaseMember(fullMember, fullProfile) const applicableAttributes = await getApplicableMemberLeaderboardAttributes(fullMember) - const memberLeaderboardSpots = [] + const memberLeaderboardSpots: LeaderboardSpot[] = [] for (const leaderboardName in applicableAttributes) { const leaderboard = await fetchMemberLeaderboardRaw(leaderboardName) @@ -472,7 +487,7 @@ export async function fetchMemberLeaderboardSpots(player: string, profile: strin return memberLeaderboardSpots } -async function getLeaderboardRequirement(name: string, leaderboardType: 'member' | 'profile'): Promise { +async function getLeaderboardRequirement(name: string, leaderboardType: 'member' | 'profile'): Promise { let leaderboard: memberRawLeaderboardItem[] | profileRawLeaderboardItem[] if (leaderboardType === 'member') leaderboard = await fetchMemberLeaderboardRaw(name) @@ -480,8 +495,8 @@ async function getLeaderboardRequirement(name: string, leaderboardType: 'member' leaderboard = await fetchProfileLeaderboardRaw(name) // if there's more than 100 items, return the 100th. if there's less, return null - if (leaderboard.length >= leaderboardMax) - return leaderboard[leaderboardMax - 1].value + if (leaderboard!.length >= leaderboardMax) + return leaderboard![leaderboardMax - 1].value else return null } @@ -504,7 +519,7 @@ async function getApplicableMemberLeaderboardAttributes(member: CleanMember): Pr let leaderboardsCount: number = Object.keys(applicableAttributes).length - const leaderboardsCountRequirement: number = await getLeaderboardRequirement('leaderboards_count', 'member') + const leaderboardsCountRequirement: number | null = await getLeaderboardRequirement('leaderboards_count', 'member') if ( (leaderboardsCountRequirement === null) @@ -534,11 +549,11 @@ async function getApplicableProfileLeaderboardAttributes(profile: CleanFullProfi let leaderboardsCount: number = Object.keys(applicableAttributes).length - const leaderboardsCountRequirement: number = await getLeaderboardRequirement('leaderboards_count', 'member') + const leaderboardsCountRequirement: number | null = await getLeaderboardRequirement('leaderboards_count', 'member') if ( - (leaderboardsCountRequirement === null) - || (leaderboardsCount > leaderboardsCountRequirement) + leaderboardsCountRequirement === null + || leaderboardsCount > leaderboardsCountRequirement ) { applicableAttributes['leaderboards_count'] = leaderboardsCount } @@ -557,7 +572,8 @@ export async function updateDatabaseMember(member: CleanMember, profile: CleanFu if (debug) console.debug('adding member to leaderboards', member.username) - await constants.addStats(Object.keys(member.rawHypixelStats)) + if (member.rawHypixelStats) + await constants.addStats(Object.keys(member.rawHypixelStats)) await constants.addCollections(member.collections.map(coll => coll.name)) await constants.addSkills(member.skills.map(skill => skill.name)) await constants.addZones(member.visited_zones.map(zone => zone.name)) @@ -738,15 +754,15 @@ export async function createSession(refreshToken: string, userData: discord.Disc return sessionId } -export async function fetchSession(sessionId: string): Promise { +export async function fetchSession(sessionId: string): Promise { return await sessionsCollection?.findOne({ _id: sessionId }) } -export async function fetchAccount(minecraftUuid: string): Promise { +export async function fetchAccount(minecraftUuid: string): Promise { return await accountsCollection?.findOne({ minecraftUuid }) } -export async function fetchAccountFromDiscord(discordId: string): Promise { +export async function fetchAccountFromDiscord(discordId: string): Promise { return await accountsCollection?.findOne({ discordId }) } diff --git a/src/discord.ts b/src/discord.ts index 48146b5..fac5438 100644 --- a/src/discord.ts +++ b/src/discord.ts @@ -26,9 +26,13 @@ export interface DiscordUser { mfa_enabled: boolean } -export async function exchangeCode(redirectUri: string, code: string): Promise { +export async function exchangeCode(redirectUri: string, code: string): Promise { const API_ENDPOINT = 'https://discord.com/api/v6' const CLIENT_SECRET = process.env.discord_client_secret + if (!CLIENT_SECRET) { + console.error('discord_client_secret isn\'t in env, couldn\'t login with discord') + return null + } const data = { 'client_id': DISCORD_CLIENT_ID, 'client_secret': CLIENT_SECRET, diff --git a/src/hypixel.ts b/src/hypixel.ts index eb66d48..d6f9661 100644 --- a/src/hypixel.ts +++ b/src/hypixel.ts @@ -11,7 +11,7 @@ import { CleanPlayer, cleanPlayerResponse } from './cleaners/player' import * as cached from './hypixelCached' import { debug } from '.' -export type Included = 'profiles' | 'player' | 'stats' | 'inventories' +export type Included = 'profiles' | 'player' | 'stats' | 'inventories' | undefined // the interval at which the "last_save" parameter updates in the hypixel api, this is 3 minutes export const saveInterval = 60 * 3 * 1000 @@ -62,7 +62,7 @@ export interface UserAny { } export interface CleanUser { - player: CleanPlayer + player: CleanPlayer | null profiles?: CleanProfile[] activeProfile?: string online?: boolean @@ -76,24 +76,25 @@ export interface CleanUser { * @param included lets you choose what is returned, so there's less processing required on the backend * used inclusions: player, profiles */ -export async function fetchUser({ user, uuid, username }: UserAny, included: Included[]=['player'], customization?: boolean): Promise { +export async function fetchUser({ user, uuid, username }: UserAny, included: Included[]=['player'], customization?: boolean): Promise { if (!uuid) { // If the uuid isn't provided, get it - uuid = await cached.uuidFromUser(user || username) + if (!username && !user) return null + uuid = await cached.uuidFromUser((user ?? username)!) } - const websiteAccountPromise = customization ? fetchAccount(uuid) : null if (!uuid) { // the user doesn't exist. if (debug) console.debug('error:', user, 'doesnt exist') return null } + const websiteAccountPromise = customization ? fetchAccount(uuid) : null const includePlayers = included.includes('player') const includeProfiles = included.includes('profiles') - let profilesData: CleanProfile[] - let basicProfilesData: CleanBasicProfile[] - let playerData: CleanPlayer + let profilesData: CleanProfile[] | undefined + let basicProfilesData: CleanBasicProfile[] | undefined + let playerData: CleanPlayer | null = null if (includePlayers) { playerData = await cached.fetchPlayer(uuid) @@ -103,31 +104,30 @@ export async function fetchUser({ user, uuid, username }: UserAny, included: Inc if (playerData) delete playerData.profiles } - if (includeProfiles) { + if (includeProfiles) profilesData = await cached.fetchSkyblockProfiles(uuid) - } - let activeProfile: CleanProfile = null + let activeProfile: CleanProfile let lastOnline: number = 0 if (includeProfiles) { - for (const profile of profilesData) { - const member = profile.members.find(member => member.uuid === uuid) - if (member.last_save > lastOnline) { + for (const profile of profilesData!) { + const member = profile.members?.find(member => member.uuid === uuid) + if (member && member.last_save > lastOnline) { lastOnline = member.last_save activeProfile = profile } } } - let websiteAccount: AccountSchema = undefined + let websiteAccount: AccountSchema | null = null - if (websiteAccountPromise) { + if (websiteAccountPromise) websiteAccount = await websiteAccountPromise - } + return { - player: playerData ?? null, + player: playerData, profiles: profilesData ?? basicProfilesData, - activeProfile: includeProfiles ? activeProfile?.uuid : undefined, + activeProfile: includeProfiles ? activeProfile!?.uuid : undefined, online: includeProfiles ? lastOnline > (Date.now() - saveInterval): undefined, customization: websiteAccount?.customization } @@ -140,9 +140,9 @@ export async function fetchUser({ user, uuid, username }: UserAny, included: Inc * @param profile A profile name or profile uuid * @param customization Whether stuff like the user's custom background will be returned */ -export async function fetchMemberProfile(user: string, profile: string, customization: boolean): Promise { +export async function fetchMemberProfile(user: string, profile: string, customization: boolean): Promise { const playerUuid = await cached.uuidFromUser(user) - if (!playerUuid) return + if (!playerUuid) return null // we don't await the promise immediately so it can load while we do other stuff const websiteAccountPromise = customization ? fetchAccount(playerUuid) : null const profileUuid = await cached.fetchProfileUuid(user, profile) @@ -153,9 +153,12 @@ export async function fetchMemberProfile(user: string, profile: string, customiz const player = await cached.fetchPlayer(playerUuid) + if (!player) return null // this should never happen, but if it does just return null + const cleanProfile = await cached.fetchProfile(playerUuid, profileUuid) as CleanFullProfileBasicMembers const member = cleanProfile.members.find(m => m.uuid === playerUuid) + if (!member) return null // this should never happen, but if it does just return null // remove unnecessary member data const simpleMembers: CleanBasicMember[] = cleanProfile.members.map(m => { @@ -170,7 +173,7 @@ export async function fetchMemberProfile(user: string, profile: string, customiz cleanProfile.members = simpleMembers - let websiteAccount: AccountSchema = undefined + let websiteAccount: AccountSchema | null = null if (websiteAccountPromise) websiteAccount = await websiteAccountPromise @@ -178,7 +181,7 @@ export async function fetchMemberProfile(user: string, profile: string, customiz return { member: { // the profile name is in member rather than profile since they sometimes differ for each member - profileName: cleanProfile.name, + profileName: cleanProfile.name!, // add all the member data ...member, // add all other data relating to the hypixel player, such as username, rank, etc @@ -200,7 +203,7 @@ export async function fetchMemberProfile(user: string, profile: string, customiz path: 'skyblock/profile', args: { profile: profileUuid } }, - null, + undefined, { mainMemberUuid: playerUuid } ) @@ -223,7 +226,7 @@ export async function fetchMemberProfile(user: string, profile: string, customiz path: 'skyblock/profile', args: { profile: profileUuid } }, - null, + undefined, { basic: true } ) @@ -237,7 +240,7 @@ export async function fetchMemberProfilesUncached(playerUuid: string): Promise { +export async function uuidFromUser(user: string): Promise { // if the user is 32 characters long, it has to be a uuid if (isUuid(user)) return undashUuid(user) if (usernameCache.has(undashUuid(user))) { // check if the uuid is a key - const username: Promise | string | null = usernameCache.get>(undashUuid(user)) + const username: Promise | string | undefined = usernameCache.get>(undashUuid(user)) // sometimes the username will be null, return that - if (username === null) return null + if (username === null) return undefined // if it has .then, then that means its a waitForCacheSet promise. This is done to prevent requests made while it is already requesting if ((username as Promise).then) { @@ -136,15 +136,16 @@ export async function uuidFromUser(user: string): Promise { * Fetch the username from a user * @param user A user can be either a uuid or a username */ -export async function usernameFromUser(user: string): Promise { +export async function usernameFromUser(user: string): Promise { if (usernameCache.has(undashUuid(user))) { if (debug) console.debug('Cache hit! usernameFromUser', user) - return usernameCache.get(undashUuid(user)) + return usernameCache.get(undashUuid(user)) ?? null } if (debug) console.debug('Cache miss: usernameFromUser', user) let { uuid, username } = await mojang.profileFromUser(user) + if (!uuid) return null uuid = undashUuid(uuid) usernameCache.set(uuid, username) return username @@ -152,12 +153,12 @@ export async function usernameFromUser(user: string): Promise { let fetchingPlayers: Set = new Set() -export async function fetchPlayer(user: string): Promise { +export async function fetchPlayer(user: string): Promise { const playerUuid = await uuidFromUser(user) - + if (!playerUuid) return null if (playerCache.has(playerUuid)) - return playerCache.get(playerUuid) + return playerCache.get(playerUuid)! // if it's already in the process of fetching, check every 100ms until it's not fetching the player anymore and fetch it again, since it'll be cached now if (fetchingPlayers.has(playerUuid)) { @@ -176,7 +177,7 @@ export async function fetchPlayer(user: string): Promise { fetchingPlayers.delete(playerUuid) - if (!cleanPlayer) return + if (!cleanPlayer) return null // clone in case it gets modified somehow later playerCache.set(playerUuid, cleanPlayer) @@ -190,14 +191,19 @@ export async function fetchPlayer(user: string): Promise { } /** Fetch a player without their profiles. This is heavily cached. */ -export async function fetchBasicPlayer(user: string): Promise { +export async function fetchBasicPlayer(user: string): Promise { const playerUuid = await uuidFromUser(user) + if (!playerUuid) return null + if (basicPlayerCache.has(playerUuid)) - return basicPlayerCache.get(playerUuid) + return basicPlayerCache.get(playerUuid)! const player = await fetchPlayer(playerUuid) - if (!player) console.debug('no player? this should never happen', user, playerUuid) + if (!player) { + console.debug('no player? this should never happen', user, playerUuid) + return null + } delete player.profiles return player @@ -206,7 +212,7 @@ export async function fetchBasicPlayer(user: string): Promise { export async function fetchSkyblockProfiles(playerUuid: string): Promise { if (profilesCache.has(playerUuid)) { if (debug) console.debug('Cache hit! fetchSkyblockProfiles', playerUuid) - return profilesCache.get(playerUuid) + return profilesCache.get(playerUuid)! } if (debug) console.debug('Cache miss: fetchSkyblockProfiles', playerUuid) @@ -220,7 +226,7 @@ export async function fetchSkyblockProfiles(playerUuid: string): Promise { + members: profile.members?.map(m => { return { uuid: m.uuid, username: m.username, @@ -240,14 +246,14 @@ export async function fetchSkyblockProfiles(playerUuid: string): Promise { +async function fetchBasicProfiles(user: string): Promise { const playerUuid = await uuidFromUser(user) - if (!playerUuid) return // invalid player, just return + if (!playerUuid) return null // invalid player, just return if (basicProfilesCache.has(playerUuid)) { if (debug) console.debug('Cache hit! fetchBasicProfiles', playerUuid) - return basicProfilesCache.get(playerUuid) + return basicProfilesCache.get(playerUuid)! } if (debug) console.debug('Cache miss: fetchBasicProfiles', user) @@ -259,6 +265,7 @@ async function fetchBasicProfiles(user: string): Promise { } const profiles = player.profiles basicProfilesCache.set(playerUuid, profiles) + if (!profiles) return null // cache the profile names and uuids to profileNameCache because we can for (const profile of profiles) @@ -272,7 +279,7 @@ async function fetchBasicProfiles(user: string): Promise { * @param user A username or uuid * @param profile A profile name or profile uuid */ -export async function fetchProfileUuid(user: string, profile: string): Promise { +export async function fetchProfileUuid(user: string, profile: string): Promise { // if a profile wasn't provided, return if (!profile) { if (debug) console.debug('no profile provided?', user, profile) @@ -282,12 +289,12 @@ export async function fetchProfileUuid(user: string, profile: string): Promise { +export async function fetchProfile(user: string, profile: string): Promise { const playerUuid = await uuidFromUser(user) + if (!playerUuid) return null const profileUuid = await fetchProfileUuid(playerUuid, profile) if (!profileUuid) return null @@ -309,13 +317,15 @@ export async function fetchProfile(user: string, profile: string): Promise { +export async function fetchBasicProfileFromUuid(profileUuid: string): Promise { if (profileCache.has(profileUuid)) { // we have the profile cached, return it :) if (debug) console.debug('Cache hit! fetchBasicProfileFromUuid', profileUuid) - const profile: CleanFullProfile = profileCache.get(profileUuid) + const profile: CleanFullProfile | undefined = profileCache.get(profileUuid) + if (!profile) return undefined return { uuid: profile.uuid, members: profile.members.map(m => ({ @@ -357,26 +368,32 @@ export async function fetchBasicProfileFromUuid(profileUuid: string): Promise { +export async function fetchProfileName(user: string, profile: string): Promise { // we're fetching the profile and player uuid again in case we were given a name, but it's cached so it's not much of a problem const profileUuid = await fetchProfileUuid(user, profile) - if (!profileUuid) - return null + if (!profileUuid) return null + const playerUuid = await uuidFromUser(user) + if (!playerUuid) return null + if (profileNameCache.has(`${playerUuid}.${profileUuid}`)) { // Return the profile name if it's cached if (debug) console.debug('Cache hit! fetchProfileName', profileUuid) - return profileNameCache.get(`${playerUuid}.${profileUuid}`) + return profileNameCache.get!(`${playerUuid}.${profileUuid}`) ?? null } if (debug) console.debug('Cache miss: fetchProfileName', user, profile) const basicProfiles = await fetchBasicProfiles(playerUuid) - let profileName + + if (!basicProfiles) return null + + let profileName: string | null = null + for (const basicProfile of basicProfiles) if (basicProfile.uuid === playerUuid) - profileName = basicProfile.name + profileName = basicProfile.name ?? null profileNameCache.set(`${playerUuid}.${profileUuid}`, profileName) return profileName diff --git a/src/index.ts b/src/index.ts index 4f4ad00..647038f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -132,7 +132,12 @@ app.get('/constants', async(req, res) => { 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) + const codeExchange = await discord.exchangeCode(`${mainSiteUrl}/loggedin`, code) + if (!codeExchange) { + res.json({ ok: false, error: 'discord_client_secret isn\'t in env' }) + return + } + const { access_token: accessToken, refresh_token: refreshToken } = codeExchange if (!accessToken) // access token is invalid :( return res.json({ ok: false }) @@ -148,6 +153,8 @@ app.post('/accounts/session', async(req, res) => { try { const { uuid } = req.body const session = await fetchSession(uuid) + if (!session) + return res.json({ ok: false }) const account = await fetchAccountFromDiscord(session.discord_user.id) res.json({ session, account }) } catch (err) { diff --git a/src/mojang.ts b/src/mojang.ts index e22c8d8..84c8c7d 100644 --- a/src/mojang.ts +++ b/src/mojang.ts @@ -14,9 +14,8 @@ const httpsAgent = new Agent({ interface MojangApiResponse { /** These uuids are already undashed */ - uuid: string - - username: string + uuid: string | null + username: string | null } /** @@ -73,7 +72,7 @@ export async function profileFromUsername(username: string): Promise 9 * @param colorName The name of the color (blue, red, aqua, etc) */ -export function colorCodeFromName(colorName: string): string { +export function colorCodeFromName(colorName: string): string | undefined { const hexColor = minecraftColorCodes[colorName.toLowerCase()] for (const key in minecraftColorCodes) { const value = minecraftColorCodes[key] -- cgit