From 8e40c715637e21af7b240c9f2288b13111925151 Mon Sep 17 00:00:00 2001 From: Akash Mozumdar Date: Sat, 16 Feb 2019 22:43:31 -0500 Subject: [PATCH] refactor --- extensions/bingtranslate.cpp | 7 ++++--- extensions/googletranslate.cpp | 11 +++++++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/extensions/bingtranslate.cpp b/extensions/bingtranslate.cpp index a073fa5..4fc65aa 100644 --- a/extensions/bingtranslate.cpp +++ b/extensions/bingtranslate.cpp @@ -94,12 +94,12 @@ std::wstring Translate(const std::wstring& text, std::wstring translateFrom, std { wchar_t escapedChar[4] = {}; swprintf_s<4>(escapedChar, L"%%%02X", (int)ch); - escapedText = escapedChar; + escapedText += escapedChar; } std::wstring location = translateFrom.empty() - ? L"/tdetect?text=" + text - : L"/ttranslate?from=" + translateFrom + L"&to=" + translateTo + L"&text=" + text; + ? L"/tdetect?text=" + escapedText + : L"/ttranslate?from=" + translateFrom + L"&to=" + translateTo + L"&text=" + escapedText; std::wstring translation; if (internet) if (InternetHandle connection = WinHttpConnect(internet, L"www.bing.com", INTERNET_DEFAULT_HTTPS_PORT, 0)) @@ -107,6 +107,7 @@ std::wstring Translate(const std::wstring& text, std::wstring translateFrom, std if (WinHttpSendRequest(request, NULL, 0, NULL, 0, 0, NULL)) if (auto response = ReceiveHttpRequest(request)) if (translateFrom.empty()) translation = response.value(); + // Response formatted as JSON: translation starts with :" and ends with "} else if (std::wsmatch results; std::regex_search(response.value(), results, std::wregex(L":\"(.+)\"\\}"))) translation = results[1]; Escape(translation); diff --git a/extensions/googletranslate.cpp b/extensions/googletranslate.cpp index 90d1368..1be18c5 100644 --- a/extensions/googletranslate.cpp +++ b/extensions/googletranslate.cpp @@ -151,14 +151,21 @@ bool ProcessSentence(std::wstring& sentence, SentenceInfo sentenceInfo) if (InternetHandle request = WinHttpOpenRequest(connection, L"GET", GetTranslationUri(sentence, TKK).c_str(), NULL, NULL, NULL, WINHTTP_FLAG_ESCAPE_DISABLE | WINHTTP_FLAG_SECURE)) if (WinHttpSendRequest(request, NULL, 0, NULL, 0, 0, NULL)) if (auto response = ReceiveHttpRequest(request)) + // Response formatted as JSON: starts with [[[" if (response.value()[0] == L'[') + { for (std::wsmatch results; std::regex_search(response.value(), results, std::wregex(L"\\[\"(.*?)\",[n\"]")); response = results.suffix()) translation += std::wstring(results[1]) + L" "; - else std::tie(translation, TKK) = std::tuple(TRANSLATION_ERROR + (L" (TKK=" + std::to_wstring(TKK) + L")"), 0); + Escape(translation); + } + else + { + translation = TRANSLATION_ERROR + (L" (TKK=" + std::to_wstring(TKK) + L")"); + TKK = 0; + } } if (translation.empty()) translation = TRANSLATION_ERROR; - Escape(translation); sentence += L"\n" + translation; return true; }