File indexing completed on 2024-04-14 05:41:26

0001 /*
0002     SPDX-FileCopyrightText: 2021 Aleix Pol Gonzalez <aleixpol@kde.org>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "fetchisojob.h"
0008 #include <QDebug>
0009 #include <QDir>
0010 #include <QNetworkReply>
0011 #include <QSharedPointer>
0012 #include <QStandardPaths>
0013 
0014 FetchIsoJob::FetchIsoJob(QObject *parent)
0015     : QObject(parent)
0016 {
0017     m_network.setRedirectPolicy(QNetworkRequest::UserVerifiedRedirectPolicy);
0018     cache = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
0019     QDir().mkpath(cache);
0020 }
0021 
0022 QNetworkReply *FetchIsoJob::downloadFile(const QUrl& url)
0023 {
0024     auto file = QSharedPointer<QFile>::create(cache + '/' + url.fileName());
0025     if (!file->open(QIODevice::WriteOnly)) {
0026         qWarning() << "Could not open file to download to" << cache << url;
0027         return nullptr;
0028     }
0029     auto reply = m_network.get(QNetworkRequest(url));
0030 
0031     // Allow every redirect for now
0032     connect(reply, &QNetworkReply::redirected, reply, [reply] (const QUrl &url) {
0033         qDebug() << "redirecting to" << url << "from" << reply->url();
0034         reply->redirectAllowed();
0035     });
0036     connect(reply, &QNetworkReply::readyRead, this, [file, reply] {
0037         file->write(reply->readAll());
0038     });
0039     connect(reply, &QNetworkReply::finished, this, [file, reply] {
0040         file->close();
0041         if (reply->error()) {
0042             file->remove();
0043             qWarning() << "Could not download" << reply->url() << reply->errorString();
0044         }
0045         reply->deleteLater();
0046         qDebug() << "done";
0047     });
0048     return reply;
0049 }
0050 
0051 void FetchIsoJob::fetch(const QUrl& url)
0052 {
0053     auto reply = downloadFile(url);
0054     if (!reply) {
0055         Q_EMIT failed();
0056         return;
0057     }
0058     connect(reply, &QNetworkReply::downloadProgress, this, [this] (qint64 bytesReceived, qint64 bytesTotal) {
0059         if (bytesTotal == 0)
0060              return;
0061         Q_EMIT downloadProgressChanged(100 * bytesReceived / bytesTotal);
0062     });
0063     connect(reply, &QNetworkReply::finished, this, [reply, this, url] {
0064         if (reply->error()) {
0065             Q_EMIT failed();
0066         } else {
0067             Q_EMIT finished(cache + '/' + url.fileName());
0068         }
0069     });
0070     connect(reply, &QNetworkReply::redirected, reply, [this] (const QUrl &url) {
0071         m_fetchUrl = url;
0072     });
0073 
0074     const QString urlString = url.toString();
0075     downloadFile(QUrl(urlString + ".sig"));
0076     downloadFile(QUrl(urlString.left(urlString.length() - 4) + ".sha256sum"));
0077 
0078     m_fetchUrl = url;
0079 }
0080 
0081 #include "moc_fetchisojob.cpp"