From 1c49173c8f62d3b9e609d22a027a42376db5d3de Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Thu, 12 Nov 2015 17:03:11 +0100 Subject: Start refactoring download helpers and icon management --- src/FileDownloader.cpp | 65 ++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 15 deletions(-) (limited to 'src/FileDownloader.cpp') diff --git a/src/FileDownloader.cpp b/src/FileDownloader.cpp index 1a0297f..b9f79be 100644 --- a/src/FileDownloader.cpp +++ b/src/FileDownloader.cpp @@ -9,30 +9,65 @@ #include "FileDownloader.h" -FileDownloader::FileDownloader(QObject *parent) : - QObject(parent) { - connect(&m_WebCtrl, SIGNAL(finished(QNetworkReply*)), - SLOT(fileDownloaded(QNetworkReply*))); +// 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() { } -void FileDownloader::connectSlot(QObject* obj, const char* slot) { - QObject::connect(this, SIGNAL(downloaded(QString&, QByteArray)), - obj, slot); +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; } -void FileDownloader::fileDownloaded(QNetworkReply* pReply) { - QByteArray downloadedData = pReply->readAll(); +/* + * 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 - pReply->deleteLater(); - emit downloaded(this->fileName, downloadedData); - this->deleteLater(); // TODO: RAII - Object should not delete itself + 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::downloadFile(const QUrl& fileUrl) { - this->fileName = fileUrl.toString(); - m_WebCtrl.get(QNetworkRequest(fileUrl)); +void FileDownloader::killReply(QNetworkReply *reply) { + if (reply == NULL) + return; + reply->blockSignals(true); + reply->abort(); + reply->deleteLater(); } -- cgit v1.2.3-55-g7522