const ITEM_REGEX = /[a-zA-Z0-9]+\.(png|jpe?g|gifv?)/; | |
const DOMAIN = "cdn.elitedamyth.xyz" | |
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event)); | |
}) | |
async function handleRequest(event) { | |
let resp; | |
if (event.request.method == 'POST') { | |
let json = await event.request.json(); | |
resp = json.url.replace("i.imgur.com", DOMAIN) | |
return new Response(resp); | |
} else { | |
const request = event.request; | |
const url = new URL(request.url); | |
const path = url.pathname.substring(1); | |
if (!path) { | |
return jsonError('No Filename', 406); | |
} | |
if (!ITEM_REGEX.test(path)) { | |
return jsonError('Not found', 404); | |
} | |
resp = fetchImgurImage(path, event) | |
} | |
return resp; | |
} | |
async function fetchImgurImage(imageId, event) { | |
const lookUpUrl = "http://i.imgur.com/" + imageId; | |
const cache = caches.default; | |
let response = await cache.match(lookUpUrl); | |
if (!response) { | |
const imageResponse = await fetch(lookUpUrl, { | |
headers: { | |
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36", | |
} | |
}); | |
const headers = { | |
'cache-control': 'public, max-age=31536000', | |
}; | |
const cloned = imageResponse.clone(); | |
response = new Response(cloned.body, { | |
...cloned, | |
headers | |
}); | |
if (imageResponse.status === 200) { | |
event.waitUntil(cache.put(lookUpUrl, imageResponse.clone())); | |
} | |
} | |
return response; | |
} | |
function jsonError(message, status = 400) { | |
return new Response( | |
JSON.stringify({ | |
error: message | |
}), { | |
status: status, | |
headers: { | |
'content-type': 'application/json' | |
} | |
} | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment