Skip to content

Instantly share code, notes, and snippets.

@vipertechofficial
Last active February 24, 2022 00:43
Show Gist options
  • Save vipertechofficial/b6d942ecde7c7a2836b8f18f403edb15 to your computer and use it in GitHub Desktop.
Save vipertechofficial/b6d942ecde7c7a2836b8f18f403edb15 to your computer and use it in GitHub Desktop.
Cloudflare worker for Deepai API
function base64Encode (buf) {
let string = '';
(new Uint8Array(buf)).forEach(
(byte) => { string += String.fromCharCode(byte) }
)
return btoa(string)
}
function base64Decode (string) {
string = atob(string);
const
length = string.length,
buf = new ArrayBuffer(length),
bufView = new Uint8Array(buf);
for (var i = 0; i < length; i++) { bufView[i] = string.charCodeAt(i) }
return buf
}
function clean_json_text(json_text) {
json_text = json_text.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
json_text = json_text.replace(/[\u0000-\u0019]+/g,"");
return json_text;
}
function handleOptions(request) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
let headers = request.headers;
if (
headers.get("Origin") !== null &&
headers.get("Access-Control-Request-Method") !== null &&
headers.get("Access-Control-Request-Headers") !== null
){
// Handle CORS pre-flight request.
// If you want to check or reject the requested method + headers
// you can do that here.
let respHeaders = {
...{
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
},
// Allow all future content Request headers to go back to browser
// such as Authorization (Bearer) or X-Client-Name-Version
"Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers"),
}
return new Response(null, {
headers: respHeaders,
})
}
else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: "GET, HEAD, POST, OPTIONS",
},
})
}
}
addEventListener("fetch", (event) => {
let request = event.request;
event.respondWith(
handleRequest(request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
function fix_headers(headers, event_request) {
const isOPTIONS = (event_request.method == "OPTIONS");
headers.set("Access-Control-Allow-Origin", event_request.headers.get("Origin"));
if (isOPTIONS) {
headers.set("Access-Control-Allow-Methods", event_request.headers.get("access-control-request-method"));
acrh = event_request.headers.get("access-control-request-headers");
if (acrh) {
headers.set("Access-Control-Allow-Headers", acrh);
}
headers.delete("X-Content-Type-Options");
}
return headers;
}
function build_response(body, params, event_request) {
const isOPTIONS = (event_request.method == "OPTIONS");
if (isOPTIONS) {
body = null;
}
var init = {
headers: fix_headers(params.headers, event_request),
status: (isOPTIONS ? 200 : 200),
statusText: (isOPTIONS ? "OK" : "OK")
};
return new Response(body, init);
}
async function handleRequest(request) {
const url = new URL(request.url);
let { pathname } = url;
pathname = decodeURI(pathname);
if(request.method == "OPTIONS") {
return build_response(null, {headers: new Headers()}, request);
}else if (pathname.startsWith("/colorizer") || pathname.startsWith("/waifu2x")) {
let headers = new Headers();
//headers.append("Content-Type", "multipart/form-data");
headers.append("Api-Key", "XXX");
headers.append("Accept", "application/json, text/plain, */*",);
headers.append("client-library", "deepai-js-client");
console.log(request.body)
const img_base64 = await request.text();
const payload = {image: img_base64};
let bodyencoded = new FormData();
Object.entries(payload).forEach((entry) => {
const [key, value] = entry;
bodyencoded.append(key, value);
});
const request_url = pathname.startsWith("/colorizer") ? "https://api.deepai.org/api/colorizer": "https://api.deepai.org/api/waifu2x";
const request_options = {
method: "POST",
headers: headers,
body: bodyencoded,
};
const response = await fetch(request_url, request_options);
const response_text = await response.text();
const response_img_url = JSON.parse(response_text).output_url;
const upstream_img_response = await fetch(response_img_url);
const response_img_base64 = "data:image/jpg;base64," + base64Encode(await upstream_img_response.arrayBuffer());
return build_response(response_img_base64, {
headers: new Headers({
"Content-Type": "application/text"
}),
}, request);
}
}
// This function is required because JSON is weird with some char
function clean_json_text(json_text) {
json_text = json_text.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
json_text = json_text.replace(/[\u0000-\u0019]+/g,"");
return json_text;
}
function postJSON(url, payload, callback_function, content_type = "application/x-www-form-urlencoded") {
//url = CORS_PROXY_URL + url;
let headers = new Headers();
headers.append("Content-Type", content_type);
let bodyencoded = content_type === "multipart/form-data" ? new FormData(): new URLSearchParams();
Object.entries(payload).forEach((entry) => {
const [key, value] = entry;
bodyencoded.append(key, value);
});
let request_options = {
method: "POST",
redirect: "follow",
headers: headers,
body: content_type === "application/text" ? payload: content_type === "application/json" ? clean_json_text(JSON.stringify(payload)): bodyencoded,
};
fetch(url, request_options)
.then(response => response.text())
.then(result => callback_function(null, result))
.catch(error => callback_function(error, null));
}
postJSON("https://deepai.pixa-pics.workers.dev/colorizer", base64img, (err, base64_response) => {}, "application/text");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment