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
|
// <https://github.com/soruly/trace.moe-www/blob/master/image-proxy.js>
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",
cacheEverything: true,
},
});
if (response.status >= 400) {
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
// if (
// response.headers.get("Content-Type").toLowerCase() !==
// "application/octet-stream" &&
// !["image", "video"].includes(
// response.headers.get("Content-Type").split("/")[0].toLowerCase()
// )
// ) {
// // retry as bot to get og:image
// let webResponse = await fetch(
// new Request(imageURL, {
// redirect: "follow",
// headers: {
// referer: imageURL.origin,
// "User-Agent": "googlebot",
// },
// })
// );
// if (response.status === 200) {
// const ogImageURL = (await webResponse.text())
// ?.match(/<[^<]+?"og:image".*?>/, "$1")?.[0]
// ?.match(/content="(.*?)"/, "$1")?.[1];
// if (ogImageURL && ogImageURL.match(/^https?:\/\//)) {
// response = await fetch(
// new Request(ogImageURL, {
// redirect: "follow",
// headers: {
// referer: imageURL.origin,
// },
// })
// );
// if (response.status >= 400) {
// return new Response(response.body, {
// status: response.status,
// statusText: response.statusText,
// headers: response.headers,
// });
// }
// }
// }
// }
// if (
// response.headers.get("Content-Type").toLowerCase() !==
// "application/octet-stream" &&
// !["image", "video"].includes(
// response.headers.get("Content-Type").split("/")[0].toLowerCase()
// )
// ) {
// return errorResponse(
// "Error: Content-Type is not image or video or application/octet-stream"
// );
// }
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: {
"Cache-Control":
"public, immutable, s-maxage=31536000, max-age=31536000, stale-while-revalidate=60",
"Access-Control-Allow-Origin": "https://due.moe",
...response.headers,
},
});
};
|