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

66 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-05-22 23:33:30 +08:00
import {
CACHE_NAME,
OPT_TRANS_GOOGLE,
OPT_TRANS_MICROSOFT,
OPT_TRANS_BAIDU,
OPT_TRANS_TENCENT,
} from "../config";
2023-08-31 00:18:57 +08:00
import { browser } from "./browser";
2024-05-22 23:33:30 +08:00
import {
apiGoogleLangdetect,
apiMicrosoftLangdetect,
apiBaiduLangdetect,
apiTencentLangdetect,
} from "../apis";
2024-03-19 18:07:18 +08:00
import { kissLog } from "./log";
2023-07-20 13:45:41 +08:00
2024-05-22 23:33:30 +08:00
const langdetectMap = {
[OPT_TRANS_GOOGLE]: apiGoogleLangdetect,
[OPT_TRANS_MICROSOFT]: apiMicrosoftLangdetect,
[OPT_TRANS_BAIDU]: apiBaiduLangdetect,
[OPT_TRANS_TENCENT]: apiTencentLangdetect,
};
2023-07-20 13:45:41 +08:00
/**
2023-08-30 18:05:37 +08:00
* 清除缓存数据
2023-07-20 13:45:41 +08:00
*/
2023-08-30 18:05:37 +08:00
export const tryClearCaches = async () => {
2023-08-27 17:43:27 +08:00
try {
2023-08-30 18:05:37 +08:00
caches.delete(CACHE_NAME);
2023-08-27 17:43:27 +08:00
} catch (err) {
2024-03-19 18:07:18 +08:00
kissLog(err, "clean caches");
2023-08-27 17:43:27 +08:00
}
2023-07-20 13:45:41 +08:00
};
2023-08-31 00:18:57 +08:00
/**
2023-10-10 18:03:05 +08:00
* 语言识别
2023-08-31 00:18:57 +08:00
* @param {*} q
* @returns
*/
2024-05-22 23:33:30 +08:00
export const tryDetectLang = async (
q,
useRemote = false,
langDetector = OPT_TRANS_MICROSOFT
) => {
2023-10-10 18:03:05 +08:00
let lang = "";
2023-10-11 09:48:52 +08:00
if (useRemote) {
try {
2024-05-22 23:33:30 +08:00
lang = await langdetectMap[langDetector](q);
2023-10-11 09:48:52 +08:00
} catch (err) {
2024-03-19 18:07:18 +08:00
kissLog(err, "detect lang remote");
2023-10-10 18:03:05 +08:00
}
2023-10-11 09:48:52 +08:00
}
if (!lang) {
try {
2023-10-10 18:03:05 +08:00
const res = await browser?.i18n?.detectLanguage(q);
lang = res?.languages?.[0]?.language;
2023-10-11 09:48:52 +08:00
} catch (err) {
2024-03-19 18:07:18 +08:00
kissLog(err, "detect lang local");
2023-10-10 18:03:05 +08:00
}
2023-08-31 00:18:57 +08:00
}
2023-10-10 18:03:05 +08:00
return lang;
2023-08-31 00:18:57 +08:00
};