1 #include <linguistic/translate.hxx>
4 #include <rtl/string.h>
5 #include <boost/property_tree/ptree.hpp>
6 #include <boost/property_tree/json_parser.hpp>
7 #include <curlinit.hxx>
8 #include <vcl/htmltransferable.hxx>
9 #include <tools/long.hxx>
13 OString
Translate(const OString
& rTargetLang
, const OString
& rAPIUrl
, const OString
& rAuthKey
,
16 constexpr tools::Long CURL_TIMEOUT
= 10L;
18 std::unique_ptr
<CURL
, std::function
<void(CURL
*)>> curl(curl_easy_init(),
19 [](CURL
* p
) { curl_easy_cleanup(p
); });
21 ::InitCurl_easy(curl
.get());
23 (void)curl_easy_setopt(curl
.get(), CURLOPT_URL
, rAPIUrl
.getStr());
24 (void)curl_easy_setopt(curl
.get(), CURLOPT_FAILONERROR
, 1L);
25 (void)curl_easy_setopt(curl
.get(), CURLOPT_TIMEOUT
, CURL_TIMEOUT
);
27 std::string response_body
;
28 (void)curl_easy_setopt(curl
.get(), CURLOPT_WRITEFUNCTION
,
29 +[](void* buffer
, size_t size
, size_t nmemb
, void* userp
) -> size_t {
32 std::string
* response
= static_cast<std::string
*>(userp
);
33 size_t real_size
= size
* nmemb
;
34 response
->append(static_cast<char*>(buffer
), real_size
);
37 (void)curl_easy_setopt(curl
.get(), CURLOPT_WRITEDATA
, static_cast<void*>(&response_body
));
38 OString
aLang(curl_easy_escape(curl
.get(), rTargetLang
.getStr(), rTargetLang
.getLength()));
39 OString
aAuthKey(curl_easy_escape(curl
.get(), rAuthKey
.getStr(), rAuthKey
.getLength()));
40 OString
aData(curl_easy_escape(curl
.get(), rData
.getStr(), rData
.getLength()));
41 OString
aPostData("auth_key=" + aAuthKey
+ "&target_lang=" + aLang
+ "&text=" + aData
);
43 (void)curl_easy_setopt(curl
.get(), CURLOPT_POSTFIELDS
, aPostData
.getStr());
44 CURLcode cc
= curl_easy_perform(curl
.get());
47 SAL_WARN("linguistic",
48 "Translate: CURL perform returned with error: " << static_cast<sal_Int32
>(cc
));
51 tools::Long nStatusCode
;
52 curl_easy_getinfo(curl
.get(), CURLINFO_RESPONSE_CODE
, &nStatusCode
);
53 if (nStatusCode
!= 200)
55 SAL_WARN("linguistic",
56 "Translate: CURL request returned with status code: " << nStatusCode
);
60 boost::property_tree::ptree root
;
61 std::stringstream
aStream(response_body
.data());
62 boost::property_tree::read_json(aStream
, root
);
63 boost::property_tree::ptree
& translations
= root
.get_child("translations");
64 size_t size
= translations
.size();
67 SAL_WARN("linguistic", "Translate: API did not return any translations");
70 const boost::property_tree::ptree
& translation
= translations
.begin()->second
;
71 const std::string text
= translation
.get
<std::string
>("text");