18#ifndef QGSNETWORKACCESSMANAGER_H
19#define QGSNETWORKACCESSMANAGER_H
30#include <QNetworkAccessManager>
31#include <QNetworkCookie>
32#include <QNetworkCookieJar>
33#include <QNetworkProxy>
34#include <QNetworkRequest>
38#include <QWaitCondition>
40using namespace Qt::StringLiterals;
77 QNetworkAccessManager::Operation
operation()
const {
return mOperation; }
85 QNetworkRequest
request()
const {
return mRequest; }
101 QByteArray
content()
const {
return mContent; }
125 QNetworkAccessManager::Operation mOperation = QNetworkAccessManager::Operation::UnknownOperation;
126 QNetworkRequest mRequest;
127 QString mOriginatingThreadId;
130 QString mInitiatorClass;
131 QVariant mInitiatorRequestId;
181 virtual void handleSslErrors( QNetworkReply *reply,
const QList<QSslError> &errors );
324 void setAuthHandler( std::unique_ptr< QgsNetworkAuthenticationHandler > handler );
456 static int timeout();
465 static void setTimeout(
int time );
516 QNetworkRequest &request,
517 const QByteArray &data,
518 const QString &authCfg = QString(),
519 bool forceRefresh =
false,
536 static QString setRequestPreprocessor(
const std::function<
void( QNetworkRequest *request )> &processor );
539 static QString setRequestPreprocessor( SIP_PYCALLABLE / AllowNone / );
544 Py_BEGIN_ALLOW_THREADS
549 PyObject *s = sipCallMethod( NULL, a0,
"D", arg, sipType_QNetworkRequest, NULL );
552 QString *t1 =
reinterpret_cast<QString *
>( sipConvertToType( s, sipType_QString, 0, SIP_NOT_NONE, &state, &sipIsError ) );
553 if ( sipIsError == 0 )
555 res = QString( *t1 );
557 sipReleaseType( t1, sipType_QString, state );
563 s = sipConvertFromNewType(
new QString(
id ), sipType_QString, 0 );
580 static bool removeRequestPreprocessor(
const QString &
id );
583 static void removeRequestPreprocessor(
const QString &
id );
587 PyErr_SetString( PyExc_KeyError, u
"No processor with id %1 exists."_s.arg( *a0 ).toUtf8().constData() );
610 static QString setAdvancedRequestPreprocessor(
const std::function<
void( QNetworkRequest *,
int &op, QByteArray *data )> &processor );
613 static QString setAdvancedRequestPreprocessor( SIP_PYCALLABLE / AllowNone / );
618 Py_BEGIN_ALLOW_THREADS
623 PyObject *requestObj = sipConvertFromType( reqArg, sipType_QNetworkRequest, NULL );
624 PyObject *postDataObj = sipConvertFromType(
new QByteArray( *data ), sipType_QByteArray, Py_None );
626 PyObject *result = sipCallMethod( NULL, a0,
"RiR", requestObj, op, postDataObj );
628 Py_XDECREF( requestObj );
629 Py_XDECREF( postDataObj );
631 if ( result && PyTuple_Check( result ) && PyTuple_Size( result ) == 2 )
634 PyObject *opObj = PyTuple_GetItem( result, 0 );
635 if ( opObj && PyLong_Check( opObj ) )
637 op =
static_cast<int>( PyLong_AsLong( opObj ) );
639 PyObject *dataObj = PyTuple_GetItem( result, 1 );
640 if ( dataObj && dataObj != Py_None )
644 QByteArray *modifiedData =
reinterpret_cast<QByteArray *
>( sipConvertToType( dataObj, sipType_QByteArray, 0, SIP_NOT_NONE, &dataState, &sipIsErr ) );
648 data->append( *modifiedData );
649 sipReleaseType( modifiedData, sipType_QByteArray, dataState );
654 Py_XDECREF( result );
659 s = sipConvertFromNewType(
new QString(
id ), sipType_QString, 0 );
676 static bool removeAdvancedRequestPreprocessor(
const QString &
id );
679 static void removeAdvancedRequestPreprocessor(
const QString &
id );
683 PyErr_SetString( PyExc_KeyError, u
"No processor with id %1 exists."_s.arg( *a0 ).toUtf8().constData() );
703 static QString setReplyPreprocessor(
const std::function<
void(
const QNetworkRequest &, QNetworkReply * )> &processor );
706 static QString setReplyPreprocessor( SIP_PYCALLABLE / AllowNone / );
711 Py_BEGIN_ALLOW_THREADS
715 Py_XDECREF( sipCallMethod( NULL, a0,
"ND",
new QNetworkRequest( request ), sipType_QNetworkRequest, NULL, reply, sipType_QNetworkReply, NULL ) );
720 s = sipConvertFromNewType(
new QString(
id ), sipType_QString, 0 );
737 static bool removeReplyPreprocessor(
const QString &
id );
740 static void removeReplyPreprocessor(
const QString &
id );
744 PyErr_SetString( PyExc_KeyError, u
"No processor with id %1 exists."_s.arg( *a0 ).toUtf8().constData() );
757 void requestAuthOpenBrowser(
const QUrl &url )
const;
765 void requestAuthCloseBrowser()
const;
773 void abortAuthBrowser();
943 void sslErrorsOccurred( QNetworkReply *,
const QList<QSslError> &errors );
944 void sslErrorsHandled( QNetworkReply *reply );
963 void authRequestOccurred( QNetworkReply *, QAuthenticator *auth );
964 void authRequestHandled( QNetworkReply *reply );
985 void onReplyFinished( QNetworkReply *reply );
987 void onReplyDownloadProgress( qint64 bytesReceived, qint64 bytesTotal );
989 void onReplySslErrors(
const QList<QSslError> &errors );
991 void handleSslErrors( QNetworkReply *reply,
const QList<QSslError> &errors );
994 void onAuthRequired( QNetworkReply *reply, QAuthenticator *auth );
995 void handleAuthRequest( QNetworkReply *reply, QAuthenticator *auth );
997 void syncCookies(
const QList<QNetworkCookie> &cookies );
1000 QNetworkReply *
createRequest( QNetworkAccessManager::Operation op,
const QNetworkRequest &req, QIODevice *outgoingData =
nullptr )
override;
1004 void afterSslErrorHandled( QNetworkReply *reply );
1007 void afterAuthRequestHandled( QNetworkReply *reply );
1009 void pauseTimeout( QNetworkReply *reply );
1010 void restartTimeout( QNetworkReply *reply );
1011 static int getRequestId( QNetworkReply *reply );
1013 QList<QNetworkProxyFactory *> mProxyFactories;
1014 QNetworkProxy mFallbackProxy;
1015 QStringList mExcludedURLs;
1016 QStringList mNoProxyURLs;
1017 bool mUseSystemProxy =
false;
1018 bool mInitialized =
false;
1019 bool mCacheDisabled =
false;
1022 std::unique_ptr< QgsSslErrorHandler > mSslErrorHandler;
1024 QSemaphore mSslErrorHandlerSemaphore;
1027 std::unique_ptr< QgsNetworkAuthenticationHandler > mAuthHandler;
1029 QSemaphore mAuthRequestHandlerSemaphore;
QFlags< NetworkRequestFlag > NetworkRequestFlags
Flags controlling behavior of network requests.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
QNetworkAccessManager with additional QGIS specific logic.
QStringList noProxyList() const
Returns the no proxy list.
void finished(QgsNetworkReplyContent reply)
Emitted whenever a pending network reply is finished.
static const QgsSettingsEntryString * settingsProxyAuthCfg
Settings entry for proxy authentication configuration.
static const QgsSettingsEntryInteger * settingsNetworkTimeout
Settings entry network timeout.
void cookiesChanged(const QList< QNetworkCookie > &cookies)
Emitted when the cookies changed.
void insertProxyFactory(QNetworkProxyFactory *factory)
Inserts a factory into the proxy factories list.
void setSslErrorHandler(std::unique_ptr< QgsSslErrorHandler > handler)
Sets the application SSL error handler, which is used to respond to SSL errors encountered during net...
Q_DECL_DEPRECATED void requestAboutToBeCreated(QNetworkAccessManager::Operation operation, const QNetworkRequest &request, QIODevice *device)
void setCacheDisabled(bool disabled)
Sets whether all network caching should be disabled.
const QList< QNetworkProxyFactory * > proxyFactories() const
Returns a list of proxy factories used by the manager.
void downloadProgress(int requestId, qint64 bytesReceived, qint64 bytesTotal)
Emitted when a network reply receives a progress report.
void requestEncounteredSslErrors(int requestId, const QList< QSslError > &errors)
Emitted when a network request encounters SSL errors.
static const QgsSettingsEntryString * settingsProxyUser
Settings entry for proxy user.
static QString cacheLoadControlName(QNetworkRequest::CacheLoadControl control)
Returns the name for QNetworkRequest::CacheLoadControl.
static const QgsSettingsEntryString * settingsProxyHost
Settings entry for proxy host.
void requestAboutToBeCreated(QgsNetworkRequestParameters request)
Emitted when a network request is about to be created.
void requestCreated(const QgsNetworkRequestParameters &request)
Emitted when a network request has been created.
static QString setReplyPreprocessor(const std::function< void(const QNetworkRequest &, QNetworkReply *)> &processor)
Sets a reply pre-processor function, which allows manipulation of QNetworkReply objects after they ar...
static bool removeRequestPreprocessor(const QString &id)
Removes the custom request pre-processor function with matching id.
void requestAuthDetailsAdded(int requestId, const QString &realm, const QString &user, const QString &password)
Emitted when network authentication details have been added to a request.
void requestTimedOut(QNetworkReply *reply)
Emitted when a request times out.
friend class TestQgsNetworkAccessManager
static QString userAgent()
Returns the user agent string used by QGIS for network requests.
static const QgsSettingsEntryString * settingsProxyPort
Settings entry for proxy port.
static QNetworkRequest::CacheLoadControl cacheLoadControlFromName(const QString &name)
Returns QNetworkRequest::CacheLoadControl from a name.
bool cacheDisabled() const
Returns true if all network caching is disabled.
static const QgsSettingsEntryString * settingsProxyExcludedUrls
Settings entry for proxy excluded URLs (legacy, falls back to system proxy for these).
static bool removeAdvancedRequestPreprocessor(const QString &id)
Removes an advanced request pre-processor function with matching id.
QgsNetworkAccessManager(QObject *parent=nullptr)
void requestRequiresAuth(int requestId, const QString &realm)
Emitted when a network request prompts an authentication request.
void preprocessRequest(QNetworkRequest *req) const
Preprocesses request.
void setAuthHandler(std::unique_ptr< QgsNetworkAuthenticationHandler > handler)
Sets the application network authentication handler, which is used to respond to network authenticati...
static QString setAdvancedRequestPreprocessor(const std::function< void(QNetworkRequest *, int &op, QByteArray *data)> &processor)
Sets an advanced request pre-processor function, which allows manipulation of a network request befor...
const QNetworkProxy & fallbackProxy() const
Returns the fallback proxy used by the manager.
static const QgsSettingsEntryString * settingsUserAgent
Settings entry for user agent string.
static const QgsSettingsEntryBool * settingsProxyEnabled
Settings entry for whether proxy is enabled.
void setupDefaultProxyAndCache(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Setup the QgsNetworkAccessManager (NAM) according to the user's settings.
static QString setRequestPreprocessor(const std::function< void(QNetworkRequest *request)> &processor)
Sets a request pre-processor function, which allows manipulation of a network request before it is pr...
void setFallbackProxyAndExcludes(const QNetworkProxy &proxy, const QStringList &excludes, const QStringList &noProxyURLs)
Sets the fallback proxy and URLs which shouldn't use it.
static const QgsSettingsEntryString * settingsProxyPassword
Settings entry for proxy password.
static bool removeReplyPreprocessor(const QString &id)
Removes the custom reply pre-processor function with matching id.
Q_DECL_DEPRECATED void requestCreated(QNetworkReply *reply)
QStringList excludeList() const
Returns the proxy exclude list.
static const QgsSettingsEntryStringList * settingsNoProxyUrls
Settings entry for no-proxy URLs.
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
void removeProxyFactory(QNetworkProxyFactory *factory)
Removes a factory from the proxy factories list.
static const QgsSettingsEntryString * settingsProxyType
Settings entry for proxy type.
void authBrowserAborted()
Emitted when external browser logins are to be aborted.
void requestTimedOut(QgsNetworkRequestParameters request)
Emitted when a network request has timed out.
bool useSystemProxy() const
Returns whether the system proxy should be used.
QNetworkReply * createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData=nullptr) override
Network authentication handler, used for responding to network authentication requests during network...
virtual ~QgsNetworkAuthenticationHandler()=default
virtual void handleAuthRequest(QNetworkReply *reply, QAuthenticator *auth)
Called whenever network authentication requests are encountered during a network reply.
virtual void handleAuthRequestCloseBrowser()
Called to terminate a network authentication through external browser.
virtual void handleAuthRequestOpenBrowser(const QUrl &url)
Called to initiate a network authentication through external browser url.
Encapsulates a network reply within a container which is inexpensive to copy and safe to pass between...
Encapsulates parameters and properties of a network request.
int requestId() const
Returns a unique ID identifying the request.
RequestAttributes
Custom request attributes.
@ AttributeUserAgentSuffix
Custom string to append to the default User-Agent header.
@ AttributeOriginalHeaders
Internal ID used to store original request headers, used when checking against previously cached resp...
@ AttributeInitiatorClass
Class name of original object which created the request.
@ AttributeInitiatorRequestId
Internal ID used by originator object to identify requests.
QgsNetworkRequestParameters()=default
QNetworkAccessManager::Operation operation() const
Returns the request operation, e.g.
QNetworkRequest request() const
Returns the network request.
QString originatingThreadId() const
Returns a string identifying the thread which the request originated from.
QString initiatorClassName() const
Returns the class name of the object which initiated this request.
QByteArray content() const
Returns the request's content.
QVariant initiatorRequestId() const
Returns the internal ID used by the object which initiated this request to identify individual reques...
A boolean settings entry.
An integer settings entry.
A string list settings entry.
SSL error handler, used for responding to SSL errors encountered during network requests.
virtual ~QgsSslErrorHandler()=default
virtual void handleSslErrors(QNetworkReply *reply, const QList< QSslError > &errors)
Called whenever SSL errors are encountered during a network reply.