5#include <boost/property_tree/ptree.hpp>
6#include <boost/property_tree/json_parser.hpp>
12OString
Translate(
const OString& rTargetLang,
const OString& rAPIUrl,
const OString& rAuthKey,
17 std::unique_ptr<CURL, std::function<void(CURL*)>> curl(curl_easy_init(),
18 [](CURL*
p) { curl_easy_cleanup(
p); });
19 (void)curl_easy_setopt(curl.get(), CURLOPT_URL, rAPIUrl.getStr());
20 (void)curl_easy_setopt(curl.get(), CURLOPT_FAILONERROR, 1L);
21 (void)curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, CURL_TIMEOUT);
23 std::string response_body;
24 (void)curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION,
25 +[](
void* buffer,
size_t size,
size_t nmemb,
void* userp) ->
size_t {
28 std::string* response =
static_cast<std::string*
>(userp);
29 size_t real_size =
size * nmemb;
30 response->append(
static_cast<char*
>(buffer), real_size);
33 (void)curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA,
static_cast<void*
>(&response_body));
34 OString aLang(curl_easy_escape(curl.get(), rTargetLang.getStr(), rTargetLang.getLength()));
35 OString aAuthKey(curl_easy_escape(curl.get(), rAuthKey.getStr(), rAuthKey.getLength()));
36 OString
aData(curl_easy_escape(curl.get(), rData.getStr(), rData.getLength()));
37 OString aPostData(
"auth_key=" + aAuthKey +
"&target_lang=" + aLang +
"&text=" +
aData);
39 (void)curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, aPostData.getStr());
40 CURLcode cc = curl_easy_perform(curl.get());
44 "Translate: CURL perform returned with error: " <<
static_cast<sal_Int32
>(cc));
48 curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &nStatusCode);
49 if (nStatusCode != 200)
52 "Translate: CURL request returned with status code: " << nStatusCode);
56 boost::property_tree::ptree root;
57 std::stringstream aStream(response_body.data());
58 boost::property_tree::read_json(aStream, root);
59 boost::property_tree::ptree& translations = root.get_child(
"translations");
60 size_t size = translations.size();
63 SAL_WARN(
"linguistic",
"Translate: API did not return any translations");
66 const boost::property_tree::ptree& translation = translations.begin()->second;
67 const std::string
text = translation.get<std::string>(
"text");
#define SAL_WARN(area, stream)
constexpr OUStringLiteral aData
OString Translate(const OString &rTargetLang, const OString &rAPIUrl, const OString &rAuthKey, const OString &rData)