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