servatrice/cockatrice/src/update_downloader.cpp
Zach H 06c3edf4c6 cancel downloads from updater (#2534)
* cancel downloads from updater - fix #2534

* fix double popup
2017-03-25 16:35:43 -04:00

64 lines
1.9 KiB
C++

#include <QUrl>
#include <QDebug>
#include "update_downloader.h"
UpdateDownloader::UpdateDownloader(QObject *parent) : QObject(parent) {
netMan = new QNetworkAccessManager(this);
}
void UpdateDownloader::beginDownload(QUrl downloadUrl) {
//Save the original URL because we need it for the filename
if (originalUrl.isEmpty())
originalUrl = downloadUrl;
response = netMan->get(QNetworkRequest(downloadUrl));
connect(response, SIGNAL(finished()), this, SLOT(fileFinished()));
connect(response, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadProgress(qint64, qint64)));
connect(this, SIGNAL(stopDownload()), response, SLOT(abort()));
}
void UpdateDownloader::downloadError(QNetworkReply::NetworkError) {
if (response == nullptr)
return;
emit error(response->errorString().toUtf8());
}
void UpdateDownloader::fileFinished() {
//If we finished but there's a redirect, follow it
QVariant redirect = response->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (!redirect.isNull())
{
beginDownload(redirect.toUrl());
return;
}
//Handle any errors we had
if (response->error())
{
emit error(response->errorString());
return;
}
//Work out the file name of the download
QString fileName = QDir::temp().path() + QDir::separator() + originalUrl.toString().section('/', -1);
//Save the build in a temporary directory
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
emit error(tr("Could not open the file for reading."));
return;
}
file.write(response->readAll());
file.close();
//Emit the success signal with a URL to the download file
emit downloadSuccessful(QUrl::fromLocalFile(fileName));
}
void UpdateDownloader::downloadProgress(qint64 bytesRead, qint64 totalBytes) {
emit progressMade(bytesRead, totalBytes);
}