From 327548a2d6eaace9d621d61162e89cff5a4a9604 Mon Sep 17 00:00:00 2001 From: tisfeng Date: Sun, 12 Jan 2025 21:18:22 +0800 Subject: [PATCH] fix: set bing retry count to 3, avoid too much retry request --- src/translation/microsoft/bing.ts | 41 ++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/src/translation/microsoft/bing.ts b/src/translation/microsoft/bing.ts index c71efca..473df3a 100644 --- a/src/translation/microsoft/bing.ts +++ b/src/translation/microsoft/bing.ts @@ -32,6 +32,8 @@ const defaultBingHost = "www.bing.com"; // * bing host depends ip, if ip is in china, `must` use cn.bing.com, otherwise use www.bing.com. And vice versa. let bingHost = myPreferences.bingHost || defaultBingHost; +let retryCount = 0; + /** * Request Microsoft Bing Web Translator. */ @@ -104,24 +106,39 @@ export async function requestWebBingTranslate(queryWordInfo: QueryWordInfo): Pro const finalUrl = response.request.res.responseUrl; console.log(`bing finalUrl: ${finalUrl}`); - // get host - bingHost = new URL(finalUrl).host; + // Get new host + const newBingHost = new URL(finalUrl).host; const responseData = response.data; console.warn(`bing translate cost time: ${response.headers[requestCostTime]}`); // If bing translate response is empty, may be ip has been changed, bing tld is not correct, so check ip again, then request again. if (!responseData) { - console.warn(`bing translate response is empty, change to use new host: ${bingHost}, then request again`); - requestBingConfig().then((bingConfig) => { - if (bingConfig) { - requestWebBingTranslate(queryWordInfo) - .then((result) => resolve(result)) - .catch((error) => reject(error)); - } else { - reject(undefined); - } - }); + if (bingHost !== newBingHost && retryCount < 3) { + console.warn( + `bing translate response is empty, change to use new host: ${bingHost}, then request again, retryCount: ${retryCount}` + ); + retryCount++; + requestBingConfig().then((bingConfig) => { + if (bingConfig) { + requestWebBingTranslate(queryWordInfo) + .then((result) => resolve(result)) + .catch((error) => reject(error)); + } else { + return reject({ + type: TranslationType.Bing, + message: "Bing translate response is empty, get bing config failed", + } as RequestErrorInfo); + } + }); + } else { + return reject({ + type: TranslationType.Bing, + message: "Bing translate response is empty", + } as RequestErrorInfo); + } } else { + retryCount = 0; + console.log(`bing response: ${JSON.stringify(responseData, null, 4)}`); const bingTranslateResult = responseData[0] as BingTranslateResult; const translations = bingTranslateResult.translations[0].text.split("\n");