summaryrefslogtreecommitdiffstats
path: root/src/filedownloader.cpp
blob: e0b02892e05b2ae56ae42f2f9808b23df7fe761d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
 * filedownloader.cpp
 *
 *  Created on: Mar 7, 2014
 *      Author: nils
 */

#include <QFileInfo>

#include "filedownloader.h"

// Maximum size of download
#define MAXSIZE (200000)

static QNetworkAccessManager m_WebCtrl;

FileDownloader::FileDownloader(const QUrl& fileUrl, QObject *parent) :
    QObject(parent), started(false), url(fileUrl) {
}

FileDownloader::~FileDownloader() {

}

bool FileDownloader::downloadFile() {
    if (this->started)
        return true;
    QNetworkRequest request(this->url);
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    QNetworkReply *reply = m_WebCtrl.get(request);
    if (reply == nullptr)
        return false;
    this->started = true;
    connect(reply, SIGNAL(finished()), SLOT(fileDownloaded()));
    connect(reply, SIGNAL(downloadProgress(qint64, qint64)), SLOT(downloadProgress(qint64, qint64)));
    return true;
}

/*
 * Slots from networkreply
 */

void FileDownloader::downloadFailed(QNetworkReply::NetworkError) {
    QNetworkReply *reply = reinterpret_cast<QNetworkReply*>(this->sender());
    killReply(reply);
    emit downloaded(this->url, QByteArray());
}

void FileDownloader::fileDownloaded() {
    QNetworkReply *reply = reinterpret_cast<QNetworkReply*>(this->sender());
    if (reply == nullptr)
        return;
    QByteArray downloadedData(reply->readAll());
    killReply(reply);
    //emit a signal
    emit downloaded(this->url, downloadedData);
}

void FileDownloader::downloadProgress(qint64 received, qint64 totalSize) {
    QNetworkReply *reply = reinterpret_cast<QNetworkReply*>(this->sender());
    if (reply == nullptr)
        return;
    if (received > MAXSIZE || totalSize > MAXSIZE) {
        killReply(reply);
        emit downloaded(this->url, QByteArray());
    }
}

void FileDownloader::killReply(QNetworkReply *reply) {
    if (reply == nullptr)
        return;
    reply->blockSignals(true);
    reply->abort();
    reply->deleteLater();
}