19#include <QDesktopServices>
24#include <QTemporaryDir>
25#include <QNetworkRequest>
26#include <QJsonDocument>
27#include <QHttpMultiPart>
28#include <QMimeDatabase>
29#include <QApplication>
51#elif defined(Q_OS_MAC)
69void QgsAction::handleFormSubmitAction(
const QString &expandedAction )
const
73 QApplication::setOverrideCursor( Qt::WaitCursor );
75 QUrl url{ expandedAction };
78 const QString payload { url.query( QUrl::ComponentFormattingOption::FullyEncoded ).replace( QChar(
'+' ), QStringLiteral(
"%2B" ) ) };
81 const QUrlQuery queryString { url.query( ) };
82 url.setQuery( QString( ) );
84 QNetworkRequest req { url };
88 if ( url.toString().contains( QLatin1String(
"fake_qgis_http_endpoint" ) ) )
90 req.setUrl( QStringLiteral(
"file://%1" ).arg( url.path() ) );
93 QNetworkReply *reply =
nullptr;
97 QString contentType { QStringLiteral(
"application/x-www-form-urlencoded" ) };
99 QJsonParseError jsonError;
100 QJsonDocument::fromJson( payload.toUtf8(), &jsonError );
101 if ( jsonError.error == QJsonParseError::ParseError::NoError )
103 contentType = QStringLiteral(
"application/json" );
105 req.setHeader( QNetworkRequest::KnownHeaders::ContentTypeHeader, contentType );
111 QHttpMultiPart *multiPart =
new QHttpMultiPart( QHttpMultiPart::FormDataType );
112 const QList<QPair<QString, QString>> queryItems { queryString.queryItems( QUrl::ComponentFormattingOption::FullyDecoded ) };
113 for (
const QPair<QString, QString> &queryItem : std::as_const( queryItems ) )
116 part.setHeader( QNetworkRequest::ContentDispositionHeader,
117 QStringLiteral(
"form-data; name=\"%1\"" )
118 .arg( QString( queryItem.first ).replace(
'"', QLatin1String( R
"(\")" ) ) ) );
119 part.setBody( queryItem.second.toUtf8() );
120 multiPart->append( part );
123 multiPart->setParent( reply );
126 QObject::connect( reply, &QNetworkReply::finished, reply, [ reply ]
128 if ( reply->error() == QNetworkReply::NoError )
131 if ( QgsVariantUtils::isNull( reply->attribute( QNetworkRequest::RedirectionTargetAttribute ) ) )
134 const QByteArray replyData = reply->readAll();
136 QString filename {
"download.bin" };
137 if ( const std::string header = reply->header( QNetworkRequest::KnownHeaders::ContentDispositionHeader ).toString().toStdString(); ! header.empty() )
144 const std::string q1 { R
"(filename=)" };
146 if ( size_t pos = header.find( q1 ); pos != std::string::npos )
150 if ( header.find( R
"(filename=")" ) != std::string::npos )
155 const size_t len = pos + q1.size();
157 const std::string q2 { R"(")" };
158 if ( size_t pos = header.find( q2, len ); pos != std::string::npos )
160 bool escaped = false;
161 while ( pos != std::string::npos && header[pos - 1] == '\\' )
163 pos = header.find( q2, pos + 1 );
166 ascii = header.substr( len, pos - len );
170 for ( size_t i = 0; i < ascii.size(); ++i )
172 if ( ascii[i] ==
'\\' )
174 if ( i > 0 && ascii[i - 1] ==
'\\' )
176 cleaned.push_back( ascii[i] );
181 cleaned.push_back( ascii[i] );
191 const std::string u { R
"(UTF-8'')" };
192 if ( const size_t pos = header.find( u ); pos != std::string::npos )
194 utf8 = header.substr( pos + u.size() );
200 if ( ! utf8.empty( ) )
202 filename = QString::fromStdString( utf8 );
207 filename = QString::fromStdString( ascii );
210 else if ( !QgsVariantUtils::isNull( reply->header( QNetworkRequest::KnownHeaders::ContentTypeHeader ) ) )
212 QString contentTypeHeader { reply->header( QNetworkRequest::KnownHeaders::ContentTypeHeader ).toString() };
214 if ( contentTypeHeader.contains(
';' ) )
216 contentTypeHeader = contentTypeHeader.left( contentTypeHeader.indexOf(
';' ) );
219 QMimeType mimeType { QMimeDatabase().mimeTypeForName( contentTypeHeader ) };
220 if ( mimeType.isValid() )
222 filename = QStringLiteral(
"download.%1" ).arg( mimeType.preferredSuffix() );
226 QTemporaryDir tempDir;
227 tempDir.setAutoRemove( false );
229 const QString tempFilePath{ tempDir.path() + QDir::separator() + filename };
230 QFile tempFile{ tempFilePath };
231 tempFile.open( QIODevice::WriteOnly );
232 tempFile.write( replyData );
234 QDesktopServices::openUrl( QUrl::fromLocalFile( tempFilePath ) );
238 QgsMessageLog::logMessage( QObject::tr(
"Redirect is not supported!" ), QStringLiteral(
"Form Submit Action" ), Qgis::MessageLevel::Critical );
245 reply->deleteLater();
246 QApplication::restoreOverrideCursor( );
253 mCommand = newCommand;
260 QgsDebugMsg( QStringLiteral(
"Invalid action cannot be run" ) );
269 QApplication::setOverrideCursor( Qt::WaitCursor );
271 QApplication::restoreOverrideCursor();
275 const QFileInfo finfo( expandedAction );
276 if ( finfo.exists() && finfo.isFile() )
277 QDesktopServices::openUrl( QUrl::fromLocalFile( expandedAction ) );
279 QDesktopServices::openUrl( QUrl( expandedAction, QUrl::TolerantMode ) );
283 handleFormSubmitAction( expandedAction );
300 return mActionScopes;
310 QDomElement actionElement = actionNode.toElement();
311 const QDomNodeList actionScopeNodes = actionElement.elementsByTagName( QStringLiteral(
"actionScope" ) );
313 if ( actionScopeNodes.isEmpty() )
316 << QStringLiteral(
"Canvas" )
317 << QStringLiteral(
"Field" )
318 << QStringLiteral(
"Feature" );
322 for (
int j = 0; j < actionScopeNodes.length(); ++j )
324 const QDomElement actionScopeElem = actionScopeNodes.item( j ).toElement();
325 mActionScopes << actionScopeElem.attribute( QStringLiteral(
"id" ) );
329 mType =
static_cast< QgsAction::ActionType >( actionElement.attributeNode( QStringLiteral(
"type" ) ).value().toInt() );
330 mDescription = actionElement.attributeNode( QStringLiteral(
"name" ) ).value();
331 mCommand = actionElement.attributeNode( QStringLiteral(
"action" ) ).value();
332 mIcon = actionElement.attributeNode( QStringLiteral(
"icon" ) ).value();
333 mCaptureOutput = actionElement.attributeNode( QStringLiteral(
"capture" ) ).value().toInt() != 0;
334 mShortTitle = actionElement.attributeNode( QStringLiteral(
"shortTitle" ) ).value();
335 mNotificationMessage = actionElement.attributeNode( QStringLiteral(
"notificationMessage" ) ).value();
336 mIsEnabledOnlyWhenEditable = actionElement.attributeNode( QStringLiteral(
"isEnabledOnlyWhenEditable" ) ).value().toInt() != 0;
337 mId = QUuid( actionElement.attributeNode( QStringLiteral(
"id" ) ).value() );
339 mId = QUuid::createUuid();
344 QDomElement actionSetting = actionsNode.ownerDocument().createElement( QStringLiteral(
"actionsetting" ) );
345 actionSetting.setAttribute( QStringLiteral(
"type" ), mType );
346 actionSetting.setAttribute( QStringLiteral(
"name" ), mDescription );
347 actionSetting.setAttribute( QStringLiteral(
"shortTitle" ), mShortTitle );
348 actionSetting.setAttribute( QStringLiteral(
"icon" ), mIcon );
349 actionSetting.setAttribute( QStringLiteral(
"action" ), mCommand );
350 actionSetting.setAttribute( QStringLiteral(
"capture" ), mCaptureOutput );
351 actionSetting.setAttribute( QStringLiteral(
"notificationMessage" ), mNotificationMessage );
352 actionSetting.setAttribute( QStringLiteral(
"isEnabledOnlyWhenEditable" ), mIsEnabledOnlyWhenEditable );
353 actionSetting.setAttribute( QStringLiteral(
"id" ), mId.toString() );
355 const auto constMActionScopes = mActionScopes;
356 for (
const QString &scope : constMActionScopes )
358 QDomElement actionScopeElem = actionsNode.ownerDocument().createElement( QStringLiteral(
"actionScope" ) );
359 actionScopeElem.setAttribute( QStringLiteral(
"id" ), scope );
360 actionSetting.appendChild( actionScopeElem );
363 actionsNode.appendChild( actionSetting );
368 mExpressionContextScope = scope;
373 return mExpressionContextScope;
383 typeText = QObject::tr(
"Generic" );
388 typeText = QObject::tr(
"Generic Python" );
393 typeText = QObject::tr(
"Mac" );
398 typeText = QObject::tr(
"Windows" );
403 typeText = QObject::tr(
"Unix" );
408 typeText = QObject::tr(
"Open URL" );
413 typeText = QObject::tr(
"Submit URL (urlencoded or JSON)" );
418 typeText = QObject::tr(
"Submit URL (multipart)" );
422 return { QObject::tr( R
"html(
423<h2>Action Details</h2>
425 <b>Description:</b> %1<br>
426 <b>Short title:</b> %2<br>
432 )html" ).arg( mDescription, mShortTitle, typeText, actionScopes().values().join( QLatin1String( ", " ) ), mCommand )};
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.
void setCommand(const QString &newCommand)
Sets the action command.
bool runable() const
Checks if the action is runable on the current platform.
bool isValid() const
Returns true if this action was a default constructed one.
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.
@ SubmitUrlEncoded
POST data to an URL, using "application/x-www-form-urlencoded" or "application/json" if the body is v...
@ SubmitUrlMultipart
POST data to an URL using "multipart/form-data".
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...
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.