summaryrefslogblamecommitdiffstats
path: root/src/filedownloader.cpp
blob: 30f30daa50e90cc040585ce16125b3b866f18b54 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
                           
 


                                
                           
                        


                                       
                                            
 

                                                                                                                                    

                                                                          
                         
                     


                                                                             
                         

















                                                                                                                      

 
                                             
                         



                              
 
#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();
}