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