Version 7.6.3.2-android, tag libreoffice-7.6.3.2-android
[LibreOffice.git] / linguistic / source / translate.cxx
blobfdd95fca2988e35ad6edd3ec9c1d75d7df05b24e
1 #include <linguistic/translate.hxx>
2 #include <sal/log.hxx>
3 #include <curl/curl.h>
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>
11 namespace linguistic
13 OString Translate(const OString& rTargetLang, const OString& rAPIUrl, const OString& rAuthKey,
14 const OString& rData)
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 {
30 if (!userp)
31 return 0;
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);
35 return real_size;
36 });
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());
45 if (cc != CURLE_OK)
47 SAL_WARN("linguistic",
48 "Translate: CURL perform returned with error: " << static_cast<sal_Int32>(cc));
49 return {};
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);
57 return {};
59 // parse the response
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();
65 if (size <= 0)
67 SAL_WARN("linguistic", "Translate: API did not return any translations");
69 // take the first one
70 const boost::property_tree::ptree& translation = translations.begin()->second;
71 const std::string text = translation.get<std::string>("text");
72 return OString(text);