-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
189 lines (157 loc) · 6.17 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
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
// Add support for fetch in Node.
let fetch: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>
if (typeof window === "undefined") {
eval('fetch = require("node-fetch")')
} else {
fetch = window.fetch
}
// Support for the uploaders API V1.
export class UploadersAPIV1 {
private uploaderSlug!: string
private clientToken: string | undefined
private uploaderToken: string | undefined
constructor(init: any) {
if (!init || !init._constructedByMe) {
throw new Error("Do not try and construct this class by yourself. Run UploadersAPIV1.client or UploadersAPIV1.server instead to get this as an object!")
}
delete init._constructedByMe
for (const key of Object.keys(init)) (this as any)[key] = init[key]
if (this.uploaderSlug === "") throw new Error("Invalid uploader slug.")
}
static client(uploaderSlug: string, clientToken: string | undefined) {
const args = {
_constructedByMe: true,
uploaderSlug,
clientToken,
}
return new UploadersAPIV1(args)
}
static server(uploaderSlug: string, uploaderToken: string) {
const args = {
_constructedByMe: true,
uploaderSlug,
uploaderToken,
}
return new UploadersAPIV1(args)
}
setClientToken(clientToken: string) {
this.clientToken = clientToken
}
private _throwMisconfiguredClient() {
if (!this.clientToken) throw new Error("This class is configured as a server or does not have a token set. To do client actions, you need to have a class configured as a client and you need to turn your swap token into a client token. You can then run .setClientToken(<token>) on here or reconstruct the class with the client token.")
}
private _throwMisconfiguredServer() {
if (!this.uploaderToken) throw new Error("This class is configured as a client. To do server actions, you need to have a class configured as a server.")
}
async requestSwapToken() {
const url = `http://127.0.0.1:61222/uploaders_api/v1/auth/swap/${encodeURIComponent(this.uploaderSlug)}`
let res
try {
res = await fetch(url, {method: "GET"})
} catch (_) {
throw new Error("MagicCap is not open.")
}
const json = await res.json()
if (!res.ok) throw new Error(json.message)
return {
swapToken: json.swap_token as string,
expires: json.expires as number,
}
}
async getClientToken(swapToken: string) {
this._throwMisconfiguredServer()
const url = `https://api.magiccap.me/swap_tokens/swap/${encodeURIComponent(swapToken)}/${encodeURIComponent(this.uploaderToken!)}/${encodeURIComponent(this.uploaderSlug)}`
const res = await fetch(url, {method: "GET"})
const json = await res.json()
if (!res.ok) throw new Error(json.message)
return {
clientToken: json.client_token as string,
expires: json.expires as number,
}
}
async checkIfDefault() {
this._throwMisconfiguredClient()
const url = "http://127.0.0.1:61222/uploaders_api/v1/uploaders/default_check"
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${this.clientToken}`,
},
method: "GET",
})
const json = await res.json()
if (!res.ok) throw new Error(json.message)
return json.default as boolean
}
async showDefaultPrompt() {
this._throwMisconfiguredClient()
const url = "http://127.0.0.1:61222/uploaders_api/v1/uploaders/default_prompt"
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${this.clientToken}`,
},
method: "GET",
})
const json = await res.json()
if (!res.ok) throw new Error(json.message)
}
async revokeClientToken() {
this._throwMisconfiguredClient()
const url = "http://127.0.0.1:61222/uploaders_api/v1/auth/revoke"
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${this.clientToken}`,
},
method: "GET",
})
const json = await res.json()
if (!res.ok) throw new Error(json.message)
this.clientToken = undefined
}
async setConfigValues(values: {[key: string]: any}) {
this._throwMisconfiguredClient()
const urlQuery = []
for (const key in values) {
urlQuery.push(`${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(values[key]))}`)
}
const url = `http://127.0.0.1:61222/uploaders_api/v1/uploaders/set?${urlQuery.join("&")}`
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${this.clientToken}`,
},
method: "GET",
})
const json = await res.json()
if (!res.ok) throw new Error(json.message)
}
static async clientFromExpressHandler(uploaderSlug: string, routePath: string) {
const client = UploadersAPIV1.client(uploaderSlug, undefined)
const swapTokenInfo = await client.requestSwapToken()
const res = await fetch(`${routePath}?swap_token=${swapTokenInfo.swapToken}`)
if (!res.ok) throw new Error((await res.json()).message)
client.setClientToken((await res.json()).clientToken)
return client
}
}
export function expressWrapper(uploaderSlug: string, uploaderToken: string) {
const server = UploadersAPIV1.server(uploaderSlug, uploaderToken)
return async(req: any, res: any) => {
const swapToken = req.query.swap_token
if (!swapToken) {
res.status(400)
res.json({
success: false,
message: "Missing swap token.",
})
return
}
try {
const clientTokenResult = await server.getClientToken(swapToken)
res.json(clientTokenResult)
} catch (e) {
res.status(400)
res.json({
message: e.message,
})
}
}
}