forked from soruly/trace.moe-www
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage-proxy.js
57 lines (49 loc) · 1.34 KB
/
image-proxy.js
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
addEventListener("fetch", async (event) => {
event.respondWith(handleRequest(event.request));
});
const errorResponse = (errorMessage) =>
new Response(errorMessage, {
status: 400,
statusText: "Bad Request",
});
const handleRequest = async (originalRequest) => {
let originalURL = new URL(originalRequest.url);
if (!originalURL.searchParams.get("url")) {
return errorResponse("Error: Cannot get url from param");
}
let imageURL = null;
try {
imageURL = new URL(originalURL.searchParams.get("url"));
} catch (e) {}
if (!imageURL) {
return errorResponse("Error: Invalid URL string");
}
let imageRequest = new Request(imageURL, {
redirect: "follow",
headers: {
referer: imageURL.origin,
},
});
let response = await fetch(imageRequest, {
cf: {
polish: "lossy",
},
});
if (response.status >= 400) {
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
if (
!["image", "video"].includes(response.headers.get("Content-Type").split("/")[0].toLowerCase())
) {
return errorResponse("Error: Content-Type is not image or video");
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
};