summaryrefslogtreecommitdiff
path: root/indra/newview/lltranslate.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'indra/newview/lltranslate.cpp')
-rw-r--r--indra/newview/lltranslate.cpp366
1 files changed, 294 insertions, 72 deletions
diff --git a/indra/newview/lltranslate.cpp b/indra/newview/lltranslate.cpp
index 3692f67a8d..7eb54271f4 100644
--- a/indra/newview/lltranslate.cpp
+++ b/indra/newview/lltranslate.cpp
@@ -31,50 +31,224 @@
#include <curl/curl.h>
#include "llbufferstream.h"
+#include "lltrans.h"
#include "llui.h"
#include "llversioninfo.h"
#include "llviewercontrol.h"
#include "reader.h"
-// These two are concatenated with the language specifiers to form a complete Google Translate URL
-const char* LLTranslate::m_GoogleURL = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=";
-const char* LLTranslate::m_GoogleLangSpec = "&langpair=";
-float LLTranslate::m_GoogleTimeout = 5;
+// virtual
+void LLGoogleTranslationHandler::getTranslateURL(
+ std::string &url,
+ const std::string &from_lang,
+ const std::string &to_lang,
+ const std::string &text) const
+{
+ url = std::string("https://www.googleapis.com/language/translate/v2?key=")
+ + getAPIKey() + "&q=" + LLURI::escape(text) + "&target=" + to_lang;
+ if (!from_lang.empty())
+ {
+ url += "&source=" + from_lang;
+ }
+}
+
+// virtual
+void LLGoogleTranslationHandler::getKeyVerificationURL(
+ std::string& url,
+ const std::string& key) const
+{
+ url = std::string("https://www.googleapis.com/language/translate/v2/languages?key=")
+ + key + "&target=en";
+}
+
+// virtual
+bool LLGoogleTranslationHandler::parseResponse(
+ int& status,
+ const std::string& body,
+ std::string& translation,
+ std::string& detected_lang,
+ std::string& err_msg) const
+{
+ Json::Value root;
+ Json::Reader reader;
+
+ if (!reader.parse(body, root))
+ {
+ err_msg = reader.getFormatedErrorMessages();
+ return false;
+ }
+
+ if (!root.isObject()) // empty response? should not happen
+ {
+ return false;
+ }
+
+ if (status != STATUS_OK)
+ {
+ // Request failed. Extract error message from the response.
+ parseErrorResponse(root, status, err_msg);
+ return false;
+ }
+
+ // Request succeeded, extract translation from the response.
+ return parseTranslation(root, translation, detected_lang);
+}
+
+// static
+void LLGoogleTranslationHandler::parseErrorResponse(
+ const Json::Value& root,
+ int& status,
+ std::string& err_msg)
+{
+ const Json::Value& error = root.get("error", 0);
+ if (!error.isObject() || !error.isMember("message") || !error.isMember("code"))
+ {
+ return;
+ }
-LLSD LLTranslate::m_Header;
-// These constants are for the GET header.
-const char* LLTranslate::m_AcceptHeader = "Accept";
-const char* LLTranslate::m_AcceptType = "text/plain";
-const char* LLTranslate::m_AgentHeader = "User-Agent";
+ err_msg = error["message"].asString();
+ status = error["code"].asInt();
+}
+
+// static
+bool LLGoogleTranslationHandler::parseTranslation(
+ const Json::Value& root,
+ std::string& translation,
+ std::string& detected_lang)
+{
+ // JsonCpp is prone to aborting the program on failed assertions,
+ // so be super-careful and verify the response format.
+ const Json::Value& data = root.get("data", 0);
+ if (!data.isObject() || !data.isMember("translations"))
+ {
+ return false;
+ }
+
+ const Json::Value& translations = data["translations"];
+ if (!translations.isArray() || translations.size() == 0)
+ {
+ return false;
+ }
+
+ const Json::Value& first = translations[0U];
+ if (!first.isObject() || !first.isMember("translatedText"))
+ {
+ return false;
+ }
+
+ translation = first["translatedText"].asString();
+ detected_lang = first.get("detectedSourceLanguage", "").asString();
+ return true;
+}
-// These constants are in the JSON returned from Google
-const char* LLTranslate::m_GoogleData = "responseData";
-const char* LLTranslate::m_GoogleTranslation = "translatedText";
-const char* LLTranslate::m_GoogleLanguage = "detectedSourceLanguage";
+// static
+std::string LLGoogleTranslationHandler::getAPIKey()
+{
+ return gSavedSettings.getString("GoogleTranslateAPIKey");
+}
// virtual
-void LLTranslate::TranslationReceiver::completedRaw( U32 status,
- const std::string& reason,
- const LLChannelDescriptors& channels,
- const LLIOPipe::buffer_ptr_t& buffer)
+void LLBingTranslationHandler::getTranslateURL(
+ std::string &url,
+ const std::string &from_lang,
+ const std::string &to_lang,
+ const std::string &text) const
{
- if (200 <= status && status < 300)
+ url = std::string("http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=")
+ + getAPIKey() + "&text=" + LLURI::escape(text) + "&to=" + to_lang;
+ if (!from_lang.empty())
{
- LLBufferStream istr(channels, buffer.get());
- std::stringstream strstrm;
- strstrm << istr.rdbuf();
+ url += "&from=" + from_lang;
+ }
+}
- const std::string result = strstrm.str();
- std::string translation;
- std::string detected_language;
+// virtual
+void LLBingTranslationHandler::getKeyVerificationURL(
+ std::string& url,
+ const std::string& key) const
+{
+ url = std::string("http://api.microsofttranslator.com/v2/Http.svc/GetLanguagesForTranslate?appId=")
+ + key;
+}
- if (!parseGoogleTranslate(result, translation, detected_language))
+// virtual
+bool LLBingTranslationHandler::parseResponse(
+ int& status,
+ const std::string& body,
+ std::string& translation,
+ std::string& detected_lang,
+ std::string& err_msg) const
+{
+ if (status != STATUS_OK)
+ {
+ static const std::string MSG_BEGIN_MARKER = "Message: ";
+ size_t begin = body.find(MSG_BEGIN_MARKER);
+ if (begin != std::string::npos)
+ {
+ begin += MSG_BEGIN_MARKER.size();
+ }
+ else
{
- handleFailure();
- return;
+ begin = 0;
+ err_msg.clear();
}
-
+ size_t end = body.find("</p>", begin);
+ err_msg = body.substr(begin, end-begin);
+ LLStringUtil::replaceString(err_msg, "&#xD;", ""); // strip CR
+ return false;
+ }
+
+ // Sample response: <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hola</string>
+ size_t begin = body.find(">");
+ if (begin == std::string::npos || begin >= (body.size() - 1))
+ {
+ begin = 0;
+ }
+ else
+ {
+ ++begin;
+ }
+
+ size_t end = body.find("</string>", begin);
+
+ detected_lang = ""; // unsupported by this API
+ translation = body.substr(begin, end-begin);
+ LLStringUtil::replaceString(translation, "&#xD;", ""); // strip CR
+ return true;
+}
+
+// static
+std::string LLBingTranslationHandler::getAPIKey()
+{
+ return gSavedSettings.getString("BingTranslateAPIKey");
+}
+
+LLTranslate::TranslationReceiver::TranslationReceiver(const std::string& from_lang, const std::string& to_lang)
+: mFromLang(from_lang)
+, mToLang(to_lang)
+, mHandler(LLTranslate::getPreferredHandler())
+{
+}
+
+// virtual
+void LLTranslate::TranslationReceiver::completedRaw(
+ U32 http_status,
+ const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer)
+{
+ LLBufferStream istr(channels, buffer.get());
+ std::stringstream strstrm;
+ strstrm << istr.rdbuf();
+
+ const std::string body = strstrm.str();
+ std::string translation, detected_lang, err_msg;
+ int status = http_status;
+ LL_DEBUGS("Translate") << "HTTP status: " << status << " " << reason << LL_ENDL;
+ LL_DEBUGS("Translate") << "Response body: " << body << LL_ENDL;
+ if (mHandler.parseResponse(status, body, translation, detected_lang, err_msg))
+ {
// Fix up the response
LLStringUtil::replaceString(translation, "&lt;", "<");
LLStringUtil::replaceString(translation, "&gt;",">");
@@ -83,67 +257,66 @@ void LLTranslate::TranslationReceiver::completedRaw( U32 status,
LLStringUtil::replaceString(translation, "&amp;","&");
LLStringUtil::replaceString(translation, "&apos;","'");
- handleResponse(translation, detected_language);
+ handleResponse(translation, detected_lang);
}
else
{
- LL_WARNS("Translate") << "HTTP request for Google Translate failed with status " << status << ", reason: " << reason << LL_ENDL;
- handleFailure();
+ if (err_msg.empty())
+ {
+ err_msg = LLTrans::getString("TranslationResponseParseError");
+ }
+
+ llwarns << "Translation request failed: " << err_msg << llendl;
+ handleFailure(status, err_msg);
}
}
-//static
-void LLTranslate::translateMessage(LLHTTPClient::ResponderPtr &result, const std::string &from_lang, const std::string &to_lang, const std::string &mesg)
+LLTranslate::KeyVerificationReceiver::KeyVerificationReceiver(EService service)
+: mService(service)
{
- std::string url;
- getTranslateUrl(url, from_lang, to_lang, mesg);
-
- std::string user_agent = llformat("%s %d.%d.%d (%d)",
- LLVersionInfo::getChannel().c_str(),
- LLVersionInfo::getMajor(),
- LLVersionInfo::getMinor(),
- LLVersionInfo::getPatch(),
- LLVersionInfo::getBuild());
+}
- if (!m_Header.size())
- {
- m_Header.insert(m_AcceptHeader, LLSD(m_AcceptType));
- m_Header.insert(m_AgentHeader, LLSD(user_agent));
- }
+LLTranslate::EService LLTranslate::KeyVerificationReceiver::getService() const
+{
+ return mService;
+}
- LLHTTPClient::get(url, result, m_Header, m_GoogleTimeout);
+// virtual
+void LLTranslate::KeyVerificationReceiver::completedRaw(
+ U32 http_status,
+ const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer)
+{
+ bool ok = (http_status == 200);
+ setVerificationStatus(ok);
}
//static
-void LLTranslate::getTranslateUrl(std::string &translate_url, const std::string &from_lang, const std::string &to_lang, const std::string &mesg)
+void LLTranslate::translateMessage(
+ TranslationReceiverPtr &receiver,
+ const std::string &from_lang,
+ const std::string &to_lang,
+ const std::string &mesg)
{
- char * curl_str = curl_escape(mesg.c_str(), mesg.size());
- std::string const escaped_mesg(curl_str);
- curl_free(curl_str);
+ std::string url;
+ receiver->mHandler.getTranslateURL(url, from_lang, to_lang, mesg);
- translate_url = m_GoogleURL
- + escaped_mesg + m_GoogleLangSpec
- + from_lang // 'from' language; empty string for auto
- + "%7C" // |
- + to_lang; // 'to' language
+ LL_DEBUGS("Translate") << "Sending translation request: " << url << LL_ENDL;
+ sendRequest(url, receiver);
}
-//static
-bool LLTranslate::parseGoogleTranslate(const std::string& body, std::string &translation, std::string &detected_language)
+// static
+void LLTranslate::verifyKey(
+ KeyVerificationReceiverPtr& receiver,
+ const std::string& key)
{
- Json::Value root;
- Json::Reader reader;
-
- bool success = reader.parse(body, root);
- if (!success)
- {
- LL_WARNS("Translate") << "Non valid response from Google Translate API: '" << reader.getFormatedErrorMessages() << "'" << LL_ENDL;
- return false;
- }
-
- translation = root[m_GoogleData].get(m_GoogleTranslation, "").asString();
- detected_language = root[m_GoogleData].get(m_GoogleLanguage, "").asString();
- return true;
+ std::string url;
+ const LLTranslationAPIHandler& handler = getHandler(receiver->getService());
+ handler.getKeyVerificationURL(url, key);
+
+ LL_DEBUGS("Translate") << "Sending key verification request: " << url << LL_ENDL;
+ sendRequest(url, receiver);
}
//static
@@ -158,3 +331,52 @@ std::string LLTranslate::getTranslateLanguage()
return language;
}
+// static
+const LLTranslationAPIHandler& LLTranslate::getPreferredHandler()
+{
+ EService service = SERVICE_BING;
+
+ std::string service_str = gSavedSettings.getString("TranslationService");
+ if (service_str == "google")
+ {
+ service = SERVICE_GOOGLE;
+ }
+
+ return getHandler(service);
+}
+
+// static
+const LLTranslationAPIHandler& LLTranslate::getHandler(EService service)
+{
+ static LLGoogleTranslationHandler google;
+ static LLBingTranslationHandler bing;
+
+ if (service == SERVICE_GOOGLE)
+ {
+ return google;
+ }
+
+ return bing;
+}
+
+// static
+void LLTranslate::sendRequest(const std::string& url, LLHTTPClient::ResponderPtr responder)
+{
+ static const float REQUEST_TIMEOUT = 5;
+ static LLSD sHeader;
+
+ if (!sHeader.size())
+ {
+ std::string user_agent = llformat("%s %d.%d.%d (%d)",
+ LLVersionInfo::getChannel().c_str(),
+ LLVersionInfo::getMajor(),
+ LLVersionInfo::getMinor(),
+ LLVersionInfo::getPatch(),
+ LLVersionInfo::getBuild());
+
+ sHeader.insert("Accept", "text/plain");
+ sHeader.insert("User-Agent", user_agent);
+ }
+
+ LLHTTPClient::get(url, responder, sHeader, REQUEST_TIMEOUT);
+}