1 #include "download.h"
2 #include <iostream>
3 #include <QEventLoop>
4 #include <QUrl>
5 #include <QNetworkRequest>
6 #include <QNetworkReply>
7 #include <QByteArray>
8 #include <QDir>
9 #include <QFileInfo>
10
11 using namespace std;
12
13
Download()14 Download::Download() :
15 manager(new QNetworkAccessManager()),
16 file(NULL) {
17 }
18
~Download()19 Download::~Download() {
20 delete manager;
21 delete file;
22 }
23
load(QString f)24 QString Download::load(QString f) {
25 QUrl url(f);
26 if (url.isLocalFile() || url.isRelative()) {
27 // found local file, do not download
28 return QDir::toNativeSeparators(url.toLocalFile());
29 }
30
31 QEventLoop loop;
32 QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, SLOT(quit()));
33 QNetworkReply *reply = manager->get(QNetworkRequest(url));
34 QObject::connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(progress(qint64, qint64)));
35 loop.exec();
36 #ifdef DEBUG
37 cerr << "File downloaded" << endl;
38 #endif
39
40 // find unique temporary filename
41 QFileInfo fileInfo(url.path());
42 QString fileName = fileInfo.fileName();
43 delete file;
44 file = new QTemporaryFile(QDir::tempPath() + QDir::separator() + fileName);
45 file->setAutoRemove(true);
46 file->open();
47
48 if (reply->error() != QNetworkReply::NoError || !reply->isReadable()) {
49 cerr << reply->errorString().toStdString() << endl;
50 return QString();
51 }
52
53 // store data in tempfile
54 QByteArray data = reply->readAll();
55 reply->deleteLater();
56 file->write(data);
57 file->close();
58 #ifdef DEBUG
59 cerr << "filename: " << file->fileName().toStdString() << endl;
60 #endif
61 return file->fileName();
62 }
63
progress(qint64 bytes_received,qint64 bytes_total)64 void Download::progress(qint64 bytes_received, qint64 bytes_total) {
65 cout.precision(1);
66 cout << fixed << (bytes_received / 1024.0f) << "/";
67 cout << (bytes_total / 1024.0f) << "KB downloaded\r";
68 }
69
70