aboutsummaryrefslogtreecommitdiff
path: root/src/mojang.ts
blob: 7efc4ae8d9fdbddbca21b4746e8eb1d5a4b3422d (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
/**
 * Fetch the Mojang username API through api.ashcon.app
 */

import fetch from 'node-fetch'
import { Agent } from 'https'
import { isUuid, undashUuid } from './util'

// We need to create an agent to prevent memory leaks
const httpsAgent = new Agent({
	keepAlive: true
})

interface MojangApiResponse {
	/** These uuids are already undashed */
	uuid: string

	username: string
}

/**
 * Get mojang api data from the session server
 */
export async function mojangDataFromUuid(uuid: string): Promise<MojangApiResponse> {
	console.log('mojangDataFromUuid', uuid)
	const fetchResponse = await fetch(
		// using mojang directly is faster than ashcon lol, also mojang removed the ratelimits from here
		`https://sessionserver.mojang.com/session/minecraft/profile/${undashUuid(uuid)}`,
		{ agent: () => httpsAgent }
	)
	const data = await fetchResponse.json()
	return {
		uuid: data.id,
		username: data.name
	}
}


export async function uuidFromUsername(username: string): Promise<string> {
	console.log('uuidFromUsername', username)
	// since we don't care about anything other than the uuid, we can use /uuid/ instead of /user/
	const fetchResponse = await fetch(
		`https://api.ashcon.app/mojang/v2/uuid/${username}`,
		{ agent: () => httpsAgent }
	)
	const userUuid = await fetchResponse.text()
	return userUuid.replace(/-/g, '')
}

export async function usernameFromUuid(uuid: string): Promise<string> {
	const userJson = await mojangDataFromUuid(uuid)
	return userJson.username
}




/**
 * Fetch the uuid from a user
 * @param user A user can be either a uuid or a username 
 */
export async function uuidFromUser(user: string): Promise<string> {
	if (isUuid(user))
		// already a uuid, just return it undashed
		return undashUuid(user)
	else
		return await uuidFromUsername(user)
}


export async function mojangDataFromUser(user: string): Promise<MojangApiResponse> {
	if (!isUuid(user))
		return await mojangDataFromUuid(await uuidFromUsername(user))
	else
		return await mojangDataFromUuid(user)
}

/**
 * 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<string> {
	// we do this to fix the capitalization
	const data = await mojangDataFromUser(user)
	return data.username
}