Skip to content

Instantly share code, notes, and snippets.

@TennousuAthena
Created August 24, 2021 14:01
Show Gist options
  • Save TennousuAthena/3562680a7bb4b009a5c43696581c5231 to your computer and use it in GitHub Desktop.
Save TennousuAthena/3562680a7bb4b009a5c43696581c5231 to your computer and use it in GitHub Desktop.
Workers Image Url
const html404 = `<!DOCTYPE html>
<body>
<h1>404 Not Found.</h1>
<p>The url you visit is not found.</p>
</body>`;
const KEY = "ccccccvbddhvfhcldgvvjlcefnbihdngnfjhdbjekuic"
async function randomString(len) {
  len = len || 32;
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  let maxPos = $chars.length;
  let result = '';
  for (i = 0; i < len; i++) {
    result += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return result;
}
async function checkURL(URL){
let str=URL;
let Expression=/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
let objExp=new RegExp(Expression);
if(objExp.test(str)==true){
if (str[0] == 'h')
return true;
else
return false;
}else{
return false;
}
}
async function save_url(URL){
let random_key=await randomString()
let is_exist=await LINKS.get(random_key)
console.log(is_exist)
if (is_exist == null)
return await LINKS.put(random_key, URL),random_key
else
save_url(URL)
}
async function handleRequest(request) {
console.log(request)
if (request.method === "POST") {
let req=await request.json()
console.log(req["url"])
if(req["key"] !== KEY || !await checkURL(req["url"])){
return new Response(`{"status":400,"key":": Error: Input illegal."}`, {
headers: {
"content-type": "text/json;charset=UTF-8",
"Access-Control-Allow-Methods": "POST",
},
status: 400
})}
let stat,random_key=await save_url(req["url"])
console.log(stat)
if (typeof(stat) == "undefined"){
return new Response(`{"status":200,"key":"`+random_key+`"}`, {
headers: {
"content-type": "text/html;charset=UTF-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods": "POST",
},
})
}else{
return new Response(`{"status":200,"key":": Error:Reach the KV write limitation."}`, {
headers: {
"content-type": "text/html;charset=UTF-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods": "POST",
},
})}
}else if(request.method === "OPTIONS"){
return new Response(``, {
headers: {
"content-type": "text/html;charset=UTF-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods": "POST",
},
})
}
const requestURL = new URL(request.url)
const path = requestURL.pathname.split("/")[1]
console.log(path)
if(!path){
return new Response(html404, {
headers: {
"content-type": "text/html;charset=UTF-8",
},
status: 404
})
}
const value = await LINKS.get(path)
console.log(value)
// Construct the cache key from the cache URL
const cacheUrl = new URL(request.url)
const cacheKey = new Request(cacheUrl.toString(), request)
const cache = caches.default
// Check whether the value is already available in the cache
// if not, you will need to fetch it from origin, and store it in the cache
// for future access
let response = await cache.match(cacheKey)
if (response) {
// return response;
}
const location = value
if (location) {
let req = new Request(location, request);
let response = await fetch(req, {
headers: {
'Referer': location.hostname,
}
})
response = new Response(response.body, response)
// Cache API respects Cache-Control headers. Setting s-max-age to 10
// will limit the response to be in cache for 10 seconds max
// Any changes made to the response here will be reflected in the cached value
response.headers.append("Cache-Control", "s-maxage=360000")
response.headers.append("x-origin", value)
// Store the fetched response as cacheKey
// Use waitUntil so you can return the response without blocking on
// writing to cache
await cache.put(cacheKey, response.clone())
return response;
}
return new Response(html404, {
headers: {
"content-type": "text/html;charset=UTF-8",
},
status: 404
})
}
addEventListener("fetch", async event => {
event.respondWith(handleRequest(event.request))
})
function jugeUrl(URL) {
var str = URL;
//判断URL地址的正则表达式为:http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
//下面的代码中应用了转义字符""输出一个字符"/"
var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
var objExp = new RegExp(Expression);
if (objExp.test(str) == true) {
return true;
} else {
return false;
}
}
function isBase64(str) {
if (str ==='' || str.trim() ===''){ return false; }
try {
return btoa(atob(str)) == str;
} catch (err) {
return false;
}
}
addEventListener("fetch", event => {
let url = new URL(event.request.url);
if(isBase64(url.pathname.substr(1))){
img_url = atob(url.pathname.substr(1))
url.href = img_url;
}else{
return false;
}
if(!jugeUrl(img_url)){
return false;
}
let request = new Request(url, event.request);
event.respondWith(
fetch(request, {
headers: {
'Referer': url.hostname,
}
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment