21 #include <QNetworkAccessManager>
22 #include <QNetworkRequest>
23 #include <QNetworkReply>
30 , mDownloadCanceled( false )
32 mFile.setFileName( outputFileName );
44 mReply->deleteLater();
53 QNetworkRequest request( mUrl );
55 if ( !mAuthCfg.isEmpty() )
62 disconnect( mReply, &QNetworkReply::readyRead,
this, &QgsFileDownloader::onReadyRead );
63 disconnect( mReply, &QNetworkReply::finished,
this, &QgsFileDownloader::onFinished );
64 disconnect( mReply, &QNetworkReply::downloadProgress,
this, &QgsFileDownloader::onDownloadProgress );
66 mReply->deleteLater();
69 mReply = nam->get( request );
70 if ( !mAuthCfg.isEmpty() )
75 connect( mReply, &QNetworkReply::readyRead,
this, &QgsFileDownloader::onReadyRead );
76 connect( mReply, &QNetworkReply::finished,
this, &QgsFileDownloader::onFinished );
77 connect( mReply, &QNetworkReply::downloadProgress,
this, &QgsFileDownloader::onDownloadProgress );
80 connect( nam, &QgsNetworkAccessManager::sslErrors,
this, &QgsFileDownloader::onSslErrors, Qt::UniqueConnection );
86 mDownloadCanceled =
true;
91 void QgsFileDownloader::onRequestTimedOut( QNetworkReply *reply )
93 if ( reply == mReply )
94 error( tr(
"Network request %1 timed out" ).arg( mUrl.toString() ) );
98 void QgsFileDownloader::onSslErrors( QNetworkReply *reply,
const QList<QSslError> &errors )
100 if ( reply == mReply )
102 QStringList errorMessages;
103 errorMessages.reserve( errors.size() + 1 );
104 errorMessages << QStringLiteral(
"SSL Errors: " );
105 for (
auto end = errors.size(), i = 0; i != end; ++i )
107 errorMessages << errors[i].errorString();
109 error( errorMessages );
115 void QgsFileDownloader::error(
const QStringList &errorMessages )
117 for (
auto end = errorMessages.size(), i = 0; i != end; ++i )
119 mErrors << errorMessages[i];
126 void QgsFileDownloader::error(
const QString &errorMessage )
128 error( QStringList() << errorMessage );
131 void QgsFileDownloader::onReadyRead()
134 if ( mFile.fileName().isEmpty() )
136 error( tr(
"No output filename specified" ) );
139 else if ( ! mFile.isOpen() && ! mFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
141 error( tr(
"Cannot open output file: %1" ).arg( mFile.fileName() ) );
146 QByteArray data = mReply->readAll();
151 void QgsFileDownloader::onFinished()
154 if ( ! mErrors.isEmpty() || mDownloadCanceled )
156 if ( mFile.isOpen() )
158 if ( mFile.exists() )
164 if ( mFile.isOpen() )
171 QVariant redirectionTarget = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
172 if ( mReply->error() )
175 error( tr(
"Download failed: %1" ).arg( mReply->errorString() ) );
177 else if ( !redirectionTarget.isNull() )
179 QUrl newUrl = mUrl.resolved( redirectionTarget.toUrl() );
181 mReply->deleteLater();
182 if ( !mFile.open( QIODevice::WriteOnly ) )
185 error( tr(
"Cannot open output file: %1" ).arg( mFile.fileName() ) );
205 void QgsFileDownloader::onDownloadProgress( qint64 bytesReceived, qint64 bytesTotal )
207 if ( mDownloadCanceled )