QGIS API Documentation 4.1.0-Master (60fea48833c)
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
21#include "qgslogger.h"
22#include "qgsmessagelog.h"
24#include "qgspythonrunner.h"
25#include "qgsrunprocess.h"
26#include "qgsvariantutils.h"
27#include "qgsvectorlayer.h"
28
29#include <QApplication>
30#include <QDesktopServices>
31#include <QDir>
32#include <QFileInfo>
33#include <QHttpMultiPart>
34#include <QJsonDocument>
35#include <QMimeDatabase>
36#include <QNetworkRequest>
37#include <QString>
38#include <QTemporaryDir>
39#include <QUrl>
40#include <QUrlQuery>
41
42using namespace Qt::StringLiterals;
43
45{
46 // clang analyzer is not happy because of the multiple duplicate return branches, but this is ok :)
47 // NOLINTBEGIN(bugprone-branch-clone)
48 switch ( mType )
49 {
55 return true;
56
57#if defined( Q_OS_WIN )
59 return true;
62 return false;
63#elif defined( Q_OS_MAC )
65 return true;
68 return false;
69#else
71 return true;
74 return false;
75#endif
76 }
77 return false;
78 // NOLINTEND(bugprone-branch-clone)
79}
80
81void QgsAction::run( QgsVectorLayer *layer, const QgsFeature &feature, const QgsExpressionContext &expressionContext ) const
82{
83 QgsExpressionContext actionContext( expressionContext );
84
85 actionContext << QgsExpressionContextUtils::layerScope( layer );
86 actionContext.setFeature( feature );
87
88 run( actionContext );
89}
90
91void QgsAction::handleFormSubmitAction( const QString &expandedAction ) const
92{
93 // Show busy in case the form subit is slow
94 QApplication::setOverrideCursor( Qt::WaitCursor );
95
96 QUrl url { expandedAction };
97
98 // Encode '+' (fully encoded doesn't encode it)
99 const QString payload { url.query( QUrl::ComponentFormattingOption::FullyEncoded ).replace( QChar( '+' ), u"%2B"_s ) };
100
101 // Remove query string from URL
102 const QUrlQuery queryString { url.query() };
103 url.setQuery( QString() );
104
105 QNetworkRequest req { url };
106
107 // Specific code for testing, produces an invalid POST but we can still listen to
108 // signals and examine the request
109 if ( url.toString().contains( "fake_qgis_http_endpoint"_L1 ) )
110 {
111 req.setUrl( u"file://%1"_s.arg( url.path() ) );
112 }
113
114 QNetworkReply *reply = nullptr;
115
117 {
118 QString contentType { u"application/x-www-form-urlencoded"_s };
119 // check for json
120 QJsonParseError jsonError;
121 QJsonDocument::fromJson( payload.toUtf8(), &jsonError );
122 if ( jsonError.error == QJsonParseError::ParseError::NoError )
123 {
124 contentType = u"application/json"_s;
125 }
126 req.setHeader( QNetworkRequest::KnownHeaders::ContentTypeHeader, contentType );
127 reply = QgsNetworkAccessManager::instance()->post( req, payload.toUtf8() );
128 }
129 // for multipart create parts and headers
130 else
131 {
132 QHttpMultiPart *multiPart = new QHttpMultiPart( QHttpMultiPart::FormDataType );
133 const QList<QPair<QString, QString>> queryItems { queryString.queryItems( QUrl::ComponentFormattingOption::FullyDecoded ) };
134 for ( const QPair<QString, QString> &queryItem : std::as_const( queryItems ) )
135 {
136 QHttpPart part;
137 part.setHeader( QNetworkRequest::ContentDispositionHeader, u"form-data; name=\"%1\""_s.arg( QString( queryItem.first ).replace( '"', R"(\")"_L1 ) ) );
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 if ( reply->error() == QNetworkReply::NoError )
147 {
148 if ( QgsVariantUtils::isNull( reply->attribute( QNetworkRequest::RedirectionTargetAttribute ) ) )
149 {
150 const QByteArray replyData = reply->readAll();
151
152 QString filename { "download.bin" };
153 if ( const std::string header = reply->header( QNetworkRequest::KnownHeaders::ContentDispositionHeader ).toString().toStdString(); !header.empty() )
154 {
155 // Extract filename dealing with ill formed headers with unquoted file names
156
157 std::string ascii;
158
159 const std::string q1 { R"(filename=)" };
160
161 if ( size_t pos = header.find( q1 ); pos != std::string::npos )
162 {
163 // Deal with ill formed headers with unquoted file names
164 if ( header.find( R"(filename=")" ) != std::string::npos )
165 {
166 pos++;
167 }
168
169 const size_t len = pos + q1.size();
170
171 const std::string q2 { R"(")" };
172 if ( size_t pos = header.find( q2, len ); pos != std::string::npos )
173 {
174 bool escaped = false;
175 while ( pos != std::string::npos && header[pos - 1] == '\\' )
176 {
177 pos = header.find( q2, pos + 1 );
178 escaped = true;
179 }
180 ascii = header.substr( len, pos - len );
181 if ( escaped )
182 {
183 std::string cleaned;
184 for ( size_t i = 0; i < ascii.size(); ++i )
185 {
186 if ( ascii[i] == '\\' )
187 {
188 if ( i > 0 && ascii[i - 1] == '\\' )
189 {
190 cleaned.push_back( ascii[i] );
191 }
192 }
193 else
194 {
195 cleaned.push_back( ascii[i] );
196 }
197 }
198 ascii = std::move( cleaned );
199 }
200 }
201 }
202
203 std::string utf8;
204
205 const std::string u { R"(UTF-8'')" };
206 if ( const size_t pos = header.find( u ); pos != std::string::npos )
207 {
208 utf8 = header.substr( pos + u.size() );
209 }
210
211 // Prefer ascii over utf8
212 if ( ascii.empty() )
213 {
214 if ( !utf8.empty() )
215 {
216 filename = QString::fromStdString( utf8 );
217 }
218 }
219 else
220 {
221 filename = QString::fromStdString( ascii );
222 }
223 }
224 else if ( !QgsVariantUtils::isNull( reply->header( QNetworkRequest::KnownHeaders::ContentTypeHeader ) ) )
225 {
226 QString contentTypeHeader { reply->header( QNetworkRequest::KnownHeaders::ContentTypeHeader ).toString() };
227 // Strip charset if any
228 if ( contentTypeHeader.contains( ';' ) )
229 {
230 contentTypeHeader = contentTypeHeader.left( contentTypeHeader.indexOf( ';' ) );
231 }
232
233 QMimeType mimeType { QMimeDatabase().mimeTypeForName( contentTypeHeader ) };
234 if ( mimeType.isValid() )
235 {
236 filename = u"download.%1"_s.arg( mimeType.preferredSuffix() );
237 }
238 }
239
240 QTemporaryDir tempDir;
241 tempDir.setAutoRemove( false );
242 tempDir.path();
243 const QString tempFilePath { tempDir.path() + QDir::separator() + filename };
244 QFile tempFile { tempFilePath };
245 if ( tempFile.open( QIODevice::WriteOnly ) )
246 {
247 tempFile.write( replyData );
248 tempFile.close();
249 QDesktopServices::openUrl( QUrl::fromLocalFile( tempFilePath ) );
250 }
251 else
252 {
253 QgsMessageLog::logMessage( QObject::tr( "Could not open temporary file for writing" ), u"Form Submit Action"_s, Qgis::MessageLevel::Critical );
254 }
255 }
256 else
257 {
258 QgsMessageLog::logMessage( QObject::tr( "Redirect is not supported!" ), u"Form Submit Action"_s, Qgis::MessageLevel::Critical );
259 }
260 }
261 else
262 {
263 QgsMessageLog::logMessage( reply->errorString(), u"Form Submit Action"_s, Qgis::MessageLevel::Critical );
264 }
265 reply->deleteLater();
266 QApplication::restoreOverrideCursor();
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( u"Invalid action cannot be run"_s );
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, const QgsReadWriteContext &context )
330{
331 QDomElement actionElement = actionNode.toElement();
332 const QDomNodeList actionScopeNodes = actionElement.elementsByTagName( u"actionScope"_s );
333
334 if ( actionScopeNodes.isEmpty() )
335 {
336 mActionScopes << u"Canvas"_s << u"Field"_s << u"Feature"_s;
337 }
338 else
339 {
340 for ( int j = 0; j < actionScopeNodes.length(); ++j )
341 {
342 const QDomElement actionScopeElem = actionScopeNodes.item( j ).toElement();
343 mActionScopes << actionScopeElem.attribute( u"id"_s );
344 }
345 }
346
347 mType = static_cast< Qgis::AttributeActionType >( actionElement.attributeNode( u"type"_s ).value().toInt() );
348 mDescription = context.projectTranslator()->translate( u"project:layers:%1:actiondescriptions"_s.arg( context.currentLayerId() ), actionElement.attributeNode( u"name"_s ).value() );
349 QgsDebugMsgLevel( "context" + u"project:layers:%1:actiondescriptions"_s.arg( context.currentLayerId() ) + " source " + actionElement.attributeNode( u"name"_s ).value(), 3 );
350 mCommand = actionElement.attributeNode( u"action"_s ).value();
351 mIcon = actionElement.attributeNode( u"icon"_s ).value();
352 mCaptureOutput = actionElement.attributeNode( u"capture"_s ).value().toInt() != 0;
353 mShortTitle = context.projectTranslator()->translate( u"project:layers:%1:actionshorttitles"_s.arg( context.currentLayerId() ), actionElement.attributeNode( u"shortTitle"_s ).value() );
354 QgsDebugMsgLevel( "context" + u"project:layers:%1:actionshorttitles"_s.arg( context.currentLayerId() ) + " source " + actionElement.attributeNode( u"shortTitle"_s ).value(), 3 );
355 mNotificationMessage = actionElement.attributeNode( u"notificationMessage"_s ).value();
356 mIsEnabledOnlyWhenEditable = actionElement.attributeNode( u"isEnabledOnlyWhenEditable"_s ).value().toInt() != 0;
357 mId = QUuid( actionElement.attributeNode( u"id"_s ).value() );
358 if ( mId.isNull() )
359 mId = QUuid::createUuid();
360}
361
362void QgsAction::writeXml( QDomNode &actionsNode ) const
363{
364 QDomElement actionSetting = actionsNode.ownerDocument().createElement( u"actionsetting"_s );
365 actionSetting.setAttribute( u"type"_s, static_cast< int >( mType ) );
366 actionSetting.setAttribute( u"name"_s, mDescription );
367 actionSetting.setAttribute( u"shortTitle"_s, mShortTitle );
368 actionSetting.setAttribute( u"icon"_s, mIcon );
369 actionSetting.setAttribute( u"action"_s, mCommand );
370 actionSetting.setAttribute( u"capture"_s, mCaptureOutput );
371 actionSetting.setAttribute( u"notificationMessage"_s, mNotificationMessage );
372 actionSetting.setAttribute( u"isEnabledOnlyWhenEditable"_s, mIsEnabledOnlyWhenEditable );
373 actionSetting.setAttribute( u"id"_s, mId.toString() );
374
375 const auto constMActionScopes = mActionScopes;
376 for ( const QString &scope : constMActionScopes )
377 {
378 QDomElement actionScopeElem = actionsNode.ownerDocument().createElement( u"actionScope"_s );
379 actionScopeElem.setAttribute( u"id"_s, scope );
380 actionSetting.appendChild( actionScopeElem );
381 }
382
383 actionsNode.appendChild( actionSetting );
384}
385
387{
388 mExpressionContextScope = scope;
389}
390
392{
393 return mExpressionContextScope;
394}
395
396QString QgsAction::html() const
397{
398 QString typeText;
399 switch ( mType )
400 {
402 {
403 typeText = QObject::tr( "Generic" );
404 break;
405 }
407 {
408 typeText = QObject::tr( "Generic Python" );
409 break;
410 }
412 {
413 typeText = QObject::tr( "macOS" );
414 break;
415 }
417 {
418 typeText = QObject::tr( "Windows" );
419 break;
420 }
422 {
423 typeText = QObject::tr( "Unix" );
424 break;
425 }
427 {
428 typeText = QObject::tr( "Open URL" );
429 break;
430 }
432 {
433 typeText = QObject::tr( "Submit URL (urlencoded or JSON)" );
434 break;
435 }
437 {
438 typeText = QObject::tr( "Submit URL (multipart)" );
439 break;
440 }
441 }
442 return { QObject::tr( R"html(
443<h2>Action Details</h2>
444<p>
445 <b>Description:</b> %1<br>
446 <b>Short title:</b> %2<br>
447 <b>Type:</b> %3<br>
448 <b>Scope:</b> %4<br>
449 <b>Action:</b><br>
450 <pre>%6</pre>
451</p>
452 )html" )
453 .arg( mDescription, mShortTitle, typeText, actionScopes().values().join( ", "_L1 ), mCommand ) };
454};
AttributeActionType
Attribute action types.
Definition qgis.h:4832
@ Mac
MacOS specific.
Definition qgis.h:4835
@ OpenUrl
Open URL action.
Definition qgis.h:4838
@ Unix
Unix specific.
Definition qgis.h:4837
@ SubmitUrlMultipart
POST data to an URL using "multipart/form-data".
Definition qgis.h:4840
@ Windows
Windows specific.
Definition qgis.h:4836
@ SubmitUrlEncoded
POST data to an URL, using "application/x-www-form-urlencoded" or "application/json" if the body is v...
Definition qgis.h:4839
@ Critical
Critical/error message.
Definition qgis.h:163
QSet< QString > actionScopes() const
The action scopes define where an action will be available.
void run(QgsVectorLayer *layer, const QgsFeature &feature, const QgsExpressionContext &expressionContext) const
Run this action.
Definition qgsaction.cpp:81
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:44
bool isValid() const
Returns true if this action was a default constructed one.
Definition qgsaction.h:151
void readXml(const QDomNode &actionNode, const QgsReadWriteContext &context=QgsReadWriteContext())
Reads an XML definition from actionNode into this object.
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:60
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
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.
virtual QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const =0
Translates a string using the Qt QTranslator mechanism.
static bool run(const QString &command, const QString &messageOnError=QString())
Execute a Python statement.
A container for the context for various read/write operations on objects.
const QgsProjectTranslator * projectTranslator() const
Returns the project translator.
const QString currentLayerId() const
Returns the currently used layer id as string.
static QgsRunProcess * create(const QString &action, bool capture)
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based dataset.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59