code clean
[mdictionary] / src / plugins / xdxf / XdxfDictDownloader.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 XdxfDictDownloader.cpp
23     \brief XdxfDictDownloader is responsible for getting dict list from XDXF website
24     and other actions necessary to download and add dictionary
25
26     \author Mateusz Półrola <mateusz.polrola@comarch.com>
27 */
28
29 #include "XdxfDictDownloader.h"
30 #include "XdxfDictDownloadProgressDialog.h"
31 #include <QDebug>
32 #include <QProcess>
33 #include <bzlib.h>
34 #include <stdio.h>
35 #include <fcntl.h>
36
37 #ifndef Q_WS_MAEMO_5
38     #include <libtar.h>
39 #endif
40
41
42 typedef void BZFILE;
43
44
45 XdxfDictDownloader::XdxfDictDownloader(QObject *parent) :
46     QObject(parent) {
47     parentDialog = 0;
48     progressDialog = 0;
49     manager = new QNetworkAccessManager(this);
50
51     connect(manager, SIGNAL(finished(QNetworkReply*)),
52             this, SLOT(dictListReceived(QNetworkReply*)));
53     connect(&http, SIGNAL(finished()),
54             this, SLOT(processFinished()));
55     connect(&http, SIGNAL(error(QString)),
56             this, SLOT(downloadingError(QString)));
57     connect(&http, SIGNAL(progress(qint64,qint64)),
58             this, SLOT(updateDownloadProgress(qint64,qint64)));
59 }
60
61
62 void XdxfDictDownloader::download(QWidget *parent) {
63     parentDialog = parent;
64     aborted = false;
65
66     manager->get(QNetworkRequest(QUrl("http://xdxf.revdanica.com/down/")));
67
68     progressDialog = new XdxfDictDownloadProgressDialog(parent);
69
70     connect(progressDialog, SIGNAL(cancelDownloading()),
71             this, SLOT(breakDownloading()));
72     connect(this, SIGNAL(downloadProgress(float)),
73             progressDialog, SLOT(updateProgress(float)));
74     progressDialog->setText(tr("Downloading dictionaries list"));
75     progressDialog->show();
76 }
77
78
79 QString XdxfDictDownloader::downloadedFile() {
80     return _downloadedFile;
81 }
82
83
84 void XdxfDictDownloader::updateDownloadProgress(qint64 downloaded,
85                                                 qint64 total)   {
86     Q_EMIT downloadProgress(float(downloaded) / float(total));
87 }
88
89
90 void XdxfDictDownloader::downloadingError(QString error) {
91     breakDownloading();
92     Q_EMIT notify(Notify::Error, error);
93 }
94
95
96 void XdxfDictDownloader::breakDownloading() {
97     //if user cancel downloading we kill all running processes, hide progress dialog and set flag that user cancel downloading.
98     aborted = true;
99     http.kill();
100     if(progressDialog && progressDialog->isVisible()) {
101         progressDialog->accept();
102     }
103 }
104
105
106 void XdxfDictDownloader::processFinished() {
107     //first check if user cancel downloading
108     if(aborted) return;
109
110     if(!extract("/tmp/" + _fileName)) {
111         Q_EMIT notify(Notify::Error,
112                 "Error while extracting dictionary archive");
113         return;
114     }
115     downloadComplete();
116 }
117
118
119 void XdxfDictDownloader::downloadComplete() {
120     if(aborted) return;
121     // Downloaded tar file name is different than extracted folder so we need
122     // some clean directory to identify extracted files
123     QDir dir("/tmp/mdict");
124     QString dictDirName = dir.entryList().at(2);
125
126     // Dict is in /tmp/mdict/<extracted directory>/dict.xdxf
127     QFile dictFile("/tmp/mdict/" + dictDirName + "/dict.xdxf");
128     dictFile.copy(QDir::homePath() + "/.mdictionary/" + dictDirName + ".xdxf");
129     QFile::remove("/tmp/" + _fileName);
130     QFile::remove("/tmp/" + _fileName.replace(QRegExp(".bz2$"), ""));
131
132     _downloadedFile = QDir::homePath() + "/.mdictionary/" + dictDirName + ".xdxf";
133
134     progressDialog->accept();
135     delete progressDialog;
136     progressDialog = 0;
137
138     emit fileDownloaded(_downloadedFile);
139 }
140
141
142 void XdxfDictDownloader::dictListReceived(QNetworkReply *reply) {
143     progressDialog->accept();
144     if(aborted)
145         return;
146     if(reply->error() != QNetworkReply::NoError) {
147         Q_EMIT notify(Notify::Error, reply->errorString());
148         return;
149     }
150
151     QString page(QString::fromUtf8(reply->readAll()));
152
153     // You can look at http://xdxf.revdanica.com/down/, we need to get table
154     // with dictionaries entries following regexp match its begining
155     QRegExp regOuter("<td>Icon</td><td>Name</td><td>Archive filename</td><td>Archive file size</td><td>Dict file size</td><td>Number of articles</td><td>From</td><td>To</td><td>Submitted by</td><td>Submition date</td></tr>(.*)</table>");
156     regOuter.setMinimal(true);
157     if(!regOuter.indexIn(page))
158         return;
159
160     // Cutting each entry and creating coresponded DownloadDict object
161     page = regOuter.capturedTexts().at(1);
162     QRegExp regInner("<tr>.*</tr>");
163     regInner.setMinimal(true);
164     int pos = 0;
165     dicts.clear();
166     while ((pos = regInner.indexIn(page, pos)) != -1) {
167         DownloadDict temp = DownloadDict(regInner.cap(0));
168         if(!temp.fromLang().isEmpty())
169             dicts.append(temp);
170         pos += regInner.matchedLength();
171     }
172
173     XdxfDictSelectDialog selectDialog(dicts, parentDialog);
174
175     if(selectDialog.exec()==QDialog::Accepted) {
176         progressDialog->setText(tr("Downloading dictionary"));
177         progressDialog->show();
178
179         QString url = selectDialog.link();
180         _fileName = url.split('/').last();
181
182         QProcess clean;
183         clean.start("rm -rf /tmp/mdict");
184         clean.waitForFinished(-1);
185         clean.start("mkdir /tmp/mdict");
186         clean.waitForFinished(-1);
187
188         http.download(QUrl(url), "/tmp/" + _fileName);
189     }
190 }
191
192 bool XdxfDictDownloader::extract(QString file) {
193     // Extracting bz2
194     FILE * archive = fopen(file.toStdString().c_str(), "rb");
195     if (archive == 0)
196         return false;
197     int err;
198     BZFILE * afterbzFile = BZ2_bzReadOpen(&err, archive, 0, 0, 0, 0);
199     if(err != BZ_OK) {
200         BZ2_bzReadClose(&err, afterbzFile);
201         return false;
202     }
203
204     FILE * tarfile = fopen(file.replace(QRegExp(".bz2$"), "").
205             toStdString().c_str(), "w");
206
207     int bufflen = 100;
208     char buff[bufflen];
209     while(err == BZ_OK) {
210         unsigned int len = BZ2_bzRead(&err, afterbzFile, buff, bufflen);
211         if(fwrite(buff, 1, len, tarfile) != len)
212             return false;
213     }
214     BZ2_bzReadClose(&err, afterbzFile);
215     fclose(tarfile);
216     fclose(archive);
217
218     // Extracting tar
219     #ifndef Q_WS_MAEMO_5
220     TAR *t;
221     char * tarfname = new char[file.replace(QRegExp(".bz2%"), "").size()+1];
222     strcpy(tarfname, file.replace(QRegExp(".bz2%"), "").toStdString().c_str());
223
224     err = tar_open(&t, tarfname, 0, O_RDONLY, 0, 0);
225     if(err == -1)
226         return false;
227
228     char text[]={"/tmp/mdict/"};
229     err = tar_extract_all(t,text);
230     if(err == -1) {
231         return false;
232     }
233     tar_close(t);
234     #else
235     QProcess tar;
236     tar.start("tar -xvf " + file.replace(QRegExp(".bz2%"), "") + " -C /tmp/mdict");
237     tar.waitForFinished(-1);
238     #endif
239
240     return true;
241 }
242
243
244