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






                           
                           
 





                                                                      
                                                   





                                   
                                     








                                                                                                     

 




                                                                  


                                                          


                                       






                                                          


                                                                          






                                                          

 
                                                      




                              
 
/*
 * 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;
    QNetworkReply *reply = m_WebCtrl.get(QNetworkRequest(this->url));
    if (reply == NULL)
        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 = (QNetworkReply*)this->sender();
    killReply(reply);
    emit downloaded(this->url, QByteArray());
}

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

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

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