aboutsummaryrefslogtreecommitdiff
path: root/src/index.ts
blob: 4464ca73ef11f47d7c477df4c799209a77774c72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { createSession, fetchAccountFromDiscord, fetchAllLeaderboardsCategorized, fetchLeaderboard, fetchMemberLeaderboardSpots, fetchSession, finishedCachingRawLeaderboards, leaderboardUpdateMemberQueue, leaderboardUpdateProfileQueue, updateAccount, fetchServerStatus, deleteSession } from './database.js'
import { fetchElection, fetchMemberProfile, fetchUser } from './hypixel.js'
import rateLimit from 'express-rate-limit'
import * as constants from './constants.js'
import * as discord from './discord.js'
import express from 'express'
import { getKeyUsage } from './hypixelApi.js'
import { basicPlayerCache, basicProfilesCache, playerCache, profileCache, profileNameCache, profilesCache, usernameCache } from './hypixelCached.js'
import { register } from './metrics.js'

const app = express()

export const debug = false

const mainSiteUrl = 'https://skyblock.matdoes.dev'

// 200 requests over 5 minutes
const limiter = rateLimit({
	windowMs: 60 * 1000 * 5,
	max: 200,
	skip: (req: express.Request) => {
		return req.headers.key === process.env.key
	},
	keyGenerator: (req: express.Request) => {
		return (req.headers['cf-connecting-ip'] ?? req.ip).toString()
	}
})

app.use(limiter)
app.use(express.json())
app.use((req, res, next) => {
	res.setHeader('Access-Control-Allow-Origin', '*')
	res.setHeader('Access-Control-Allow-Headers', '*')
	next()
})

const startTime = Date.now()
app.get('/', async (req, res) => {
	const currentTime = Date.now()
	let data: any = {
		ok: true,
		uptimeHours: (currentTime - startTime) / 1000 / 60 / 60,
		finishedCachingRawLeaderboards,
		leaderboardUpdateMemberQueueSize: leaderboardUpdateMemberQueue.size,
		leaderboardUpdateProfileQueueSize: leaderboardUpdateProfileQueue.size,

		usernameCacheSize: usernameCache.keys().length,
		basicProfilesCacheSize: basicProfilesCache.keys().length,
		playerCacheSize: playerCache.keys().length,
		basicPlayerCacheSize: basicPlayerCache.size,
		profileCacheSize: profileCache.keys().length,
		profilesCacheSize: profilesCache.keys().length,
		profileNameCacheSize: profileNameCache.keys().length,
	}
	if (req.headers.key === process.env.key)
		data.key = getKeyUsage()
	res.json(data)
})

app.get('/player/:user', async (req, res) => {
	try {
		const user = await fetchUser(
			{ user: req.params.user },
			[req.query.basic as string === 'true' ? undefined : 'profiles', 'player'],
			req.query.customization as string === 'true'
		)
		if (user)
			res.json(user)
		else
			res.status(404).json({ error: true })
	} catch (err) {
		console.error(err)
		res.json({ error: true })
	}
})

app.get('/discord/:id', async (req, res) => {
	try {
		res.json(
			await fetchAccountFromDiscord(req.params.id)
		)
	} catch (err) {
		console.error(err)
		res.json({ ok: false })
	}
})

app.get('/player/:user/:profile', async (req, res) => {
	try {
		const profile = await fetchMemberProfile(req.params.user, req.params.profile, req.query.customization as string === 'true')
		if (profile)
			res.json(profile)
		else
			res.status(404).json({ error: true })
	} catch (err) {
		console.error(err)
		res.json({ error: true })
	}
})

app.get('/player/:user/:profile/leaderboards', async (req, res) => {
	try {
		res.json(
			await fetchMemberLeaderboardSpots(req.params.user, req.params.profile)
		)
	} catch (err) {
		console.error(err)
		res.json({ ok: false })
	}
})

app.get('/leaderboards/:name', async (req, res) => {
	try {
		res.json(
			await fetchLeaderboard(req.params.name)
		)
	} catch (err) {
		console.error(err)
		res.json({ 'error': err.toString() })
	}
})

app.get('/leaderboards', async (req, res) => {
	try {
		res.json(
			await fetchAllLeaderboardsCategorized()
		)
	} catch (err) {
		console.error(err)
		res.json({ ok: false })
	}
})

app.get('/constants', async (req, res) => {
	try {
		res.json(
			await constants.fetchConstantValues()
		)
	} catch (err) {
		console.error(err)
		res.json({ ok: false })
	}
})

app.get('/election', async (req, res) => {
	try {
		res.json(
			await fetchElection()
		)
	} catch (err) {
		console.error(err)
		res.json({ ok: false })
	}
})

app.post('/accounts/createsession', async (req, res) => {
	try {
		const { code } = req.body
		const redirectUri = req.body.redirectUri ?? `${mainSiteUrl}/loggedin`

		const codeExchange = await discord.exchangeCode(redirectUri, 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 :(
			console.log('error exchanging code:', codeExchange, code)
			const { error, error_description: errorDescription } = codeExchange as any
			return res.json({ ok: false, error: error ? `Discord error: ${error}: ${errorDescription}` : 'Unknown error' })
		}
		const userData = await discord.getUser(accessToken)
		const sessionId = await 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 fetchSession(uuid)
		if (!session)
			return res.json({ ok: false })
		const account = await fetchAccountFromDiscord(session.discord_user.id)
		res.json({ session, account })
	} catch (err) {
		console.error(err)
		res.json({ ok: false })
	}
})

app.delete('/accounts/session', async (req, res) => {
	// delete a session
	try {
		const { uuid } = req.body
		await deleteSession(uuid)
		res.json({ ok: true })
	} 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 updateAccount(req.body.discordId, req.body)
		res.json({ ok: true })
	} catch (err) {
		console.error(err)
		res.json({ ok: false })
	}
})


app.get('/metrics', async (req, res) => {
	if (!req.headers.host?.startsWith('0.0.0.0:'))
		return res.status(403).send('Forbidden')
	try {
		res.set('Content-Type', register.contentType)
		res.end(await register.metrics())
	} catch (err) {
		res.status(500).end(err)
	}
})

process.on('uncaughtException', err => console.error(err))
process.on('unhandledRejection', (err, promise) => console.error(promise, err))

// only run the server if it's not doing tests
if (!globalThis.isTest)
	app.listen(8080, () => console.log('App started :)'))