|
| 1 | +/*************************************************************************** |
| 2 | + qgsblockingnetworkrequest.cpp |
| 3 | + ----------------------------- |
| 4 | + begin : November 2018 |
| 5 | + copyright : (C) 2018 by Nyall Dawson |
| 6 | + email : nyall dot dawson at gmail dot com |
| 7 | + *************************************************************************** |
| 8 | + * * |
| 9 | + * This program is free software; you can redistribute it and/or modify * |
| 10 | + * it under the terms of the GNU General Public License as published by * |
| 11 | + * the Free Software Foundation; either version 2 of the License, or * |
| 12 | + * (at your option) any later version. * |
| 13 | + * * |
| 14 | + ***************************************************************************/ |
| 15 | + |
| 16 | +#include "qgsblockingnetworkrequest.h" |
| 17 | +#include "qgslogger.h" |
| 18 | +#include "qgsapplication.h" |
| 19 | +#include "qgsnetworkaccessmanager.h" |
| 20 | +#include "qgsauthmanager.h" |
| 21 | +#include "qgsmessagelog.h" |
| 22 | +#include <QUrl> |
| 23 | +#include <QNetworkRequest> |
| 24 | +#include <QNetworkReply> |
| 25 | +#include <QMutex> |
| 26 | +#include <QWaitCondition> |
| 27 | +#include <QNetworkCacheMetaData> |
| 28 | +#include <QAuthenticator> |
| 29 | + |
| 30 | +const qint64 READ_BUFFER_SIZE_HINT = 1024 * 1024; |
| 31 | + |
| 32 | +QgsBlockingNetworkRequest::QgsBlockingNetworkRequest() |
| 33 | +{ |
| 34 | + connect( QgsNetworkAccessManager::instance(), &QgsNetworkAccessManager::requestTimedOut, this, &QgsBlockingNetworkRequest::requestTimedOut ); |
| 35 | +} |
| 36 | + |
| 37 | +QgsBlockingNetworkRequest::~QgsBlockingNetworkRequest() |
| 38 | +{ |
| 39 | + abort(); |
| 40 | +} |
| 41 | + |
| 42 | +void QgsBlockingNetworkRequest::requestTimedOut( QNetworkReply *reply ) |
| 43 | +{ |
| 44 | + if ( reply == mReply ) |
| 45 | + mTimedout = true; |
| 46 | +} |
| 47 | + |
| 48 | +QString QgsBlockingNetworkRequest::authCfg() const |
| 49 | +{ |
| 50 | + return mAuthCfg; |
| 51 | +} |
| 52 | + |
| 53 | +void QgsBlockingNetworkRequest::setAuthCfg( const QString &authCfg ) |
| 54 | +{ |
| 55 | + mAuthCfg = authCfg; |
| 56 | +} |
| 57 | + |
| 58 | +QgsBlockingNetworkRequest::ErrorCode QgsBlockingNetworkRequest::get( QNetworkRequest &request, bool forceRefresh ) |
| 59 | +{ |
| 60 | + return doRequest( Get, request, forceRefresh ); |
| 61 | +} |
| 62 | + |
| 63 | +QgsBlockingNetworkRequest::ErrorCode QgsBlockingNetworkRequest::post( QNetworkRequest &request, const QByteArray &data, bool forceRefresh ) |
| 64 | +{ |
| 65 | + mPostData = data; |
| 66 | + return doRequest( Post, request, forceRefresh ); |
| 67 | +} |
| 68 | + |
| 69 | +QgsBlockingNetworkRequest::ErrorCode QgsBlockingNetworkRequest::doRequest( QgsBlockingNetworkRequest::Method method, QNetworkRequest &request, bool forceRefresh ) |
| 70 | +{ |
| 71 | + mMethod = method; |
| 72 | + |
| 73 | + abort(); // cancel previous |
| 74 | + mIsAborted = false; |
| 75 | + mTimedout = false; |
| 76 | + mGotNonEmptyResponse = false; |
| 77 | + |
| 78 | + mErrorMessage.clear(); |
| 79 | + mErrorCode = NoError; |
| 80 | + mForceRefresh = forceRefresh; |
| 81 | + mReplyContent.clear(); |
| 82 | + |
| 83 | + if ( !mAuthCfg.isEmpty() && !QgsApplication::authManager()->updateNetworkRequest( request, mAuthCfg ) ) |
| 84 | + { |
| 85 | + mErrorCode = NetworkError; |
| 86 | + mErrorMessage = errorMessageFailedAuth(); |
| 87 | + QgsMessageLog::logMessage( mErrorMessage, tr( "Network" ) ); |
| 88 | + return NetworkError; |
| 89 | + } |
| 90 | + |
| 91 | + QgsDebugMsgLevel( QStringLiteral( "Calling: %1" ).arg( request.url().toString() ), 2 ); |
| 92 | + |
| 93 | + request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, forceRefresh ? QNetworkRequest::AlwaysNetwork : QNetworkRequest::PreferCache ); |
| 94 | + request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); |
| 95 | + |
| 96 | + QWaitCondition waitCondition; |
| 97 | + QMutex waitConditionMutex; |
| 98 | + bool threadFinished = false; |
| 99 | + bool success = false; |
| 100 | + |
| 101 | + std::function<void()> downloaderFunction = [ this, request, &waitConditionMutex, &waitCondition, &threadFinished, &success ]() |
| 102 | + { |
| 103 | + if ( QThread::currentThread() != QgsApplication::instance()->thread() ) |
| 104 | + QgsNetworkAccessManager::instance( Qt::DirectConnection ); |
| 105 | + |
| 106 | + success = true; |
| 107 | + |
| 108 | + switch ( mMethod ) |
| 109 | + { |
| 110 | + case Get: |
| 111 | + mReply = QgsNetworkAccessManager::instance()->get( request ); |
| 112 | + break; |
| 113 | + |
| 114 | + case Post: |
| 115 | + mReply = QgsNetworkAccessManager::instance()->post( request, mPostData ); |
| 116 | + break; |
| 117 | + }; |
| 118 | + |
| 119 | + mReply->setReadBufferSize( READ_BUFFER_SIZE_HINT ); |
| 120 | + |
| 121 | + if ( !mAuthCfg.isEmpty() && !QgsApplication::authManager()->updateNetworkReply( mReply, mAuthCfg ) ) |
| 122 | + { |
| 123 | + mErrorCode = NetworkError; |
| 124 | + mErrorMessage = errorMessageFailedAuth(); |
| 125 | + QgsMessageLog::logMessage( mErrorMessage, tr( "Network" ) ); |
| 126 | + waitCondition.wakeAll(); |
| 127 | + success = false; |
| 128 | + } |
| 129 | + else |
| 130 | + { |
| 131 | + // We are able to use direct connection here, because we |
| 132 | + // * either run on the thread mReply lives in, so DirectConnection is standard and safe anyway |
| 133 | + // * or the owner thread of mReply is currently not doing anything because it's blocked in future.waitForFinished() (if it is the main thread) |
| 134 | + connect( mReply, &QNetworkReply::finished, this, &QgsBlockingNetworkRequest::replyFinished, Qt::DirectConnection ); |
| 135 | + connect( mReply, &QNetworkReply::downloadProgress, this, &QgsBlockingNetworkRequest::replyProgress, Qt::DirectConnection ); |
| 136 | + |
| 137 | + auto resumeMainThread = [&waitConditionMutex, &waitCondition]() |
| 138 | + { |
| 139 | + waitConditionMutex.lock(); |
| 140 | + waitCondition.wakeAll(); |
| 141 | + waitConditionMutex.unlock(); |
| 142 | + |
| 143 | + waitConditionMutex.lock(); |
| 144 | + waitCondition.wait( &waitConditionMutex ); |
| 145 | + waitConditionMutex.unlock(); |
| 146 | + }; |
| 147 | + |
| 148 | + connect( QgsNetworkAccessManager::instance(), &QgsNetworkAccessManager::authenticationRequired, this, resumeMainThread, Qt::DirectConnection ); |
| 149 | + connect( QgsNetworkAccessManager::instance(), &QgsNetworkAccessManager::proxyAuthenticationRequired, this, resumeMainThread, Qt::DirectConnection ); |
| 150 | + |
| 151 | +#ifndef QT_NO_SSL |
| 152 | + connect( QgsNetworkAccessManager::instance(), &QgsNetworkAccessManager::sslErrors, this, resumeMainThread, Qt::DirectConnection ); |
| 153 | +#endif |
| 154 | + QEventLoop loop; |
| 155 | + connect( this, &QgsBlockingNetworkRequest::downloadFinished, &loop, &QEventLoop::quit, Qt::DirectConnection ); |
| 156 | + loop.exec(); |
| 157 | + } |
| 158 | + waitConditionMutex.lock(); |
| 159 | + threadFinished = true; |
| 160 | + waitCondition.wakeAll(); |
| 161 | + waitConditionMutex.unlock(); |
| 162 | + }; |
| 163 | + |
| 164 | + if ( QThread::currentThread() == QApplication::instance()->thread() ) |
| 165 | + { |
| 166 | + std::unique_ptr<DownloaderThread> downloaderThread = qgis::make_unique<DownloaderThread>( downloaderFunction ); |
| 167 | + downloaderThread->start(); |
| 168 | + |
| 169 | + while ( true ) |
| 170 | + { |
| 171 | + waitConditionMutex.lock(); |
| 172 | + if ( threadFinished ) |
| 173 | + { |
| 174 | + waitConditionMutex.unlock(); |
| 175 | + break; |
| 176 | + } |
| 177 | + waitCondition.wait( &waitConditionMutex ); |
| 178 | + |
| 179 | + // If the downloader thread wakes us (the main thread) up and is not yet finished |
| 180 | + // he needs the authentication to run. |
| 181 | + // The processEvents() call gives the auth manager the chance to show a dialog and |
| 182 | + // once done with that, we can wake the downloaderThread again and continue the download. |
| 183 | + if ( !threadFinished ) |
| 184 | + { |
| 185 | + waitConditionMutex.unlock(); |
| 186 | + |
| 187 | + QgsApplication::instance()->processEvents(); |
| 188 | + waitConditionMutex.lock(); |
| 189 | + waitCondition.wakeAll(); |
| 190 | + waitConditionMutex.unlock(); |
| 191 | + } |
| 192 | + else |
| 193 | + { |
| 194 | + waitConditionMutex.unlock(); |
| 195 | + } |
| 196 | + } |
| 197 | + // wait for thread to gracefully exit |
| 198 | + downloaderThread->wait(); |
| 199 | + } |
| 200 | + else |
| 201 | + { |
| 202 | + downloaderFunction(); |
| 203 | + } |
| 204 | + return mErrorCode; |
| 205 | +} |
| 206 | + |
| 207 | +void QgsBlockingNetworkRequest::abort() |
| 208 | +{ |
| 209 | + mIsAborted = true; |
| 210 | + if ( mReply ) |
| 211 | + { |
| 212 | + mReply->deleteLater(); |
| 213 | + mReply = nullptr; |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +void QgsBlockingNetworkRequest::replyProgress( qint64 bytesReceived, qint64 bytesTotal ) |
| 218 | +{ |
| 219 | + QgsDebugMsgLevel( QStringLiteral( "%1 of %2 bytes downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QStringLiteral( "unknown number of" ) : QString::number( bytesTotal ) ), 2 ); |
| 220 | + |
| 221 | + if ( bytesReceived != 0 ) |
| 222 | + mGotNonEmptyResponse = true; |
| 223 | + |
| 224 | + if ( !mIsAborted && mReply ) |
| 225 | + { |
| 226 | + if ( mReply->error() == QNetworkReply::NoError ) |
| 227 | + { |
| 228 | + QVariant redirect = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute ); |
| 229 | + if ( !redirect.isNull() ) |
| 230 | + { |
| 231 | + // We don't want to emit downloadProgress() for a redirect |
| 232 | + return; |
| 233 | + } |
| 234 | + } |
| 235 | + } |
| 236 | + |
| 237 | + emit downloadProgress( bytesReceived, bytesTotal ); |
| 238 | +} |
| 239 | + |
| 240 | +void QgsBlockingNetworkRequest::replyFinished() |
| 241 | +{ |
| 242 | + if ( !mIsAborted && mReply ) |
| 243 | + { |
| 244 | + if ( mReply->error() == QNetworkReply::NoError ) |
| 245 | + { |
| 246 | + QgsDebugMsgLevel( QStringLiteral( "reply OK" ), 2 ); |
| 247 | + QVariant redirect = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute ); |
| 248 | + if ( !redirect.isNull() ) |
| 249 | + { |
| 250 | + QgsDebugMsgLevel( QStringLiteral( "Request redirected." ), 2 ); |
| 251 | + |
| 252 | + const QUrl &toUrl = redirect.toUrl(); |
| 253 | + mReply->request(); |
| 254 | + if ( toUrl == mReply->url() ) |
| 255 | + { |
| 256 | + mErrorMessage = tr( "Redirect loop detected: %1" ).arg( toUrl.toString() ); |
| 257 | + QgsMessageLog::logMessage( mErrorMessage, tr( "Network" ) ); |
| 258 | + mReplyContent.clear(); |
| 259 | + } |
| 260 | + else |
| 261 | + { |
| 262 | + QNetworkRequest request( toUrl ); |
| 263 | + |
| 264 | + if ( !mAuthCfg.isEmpty() && !QgsApplication::authManager()->updateNetworkRequest( request, mAuthCfg ) ) |
| 265 | + { |
| 266 | + mReplyContent.clear(); |
| 267 | + mErrorMessage = errorMessageFailedAuth(); |
| 268 | + mErrorCode = NetworkError; |
| 269 | + QgsMessageLog::logMessage( mErrorMessage, tr( "Network" ) ); |
| 270 | + emit downloadFinished(); |
| 271 | + return; |
| 272 | + } |
| 273 | + |
| 274 | + request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, mForceRefresh ? QNetworkRequest::AlwaysNetwork : QNetworkRequest::PreferCache ); |
| 275 | + request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); |
| 276 | + |
| 277 | + mReply->deleteLater(); |
| 278 | + mReply = nullptr; |
| 279 | + |
| 280 | + QgsDebugMsgLevel( QStringLiteral( "redirected: %1 forceRefresh=%2" ).arg( redirect.toString() ).arg( mForceRefresh ), 2 ); |
| 281 | + switch ( mMethod ) |
| 282 | + { |
| 283 | + case Get: |
| 284 | + mReply = QgsNetworkAccessManager::instance()->get( request ); |
| 285 | + break; |
| 286 | + |
| 287 | + case Post: |
| 288 | + mReply = QgsNetworkAccessManager::instance()->post( request, mPostData ); |
| 289 | + break; |
| 290 | + }; |
| 291 | + |
| 292 | + mReply->setReadBufferSize( READ_BUFFER_SIZE_HINT ); |
| 293 | + |
| 294 | + if ( !mAuthCfg.isEmpty() && !QgsApplication::authManager()->updateNetworkReply( mReply, mAuthCfg ) ) |
| 295 | + { |
| 296 | + mReplyContent.clear(); |
| 297 | + mErrorMessage = errorMessageFailedAuth(); |
| 298 | + mErrorCode = NetworkError; |
| 299 | + QgsMessageLog::logMessage( mErrorMessage, tr( "Network" ) ); |
| 300 | + emit downloadFinished(); |
| 301 | + return; |
| 302 | + } |
| 303 | + |
| 304 | + connect( mReply, &QNetworkReply::finished, this, &QgsBlockingNetworkRequest::replyFinished, Qt::DirectConnection ); |
| 305 | + connect( mReply, &QNetworkReply::downloadProgress, this, &QgsBlockingNetworkRequest::replyProgress, Qt::DirectConnection ); |
| 306 | + return; |
| 307 | + } |
| 308 | + } |
| 309 | + else |
| 310 | + { |
| 311 | + const QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance(); |
| 312 | + |
| 313 | + if ( nam->cache() ) |
| 314 | + { |
| 315 | + QNetworkCacheMetaData cmd = nam->cache()->metaData( mReply->request().url() ); |
| 316 | + |
| 317 | + QNetworkCacheMetaData::RawHeaderList hl; |
| 318 | + Q_FOREACH ( const QNetworkCacheMetaData::RawHeader &h, cmd.rawHeaders() ) |
| 319 | + { |
| 320 | + if ( h.first != "Cache-Control" ) |
| 321 | + hl.append( h ); |
| 322 | + } |
| 323 | + cmd.setRawHeaders( hl ); |
| 324 | + |
| 325 | + QgsDebugMsgLevel( QStringLiteral( "expirationDate:%1" ).arg( cmd.expirationDate().toString() ), 2 ); |
| 326 | + if ( cmd.expirationDate().isNull() ) |
| 327 | + { |
| 328 | + cmd.setExpirationDate( QDateTime::currentDateTime().addSecs( mExpirationSec ) ); |
| 329 | + } |
| 330 | + |
| 331 | + nam->cache()->updateMetaData( cmd ); |
| 332 | + } |
| 333 | + else |
| 334 | + { |
| 335 | + QgsDebugMsgLevel( QStringLiteral( "No cache!" ), 2 ); |
| 336 | + } |
| 337 | + |
| 338 | +#ifdef QGISDEBUG |
| 339 | + bool fromCache = mReply->attribute( QNetworkRequest::SourceIsFromCacheAttribute ).toBool(); |
| 340 | + QgsDebugMsgLevel( QStringLiteral( "Reply was cached: %1" ).arg( fromCache ), 2 ); |
| 341 | +#endif |
| 342 | + |
| 343 | + mReplyContent = QgsNetworkReplyContent( mReply ); |
| 344 | + if ( mReplyContent.content().isEmpty() && !mGotNonEmptyResponse ) |
| 345 | + { |
| 346 | + mErrorMessage = tr( "empty response: %1" ).arg( mReply->errorString() ); |
| 347 | + mErrorCode = ServerExceptionError; |
| 348 | + QgsMessageLog::logMessage( mErrorMessage, tr( "Network" ) ); |
| 349 | + } |
| 350 | + } |
| 351 | + } |
| 352 | + else |
| 353 | + { |
| 354 | + mErrorMessage = mReply->errorString(); |
| 355 | + mErrorCode = ServerExceptionError; |
| 356 | + QgsMessageLog::logMessage( mErrorMessage, tr( "Network" ) ); |
| 357 | + mReplyContent.clear(); |
| 358 | + } |
| 359 | + } |
| 360 | + if ( mTimedout ) |
| 361 | + mErrorCode = TimeoutError; |
| 362 | + |
| 363 | + if ( mReply ) |
| 364 | + { |
| 365 | + mReply->deleteLater(); |
| 366 | + mReply = nullptr; |
| 367 | + } |
| 368 | + |
| 369 | + emit downloadFinished(); |
| 370 | +} |
| 371 | + |
| 372 | +QString QgsBlockingNetworkRequest::errorMessageFailedAuth() |
| 373 | +{ |
| 374 | + return tr( "network request update failed for authentication config" ); |
| 375 | +} |
0 commit comments