26#include <QAuthenticator>
29#include <QNetworkCacheMetaData>
30#include <QNetworkReply>
31#include <QNetworkRequest>
34#include <QWaitCondition>
36#include "moc_qgsblockingnetworkrequest.cpp"
38using namespace Qt::StringLiterals;
51void QgsBlockingNetworkRequest::requestTimedOut( QNetworkReply *reply )
53 if (
reply == mReply )
74 QByteArray ldata( data );
75 QBuffer buffer( &ldata );
76 buffer.open( QIODevice::ReadOnly );
77 return post( request, &buffer, forceRefresh, feedback );
82 mPayloadDataVariant = data;
88 mPayloadDataVariant = data;
99 QByteArray ldata( data );
100 QBuffer buffer( &ldata );
101 buffer.open( QIODevice::ReadOnly );
102 return put( request, &buffer, feedback );
107 mPayloadDataVariant = data;
113 QByteArray ldata( data );
114 QBuffer buffer( &ldata );
115 buffer.open( QIODevice::ReadOnly );
116 return patch( request, &buffer, feedback );
121 mPayloadDataVariant = data;
131void QgsBlockingNetworkRequest::sendRequestToNetworkAccessManager(
const QNetworkRequest &request )
140 if ( std::holds_alternative<QHttpMultiPart *>( mPayloadDataVariant ) )
144 else if ( std::holds_alternative<QIODevice *>( mPayloadDataVariant ) )
151 QgsDebugError( QString(
"Not implemented std::variant type" ) );
176 mFeedback = feedback;
181 mGotNonEmptyResponse =
false;
182 mRequestFlags = requestFlags;
184 mErrorMessage.clear();
186 mForceRefresh = forceRefresh;
187 mReplyContent.clear();
192 mErrorMessage = errorMessageFailedAuth();
202 request.setAttribute( QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::ManualRedirectPolicy );
203 request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, forceRefresh ? QNetworkRequest::AlwaysNetwork : QNetworkRequest::PreferCache );
204 request.setAttribute( QNetworkRequest::CacheSaveControlAttribute,
true );
206 QWaitCondition authRequestBufferNotEmpty;
207 QMutex waitConditionMutex;
209 bool threadFinished =
false;
210 bool success =
false;
212 const bool requestMadeFromMainThread = QThread::currentThread() == QApplication::instance()->thread();
217 const std::function<void()> downloaderFunction = [
this, request, &waitConditionMutex, &authRequestBufferNotEmpty, &threadFinished, &success, requestMadeFromMainThread]() {
226 sendRequestToNetworkAccessManager( request );
234 mErrorMessage = errorMessageFailedAuth();
239 if ( requestMadeFromMainThread )
240 authRequestBufferNotEmpty.wakeAll();
248 connect( mReply, &QNetworkReply::finished,
this, &QgsBlockingNetworkRequest::replyFinished, Qt::DirectConnection );
249 connect( mReply, &QNetworkReply::downloadProgress,
this, &QgsBlockingNetworkRequest::replyProgress, Qt::DirectConnection );
250 connect( mReply, &QNetworkReply::uploadProgress,
this, &QgsBlockingNetworkRequest::replyProgress, Qt::DirectConnection );
252 if ( request.hasRawHeader(
"Range" ) )
253 connect( mReply, &QNetworkReply::metaDataChanged,
this, &QgsBlockingNetworkRequest::abortIfNotPartialContentReturned, Qt::DirectConnection );
255 auto resumeMainThread = [&waitConditionMutex, &authRequestBufferNotEmpty]() {
258 waitConditionMutex.lock();
259 authRequestBufferNotEmpty.wakeAll();
260 waitConditionMutex.unlock();
265 QMetaObject::Connection authRequestConnection;
266 QMetaObject::Connection proxyAuthenticationConnection;
268 QMetaObject::Connection sslErrorsConnection;
271 if ( requestMadeFromMainThread )
273 authRequestConnection = connect(
QgsNetworkAccessManager::instance(), &QgsNetworkAccessManager::authRequestOccurred,
this, resumeMainThread, Qt::DirectConnection );
274 proxyAuthenticationConnection = connect(
QgsNetworkAccessManager::instance(), &QgsNetworkAccessManager::proxyAuthenticationRequired,
this, resumeMainThread, Qt::DirectConnection );
284 connect( qApp, &QCoreApplication::aboutToQuit, &loop, &QEventLoop::quit, Qt::DirectConnection );
288 if ( requestMadeFromMainThread )
291 disconnect( authRequestConnection );
292 disconnect( proxyAuthenticationConnection );
294 disconnect( sslErrorsConnection );
299 if ( requestMadeFromMainThread )
301 waitConditionMutex.lock();
302 threadFinished =
true;
303 authRequestBufferNotEmpty.wakeAll();
304 waitConditionMutex.unlock();
308 if ( requestMadeFromMainThread )
310 auto downloaderThread = std::make_unique<DownloaderThread>( downloaderFunction );
311 downloaderThread->start();
315 waitConditionMutex.lock();
316 if ( threadFinished )
318 waitConditionMutex.unlock();
321 authRequestBufferNotEmpty.wait( &waitConditionMutex );
327 if ( !threadFinished )
329 waitConditionMutex.unlock();
331 QgsApplication::processEvents();
337 waitConditionMutex.unlock();
341 downloaderThread->wait();
345 downloaderFunction();
355 mReply->deleteLater();
360void QgsBlockingNetworkRequest::replyProgress( qint64 bytesReceived, qint64 bytesTotal )
362 QgsDebugMsgLevel( u
"%1 of %2 bytes downloaded."_s.arg( bytesReceived ).arg( bytesTotal < 0 ? u
"unknown number of"_s : QString::number( bytesTotal ) ), 2 );
364 if ( bytesReceived != 0 )
365 mGotNonEmptyResponse =
true;
367 if ( !mIsAborted && mReply && ( !mFeedback || !mFeedback->isCanceled() ) )
369 if ( mReply->error() == QNetworkReply::NoError )
371 const QVariant redirect = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
386void QgsBlockingNetworkRequest::replyFinished()
388 if ( !mIsAborted && mReply )
390 if ( mReply->error() == QNetworkReply::NoError && ( !mFeedback || !mFeedback->isCanceled() ) )
393 const QVariant redirect = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
398 const QUrl &toUrl = redirect.toUrl();
400 if ( toUrl == mReply->url() )
402 mErrorMessage = tr(
"Redirect loop detected: %1" ).arg( toUrl.toString() );
407 mReplyContent.clear();
411 QNetworkRequest request( toUrl );
415 mReplyContent.clear();
416 mErrorMessage = errorMessageFailedAuth();
429 request.setAttribute( QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::ManualRedirectPolicy );
430 request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, mForceRefresh ? QNetworkRequest::AlwaysNetwork : QNetworkRequest::PreferCache );
431 request.setAttribute( QNetworkRequest::CacheSaveControlAttribute,
true );
434 if ( mReply->request().hasRawHeader(
"Range" ) )
435 request.setRawHeader(
"Range", mReply->request().rawHeader(
"Range" ) );
437 mReply->deleteLater();
440 QgsDebugMsgLevel( u
"redirected: %1 forceRefresh=%2"_s.arg( redirect.toString() ).arg( mForceRefresh ), 2 );
442 sendRequestToNetworkAccessManager( request );
449 mReplyContent.clear();
450 mErrorMessage = errorMessageFailedAuth();
463 connect( mReply, &QNetworkReply::finished,
this, &QgsBlockingNetworkRequest::replyFinished, Qt::DirectConnection );
464 connect( mReply, &QNetworkReply::downloadProgress,
this, &QgsBlockingNetworkRequest::replyProgress, Qt::DirectConnection );
465 connect( mReply, &QNetworkReply::uploadProgress,
this, &QgsBlockingNetworkRequest::replyProgress, Qt::DirectConnection );
467 if ( request.hasRawHeader(
"Range" ) )
468 connect( mReply, &QNetworkReply::metaDataChanged,
this, &QgsBlockingNetworkRequest::abortIfNotPartialContentReturned, Qt::DirectConnection );
479 QNetworkCacheMetaData cmd = nam->cache()->metaData( mReply->request().url() );
481 QNetworkCacheMetaData::RawHeaderList hl;
482 const auto constRawHeaders = cmd.rawHeaders();
483 for (
const QNetworkCacheMetaData::RawHeader &h : constRawHeaders )
485 if ( h.first !=
"Cache-Control" )
488 cmd.setRawHeaders( hl );
490 QgsDebugMsgLevel( u
"expirationDate:%1"_s.arg( cmd.expirationDate().toString() ), 2 );
491 if ( cmd.expirationDate().isNull() )
493 cmd.setExpirationDate( QDateTime::currentDateTime().addSecs( mExpirationSec ) );
496 nam->cache()->updateMetaData( cmd );
504 const bool fromCache = mReply->attribute( QNetworkRequest::SourceIsFromCacheAttribute ).toBool();
508 mReplyContent = QgsNetworkReplyContent( mReply );
509 const QByteArray content = mReply->readAll();
512 mErrorMessage = tr(
"empty response: %1" ).arg( mReply->errorString() );
519 mReplyContent.setContent( content );
524 if ( mReply->error() != QNetworkReply::OperationCanceledError && ( !mFeedback || !mFeedback->isCanceled() ) )
526 mErrorMessage = mReply->errorString();
533 mReplyContent = QgsNetworkReplyContent( mReply );
534 mReplyContent.setContent( mReply->readAll() );
542 mReply->deleteLater();
552QString QgsBlockingNetworkRequest::errorMessageFailedAuth()
554 return tr(
"network request update failed for authentication config" );
557void QgsBlockingNetworkRequest::abortIfNotPartialContentReturned()
559 if ( mReply && mReply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt() == 200 )
564 mErrorMessage = tr(
"The server does not support range requests" );
@ DisableMessageLogging
If present, indicates that no message logging should be performed when network errors are encountered...
QFlags< NetworkRequestFlag > NetworkRequestFlags
Flags controlling behavior of network requests.
HttpMethod
Different methods of HTTP requests.
static QgsApplication * instance()
Returns the singleton instance of the QgsApplication.
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
bool updateNetworkRequest(QNetworkRequest &request, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkRequest with an authentication config.
bool updateNetworkReply(QNetworkReply *reply, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkReply with an authentication config (used to skip known SSL errors,...
ErrorCode put(QNetworkRequest &request, QIODevice *data, QgsFeedback *feedback=nullptr)
Performs a "put" operation on the specified request, using the given data.
QgsBlockingNetworkRequest(Qgis::NetworkRequestFlags flags=Qgis::NetworkRequestFlags())
Constructor for QgsBlockingNetworkRequest.
void uploadProgress(qint64 bytesReceived, qint64 bytesTotal)
Emitted when when data are sent during a request.
~QgsBlockingNetworkRequest() override
Qgis::NetworkRequestFlags flags() const
Returns the network request flags.
ErrorCode head(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr)
Performs a "head" operation on the specified request.
void abort()
Aborts the network request immediately.
Q_DECL_DEPRECATED void downloadFinished()
Emitted once a request has finished downloading.
ErrorCode post(QNetworkRequest &request, QIODevice *data, bool forceRefresh=false, QgsFeedback *feedback=nullptr)
Performs a "post" operation on the specified request, using the given data.
ErrorCode deleteResource(QNetworkRequest &request, QgsFeedback *feedback=nullptr)
Performs a "delete" operation on the specified request.
void finished()
Emitted once a request has finished.
void setAuthCfg(const QString &authCfg)
Sets the authentication config id which should be used during the request.
QString authCfg() const
Returns the authentication config id which will be used during the request.
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
Emitted when when data arrives during a request.
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
@ EmptyResponseIsValid
Do not generate an error if getting an empty response (e.g. HTTP 204).
ErrorCode patch(QNetworkRequest &request, QIODevice *data, QgsFeedback *feedback=nullptr)
Performs a "patch" operation on the specified request, using the given data.
QFlags< RequestFlag > RequestFlags
@ NetworkError
A network error occurred.
@ ServerExceptionError
An exception was raised by the server.
@ NoError
No error was encountered.
@ TimeoutError
Timeout was reached before a reply was received.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
Base class for feedback objects to be used for cancellation of something running in a worker thread.
void canceled()
Internal routines can connect to this signal if they use event loop.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
void requestTimedOut(QgsNetworkRequestParameters request)
Emitted when a network request has timed out.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)