Simplify download code.

This commit is contained in:
Hannah von Reth 2015-09-29 16:39:56 +02:00
parent a2950d0592
commit e1e3c4ec21

View File

@ -21,7 +21,6 @@
#include "../snore_p.h" #include "../snore_p.h"
#include <QApplication> #include <QApplication>
#include <QMutex>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include <QNetworkReply> #include <QNetworkReply>
#include <QNetworkRequest> #include <QNetworkRequest>
@ -43,10 +42,6 @@ Icon Icon::fromWebUrl(const QUrl &url, int maxTime)
Icon icon = defaultIcon(); Icon icon = defaultIcon();
snoreDebug(SNORE_DEBUG) << url; snoreDebug(SNORE_DEBUG) << url;
if (!s_downloadImageCache.contains(url)) { if (!s_downloadImageCache.contains(url)) {
QTime timeout;
timeout.start();
QMutex isDownloading;
isDownloading.lock();
snoreDebug(SNORE_DEBUG) << "Downloading:" << url; snoreDebug(SNORE_DEBUG) << "Downloading:" << url;
QNetworkAccessManager *manager = new QNetworkAccessManager(); QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request(url); QNetworkRequest request(url);
@ -55,26 +50,25 @@ Icon Icon::fromWebUrl(const QUrl &url, int maxTime)
snoreDebug(SNORE_DEBUG) << "Downloading:" << url << bytesReceived / double(bytesTotal) * 100.0 << "%"; snoreDebug(SNORE_DEBUG) << "Downloading:" << url << bytesReceived / double(bytesTotal) * 100.0 << "%";
}); });
QObject::connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [ & ](QNetworkReply::NetworkError code) { QTime time;
snoreDebug(SNORE_WARNING) << "Error downloading" << url << ":" << code; time.start();
isDownloading.unlock(); while (!reply->isFinished() && time.elapsed() < maxTime) {
}); qApp->processEvents(QEventLoop::AllEvents, maxTime);
QObject::connect(reply, &QNetworkReply::finished, [ & ]() { }
if (reply->isOpen()) { if (reply->error() != QNetworkReply::NoError) {
QImage img(QImage::fromData(reply->readAll(), "PNG")); snoreDebug(SNORE_WARNING) << "Error downloading" << url << ":" << reply->errorString();
icon = Icon(QPixmap::fromImage(img)); } else {
if (reply->isFinished()) {
QPixmap pix;
pix.loadFromData(reply->readAll());
icon = Icon(pix);
s_downloadImageCache.insert(url, icon); s_downloadImageCache.insert(url, icon);
snoreDebug(SNORE_DEBUG) << url << "added to cache."; snoreDebug(SNORE_DEBUG) << url << "added to cache.";
isDownloading.unlock();
} else { } else {
snoreDebug(SNORE_DEBUG) << "Download of " << url << "timed out."; snoreDebug(SNORE_DEBUG) << "Download of " << url << "timed out.";
} }
});
while (!isDownloading.tryLock() && (maxTime != -1 && timeout.elapsed() < maxTime)) {
qApp->processEvents();
} }
reply->close(); reply->close();
reply->deleteLater(); reply->deleteLater();
manager->deleteLater(); manager->deleteLater();