summaryrefslogtreecommitdiffstats
path: root/src/filedownloader.cpp
blob: 30f30daa50e90cc040585ce16125b3b866f18b54 (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
#include "filedownloader.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>

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

static QNetworkAccessManager m_WebCtrl;

static void killReply(QNetworkReply *reply);

bool FileDownloader::download(const QUrl& fileUrl, const std::function <void (QNetworkReply::NetworkError, const QByteArray&)>& f) {
    QNetworkRequest request(fileUrl);
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    QNetworkReply *reply = m_WebCtrl.get(request);
    if (reply == nullptr)
        return false;
    // Handle normal finish
    QObject::connect(reply, &QNetworkReply::finished, [reply, f, fileUrl]() {
        QByteArray downloadedData(reply->readAll());
        killReply(reply);
        f(QNetworkReply::NoError, downloadedData);
    });
    // Handle files that are too large
    QObject::connect(reply, &QNetworkReply::downloadProgress, [reply, f, fileUrl](qint64 received, qint64 totalSize) {
        if (received > MAXSIZE || totalSize > MAXSIZE) {
            qDebug() << fileUrl << "too large";
            killReply(reply);
            f(QNetworkReply::NetworkError::UnknownNetworkError, QByteArray());
        }
    });
    // Handle errors
    QObject::connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
            [reply, f, fileUrl](QNetworkReply::NetworkError err) {
        qDebug() << fileUrl << "error" << err;
        killReply(reply);
        f(err, QByteArray());
    });
    return true;
}

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