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