Clean and order documentation in source files. Source ready to beta 2 release
[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
75     progressDialog->setText(tr("Downloading dictionaries list"));
76     progressDialog->show();
77 }
78
79
80 QString XdxfDictDownloader::downloadedFile() {
81     return _downloadedFile;
82 }
83
84
85 void XdxfDictDownloader::updateDownloadProgress(qint64 downloaded,
86                                                 qint64 total)   {
87     Q_EMIT downloadProgress(float(downloaded) / float(total));
88 }
89
90
91 void XdxfDictDownloader::downloadingError(QString error) {
92     breakDownloading();
93     Q_EMIT notify(Notify::Error, error);
94 }
95
96
97 void XdxfDictDownloader::breakDownloading() {
98     //if user cancel downloading we kill all running processes, hide progress dialog and set flag that user cancel downloading.
99     aborted = true;
100     http.kill();
101
102     if(progressDialog && progressDialog->isVisible()) {
103         progressDialog->accept();
104     }
105 }
106
107
108 void XdxfDictDownloader::processFinished() {
109     //first check if user cancel downloading
110     if(aborted) return;
111
112     if(!extract("/tmp/" + _fileName)) {
113         Q_EMIT notify(Notify::Error,
114                 "Error while extracting dictionary archive");
115         return;
116     }
117     downloadComplete();
118 }
119
120
121 void XdxfDictDownloader::downloadComplete() {
122     if(aborted) return;
123     // Downloaded tar file name is different than extracted folder so we need
124     // some clean directory to identify extracted files
125     QDir dir("/tmp/mdict");
126     QString dictDirName = dir.entryList().at(2);
127
128     // Dict is in /tmp/mdict/<extracted directory>/dict.xdxf
129     QFile dictFile("/tmp/mdict/" + dictDirName + "/dict.xdxf");
130     dictFile.copy(QDir::homePath() + "/.mdictionary/" + dictDirName + ".xdxf");
131     QFile::remove("/tmp/" + _fileName);
132     QFile::remove("/tmp/" + _fileName.replace(QRegExp(".bz2$"), ""));
133
134     _downloadedFile = QDir::homePath() + "/.mdictionary/" + dictDirName + ".xdxf";
135
136     progressDialog->accept();
137     delete progressDialog;
138     progressDialog = 0;
139
140     emit fileDownloaded(_downloadedFile);
141 }
142
143
144 void XdxfDictDownloader::dictListReceived(QNetworkReply *reply) {
145     progressDialog->accept();
146     if(aborted)
147         return;
148     if(reply->error() != QNetworkReply::NoError) {
149         Q_EMIT notify(Notify::Error, reply->errorString());
150         return;
151     }
152
153     QString page(QString::fromUtf8(reply->readAll()));
154
155     // You can look at http://xdxf.revdanica.com/down/, we need to get table
156     // with dictionaries entries following regexp match its begining
157     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>");
158     regOuter.setMinimal(true);
159     if(!regOuter.indexIn(page))
160         return;
161
162     // Cutting each entry and creating coresponded DownloadDict object
163     page = regOuter.capturedTexts().at(1);
164     QRegExp regInner("<tr>.*</tr>");
165     regInner.setMinimal(true);
166     int pos = 0;
167     dicts.clear();
168     while ((pos = regInner.indexIn(page, pos)) != -1) {
169         DownloadDict temp = DownloadDict(regInner.cap(0));
170         if(!temp.fromLang().isEmpty())
171             dicts.append(temp);
172         pos += regInner.matchedLength();
173     }
174
175     XdxfDictSelectDialog selectDialog(dicts, parentDialog);
176
177     if(selectDialog.exec()==QDialog::Accepted) {
178
179         progressDialog->setText(tr("Downloading dictionary"));
180         progressDialog->show();
181
182         QString url = selectDialog.link();
183         _fileName = url.split('/').last();
184
185         QProcess clean;
186         clean.start("rm -rf /tmp/mdict");
187         clean.waitForFinished(-1);
188         clean.start("mkdir /tmp/mdict");
189         clean.waitForFinished(-1);
190
191         http.download(QUrl(url), "/tmp/" + _fileName);
192     }
193 }
194
195 bool XdxfDictDownloader::extract(QString file) {
196     // Extracting bz2
197     FILE * archive = fopen(file.toStdString().c_str(), "rb");
198     if (archive == 0)
199         return false;
200     int err;
201     BZFILE * afterbzFile = BZ2_bzReadOpen(&err, archive, 0, 0, 0, 0);
202     if(err != BZ_OK) {
203         BZ2_bzReadClose(&err, afterbzFile);
204         return false;
205     }
206
207     FILE * tarfile = fopen(file.replace(QRegExp(".bz2$"), "").
208             toStdString().c_str(), "w");
209
210     int bufflen = 100;
211     char buff[bufflen];
212     while(err == BZ_OK) {
213         unsigned int len = BZ2_bzRead(&err, afterbzFile, buff, bufflen);
214         if(fwrite(buff, 1, len, tarfile) != len)
215             return false;
216     }
217     BZ2_bzReadClose(&err, afterbzFile);
218     fclose(tarfile);
219     fclose(archive);
220
221     // Extracting tar
222     #ifndef Q_WS_MAEMO_5
223     TAR *t;
224     char * tarfname = new char[file.replace(QRegExp(".bz2%"), "").size()+1];
225     strcpy(tarfname, file.replace(QRegExp(".bz2%"), "").toStdString().c_str());
226
227     err = tar_open(&t, tarfname, 0, O_RDONLY, 0, 0);
228     if(err == -1)
229         return false;
230
231     char text[]={"/tmp/mdict/"};
232     err = tar_extract_all(t,text);
233     if(err == -1) {
234         return false;
235     }
236     tar_close(t);
237     #else
238     QProcess tar;
239     tar.start("tar -xvf " + file.replace(QRegExp(".bz2%"), "") + " -C /tmp/mdict");
240     tar.waitForFinished(-1);
241     #endif
242
243     return true;
244 }
245
246