last change before margr with master
[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         qDebug()<<"etap 3.2";
177         progressDialog->setText(tr("Downloading dictionary"));
178         progressDialog->show();
179
180         QString url = selectDialog.link();
181         _fileName = url.split('/').last();
182
183         QProcess clean;
184         clean.start("rm -rf /tmp/mdict");
185         clean.waitForFinished(-1);
186         clean.start("mkdir /tmp/mdict");
187         clean.waitForFinished(-1);
188
189         http.download(QUrl(url), "/tmp/" + _fileName);
190     }
191 }
192
193 bool XdxfDictDownloader::extract(QString file) {
194     // Extracting bz2
195     FILE * archive = fopen(file.toStdString().c_str(), "rb");
196     if (archive == 0)
197         return false;
198     int err;
199     BZFILE * afterbzFile = BZ2_bzReadOpen(&err, archive, 0, 0, 0, 0);
200     if(err != BZ_OK) {
201         BZ2_bzReadClose(&err, afterbzFile);
202         return false;
203     }
204
205     FILE * tarfile = fopen(file.replace(QRegExp(".bz2$"), "").
206             toStdString().c_str(), "w");
207
208     int bufflen = 100;
209     char buff[bufflen];
210     while(err == BZ_OK) {
211         unsigned int len = BZ2_bzRead(&err, afterbzFile, buff, bufflen);
212         if(fwrite(buff, 1, len, tarfile) != len)
213             return false;
214     }
215     BZ2_bzReadClose(&err, afterbzFile);
216     fclose(tarfile);
217     fclose(archive);
218
219     // Extracting tar
220     #ifndef Q_WS_MAEMO_5
221     TAR *t;
222     char * tarfname = new char[file.replace(QRegExp(".bz2%"), "").size()+1];
223     strcpy(tarfname, file.replace(QRegExp(".bz2%"), "").toStdString().c_str());
224
225     err = tar_open(&t, tarfname, 0, O_RDONLY, 0, 0);
226     if(err == -1)
227         return false;
228
229     char text[]={"/tmp/mdict/"};
230     err = tar_extract_all(t,text);
231     if(err == -1) {
232         return false;
233     }
234     tar_close(t);
235     #else
236     QProcess tar;
237     tar.start("tar -xvf " + file.replace(QRegExp(".bz2%"), "") + " -C /tmp/mdict");
238     tar.waitForFinished(-1);
239     #endif
240
241     return true;
242 }
243
244
245