reduce a request to google
[mdictionary] / trunk / src / plugins / google / src / GooglePlugin.cpp
1 /*******************************************************************************
2
3     This file is part of mDictionary.
4
5     mDictionary is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9
10     mDictionary is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with mDictionary.  If not, see <http://www.gnu.org/licenses/>.
17
18     Copyright 2010 Comarch S.A.
19
20 *******************************************************************************/
21
22 /*! \file GooglePlugin.cpp
23     \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
24 */
25
26 #include "GooglePlugin.h"
27 #include <QDebug>
28 #include "GoogleDictDialog.h"
29
30 GooglePlugin::GooglePlugin(QObject *parent): CommonDictInterface(parent),
31                     _langFrom(tr("")), _langTo(tr("")),_name(tr("")),
32                     _type(tr("google")), _infoNote(tr("")) {
33
34     _settings = new Settings();
35     _dictDialog = new GoogleDictDialog(this,this);
36     http = new QHttp(this);
37
38     stopped = false;
39     _connectionAccept = false;
40     _icon = QIcon(":/icons/drawing.png");
41     languages=initLanguages();
42     _settings->setValue("type","google");
43     _settings->setValue("connectionAcepted","true");
44
45     connect(http, SIGNAL(done(bool)), this, SLOT(done()));
46 }
47
48 GooglePlugin::~GooglePlugin() {
49     delete _settings;
50 }
51
52 QString GooglePlugin::langFrom() const {
53     return languages.key(_langFrom);
54 }
55 QString GooglePlugin::langTo() const {
56     return languages.key(_langTo);
57 }
58
59 QString GooglePlugin::name() const {
60     return QString("dictionary");
61 }
62
63 QString GooglePlugin::type() const {
64     return _type;
65 }
66
67 QString GooglePlugin::infoNote() const {
68     return _infoNote;
69 }
70
71 void GooglePlugin::setLangTo(QString langTo){
72     _langTo=langTo;
73 }
74
75 void GooglePlugin::setLangFrom(QString langFrom){
76     _langFrom=langFrom;
77 }
78
79 DictDialog* GooglePlugin::dictDialog() {
80     return _dictDialog;
81 }
82
83 bool GooglePlugin::isAvailable() const {
84     if(_settings->value("connectionAcepted")=="true") {
85  //       _connectionAccept=true;
86         return true;
87     }
88     else {
89 //        _connectionAccept=false;
90         return false;
91     }
92 }
93
94 void GooglePlugin::setConnectionAccept(QString connectionAcepted) {
95     if(connectionAcepted=="true")
96         _connectionAccept=true;
97     else
98         _connectionAccept=false;
99 }
100
101 bool GooglePlugin::isConnectionAccept() {
102     return _connectionAccept;
103 }
104
105 QString GooglePlugin::search(QString) {
106     /*function is not used on this plagin */
107     return QString("");
108 }
109
110 uint GooglePlugin::hash() const {
111     return _hash;
112 }
113
114 void GooglePlugin::setHash(uint) {
115     this->_hash=_hash;
116 }
117
118 Settings* GooglePlugin::settings() {
119     return _settings;
120 }
121
122 QIcon* GooglePlugin::icon() {
123     return &_icon;
124 }
125
126 CommonDictInterface* GooglePlugin::getNew(const Settings* settings) const
127 {
128     GooglePlugin *plugin = new GooglePlugin();
129
130     if(settings) {
131         plugin->setLangFrom(settings->value("langFrom"));
132         plugin->setLangTo(settings->value("langTo"));
133         plugin->setConnectionAccept(settings->value("connectionAccept"));
134         QStringList list = settings->keys();
135         foreach(QString key, list)
136             plugin->settings()->setValue(key, settings->value(key));
137     }
138     delete settings;
139     plugin->getDictionaryInfo();
140     return plugin;
141 }
142
143 void GooglePlugin::setSettings(Settings* settings) {
144     if(settings){
145         _langFrom=settings->value("langFrom");
146         _langTo=settings->value("langTo");
147         setConnectionAccept(settings->value("connectionAccept"));
148         QStringList list = settings->keys();
149         foreach(QString key, list)
150             _settings->setValue(key, settings->value(key));
151         delete settings;
152         getDictionaryInfo();
153     }
154 }
155
156 Translation* GooglePlugin::getTranslationFor(QString key) {
157     return (new TranslationGoogle(key,"",_infoNote,this));
158 }
159
160 QList<Translation*> GooglePlugin::searchWordList(QString word, int ) {
161     QList<Translation*> translations;
162     if(isAvailable()) {
163         word.replace("*","");   /*remove wildcard*/
164         word.replace("?","");
165
166        QString url=QString("/translate_a/t?client=t&sl=%1&tl=%2").arg(_langFrom,
167                                                                      _langTo);
168         qDebug()<<  url;
169         QHttpRequestHeader head = QHttpRequestHeader("POST", url, 1,1);
170         head.setValue("Host","www.google.pl");
171         head.setValue("User-Agent", "Mozilla/5.0");
172         head.setValue("Accept-Encoding", "deflate");
173         head.setContentLength(word.length());
174         head.setValue("Connection", "Close");
175
176         QByteArray data("text=");
177         data.append(word.toUtf8());
178         http->setHost("www.google.pl");
179
180         wait=true;
181         stopped=false;
182         http->request(head, data);
183         QString error("");
184         while(wait && (error=="" || error=="Unknown error") && !stopped)
185             error=http->errorString();
186
187         if(error!="" && error!="Unknown error") {
188             qDebug()<<error;
189             Q_EMIT notify(Notify::Warning,
190                     QString("GooglePlugin: %1").arg(error));
191         }
192         QString text = QString::fromUtf8(http->readAll());
193         text=jsonParse(text);
194         if(text!="") {
195             text="<key>" + word + "</key>" + "<t>" + text + "</t>";
196             translations<<(new TranslationGoogle(word,text,_infoNote,this));
197         }
198     }
199     return translations;
200 }
201
202 QString GooglePlugin::jsonParse(QString result) {
203     qDebug()<<result;
204     int pos=0,pos2=0,index=0,size=0;
205     QString returnLang;
206     QString translation;
207     QString original;
208     QList<QString> partOfSpeach;
209     QList<QList<QString>* > words;
210     QStringList list1 = result.split("\"");
211
212     size=(list1.size()-1)/2;
213     if(size<=2)
214         return QString(""); // wrong format of data
215
216     translation=list1.at(index*2+1);
217     index++;
218     original=list1.at(index*2+1);
219     pos=result.indexOf("]");
220     index++;
221     while(result.at(pos+1)==QChar(',')) {
222         index++;
223         translation+=list1.at(index*2+1);
224         index++;
225         original=list1.at(index*2+1);
226         pos=result.indexOf("]",pos+1);
227         index++;
228     }
229
230     pos=result.indexOf("]",pos+1);
231     pos++;
232     index++;
233     if(result.at(pos+1)==QChar(','))
234         returnLang=list1.at(index*2+1); /*return when translate sentence*/
235
236     while(result.indexOf("[",pos+1)!=-1){
237         partOfSpeach.append(list1.at(index*2+1));
238         pos2=result.indexOf("]",pos+1);
239         pos=result.indexOf("\"",pos+1);
240         pos=result.indexOf("\"",pos+1);
241         pos=result.indexOf("\"",pos+1);
242         pos=result.indexOf("\"",pos+1);
243         QList<QString> *list=new QList<QString>;
244         while(pos2>pos && pos2!=-1 && pos!= -1) {
245             index++;
246             if(size==index)
247                 return QString("");
248             list->append(list1.at(index*2+1));
249             pos=result.indexOf("\"",pos+1);
250             pos=result.indexOf("\"",pos+1);
251         }
252         words.append(list);
253         index++;
254         if(size==index)
255             return QString("");
256         pos=pos2+2;
257     }
258
259     if(words.size()!=partOfSpeach.size()) {
260         qDebug()<<"Error in Google Plugin (JsonParse)";
261         Q_EMIT notify(Notify::Warning,
262                 QString("GooglePlugin: can't parse Json"));
263         return QString("");
264     }
265     returnLang=list1.at(index*2+1);
266     if(partOfSpeach.size()==0){
267         if(translation.toLower()==original.toLower()){
268             return QString(""); // word don't exist";
269         }
270         else
271             return "\""+translation+"\"";
272     }
273     result=translation;
274     for(int i=0; i<words.size();i++) {
275         result+="<br/>";
276         result+="<pos>"+partOfSpeach.at(i)+"</pos>: S";
277         for(int j=0; j<words.at(i)->size();j++)
278             result+=words.at(i)->at(j)+", ";
279         result.remove(result.size()-2,2);
280     }
281     return result;
282 }
283
284 void GooglePlugin::done() {
285     wait=false;
286 }
287
288 void GooglePlugin::stop() {
289     stopped=true;
290 }
291
292 QMap<QString, QString> GooglePlugin::initLanguages() {
293     QMap<QString, QString> languages;
294     languages["AFRIKAANS"] = "af";
295     languages["ALBANIAN"] = "sq";
296 //    languages["AMHARIC"] = "am";
297     languages["ARABIC"] = "ar";
298     languages["ARMENIAN"] = "hy";
299     languages["AZERBAIJANI"] = "az";
300     languages["BASQUE"] = "eu";
301     languages["BELARUSIAN"] = "be";
302 //    languages["BENGALI"] = "bn";
303 //    languages["BIHARI"] = "bh";
304 //    languages["BRETON"] = "br";
305     languages["BULGARIAN"] = "bg";
306 //    languages["BURMESE"] = "my";
307     languages["CATALAN"] = "ca";
308 //    languages["CHEROKEE"] = "chr";
309     languages["CHINESE"] = "zh";
310 //    languages["CHINESE_SIMPLIFIED"] = "zh-CN";
311 //    languages["CHINESE_TRADITIONAL"] = "zh-TW";
312 //    languages["CORSICAN"] = "co";
313     languages["CROATIAN"] = "hr";
314     languages["CZECH"] = "cs";
315     languages["DANISH"] = "da";
316 //    languages["DHIVEHI"] = "dv";
317     languages["DUTCH"] = "nl";
318     languages["ENGLISH"] = "en";
319 //    languages["ESPERANTO"] = "eo";
320     languages["ESTONIAN"] = "et";
321 //    languages["FAROESE"] = "fo";
322     languages["FILIPINO"] = "tl";
323     languages["FINNISH"] = "fi";
324     languages["FRENCH"] = "fr";
325 //    languages["FRISIAN"] = "fy";
326     languages["GALICIAN"] = "gl";
327     languages["GEORGIAN"] = "ka";
328     languages["GERMAN"] = "de";
329     languages["GREEK"] = "el";
330 //    languages["GUJARATI"] = "gu";
331     languages["HAITIAN_CREOLE"] = "ht";
332     languages["HEBREW"] = "iw";
333     languages["HINDI"] = "hi";
334     languages["HUNGARIAN"] = "hu";
335     languages["ICELANDIC"] = "is";
336     languages["INDONESIAN"] = "id";
337 //    languages["INUKTITUT"] = "iu";
338     languages["IRISH"] = "ga";
339     languages["ITALIAN"] = "it";
340     languages["JAPANESE"] = "ja";
341 //    languages["JAVANESE"] = "jw";
342 //    languages["KANNADA"] = "kn";
343 //    languages["KAZAKH"] = "kk";
344 //    languages["KHMER"] = "km";
345     languages["KOREAN"] = "ko";
346 //    languages["KURDISH"] = "ku";
347 //    languages["KYRGYZ"] = "ky";
348 //    languages["LAO"] = "lo";
349 //    languages["LATIN"] = "la";
350     languages["LATVIAN"] = "lv";
351     languages["LITHUANIAN"] = "lt";
352 //    languages["LUXEMBOURGISH"] = "lb";
353     languages["MACEDONIAN"] = "mk";
354     languages["MALAY"] = "ms";
355 //    languages["MALAYALAM"] = "ml";
356     languages["MALTESE"] = "mt";
357 //    languages["MAORI"] = "mi";
358 //    languages["MARATHI"] = "mr";
359 //    languages["MONGOLIAN"] = "mn";
360 //    languages["NEPALI"] = "ne";
361     languages["NORWEGIAN"] = "no";
362 //    languages["OCCITAN"] = "oc";
363 //    languages["ORIYA"] = "or";
364 //    languages["PASHTO"] = "ps";
365     languages["PERSIAN"] = "fa";
366     languages["POLISH"] = "pl";
367     languages["PORTUGUESE"] = "pt";
368 //    languages["PORTUGUESE_PORTUGAL"] = "pt-PT";
369 //    languages["PUNJABI"] = "pa";
370 //    languages["QUECHUA"] = "qu";
371     languages["ROMANIAN"] = "ro";
372     languages["RUSSIAN"] = "ru";
373 //    languages["SANSKRIT"] = "sa";
374 //    languages["SCOTS_GAELIC"] = "gd";
375     languages["SERBIAN"] = "sr";
376 //    languages["SINDHI"] = "sd";
377 //    languages["SINHALESE"] = "si";
378     languages["SLOVAK"] = "sk";
379     languages["SLOVENIAN"] = "sl";
380     languages["SPANISH"] = "es";
381 //    languages["SUNDANESE"] = "su";
382     languages["SWAHILI"] = "sw";
383     languages["SWEDISH"] = "sv";
384 //    languages["SYRIAC"] = "syr";
385 //    languages["TAJIK"] = "tg";
386 //    languages["TAMIL"] = "ta";
387 //    languages["TATAR"] = "tt";
388 //    languages["TELUGU"] = "te";
389     languages["THAI"] = "th";
390 //    languages["TIBETAN"] = "bo";
391 //    languages["TONGA"] = "to";
392     languages["TURKISH"] = "tr";
393     languages["UKRAINIAN"] = "uk";
394     languages["URDU"] = "ur";
395 //    languages["UZBEK"] = "uz";
396 //    languages["UIGHUR"] = "ug";
397     languages["VIETNAMESE"] = "vi";
398     languages["WELSH"] = "cy";
399     languages["YIDDISH"] = "yi";
400 //    languages["YORUBA"] = "yo";
401     languages["DETECT LANGLAGE"] = "";
402     return languages;
403 }
404
405 void GooglePlugin::getDictionaryInfo() {
406     QString fullLangFrom=languages.key(_langFrom);
407     QString fullLangTo=languages.key(_langTo);
408     _infoNote=" [" + fullLangFrom + "-";
409     _infoNote+= fullLangTo + "] (" + _type + ")";
410 }
411
412
413 Q_EXPORT_PLUGIN2(google, GooglePlugin)