forked from Offroaders123/Mojang-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
95 lines (86 loc) · 2.18 KB
/
index.ts
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
export interface Error {
error: string;
errorMessage?: string;
}
export function assertsNonError<T>(value: unknown): asserts value is T {
if ("error" in (value as Error)){
const { error, errorMessage } = value as Error;
throw new Error(errorMessage ?? error);
}
}
export interface User {
name: string;
id: string;
}
export async function getUser(username: string){
const response = await fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`);
const user = await response.json();
assertsNonError<User>(user);
return user;
}
export interface Profile {
id: string;
name: string;
legacy?: true;
properties: [
{
name: "textures";
value: string;
signature?: string;
}
];
}
export async function getProfile(user: User){
const { id } = user;
const response = await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${id}`);
const profile = await response.json();
assertsNonError<Profile>(profile);
return profile;
}
export interface Textures {
timestamp: number;
profileId: string;
profileName: string;
signatureRequired?: true;
textures: {
SKIN?: {
url: string;
metadata?: {
model: "slim";
};
},
CAPE?: {
url: string;
}
}
}
export function getTextures(profile: Profile){
const { properties } = profile;
const property = properties.find(property => property.name === "textures");
if (property === undefined){
throw new Error("No textures were found.");
}
const { value } = property;
const textures = JSON.parse(atob(value)) as Textures;
return textures;
}
export async function getSkin({ textures }: Textures){
const { SKIN } = textures;
if (SKIN === undefined){
throw new Error("No skin was found.");
}
const { url } = SKIN;
const response = await fetch(url);
const skin = new Uint8Array(await response.arrayBuffer());
return skin;
}
export async function getCape({ textures }: Textures){
const { CAPE } = textures;
if (CAPE === undefined){
throw new Error("No cape was found.");
}
const { url } = CAPE;
const response = await fetch(url);
const cape = new Uint8Array(await response.arrayBuffer());
return cape;
}