QGIS API Documentation 4.5.0-Master (3b5d115045b)
Loading...
Searching...
No Matches
qgsnetworkaccessmanager.h
Go to the documentation of this file.
1/***************************************************************************
2 qgsnetworkaccessmanager.h - description
3 -------------------
4 begin : 2010-05-08
5 copyright : (C) 2010 by Juergen E. Fischer
6 email : jef at norbit dot de
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
18#ifndef QGSNETWORKACCESSMANAGER_H
19#define QGSNETWORKACCESSMANAGER_H
20
21#include <memory>
22
23#include "qgis.h"
24#include "qgis_core.h"
25#include "qgis_sip.h"
26#include "qgsnetworkreply.h"
27
28#include <QList>
29#include <QMutex>
30#include <QNetworkAccessManager>
31#include <QNetworkCookie>
32#include <QNetworkCookieJar>
33#include <QNetworkProxy>
34#include <QNetworkRequest>
35#include <QSemaphore>
36#include <QString>
37#include <QStringList>
38#include <QWaitCondition>
39
40using namespace Qt::StringLiterals;
41
42class QgsFeedback;
47
55{
56 public:
65
67
72 QgsNetworkRequestParameters( QNetworkAccessManager::Operation operation, const QNetworkRequest &request, int requestId, const QByteArray &content = QByteArray() );
73
77 QNetworkAccessManager::Operation operation() const { return mOperation; }
78
85 QNetworkRequest request() const { return mRequest; }
86
90 QString originatingThreadId() const { return mOriginatingThreadId; }
91
95 int requestId() const { return mRequestId; }
96
101 QByteArray content() const { return mContent; }
102
111 QString initiatorClassName() const { return mInitiatorClass; }
112
122 QVariant initiatorRequestId() const { return mInitiatorRequestId; }
123
124 private:
125 QNetworkAccessManager::Operation mOperation = QNetworkAccessManager::Operation::UnknownOperation;
126 QNetworkRequest mRequest;
127 QString mOriginatingThreadId;
128 int mRequestId = 0;
129 QByteArray mContent;
130 QString mInitiatorClass;
131 QVariant mInitiatorRequestId;
132};
133
135
136#ifndef SIP_RUN
137
166class CORE_EXPORT QgsSslErrorHandler
167{
168 public:
169 virtual ~QgsSslErrorHandler() = default;
170
181 virtual void handleSslErrors( QNetworkReply *reply, const QList<QSslError> &errors );
182};
183
208{
209 public:
211
220 virtual void handleAuthRequest( QNetworkReply *reply, QAuthenticator *auth );
221
227 virtual void handleAuthRequestOpenBrowser( const QUrl &url );
228
234 virtual void handleAuthRequestCloseBrowser();
235};
236#endif
237
238
254class CORE_EXPORT QgsNetworkAccessManager : public QNetworkAccessManager
255{
256 Q_OBJECT
257
258 public:
277 static QgsNetworkAccessManager *instance( Qt::ConnectionType connectionType = Qt::BlockingQueuedConnection ) SIP_DISALLOWNONE;
278
279 QgsNetworkAccessManager( QObject *parent = nullptr );
280
286 static QString userAgent();
287
288#ifndef SIP_RUN
289
306 void setSslErrorHandler( std::unique_ptr< QgsSslErrorHandler > handler );
307
324 void setAuthHandler( std::unique_ptr< QgsNetworkAuthenticationHandler > handler );
325#endif
326
335 void insertProxyFactory( QNetworkProxyFactory *factory SIP_TRANSFER );
336
343 void removeProxyFactory( QNetworkProxyFactory *factory SIP_TRANSFERBACK );
344
351 const QList<QNetworkProxyFactory *> proxyFactories() const;
352
361 const QNetworkProxy &fallbackProxy() const;
362
372 QStringList excludeList() const;
373
383 QStringList noProxyList() const;
384
396 void setFallbackProxyAndExcludes( const QNetworkProxy &proxy, const QStringList &excludes, const QStringList &noProxyURLs );
397
403 static QString cacheLoadControlName( QNetworkRequest::CacheLoadControl control );
404
410 static QNetworkRequest::CacheLoadControl cacheLoadControlFromName( const QString &name );
411
419 void setupDefaultProxyAndCache( Qt::ConnectionType connectionType = Qt::BlockingQueuedConnection );
420
421#ifndef SIP_RUN
422
430 bool cacheDisabled() const { return mCacheDisabled; }
431
442 void setCacheDisabled( bool disabled ) { mCacheDisabled = disabled; }
443#endif
444
448 bool useSystemProxy() const { return mUseSystemProxy; }
449
456 static int timeout();
457
465 static void setTimeout( int time );
466
489 static QgsNetworkReplyContent blockingGet(
490 QNetworkRequest &request, const QString &authCfg = QString(), bool forceRefresh = false, QgsFeedback *feedback = nullptr, Qgis::NetworkRequestFlags flags = Qgis::NetworkRequestFlags()
491 );
492
515 static QgsNetworkReplyContent blockingPost(
516 QNetworkRequest &request,
517 const QByteArray &data,
518 const QString &authCfg = QString(),
519 bool forceRefresh = false,
520 QgsFeedback *feedback = nullptr,
522 );
523
535#ifndef SIP_RUN
536 static QString setRequestPreprocessor( const std::function< void( QNetworkRequest *request )> &processor );
537#else
538 // clang-format off
539 static QString setRequestPreprocessor( SIP_PYCALLABLE / AllowNone / );
540 % MethodCode
541 PyObject *s = 0;
542 QString id;
543 Py_XINCREF( a0 );
544 Py_BEGIN_ALLOW_THREADS
545 id = QgsNetworkAccessManager::setRequestPreprocessor( [a0]( QNetworkRequest *arg )->QString
546 {
547 QString res;
548 SIP_BLOCK_THREADS
549 PyObject *s = sipCallMethod( NULL, a0, "D", arg, sipType_QNetworkRequest, NULL );
550 int state;
551 int sipIsError = 0;
552 QString *t1 = reinterpret_cast<QString *>( sipConvertToType( s, sipType_QString, 0, SIP_NOT_NONE, &state, &sipIsError ) );
553 if ( sipIsError == 0 )
554 {
555 res = QString( *t1 );
556 }
557 sipReleaseType( t1, sipType_QString, state );
558 SIP_UNBLOCK_THREADS
559 return res;
560 } );
561 Py_END_ALLOW_THREADS
562
563 s = sipConvertFromNewType( new QString( id ), sipType_QString, 0 );
564 return s;
565 % End
566// clang-format on
567#endif
568
579#ifndef SIP_RUN
580 static bool removeRequestPreprocessor( const QString &id );
581#else
582 // clang-format off
583 static void removeRequestPreprocessor( const QString &id );
584 % MethodCode
586 {
587 PyErr_SetString( PyExc_KeyError, u"No processor with id %1 exists."_s.arg( *a0 ).toUtf8().constData() );
588 sipIsErr = 1;
589 }
590 % End
591// clang-format on
592#endif
593
609#ifndef SIP_RUN
610 static QString setAdvancedRequestPreprocessor( const std::function< void( QNetworkRequest *, int &op, QByteArray *data )> &processor );
611#else
612 // clang-format off
613 static QString setAdvancedRequestPreprocessor( SIP_PYCALLABLE / AllowNone / );
614 % MethodCode
615 PyObject *s = 0;
616 QString id;
617 Py_XINCREF( a0 );
618 Py_BEGIN_ALLOW_THREADS
619 id = QgsNetworkAccessManager::setAdvancedRequestPreprocessor( [a0]( QNetworkRequest *reqArg, int &op, QByteArray *data )
620 {
621 SIP_BLOCK_THREADS
622
623 PyObject *requestObj = sipConvertFromType( reqArg, sipType_QNetworkRequest, NULL );
624 PyObject *postDataObj = sipConvertFromType( new QByteArray( *data ), sipType_QByteArray, Py_None );
625
626 PyObject *result = sipCallMethod( NULL, a0, "RiR", requestObj, op, postDataObj );
627
628 Py_XDECREF( requestObj );
629 Py_XDECREF( postDataObj );
630
631 if ( result && PyTuple_Check( result ) && PyTuple_Size( result ) == 2 )
632 {
633 // Extract modified operation
634 PyObject *opObj = PyTuple_GetItem( result, 0 );
635 if ( opObj && PyLong_Check( opObj ) )
636 {
637 op = static_cast<int>( PyLong_AsLong( opObj ) );
638 }
639 PyObject *dataObj = PyTuple_GetItem( result, 1 );
640 if ( dataObj && dataObj != Py_None )
641 {
642 int dataState;
643 int sipIsErr = 0;
644 QByteArray *modifiedData = reinterpret_cast<QByteArray *>( sipConvertToType( dataObj, sipType_QByteArray, 0, SIP_NOT_NONE, &dataState, &sipIsErr ) );
645 if ( sipIsErr == 0 )
646 {
647 data->clear();
648 data->append( *modifiedData );
649 sipReleaseType( modifiedData, sipType_QByteArray, dataState );
650 }
651 }
652 }
653
654 Py_XDECREF( result );
655 SIP_UNBLOCK_THREADS
656 } );
657 Py_END_ALLOW_THREADS
658
659 s = sipConvertFromNewType( new QString( id ), sipType_QString, 0 );
660 return s;
661 % End
662// clang-format on
663#endif
664
675#ifndef SIP_RUN
676 static bool removeAdvancedRequestPreprocessor( const QString &id );
677#else
678 // clang-format off
679 static void removeAdvancedRequestPreprocessor( const QString &id );
680 % MethodCode
682 {
683 PyErr_SetString( PyExc_KeyError, u"No processor with id %1 exists."_s.arg( *a0 ).toUtf8().constData() );
684 sipIsErr = 1;
685 }
686 % End
687// clang-format on
688#endif
689
690
702#ifndef SIP_RUN
703 static QString setReplyPreprocessor( const std::function<void( const QNetworkRequest &, QNetworkReply * )> &processor );
704#else
705 // clang-format off
706 static QString setReplyPreprocessor( SIP_PYCALLABLE / AllowNone / );
707 % MethodCode
708 PyObject *s = 0;
709 QString id;
710 Py_XINCREF( a0 );
711 Py_BEGIN_ALLOW_THREADS
712 id = QgsNetworkAccessManager::setReplyPreprocessor( [a0]( const QNetworkRequest &request, QNetworkReply *reply )
713 {
714 SIP_BLOCK_THREADS
715 Py_XDECREF( sipCallMethod( NULL, a0, "ND", new QNetworkRequest( request ), sipType_QNetworkRequest, NULL, reply, sipType_QNetworkReply, NULL ) );
716 SIP_UNBLOCK_THREADS
717 } );
718
719 Py_END_ALLOW_THREADS
720 s = sipConvertFromNewType( new QString( id ), sipType_QString, 0 );
721 return s;
722 % End
723// clang-format on
724#endif
725
736#ifndef SIP_RUN
737 static bool removeReplyPreprocessor( const QString &id );
738#else
739 // clang-format off
740 static void removeReplyPreprocessor( const QString &id );
741 % MethodCode
743 {
744 PyErr_SetString( PyExc_KeyError, u"No processor with id %1 exists."_s.arg( *a0 ).toUtf8().constData() );
745 sipIsErr = 1;
746 }
747 % End
748// clang-format on
749#endif
750
757 void requestAuthOpenBrowser( const QUrl &url ) const;
758
765 void requestAuthCloseBrowser() const;
766
773 void abortAuthBrowser();
774
775
776#ifndef SIP_RUN
799#endif
800
806 void preprocessRequest( QNetworkRequest *req ) const;
807
808 signals:
809
813 Q_DECL_DEPRECATED void requestAboutToBeCreated( QNetworkAccessManager::Operation operation, const QNetworkRequest &request, QIODevice *device ) SIP_DEPRECATED;
814
828
842
858
871
886 void downloadProgress( int requestId, qint64 bytesReceived, qint64 bytesTotal );
887
903 void requestRequiresAuth( int requestId, const QString &realm );
904
920 void requestAuthDetailsAdded( int requestId, const QString &realm, const QString &user, const QString &password );
921
922#ifndef QT_NO_SSL
923
938 void requestEncounteredSslErrors( int requestId, const QList<QSslError> &errors );
939
940#ifndef SIP_RUN
942 // these signals are for internal use only - it's not safe to connect by external code
943 void sslErrorsOccurred( QNetworkReply *, const QList<QSslError> &errors );
944 void sslErrorsHandled( QNetworkReply *reply );
946#endif
947
948#endif
949
953 Q_DECL_DEPRECATED void requestCreated( QNetworkReply *reply ) SIP_DEPRECATED;
954
958 void requestTimedOut( QNetworkReply *reply );
959
960#ifndef SIP_RUN
962 // these signals are for internal use only - it's not safe to connect by external code
963 void authRequestOccurred( QNetworkReply *, QAuthenticator *auth );
964 void authRequestHandled( QNetworkReply *reply );
966#endif
967
974
979
980 void cookiesChanged( const QList<QNetworkCookie> &cookies );
981
982 private slots:
983 void abortRequest();
984
985 void onReplyFinished( QNetworkReply *reply );
986
987 void onReplyDownloadProgress( qint64 bytesReceived, qint64 bytesTotal );
988#ifndef QT_NO_SSL
989 void onReplySslErrors( const QList<QSslError> &errors );
990
991 void handleSslErrors( QNetworkReply *reply, const QList<QSslError> &errors );
992#endif
993
994 void onAuthRequired( QNetworkReply *reply, QAuthenticator *auth );
995 void handleAuthRequest( QNetworkReply *reply, QAuthenticator *auth );
996
997 void syncCookies( const QList<QNetworkCookie> &cookies );
998
999 protected:
1000 QNetworkReply *createRequest( QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData = nullptr ) override;
1001
1002 private:
1003#ifndef QT_NO_SSL
1004 void afterSslErrorHandled( QNetworkReply *reply );
1005#endif
1006
1007 void afterAuthRequestHandled( QNetworkReply *reply );
1008
1009 void pauseTimeout( QNetworkReply *reply );
1010 void restartTimeout( QNetworkReply *reply );
1011 static int getRequestId( QNetworkReply *reply );
1012
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;
1020 static QgsNetworkAccessManager *sMainNAM;
1021 // ssl error handler, will be set for main thread ONLY
1022 std::unique_ptr< QgsSslErrorHandler > mSslErrorHandler;
1023 // Used by worker threads to wait for ssl error handler run in main thread
1024 QSemaphore mSslErrorHandlerSemaphore;
1025
1026 // auth request handler, will be set for main thread ONLY
1027 std::unique_ptr< QgsNetworkAuthenticationHandler > mAuthHandler;
1028 // Used by worker threads to wait for authentication handler run in main thread
1029 QSemaphore mAuthRequestHandlerSemaphore;
1030
1032};
1033
1034#endif // QGSNETWORKACCESSMANAGER_H
QFlags< NetworkRequestFlag > NetworkRequestFlags
Flags controlling behavior of network requests.
Definition qgis.h:197
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
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.
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.
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.
A string 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.
#define SIP_DEPRECATED
Definition qgis_sip.h:113
#define SIP_DISALLOWNONE
Definition qgis_sip.h:133
#define SIP_TRANSFER
Definition qgis_sip.h:35
#define SIP_TRANSFERBACK
Definition qgis_sip.h:47