-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
53 lines (50 loc) · 1.83 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
const defaultResponseOptions = {
'headers': {
'Content-Type': 'text/xml'
}
}
const generateUniqueID = (idLength = 6, start = '') => {
const chars = 'abcdefghijklmnopqrstuvwxyz123456789._';
let id = start;
for (let i = 0; i < idLength; i++) {
id += chars[Math.floor(Math.random() * chars.length)];
}
return id;
}
/**
* @param body with image
* @returns XML response with url
*/
const upload = async (body: FormData): Promise<Response> => {
const id = generateUniqueID();
if (!body.has("image")) throw new Error("No image found!");
console.log('uploading...')
await Bun.write(`./screens/${id}/img.png`, body.get("image") as FormDataEntryValue);
console.log(`upload -> ./screens/${id}/img.png`)
return new Response(`<response>\n<status>success</status>\n<url>http://upload.prntscr.com/get/${id}</url>\n</response>`, defaultResponseOptions);
}
const read = async (id: string): Promise<Response> => {
if (!id) return new Response("No ID found!", defaultResponseOptions);
const file = Bun.file(`./screens/${id}/img.png`).stream();
console.log(`found -> ./screens/${id}/img.png`)
return new Response(file, defaultResponseOptions);
}
Bun.serve({
port: process.env.PORT || 80,
async fetch(req) {
const url = new URL(req.url);
try {
if (req.url.startsWith("http://upload.prntscr.com/upload/")) {
return await upload(await req.formData());
} else if (req.url.startsWith("http://upload.prntscr.com/get/")) {
return new Response((await read(url.pathname.split('/get/')[1])).body)
} else {
return new Response("Prntscr 404");
}
} catch (error) {
console.log(error)
return new Response("Failed")
}
},
});
console.log('Server started')