summaryrefslogtreecommitdiff
path: root/indra/newview/lltranslate.h
blob: c2330daa8176628ca9a92cf560d10202d4823684 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
* @file lltranslate.h
* @brief Human language translation class and JSON response receiver.
*
 * $LicenseInfo:firstyear=2009&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#ifndef LL_LLTRANSLATE_H
#define LL_LLTRANSLATE_H

#include "llhttpclient.h"
#include "llbufferstream.h"

namespace Json
{
    class Value;
}

/**
 * Handler of an HTTP machine translation service.
 *
 * Derived classes know the service URL
 * and how to parse the translation result.
 */
class LLTranslationAPIHandler
{
public:
	/**
	 * Get URL for translation of the given string.
	 *
	 * Sending HTTP GET request to the URL will initiate translation.
	 *
	 * @param[out] url        Place holder for the result.
	 * @param      from_lang  Source language. Leave empty for auto-detection.
	 * @param      to_lang    Target language.
	 * @param      text       Text to translate.
	 */
	virtual void getTranslateURL(
		std::string &url,
		const std::string &from_lang,
		const std::string &to_lang,
		const std::string &text) const = 0;

	/**
	 * Get URL to verify the given API key.
	 *
	 * Sending request to the URL verifies the key.
	 * Positive HTTP response (code 200) means that the key is valid.
	 *
	 * @param[out] url  Place holder for the URL.
	 * @param[in]  key  Key to verify.
	 */
	virtual void getKeyVerificationURL(
		std::string &url,
		const std::string &key) const = 0;

	/**
	 * Parse translation response.
	 *
	 * @param[in,out] status        HTTP status. May be modified while parsing.
	 * @param         body          Response text.
	 * @param[out]    translation   Translated text.
	 * @param[out]    detected_lang Detected source language. May be empty.
	 * @param[out]    err_msg       Error message (in case of error).
	 */
	virtual bool parseResponse(
		int& status,
		const std::string& body,
		std::string& translation,
		std::string& detected_lang,
		std::string& err_msg) const = 0;

	virtual ~LLTranslationAPIHandler() {}

protected:
	static const int STATUS_OK = 200;
};

/// Google Translate v2 API handler.
class LLGoogleTranslationHandler : public LLTranslationAPIHandler
{
	LOG_CLASS(LLGoogleTranslationHandler);

public:
	/*virtual*/ void getTranslateURL(
		std::string &url,
		const std::string &from_lang,
		const std::string &to_lang,
		const std::string &text) const;
	/*virtual*/ void getKeyVerificationURL(
		std::string &url,
		const std::string &key) const;
	/*virtual*/ bool parseResponse(
		int& status,
		const std::string& body,
		std::string& translation,
		std::string& detected_lang,
		std::string& err_msg) const;

private:
	static void parseErrorResponse(
		const Json::Value& root,
		int& status,
		std::string& err_msg);
	static bool parseTranslation(
		const Json::Value& root,
		std::string& translation,
		std::string& detected_lang);
	static std::string getAPIKey();
};

/// Microsoft Translator v2 API handler.
class LLBingTranslationHandler : public LLTranslationAPIHandler
{
	LOG_CLASS(LLBingTranslationHandler);

public:
	/*virtual*/ void getTranslateURL(
		std::string &url,
		const std::string &from_lang,
		const std::string &to_lang,
		const std::string &text) const;
	/*virtual*/ void getKeyVerificationURL(
		std::string &url,
		const std::string &key) const;
	/*virtual*/ bool parseResponse(
		int& status,
		const std::string& body,
		std::string& translation,
		std::string& detected_lang,
		std::string& err_msg) const;
private:
	static std::string getAPIKey();
};

/**
 * Entry point for machine translation services.
 *
 * Basically, to translate a string, we need to know the URL
 * of a translation service, have a valid API for the service
 * and be given the target language.
 *
 * Callers specify the string to translate and the target language,
 * LLTranslate takes care of the rest.
 *
 * API keys for translation are taken from saved settings.
 */
class LLTranslate
{
	LOG_CLASS(LLTranslate);

public :

	typedef enum e_service {
		SERVICE_BING,
		SERVICE_GOOGLE,
	} EService;

	/**
	 * Subclasses are supposed to handle translation results (e.g. show them in chat)
	 */
	class TranslationReceiver: public LLHTTPClient::Responder
	{
	public:

		/**
		 * Using mHandler, parse incoming response.
		 *
		 * Calls either handleResponse() or handleFailure()
		 * depending on the HTTP status code and parsing success.
		 *
		 * @see handleResponse()
		 * @see handleFailure()
		 * @see mHandler
		 */
		/*virtual*/ void completedRaw(
			U32 http_status,
			const std::string& reason,
			const LLChannelDescriptors& channels,
			const LLIOPipe::buffer_ptr_t& buffer);

	protected:
		friend class LLTranslate;

		/// Remember source and target languages for subclasses to be able to filter inappropriate results.
		TranslationReceiver(const std::string& from_lang, const std::string& to_lang);

		/// Override point to handle successful translation.
		virtual void handleResponse(const std::string &translation, const std::string &recognized_lang) = 0;

		/// Override point to handle unsuccessful translation.
		virtual void handleFailure(int status, const std::string& err_msg) = 0;

		std::string mFromLang;
		std::string mToLang;
		const LLTranslationAPIHandler& mHandler;
	};

	/**
	 * Subclasses are supposed to handle API key verification result.
	 */
	class KeyVerificationReceiver: public LLHTTPClient::Responder
	{
	public:
		EService getService() const;

	protected:
		/**
		 * Save the translation service the key belongs to.
		 *
		 * Subclasses need to know it.
		 *
		 * @see getService()
		 */
		KeyVerificationReceiver(EService service);

		/**
		 * Parse verification response.
		 *
		 * Calls setVerificationStatus() with the verification status,
		 * which is true if HTTP status code is 200.
		 *
		 * @see setVerificationStatus()
		 */
		/*virtual*/ void completedRaw(
			U32 http_status,
			const std::string& reason,
			const LLChannelDescriptors& channels,
			const LLIOPipe::buffer_ptr_t& buffer);

		/**
		 * Override point for subclasses to handle key verification status.
		 */
		virtual void setVerificationStatus(bool ok) = 0;

		EService mService;
	};

	typedef boost::intrusive_ptr<TranslationReceiver> TranslationReceiverPtr;
	typedef boost::intrusive_ptr<KeyVerificationReceiver> KeyVerificationReceiverPtr;

	/**
	 * Translate given text.
	 *
	 * @param receiver   Object to pass translation result to.
	 * @param from_lang  Source language. Leave empty for auto-detection.
	 * @param to_lang    Target language.
	 * @param mesg       Text to translate.
	 */
	static void translateMessage(TranslationReceiverPtr &receiver, const std::string &from_lang, const std::string &to_lang, const std::string &mesg);

	/**
	 * Verify given API key of a translation service.
	 *
	 * @param receiver  Object to pass verification result to.
	 * @param key       Key to verify.
	 */
	static void verifyKey(KeyVerificationReceiverPtr& receiver, const std::string& key);
	static std::string getTranslateLanguage();

private:
	static const LLTranslationAPIHandler& getPreferredHandler();
	static const LLTranslationAPIHandler& getHandler(EService service);
	static void sendRequest(const std::string& url, LLHTTPClient::ResponderPtr responder);
};

#endif