From febff243d31752fc40d253c3abba03b3b49f1e35 Mon Sep 17 00:00:00 2001 From: Akash Mozumdar Date: Sat, 6 Nov 2021 17:48:45 -0600 Subject: [PATCH] fix bing translate --- extensions/bingtranslate.cpp | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/extensions/bingtranslate.cpp b/extensions/bingtranslate.cpp index 04aac88..0f9f831 100644 --- a/extensions/bingtranslate.cpp +++ b/extensions/bingtranslate.cpp @@ -213,18 +213,27 @@ std::pair Translate(const std::wstring& text, TranslationPar else return { false, FormatString(L"%s (code=%u)", TRANSLATION_ERROR, httpRequest.errorCode) }; } + static std::atomic i = 0; static Synchronized token; - if (token->empty()) - if (HttpRequest httpRequest{ L"Mozilla/5.0 Textractor", L"www.bing.com", L"GET", L"translator" }) - if (auto tokenPos = httpRequest.response.find(L"[" + std::to_wstring(time(nullptr) / 100)); tokenPos != std::string::npos) - token->assign(FormatString(L"&key=%s&token=%s", httpRequest.response.substr(tokenPos + 1, 13), httpRequest.response.substr(tokenPos + 16, 32))); - else return { false, FormatString(L"%s: %s\ntoken not found", TRANSLATION_ERROR, httpRequest.response) }; - else return { false, FormatString(L"%s: could not acquire token", TRANSLATION_ERROR) }; + if (token->empty()) if (HttpRequest httpRequest{ L"Mozilla/5.0 Textractor", L"www.bing.com", L"GET", L"translator" }) + { + std::wstring tokenBuilder; + if (auto tokenPos = httpRequest.response.find(L"[" + std::to_wstring(time(nullptr) / 100)); tokenPos != std::string::npos) + tokenBuilder = FormatString(L"&key=%s&token=%s", httpRequest.response.substr(tokenPos + 1, 13), httpRequest.response.substr(tokenPos + 16, 32)); + if (auto tokenPos = httpRequest.response.find(L"IG:\""); tokenPos != std::string::npos) + tokenBuilder += L"&IG=" + httpRequest.response.substr(tokenPos + 4, 32); + if (auto tokenPos = httpRequest.response.find(L"data-iid=\""); tokenPos != std::string::npos) + tokenBuilder += L"&IID=" + httpRequest.response.substr(tokenPos + 10, 15); + if (!tokenBuilder.empty()) token->assign(tokenBuilder); + else return { false, FormatString(L"%s: %s\ntoken not found", TRANSLATION_ERROR, httpRequest.response) }; + } + else return { false, FormatString(L"%s: could not acquire token", TRANSLATION_ERROR) }; + if (HttpRequest httpRequest{ L"Mozilla/5.0 Textractor", L"www.bing.com", L"POST", - FormatString(L"/ttranslatev3?fromLang=%s&to=%s&text=%s%s", codes.at(tlp.translateFrom), codes.at(tlp.translateTo), Escape(text), token.Copy()).c_str() + FormatString(L"/ttranslatev3?fromLang=%s&to=%s&text=%s%s%d", codes.at(tlp.translateFrom), codes.at(tlp.translateTo), Escape(text), token.Copy(), i++).c_str() }) if (auto translation = Copy(JSON::Parse(httpRequest.response)[0][L"translations"][0][L"text"].String())) return { true, translation.value() }; else return { false, FormatString(L"%s (token=%s): %s", TRANSLATION_ERROR, std::exchange(token.Acquire().contents, L""), httpRequest.response) };