QGIS API Documentation  2.14.9-Essen
qgsfiledownloader.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsfiledownloader.cpp
3  --------------------------------------
4  Date : November 2016
5  Copyright : (C) 2016 by Alessandro Pasotti
6  Email : apasotti at boundlessgeo 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 "qgsfiledownloader.h"
18 
19 #include <QNetworkAccessManager>
20 #include <QNetworkRequest>
21 #include <QNetworkReply>
22 #include <QMessageBox>
23 #ifndef QT_NO_OPENSSL
24 #include <QSslError>
25 #endif
26 
27 QgsFileDownloader::QgsFileDownloader( QUrl url, QString outputFileName, bool enableGuiNotifications )
28  : mUrl( url )
29  , mReply( nullptr )
30  , mProgressDialog( nullptr )
31  , mDownloadCanceled( false )
32  , mErrors()
33  , mGuiNotificationsEnabled( enableGuiNotifications )
34 {
35  mFile.setFileName( outputFileName );
36  startDownload();
37 }
38 
39 
40 QgsFileDownloader::~QgsFileDownloader()
41 {
42  if ( mReply )
43  {
44  mReply->abort();
45  mReply->deleteLater();
46  }
47  if ( mProgressDialog )
48  {
49  mProgressDialog->deleteLater();
50  }
51 }
52 
53 
54 void QgsFileDownloader::startDownload()
55 {
57 
58  QNetworkRequest request( mUrl );
59 
60  mReply = nam->get( request );
61 
62  connect( mReply, SIGNAL( readyRead() ), this, SLOT( onReadyRead() ) );
63  connect( mReply, SIGNAL( error( QNetworkReply::NetworkError ) ), this, SLOT( onNetworkError( QNetworkReply::NetworkError ) ) );
64  connect( mReply, SIGNAL( finished() ), this, SLOT( onFinished() ) );
65  connect( mReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( onDownloadProgress( qint64, qint64 ) ) );
66  connect( nam, SIGNAL( requestTimedOut( QNetworkReply* ) ), this, SLOT( onRequestTimedOut() ) );
67 #ifndef QT_NO_OPENSSL
68  connect( nam, SIGNAL( sslErrors( QNetworkReply*, QList<QSslError> ) ), this, SLOT( onSslErrors( QNetworkReply*, QList<QSslError> ) ) );
69 #endif
70  if ( mGuiNotificationsEnabled )
71  {
72  mProgressDialog = new QProgressDialog();
73  mProgressDialog->setWindowTitle( tr( "Download" ) );
74  mProgressDialog->setLabelText( tr( "Downloading %1." ).arg( mFile.fileName() ) );
75  mProgressDialog->show();
76  connect( mProgressDialog, SIGNAL( canceled() ), this, SLOT( onDownloadCanceled() ) );
77  }
78 }
79 
81 {
82  mDownloadCanceled = true;
83  emit downloadCanceled();
84  onFinished();
85 }
86 
87 void QgsFileDownloader::onRequestTimedOut()
88 {
89  error( tr( "Network request %1 timed out" ).arg( mUrl.toString() ) );
90 }
91 
92 #ifndef QT_NO_OPENSSL
93 void QgsFileDownloader::onSslErrors( QNetworkReply *reply, const QList<QSslError> &errors )
94 {
95  Q_UNUSED( reply );
96  QStringList errorMessages;
97  errorMessages << "SSL Errors: ";
98  for ( int end = errors.size(), i = 0; i != end; ++i )
99  {
100  errorMessages << errors[i].errorString();
101  }
102  error( errorMessages );
103 }
104 #endif
105 
106 
107 void QgsFileDownloader::error( QStringList errorMessages )
108 {
109  for ( int end = errorMessages.size(), i = 0; i != end; ++i )
110  {
111  mErrors.append( errorMessages[i] );
112  }
113  // Show error
114  if ( mGuiNotificationsEnabled )
115  {
116  QMessageBox::warning( nullptr, tr( "Download failed" ), mErrors.join( "<br>" ) );
117  }
118  emit downloadError( mErrors );
119 }
120 
121 void QgsFileDownloader::error( QString errorMessage )
122 {
123  error( QStringList() << errorMessage );
124 }
125 
126 void QgsFileDownloader::onReadyRead()
127 {
128  Q_ASSERT( mReply );
129  if ( ! mFile.isOpen() && ! mFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
130  {
131  error( tr( "Cannot open output file: %1" ).arg( mFile.fileName() ) );
132  onFinished();
133  }
134  else
135  {
136  QByteArray data = mReply->readAll();
137  mFile.write( data );
138  }
139 }
140 
141 void QgsFileDownloader::onFinished()
142 {
143  // when canceled
144  if ( ! mErrors.isEmpty() || mDownloadCanceled )
145  {
146  mFile.close();
147  mFile.remove();
148  if ( mGuiNotificationsEnabled )
149  mProgressDialog->hide();
150  }
151  else
152  {
153  // download finished normally
154  if ( mGuiNotificationsEnabled )
155  mProgressDialog->hide();
156  mFile.flush();
157  mFile.close();
158 
159  // get redirection url
160  QVariant redirectionTarget = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
161  if ( mReply->error() )
162  {
163  mFile.remove();
164  error( tr( "Download failed: %1." ).arg( mReply->errorString() ) );
165  }
166  else if ( !redirectionTarget.isNull() )
167  {
168  QUrl newUrl = mUrl.resolved( redirectionTarget.toUrl() );
169  mUrl = newUrl;
170  mReply->deleteLater();
171  mFile.open( QIODevice::WriteOnly );
172  mFile.resize( 0 );
173  mFile.close();
174  startDownload();
175  return;
176  }
177  // All done
178  emit downloadCompleted();
179  }
180  emit downloadExited();
181  this->deleteLater();
182 }
183 
184 void QgsFileDownloader::onNetworkError( QNetworkReply::NetworkError err )
185 {
186  Q_ASSERT( mReply );
187  error( QString( "Network error %1: %2" ).arg( err ).arg( mReply->errorString() ) );
188 }
189 
190 void QgsFileDownloader::onDownloadProgress( qint64 bytesReceived, qint64 bytesTotal )
191 {
192  if ( mDownloadCanceled )
193  {
194  return;
195  }
196  if ( mGuiNotificationsEnabled )
197  {
198  mProgressDialog->setMaximum( bytesTotal );
199  mProgressDialog->setValue( bytesReceived );
200  }
201  emit downloadProgress( bytesReceived, bytesTotal );
202 }
203 
QUrl toUrl() const
bool flush()
bool resize(qint64 sz)
void setMaximum(int maximum)
bool remove()
QString errorString() const
void setLabelText(const QString &text)
QString fileName() const
void setFileName(const QString &name)
QString join(const QString &separator) const
QString toString(QFlags< QUrl::FormattingOption > options) const
QString tr(const char *sourceText, const char *disambiguation, int n)
int size() const
void setValue(int progress)
void append(const T &value)
bool isNull() const
bool isEmpty() const
QByteArray readAll()
bool isOpen() const
void deleteLater()
void hide()
virtual bool open(QFlags< QIODevice::OpenModeFlag > mode)
virtual void abort()=0
virtual void close()
QgsFileDownloader(QUrl url, QString outputFileName, bool guiNotificationsEnabled=true)
QgsFileDownloader.
static QgsNetworkAccessManager * instance()
returns a pointer to the single instance
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
Emitted when data ready to be processed.
void setWindowTitle(const QString &)
void downloadCanceled()
Emitted when the download was canceled by the user.
QUrl resolved(const QUrl &relative) const
QVariant attribute(QNetworkRequest::Attribute code) const
qint64 write(const char *data, qint64 maxSize)
NetworkError error() const
void onDownloadCanceled()
Called when a download is canceled by the user this slot aborts the download and deletes the object...
StandardButton warning(QWidget *parent, const QString &title, const QString &text, QFlags< QMessageBox::StandardButton > buttons, StandardButton defaultButton)
void show()
QNetworkReply * get(const QNetworkRequest &request)
void downloadCompleted()
Emitted when the download has completed successfully.
bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
void downloadError(QStringList errorMessages)
Emitted when an error makes the download fail.
void downloadExited()
Emitted always when the downloader exits.