Files
kiss-translator/src/libs/fetch.js

334 lines
7.3 KiB
JavaScript
Raw Normal View History

2023-10-20 17:44:48 +08:00
import queryString from "query-string";
2023-08-30 18:05:37 +08:00
import { isExt, isGm } from "./client";
2023-08-31 13:38:06 +08:00
import { sendBgMsg } from "./msg";
2023-08-10 11:55:40 +08:00
import { taskPool } from "./pool";
2023-07-20 13:45:41 +08:00
import {
MSG_FETCH,
2023-08-10 11:55:40 +08:00
MSG_FETCH_LIMIT,
2023-08-11 16:48:09 +08:00
MSG_FETCH_CLEAR,
2023-07-20 13:45:41 +08:00
CACHE_NAME,
2023-10-20 17:44:48 +08:00
OPT_TRANS_GOOGLE,
2023-07-20 13:45:41 +08:00
OPT_TRANS_MICROSOFT,
2023-09-02 16:57:09 +08:00
OPT_TRANS_DEEPL,
2023-10-20 17:44:48 +08:00
OPT_TRANS_DEEPLFREE,
OPT_TRANS_DEEPLX,
OPT_TRANS_BAIDU,
OPT_TRANS_TENCENT,
2023-07-20 13:45:41 +08:00
OPT_TRANS_OPENAI,
2023-10-20 17:44:48 +08:00
OPT_TRANS_CUSTOMIZE,
2023-08-10 11:55:40 +08:00
DEFAULT_FETCH_INTERVAL,
DEFAULT_FETCH_LIMIT,
2023-10-20 17:44:48 +08:00
OPT_LANGS_SPECIAL,
URL_MICROSOFT_TRAN,
URL_TENCENT_TRANSMART,
2023-07-20 13:45:41 +08:00
} from "../config";
2023-08-10 11:55:40 +08:00
import { msAuth } from "./auth";
2023-09-20 17:47:23 +08:00
import { isBg } from "./browser";
2023-07-20 13:45:41 +08:00
/**
2023-08-05 18:15:01 +08:00
* 油猴脚本的请求封装
* @param {*} input
* @param {*} init
* @returns
*/
2023-08-29 00:06:50 +08:00
export const fetchGM = async (input, { method = "GET", headers, body } = {}) =>
2023-08-05 18:15:01 +08:00
new Promise((resolve, reject) => {
GM.xmlHttpRequest({
method,
url: input,
headers,
data: body,
2023-09-28 16:18:28 +08:00
onload: ({ response, responseHeaders, status, statusText }) => {
const headers = new Headers();
responseHeaders.split("\n").forEach((line) => {
const [name, value] = line.split(":").map((item) => item.trim());
if (name && value) {
headers.append(name, value);
}
});
resolve(
new Response(response, {
headers,
status,
statusText,
})
);
},
onerror: reject,
});
2023-08-05 18:15:01 +08:00
});
/**
* 构造缓存 request
2023-07-20 13:45:41 +08:00
* @param {*} request
* @returns
*/
2023-10-20 17:44:48 +08:00
const newCacheReq = async (input, init) => {
let request = new Request(input, init);
2023-08-04 16:05:14 +08:00
if (request.method !== "GET") {
const body = await request.text();
const cacheUrl = new URL(request.url);
cacheUrl.pathname += body;
request = new Request(cacheUrl.toString(), { method: "GET" });
}
2023-07-20 13:45:41 +08:00
2023-08-04 16:05:14 +08:00
return request;
2023-07-20 13:45:41 +08:00
};
2023-10-20 17:44:48 +08:00
const newTransReq = (
{ translator, text, fromLang, toLang },
{ url, key } = {}
) => {
// console.log({ translator, text, fromLang, toLang }, { url, key });
let params;
let data;
let input;
let init;
const from = OPT_LANGS_SPECIAL[translator].get(fromLang) ?? "";
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
if (!to) {
throw new Error(`[trans] target lang: ${toLang} not support`);
}
switch (translator) {
case OPT_TRANS_GOOGLE:
break;
case OPT_TRANS_MICROSOFT:
params = {
from,
to,
"api-version": "3.0",
};
input = `${URL_MICROSOFT_TRAN}?${queryString.stringify(params)}`;
init = {
headers: {
"Content-type": "application/json",
Authorization: `Bearer ${key}`,
},
method: "POST",
body: JSON.stringify([{ Text: text }]),
};
break;
case OPT_TRANS_DEEPL:
break;
case OPT_TRANS_DEEPLFREE:
break;
case OPT_TRANS_DEEPLX:
break;
case OPT_TRANS_BAIDU:
break;
case OPT_TRANS_TENCENT:
data = {
header: {
fn: "auto_translation_block",
},
source: {
text_block: text,
},
target: {
lang: to,
},
};
if (from) {
data.source.lang = from;
}
input = URL_TENCENT_TRANSMART;
init = {
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify(data),
};
break;
case OPT_TRANS_OPENAI:
break;
case OPT_TRANS_CUSTOMIZE:
break;
default:
break;
}
if (!input) {
throw new Error(`[trans] translator: ${translator} not support`);
}
return [input, init];
};
2023-08-04 17:56:47 +08:00
/**
2023-08-10 11:55:40 +08:00
* 发起请求
* @param {*} param0
* @returns
*/
2023-10-20 17:44:48 +08:00
export const fetchApi = async ({
input,
init,
transOpts,
apiSetting,
token,
}) => {
2023-09-06 00:25:46 +08:00
if (token) {
2023-10-20 17:44:48 +08:00
apiSetting.key = token;
}
if (transOpts?.translator) {
[input, init] = newTransReq(transOpts, apiSetting);
2023-08-10 11:55:40 +08:00
}
2023-10-20 17:44:48 +08:00
// if (token) {
// if (translator === OPT_TRANS_DEEPL) {
// init.headers["Authorization"] = `DeepL-Auth-Key ${token}`; // DeepL
// } else if (translator === OPT_TRANS_OPENAI) {
// init.headers["Authorization"] = `Bearer ${token}`; // OpenAI
// init.headers["api-key"] = token; // Azure OpenAI
// } else {
// init.headers["Authorization"] = `Bearer ${token}`; // Microsoft & others
// }
// }
2023-08-10 11:55:40 +08:00
2023-08-21 23:46:42 +08:00
if (isGm) {
2023-08-29 00:06:50 +08:00
let info;
if (window.KISS_GM) {
info = await window.KISS_GM.getInfo();
} else {
info = GM.info;
}
2023-09-03 21:45:06 +08:00
// Tampermonkey --> .connects
// Violentmonkey --> .connect
const connects = info?.script?.connects || info?.script?.connect || [];
2023-08-21 23:46:42 +08:00
const url = new URL(input);
const isSafe = connects.find((item) => url.hostname.endsWith(item));
if (isSafe) {
2023-08-29 00:06:50 +08:00
if (window.KISS_GM) {
return window.KISS_GM.fetch(input, init);
} else {
return fetchGM(input, init);
}
2023-08-21 23:46:42 +08:00
}
2023-08-10 11:55:40 +08:00
}
return fetch(input, init);
};
/**
* 请求池实例
*/
export const fetchPool = taskPool(
fetchApi,
2023-10-20 17:44:48 +08:00
async ({ transOpts }) => {
if (transOpts?.translator === OPT_TRANS_MICROSOFT) {
2023-08-10 11:55:40 +08:00
const [token] = await msAuth();
return { token };
}
return {};
},
DEFAULT_FETCH_INTERVAL,
DEFAULT_FETCH_LIMIT
);
/**
* 请求数据统一接口
2023-08-04 17:56:47 +08:00
* @param {*} input
* @param {*} opts
2023-07-20 13:45:41 +08:00
* @returns
*/
2023-08-09 10:33:00 +08:00
export const fetchData = async (
input,
2023-10-20 17:44:48 +08:00
{ useCache, usePool, transOpts, apiSetting, ...init } = {}
2023-08-09 10:33:00 +08:00
) => {
2023-10-20 17:44:48 +08:00
const cacheReq = await newCacheReq(input, init);
2023-07-20 13:45:41 +08:00
let res;
// 查询缓存
if (useCache) {
try {
2023-08-29 21:24:25 +08:00
const cache = await caches.open(CACHE_NAME);
2023-07-20 13:45:41 +08:00
res = await cache.match(cacheReq);
} catch (err) {
2023-08-29 21:33:27 +08:00
console.log("[cache match]", err.message);
2023-07-20 13:45:41 +08:00
}
}
if (!res) {
2023-08-10 11:55:40 +08:00
// 发送请求
if (usePool) {
2023-10-20 17:44:48 +08:00
res = await fetchPool.push({ input, init, transOpts, apiSetting });
2023-08-05 18:15:01 +08:00
} else {
2023-10-20 17:44:48 +08:00
res = await fetchApi({ input, init, transOpts, apiSetting });
2023-08-05 18:15:01 +08:00
}
2023-07-20 13:45:41 +08:00
2023-08-10 11:55:40 +08:00
if (!res?.ok) {
throw new Error(`response: ${res.statusText}`);
}
2023-07-20 13:45:41 +08:00
2023-08-10 11:55:40 +08:00
// 插入缓存
if (useCache) {
try {
2023-08-29 21:24:25 +08:00
const cache = await caches.open(CACHE_NAME);
2023-08-10 11:55:40 +08:00
await cache.put(cacheReq, res.clone());
} catch (err) {
2023-08-29 21:33:27 +08:00
console.log("[cache put]", err.message);
2023-08-10 11:55:40 +08:00
}
2023-07-20 13:45:41 +08:00
}
}
const contentType = res.headers.get("Content-Type");
if (contentType?.includes("json")) {
return await res.json();
}
return await res.text();
};
2023-08-05 18:15:01 +08:00
/**
* fetch 兼容性封装
* @param {*} input
* @param {*} opts
* @returns
*/
2023-09-20 17:47:23 +08:00
export const fetchPolyfill = async (input, opts) => {
2023-10-20 17:44:48 +08:00
if (!input?.trim()) {
2023-09-06 14:57:02 +08:00
throw new Error("URL is empty");
}
2023-08-05 18:15:01 +08:00
// 插件
2023-09-20 17:47:23 +08:00
if (isExt && !isBg()) {
2023-08-31 13:38:06 +08:00
const res = await sendBgMsg(MSG_FETCH, { input, opts });
2023-08-05 18:15:01 +08:00
if (res.error) {
throw new Error(res.error);
}
return res.data;
}
// 油猴/网页/BackgroundPage
return await fetchData(input, opts);
2023-08-05 18:15:01 +08:00
};
2023-08-10 11:55:40 +08:00
/**
* 更新 fetch pool 参数
* @param {*} interval
* @param {*} limit
*/
2023-08-31 13:38:06 +08:00
export const updateFetchPool = async (interval, limit) => {
2023-08-10 11:55:40 +08:00
if (isExt) {
2023-08-31 13:38:06 +08:00
const res = await sendBgMsg(MSG_FETCH_LIMIT, { interval, limit });
2023-08-10 11:55:40 +08:00
if (res.error) {
throw new Error(res.error);
}
} else {
fetchPool.update(interval, limit);
}
};
2023-08-11 16:48:09 +08:00
/**
* 清空任务池
*/
2023-08-31 13:38:06 +08:00
export const clearFetchPool = async () => {
2023-08-11 16:48:09 +08:00
if (isExt) {
2023-08-31 13:38:06 +08:00
const res = await sendBgMsg(MSG_FETCH_CLEAR);
2023-08-11 16:48:09 +08:00
if (res.error) {
throw new Error(res.error);
}
} else {
fetchPool.clear();
}
};