From f8356a6dcc7fa935af8e5cc681b68ab75a22d88d Mon Sep 17 00:00:00 2001 From: Adriaan de Groot Date: Mon, 2 Sep 2019 12:21:33 +0200 Subject: [PATCH] [libcalamares] Add an async get method - Mostly a "cheap" wrapper for a half-dozen boilerplate lines of Qt NAM code. --- src/libcalamares/network/Manager.cpp | 41 ++++++++++++++++++++++++++++ src/libcalamares/network/Manager.h | 9 ++++++ 2 files changed, 50 insertions(+) diff --git a/src/libcalamares/network/Manager.cpp b/src/libcalamares/network/Manager.cpp index 6c2d6caab..0cf5be20f 100644 --- a/src/libcalamares/network/Manager.cpp +++ b/src/libcalamares/network/Manager.cpp @@ -99,6 +99,40 @@ Manager::setCheckHasInternetUrl( const QUrl& url ) d->m_hasInternetUrl = url; } +/** @brief Does a request asynchronously, returns the (pending) reply + * + * The extra options for the request are taken from @p options, + * including the timeout setting. A timeout will cause the reply + * to abort. + * + * On failure, returns nullptr (e.g. bad URL, timeout). + */ +static QNetworkReply* +asynchronousRun( const std::unique_ptr< QNetworkAccessManager >& nam, const QUrl& url, const RequestOptions& options ) +{ + QNetworkRequest request = QNetworkRequest( url ); + QNetworkReply* reply = nam->get( request ); + QTimer* timer = nullptr; + + // Bail out early if the request is bad + if ( reply->error() ) + { + reply->deleteLater(); + return nullptr; + } + + options.applyToRequest( &request ); + if ( options.hasTimeout() ) + { + timer = new QTimer( reply ); + timer->setSingleShot( true ); + QObject::connect( timer, &QTimer::timeout, reply, &QNetworkReply::abort ); + timer->start( options.timeout() ); + } + + return reply; +} + /** @brief Does a request synchronously, returns the request itself * * The extra options for the request are taken from @p options, @@ -173,5 +207,12 @@ Manager::synchronousGet( const QUrl& url, const RequestOptions& options ) return reply.first ? reply.second->readAll() : QByteArray(); } +QNetworkReply* +Manager::asynchronouseGet( const QUrl& url, const CalamaresUtils::Network::RequestOptions& options ) +{ + return asynchronousRun( d->m_nam, url, options ); +} + + } // namespace Network } // namespace CalamaresUtils diff --git a/src/libcalamares/network/Manager.h b/src/libcalamares/network/Manager.h index 041314f13..62788f504 100644 --- a/src/libcalamares/network/Manager.h +++ b/src/libcalamares/network/Manager.h @@ -28,6 +28,7 @@ #include #include +class QNetworkReply; class QNetworkRequest; namespace CalamaresUtils @@ -139,6 +140,14 @@ public: */ bool hasInternet(); + /** @brief Do a network request asynchronously. + * + * Returns a pointer to the reply-from-the-request. + * This may be a nullptr if an error occurs immediately. + * The caller is responsible for cleaning up the reply (eventually). + */ + QNetworkReply* asynchronouseGet( const QUrl& url, const RequestOptions& options = RequestOptions() ); + private: struct Private; std::unique_ptr< Private > d;