1 #include "downloader.h"
3 #include <QDesktopServices>
7 void Downloader::download(const QUrl &url) {
8 const QString tempDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
9 QString filename = tempDir + "/" +
10 QByteArray::number(QRandomGenerator::global()->generate()).toHex() +
12 file.setFileName(filename);
14 qDebug() << "Downloading" << url << "to" << filename;
17 reply = Http::instance().networkReply(req);
19 connect(reply, &QNetworkReply::readyRead, this, [this] {
23 if (!file.open(QIODevice::ReadWrite)) {
24 emit error(QString("Error opening file: %1").arg(file.errorString()));
32 if (-1 == file.write(reply->readAll())) {
33 emit error(file.errorString());
42 static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(
43 &QNetworkReply::error),
45 emit error(reply->errorString());
52 connect(reply, &QNetworkReply::downloadProgress, this,
53 [this](qint64 bytesReceived, qint64 bytesTotal) {
54 if (bytesTotal <= 0) return;
55 int percent = bytesReceived * 100 / bytesTotal;
56 emit progress(percent);
59 connect(reply, &QNetworkReply::finished, this, [this] {
61 int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
64 reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
65 if (message.isEmpty()) message = reply->errorString();
75 emit fileReady(file.fileName());
79 void Downloader::stop() {
85 emit error("Canceled");
88 } // namespace updater