QGIS API Documentation 3.38.0-Grenoble (exported)
Loading...
Searching...
No Matches
qgsaction.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsaction.cpp - QgsAction
3
4 ---------------------
5 begin : 18.4.2016
6 copyright : (C) 2016 by Matthias Kuhn
8 ***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
17#include "qgsaction.h"
18
19#include <QDesktopServices>
20#include <QFileInfo>
21#include <QUrl>
22#include <QUrlQuery>
23#include <QDir>
24#include <QTemporaryDir>
25#include <QNetworkRequest>
26#include <QJsonDocument>
27#include <QHttpMultiPart>
28#include <QMimeDatabase>
29#include <QApplication>
30
31#include "qgspythonrunner.h"
32#include "qgsrunprocess.h"
34#include "qgsvectorlayer.h"
35#include "qgslogger.h"
38#include "qgsmessagelog.h"
39#include "qgsvariantutils.h"
40
42{
43// clang analyzer is not happy because of the multiple duplicate return branches, but this is ok :)
44// NOLINTBEGIN(bugprone-branch-clone)
45 switch ( mType )
46 {
52 return true;
53
54#if defined(Q_OS_WIN)
56 return true;
59 return false;
60#elif defined(Q_OS_MAC)
62 return true;
65 return false;
66#else
68 return true;
71 return false;
72#endif
73 }
74 return false;
75 // NOLINTEND(bugprone-branch-clone)
76}
77
78void QgsAction::run( QgsVectorLayer *layer, const QgsFeature &feature, const QgsExpressionContext &expressionContext ) const
79{
80 QgsExpressionContext actionContext( expressionContext );
81
82 actionContext << QgsExpressionContextUtils::layerScope( layer );
83 actionContext.setFeature( feature );
84
85 run( actionContext );
86}
87
88void QgsAction::handleFormSubmitAction( const QString &expandedAction ) const
89{
90
91 // Show busy in case the form subit is slow
92 QApplication::setOverrideCursor( Qt::WaitCursor );
93
94 QUrl url{ expandedAction };
95
96 // Encode '+' (fully encoded doesn't encode it)
97 const QString payload { url.query( QUrl::ComponentFormattingOption::FullyEncoded ).replace( QChar( '+' ), QStringLiteral( "%2B" ) ) };
98
99 // Remove query string from URL
100 const QUrlQuery queryString { url.query( ) };
101 url.setQuery( QString( ) );
102
103 QNetworkRequest req { url };
104
105 // Specific code for testing, produces an invalid POST but we can still listen to
106 // signals and examine the request
107 if ( url.toString().contains( QLatin1String( "fake_qgis_http_endpoint" ) ) )
108 {
109 req.setUrl( QStringLiteral( "file://%1" ).arg( url.path() ) );
110 }
111
112 QNetworkReply *reply = nullptr;
113
115 {
116 QString contentType { QStringLiteral( "application/x-www-form-urlencoded" ) };
117 // check for json
118 QJsonParseError jsonError;
119 QJsonDocument::fromJson( payload.toUtf8(), &jsonError );
120 if ( jsonError.error == QJsonParseError::ParseError::NoError )
121 {
122 contentType = QStringLiteral( "application/json" );
123 }
124 req.setHeader( QNetworkRequest::KnownHeaders::ContentTypeHeader, contentType );
125 reply = QgsNetworkAccessManager::instance()->post( req, payload.toUtf8() );
126 }
127 // for multipart create parts and headers
128 else
129 {
130 QHttpMultiPart *multiPart = new QHttpMultiPart( QHttpMultiPart::FormDataType );
131 const QList<QPair<QString, QString>> queryItems { queryString.queryItems( QUrl::ComponentFormattingOption::FullyDecoded ) };
132 for ( const QPair<QString, QString> &queryItem : std::as_const( queryItems ) )
133 {
134 QHttpPart part;
135 part.setHeader( QNetworkRequest::ContentDispositionHeader,
136 QStringLiteral( "form-data; name=\"%1\"" )
137 .arg( QString( queryItem.first ).replace( '"', QLatin1String( R"(\")" ) ) ) );
138 part.setBody( queryItem.second.toUtf8() );
139 multiPart->append( part );
140 }
141 reply = QgsNetworkAccessManager::instance()->post( req, multiPart );
142 multiPart->setParent( reply );
143 }
144
145 QObject::connect( reply, &QNetworkReply::finished, reply, [ reply ]
146 {
147 if ( reply->error() == QNetworkReply::NoError )
148 {
149
150 if ( QgsVariantUtils::isNull( reply->attribute( QNetworkRequest::RedirectionTargetAttribute ) ) )
151 {
152
153 const QByteArray replyData = reply->readAll();
154
155 QString filename { "download.bin" };
156 if ( const std::string header = reply->header( QNetworkRequest::KnownHeaders::ContentDispositionHeader ).toString().toStdString(); ! header.empty() )
157 {
158
159 // Extract filename dealing with ill formed headers with unquoted file names
160
161 std::string ascii;
162
163 const std::string q1 { R"(filename=)" };
164
165 if ( size_t pos = header.find( q1 ); pos != std::string::npos )
166 {
167
168 // Deal with ill formed headers with unquoted file names
169 if ( header.find( R"(filename=")" ) != std::string::npos )
170 {
171 pos++;
172 }
173
174 const size_t len = pos + q1.size();
175
176 const std::string q2 { R"(")" };
177 if ( size_t pos = header.find( q2, len ); pos != std::string::npos )
178 {
179 bool escaped = false;
180 while ( pos != std::string::npos && header[pos - 1] == '\\' )
181 {
182 pos = header.find( q2, pos + 1 );
183 escaped = true;
184 }
185 ascii = header.substr( len, pos - len );
186 if ( escaped )
187 {
188 std::string cleaned;
189 for ( size_t i = 0; i < ascii.size(); ++i )
190 {
191 if ( ascii[i] == '\\' )
192 {
193 if ( i > 0 && ascii[i - 1] == '\\' )
194 {
195 cleaned.push_back( ascii[i] );
196 }
197 }
198 else
199 {
200 cleaned.push_back( ascii[i] );
201 }
202 }
203 ascii = cleaned;
204 }
205 }
206 }
207
208 std::string utf8;
209
210 const std::string u { R"(UTF-8'')" };
211 if ( const size_t pos = header.find( u ); pos != std::string::npos )
212 {
213 utf8 = header.substr( pos + u.size() );
214 }
215
216 // Prefer ascii over utf8
217 if ( ascii.empty() )
218 {
219 if ( ! utf8.empty( ) )
220 {
221 filename = QString::fromStdString( utf8 );
222 }
223 }
224 else
225 {
226 filename = QString::fromStdString( ascii );
227 }
228 }
229 else if ( !QgsVariantUtils::isNull( reply->header( QNetworkRequest::KnownHeaders::ContentTypeHeader ) ) )
230 {
231 QString contentTypeHeader { reply->header( QNetworkRequest::KnownHeaders::ContentTypeHeader ).toString() };
232 // Strip charset if any
233 if ( contentTypeHeader.contains( ';' ) )
234 {
235 contentTypeHeader = contentTypeHeader.left( contentTypeHeader.indexOf( ';' ) );
236 }
237
238 QMimeType mimeType { QMimeDatabase().mimeTypeForName( contentTypeHeader ) };
239 if ( mimeType.isValid() )
240 {
241 filename = QStringLiteral( "download.%1" ).arg( mimeType.preferredSuffix() );
242 }
243 }
244
245 QTemporaryDir tempDir;
246 tempDir.setAutoRemove( false );
247 tempDir.path();
248 const QString tempFilePath{ tempDir.path() + QDir::separator() + filename };
249 QFile tempFile{ tempFilePath };
250 tempFile.open( QIODevice::WriteOnly );
251 tempFile.write( replyData );
252 tempFile.close();
253 QDesktopServices::openUrl( QUrl::fromLocalFile( tempFilePath ) );
254 }
255 else
256 {
257 QgsMessageLog::logMessage( QObject::tr( "Redirect is not supported!" ), QStringLiteral( "Form Submit Action" ), Qgis::MessageLevel::Critical );
258 }
259 }
260 else
261 {
262 QgsMessageLog::logMessage( reply->errorString(), QStringLiteral( "Form Submit Action" ), Qgis::MessageLevel::Critical );
263 }
264 reply->deleteLater();
265 QApplication::restoreOverrideCursor( );
266 } );
267
268}
269
270void QgsAction::setCommand( const QString &newCommand )
271{
272 mCommand = newCommand;
273}
274
275void QgsAction::run( const QgsExpressionContext &expressionContext ) const
276{
277 if ( !isValid() )
278 {
279 QgsDebugError( QStringLiteral( "Invalid action cannot be run" ) );
280 return;
281 }
282
283 QgsExpressionContextScope *scope = new QgsExpressionContextScope( mExpressionContextScope );
284 QgsExpressionContext context( expressionContext );
285 context << scope;
286
287 // Show busy in case the expression evaluation is slow
288 QApplication::setOverrideCursor( Qt::WaitCursor );
289 const QString expandedAction = QgsExpression::replaceExpressionText( mCommand, &context );
290 QApplication::restoreOverrideCursor();
291
293 {
294 const QFileInfo finfo( expandedAction );
295 if ( finfo.exists() && finfo.isFile() )
296 QDesktopServices::openUrl( QUrl::fromLocalFile( expandedAction ) );
297 else
298 QDesktopServices::openUrl( QUrl( expandedAction, QUrl::TolerantMode ) );
299 }
301 {
302 handleFormSubmitAction( expandedAction );
303 }
305 {
306 // TODO: capture output from QgsPythonRunner (like QgsRunProcess does)
307 QgsPythonRunner::run( expandedAction );
308 }
309 else
310 {
311 // The QgsRunProcess instance created by this static function
312 // deletes itself when no longer needed.
313#ifndef __clang_analyzer__
314 QgsRunProcess::create( expandedAction, mCaptureOutput );
315#endif
316 }
317}
318
319QSet<QString> QgsAction::actionScopes() const
320{
321 return mActionScopes;
322}
323
324void QgsAction::setActionScopes( const QSet<QString> &actionScopes )
325{
326 mActionScopes = actionScopes;
327}
328
329void QgsAction::readXml( const QDomNode &actionNode )
330{
331 QDomElement actionElement = actionNode.toElement();
332 const QDomNodeList actionScopeNodes = actionElement.elementsByTagName( QStringLiteral( "actionScope" ) );
333
334 if ( actionScopeNodes.isEmpty() )
335 {
336 mActionScopes
337 << QStringLiteral( "Canvas" )
338 << QStringLiteral( "Field" )
339 << QStringLiteral( "Feature" );
340 }
341 else
342 {
343 for ( int j = 0; j < actionScopeNodes.length(); ++j )
344 {
345 const QDomElement actionScopeElem = actionScopeNodes.item( j ).toElement();
346 mActionScopes << actionScopeElem.attribute( QStringLiteral( "id" ) );
347 }
348 }
349
350 mType = static_cast< Qgis::AttributeActionType >( actionElement.attributeNode( QStringLiteral( "type" ) ).value().toInt() );
351 mDescription = actionElement.attributeNode( QStringLiteral( "name" ) ).value();
352 mCommand = actionElement.attributeNode( QStringLiteral( "action" ) ).value();
353 mIcon = actionElement.attributeNode( QStringLiteral( "icon" ) ).value();
354 mCaptureOutput = actionElement.attributeNode( QStringLiteral( "capture" ) ).value().toInt() != 0;
355 mShortTitle = actionElement.attributeNode( QStringLiteral( "shortTitle" ) ).value();
356 mNotificationMessage = actionElement.attributeNode( QStringLiteral( "notificationMessage" ) ).value();
357 mIsEnabledOnlyWhenEditable = actionElement.attributeNode( QStringLiteral( "isEnabledOnlyWhenEditable" ) ).value().toInt() != 0;
358 mId = QUuid( actionElement.attributeNode( QStringLiteral( "id" ) ).value() );
359 if ( mId.isNull() )
360 mId = QUuid::createUuid();
361}
362
363void QgsAction::writeXml( QDomNode &actionsNode ) const
364{
365 QDomElement actionSetting = actionsNode.ownerDocument().createElement( QStringLiteral( "actionsetting" ) );
366 actionSetting.setAttribute( QStringLiteral( "type" ), static_cast< int >( mType ) );
367 actionSetting.setAttribute( QStringLiteral( "name" ), mDescription );
368 actionSetting.setAttribute( QStringLiteral( "shortTitle" ), mShortTitle );
369 actionSetting.setAttribute( QStringLiteral( "icon" ), mIcon );
370 actionSetting.setAttribute( QStringLiteral( "action" ), mCommand );
371 actionSetting.setAttribute( QStringLiteral( "capture" ), mCaptureOutput );
372 actionSetting.setAttribute( QStringLiteral( "notificationMessage" ), mNotificationMessage );
373 actionSetting.setAttribute( QStringLiteral( "isEnabledOnlyWhenEditable" ), mIsEnabledOnlyWhenEditable );
374 actionSetting.setAttribute( QStringLiteral( "id" ), mId.toString() );
375
376 const auto constMActionScopes = mActionScopes;
377 for ( const QString &scope : constMActionScopes )
378 {
379 QDomElement actionScopeElem = actionsNode.ownerDocument().createElement( QStringLiteral( "actionScope" ) );
380 actionScopeElem.setAttribute( QStringLiteral( "id" ), scope );
381 actionSetting.appendChild( actionScopeElem );
382 }
383
384 actionsNode.appendChild( actionSetting );
385}
386
388{
389 mExpressionContextScope = scope;
390}
391
393{
394 return mExpressionContextScope;
395}
396
397QString QgsAction::html() const
398{
399 QString typeText;
400 switch ( mType )
401 {
403 {
404 typeText = QObject::tr( "Generic" );
405 break;
406 }
408 {
409 typeText = QObject::tr( "Generic Python" );
410 break;
411 }
413 {
414 typeText = QObject::tr( "macOS" );
415 break;
416 }
418 {
419 typeText = QObject::tr( "Windows" );
420 break;
421 }
423 {
424 typeText = QObject::tr( "Unix" );
425 break;
426 }
428 {
429 typeText = QObject::tr( "Open URL" );
430 break;
431 }
433 {
434 typeText = QObject::tr( "Submit URL (urlencoded or JSON)" );
435 break;
436 }
438 {
439 typeText = QObject::tr( "Submit URL (multipart)" );
440 break;
441 }
442 }
443 return { QObject::tr( R"html(
444<h2>Action Details</h2>
445<p>
446 <b>Description:</b> %1<br>
447 <b>Short title:</b> %2<br>
448 <b>Type:</b> %3<br>
449 <b>Scope:</b> %4<br>
450 <b>Action:</b><br>
451 <pre>%6</pre>
452</p>
453 )html" ).arg( mDescription, mShortTitle, typeText, actionScopes().values().join( QLatin1String( ", " ) ), mCommand )};
454};
AttributeActionType
Attribute action types.
Definition qgis.h:4042
@ Mac
MacOS specific.
@ OpenUrl
Open URL action.
@ SubmitUrlMultipart
POST data to an URL using "multipart/form-data".
@ Windows
Windows specific.
@ SubmitUrlEncoded
POST data to an URL, using "application/x-www-form-urlencoded" or "application/json" if the body is v...
@ Critical
Critical/error message.
Definition qgis.h:102
QSet< QString > actionScopes() const
The action scopes define where an action will be available.
void readXml(const QDomNode &actionNode)
Reads an XML definition from actionNode into this object.
void run(QgsVectorLayer *layer, const QgsFeature &feature, const QgsExpressionContext &expressionContext) const
Run this action.
Definition qgsaction.cpp:78
void setCommand(const QString &newCommand)
Sets the action command.
bool runable() const
Checks if the action is runable on the current platform.
Definition qgsaction.cpp:41
bool isValid() const
Returns true if this action was a default constructed one.
Definition qgsaction.h:133
void setExpressionContextScope(const QgsExpressionContextScope &scope)
Sets an expression context scope to use for running the action.
QString html() const
Returns an HTML table with the basic information about this action.
void writeXml(QDomNode &actionsNode) const
Appends an XML definition for this action as a new child node to actionsNode.
QgsExpressionContextScope expressionContextScope() const
Returns an expression context scope used for running the action.
void setActionScopes(const QSet< QString > &actionScopes)
The action scopes define where an action will be available.
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
static QString replaceExpressionText(const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea=nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluat...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
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.
static bool run(const QString &command, const QString &messageOnError=QString())
Execute a Python statement.
static QgsRunProcess * create(const QString &action, bool capture)
Represents a vector layer which manages a vector based data sets.
#define QgsDebugError(str)
Definition qgslogger.h:38