QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmfiledownloader.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmfiledownloader.cpp
3 ---------------------
4 begin : October 2017
5 copyright : (C) 2017 by Etienne Trimaille
6 email : etienne at kartoza dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "qgis.h"
21#include "qgsfiledownloader.h"
22#include "qgsfileutils.h"
24
25#include <QEventLoop>
26#include <QFileInfo>
27#include <QString>
28#include <QTimer>
29#include <QUrl>
30
31#include "moc_qgsalgorithmfiledownloader.cpp"
32
33using namespace Qt::StringLiterals;
34
36
37QString QgsFileDownloaderAlgorithm::name() const
38{
39 return u"filedownloader"_s;
40}
41
42QString QgsFileDownloaderAlgorithm::displayName() const
43{
44 return tr( "Download file via HTTP(S)" );
45}
46
47QString QgsFileDownloaderAlgorithm::shortDescription() const
48{
49 return tr( "Downloads a URL to the file system with an HTTP(S) GET or POST request." );
50}
51
52QStringList QgsFileDownloaderAlgorithm::tags() const
53{
54 return tr( "file,downloader,internet,url,fetch,get,post,request,https" ).split( ',' );
55}
56
57QString QgsFileDownloaderAlgorithm::group() const
58{
59 return tr( "File tools" );
60}
61
62QString QgsFileDownloaderAlgorithm::groupId() const
63{
64 return u"filetools"_s;
65}
66
67QString QgsFileDownloaderAlgorithm::shortHelpString() const
68{
69 return tr( "This algorithm downloads a URL to the file system with an HTTP(S) GET or POST request" );
70}
71
72QgsFileDownloaderAlgorithm *QgsFileDownloaderAlgorithm::createInstance() const
73{
74 return new QgsFileDownloaderAlgorithm();
75}
76
77void QgsFileDownloaderAlgorithm::initAlgorithm( const QVariantMap & )
78{
79 addParameter( new QgsProcessingParameterString( u"URL"_s, tr( "URL" ), QVariant(), false, false ) );
80
81 auto methodParam = std::make_unique<QgsProcessingParameterEnum>(
82 u"METHOD"_s,
83 QObject::tr( "Method" ),
84 QStringList()
85 << QObject::tr( "GET" )
86 << QObject::tr( "POST" ),
87 false,
88 0
89 );
90 methodParam->setHelp( QObject::tr( "The HTTP method to use for the request" ) );
91 methodParam->setFlags( methodParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
92 addParameter( methodParam.release() );
93
94 auto dataParam = std::make_unique<QgsProcessingParameterString>(
95 u"DATA"_s, tr( "Data" ), QVariant(), false, true
96 );
97 dataParam->setHelp( QObject::tr( "The data to add in the body if the request is a POST" ) );
98 dataParam->setFlags( dataParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
99 addParameter( dataParam.release() );
100 addParameter( new QgsProcessingParameterFileDestination( u"OUTPUT"_s, tr( "File destination" ), QObject::tr( "All files (*.*)" ), QVariant(), false ) );
101}
102
103QVariantMap QgsFileDownloaderAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
104{
105 mFeedback = feedback;
106 QString url = parameterAsString( parameters, u"URL"_s, context );
107 if ( url.isEmpty() )
108 throw QgsProcessingException( tr( "No URL specified" ) );
109
110 QString data = parameterAsString( parameters, u"DATA"_s, context );
111 QString outputFile = parameterAsFileOutput( parameters, u"OUTPUT"_s, context );
112
113 QEventLoop loop;
114 QTimer timer;
115 QUrl downloadedUrl;
116 QStringList errors;
117
118 Qgis::HttpMethod httpMethod = static_cast<Qgis::HttpMethod>( parameterAsEnum( parameters, u"METHOD"_s, context ) );
119
120 if ( httpMethod == Qgis::HttpMethod::Get && !data.isEmpty() )
121 {
122 feedback->pushWarning( tr( "DATA parameter is not used when it's a GET request." ) );
123 data = QString();
124 }
125
126 QgsFileDownloader *downloader = new QgsFileDownloader( QUrl( url ), outputFile, QString(), true, httpMethod, data.toUtf8() );
127 connect( mFeedback, &QgsFeedback::canceled, downloader, &QgsFileDownloader::cancelDownload );
128 connect( downloader, &QgsFileDownloader::downloadError, this, [&errors, &loop]( const QStringList &e ) { errors = e; loop.exit(); } );
129 connect( downloader, &QgsFileDownloader::downloadProgress, this, &QgsFileDownloaderAlgorithm::receiveProgressFromDownloader );
130 connect( downloader, &QgsFileDownloader::downloadCompleted, this, [&downloadedUrl]( const QUrl url ) { downloadedUrl = url; } );
131 connect( downloader, &QgsFileDownloader::downloadExited, this, [&loop]() { loop.exit(); } );
132 connect( &timer, &QTimer::timeout, this, &QgsFileDownloaderAlgorithm::sendProgressFeedback );
133 downloader->startDownload();
134 timer.start( 1000 );
135
136 loop.exec();
137
138 timer.stop();
139 if ( errors.size() > 0 )
140 throw QgsProcessingException( errors.join( '\n' ) );
141
142 const bool exists = QFileInfo::exists( outputFile );
143 if ( !feedback->isCanceled() && !exists )
144 throw QgsProcessingException( tr( "Output file doesn't exist." ) );
145
146 url = downloadedUrl.toDisplayString();
147 feedback->pushInfo( QObject::tr( "Successfully downloaded %1" ).arg( url ) );
148
149 if ( parameters.value( u"OUTPUT"_s ) == QgsProcessing::TEMPORARY_OUTPUT )
150 {
151 // the output is temporary and its file name automatically generated, try to add a file extension
152 const int length = url.size();
153 const int lastDotIndex = url.lastIndexOf( "." );
154 const int lastSlashIndex = url.lastIndexOf( "/" );
155 if ( lastDotIndex > -1 && lastDotIndex > lastSlashIndex && length - lastDotIndex <= 6 )
156 {
157 QFile tmpFile( outputFile );
158 tmpFile.rename( tmpFile.fileName() + url.mid( lastDotIndex ) );
159 outputFile += url.mid( lastDotIndex );
160 }
161 }
162
163 QVariantMap outputs;
164 outputs.insert( u"OUTPUT"_s, exists ? outputFile : QString() );
165 return outputs;
166}
167
168void QgsFileDownloaderAlgorithm::sendProgressFeedback()
169{
170 if ( !mReceived.isEmpty() && mLastReport != mReceived )
171 {
172 mLastReport = mReceived;
173 if ( mTotal.isEmpty() )
174 mFeedback->pushInfo( tr( "%1 downloaded" ).arg( mReceived ) );
175 else
176 mFeedback->pushInfo( tr( "%1 of %2 downloaded" ).arg( mReceived, mTotal ) );
177 }
178}
179
180void QgsFileDownloaderAlgorithm::receiveProgressFromDownloader( qint64 bytesReceived, qint64 bytesTotal )
181{
182 mReceived = QgsFileUtils::representFileSize( bytesReceived );
183 if ( bytesTotal > 0 )
184 {
185 if ( mTotal.isEmpty() )
186 mTotal = QgsFileUtils::representFileSize( bytesTotal );
187
188 mFeedback->setProgress( ( bytesReceived * 100 ) / bytesTotal );
189 }
190}
191
HttpMethod
Different methods of HTTP requests.
Definition qgis.h:1056
@ Get
GET method.
Definition qgis.h:1057
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void canceled()
Internal routines can connect to this signal if they use event loop.
A utility class for downloading files.
void cancelDownload()
Call to abort the download and delete this object after the cancellation has been processed.
void downloadExited()
Emitted always when the downloader exits.
void downloadError(QStringList errorMessages)
Emitted when an error makes the download fail.
void startDownload()
Called to start the download.
void downloadCompleted(const QUrl &url)
Emitted when the download has completed successfully.
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
Emitted when data are ready to be processed.
static QString representFileSize(qint64 bytes)
Returns the human size from bytes.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
A string parameter for processing algorithms.
static const QString TEMPORARY_OUTPUT
Constant used to indicate that a Processing algorithm output should be a temporary layer/file.