QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
qgsnetworkcontentfetcherregistry.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsnetworkcontentfetcherregistry.cpp
3 -------------------
4 begin : April, 2018
5 copyright : (C) 2018 by Denis Rouzaud
7
8 ***************************************************************************/
9
10/***************************************************************************
11 * *
12 * This program is free software; you can redistribute it and/or modify *
13 * it under the terms of the GNU General Public License as published by *
14 * the Free Software Foundation; either version 2 of the License, or *
15 * (at your option) any later version. *
16 * *
17 ***************************************************************************/
18
20
21#include "qgsapplication.h"
22#include <QUrl>
23#include <QFileInfo>
24#include <QDir>
25#include <QMimeType>
26#include <QMimeDatabase>
27
29{
30 QMap<QString, QgsFetchedContent *>::const_iterator it = mFileRegistry.constBegin();
31 for ( ; it != mFileRegistry.constEnd(); ++it )
32 {
33 delete it.value();
34 }
35 mFileRegistry.clear();
36}
37
38QgsFetchedContent *QgsNetworkContentFetcherRegistry::fetch( const QString &url, const Qgis::ActionStart fetchingMode, const QString &authConfig )
39{
40
41 if ( mFileRegistry.contains( url ) )
42 {
43 return mFileRegistry.value( url );
44 }
45
46 QgsFetchedContent *content = new QgsFetchedContent( url, nullptr, QgsFetchedContent::NotStarted, authConfig );
47
48 mFileRegistry.insert( url, content );
49
50 if ( fetchingMode == Qgis::ActionStart::Immediate )
51 content->download();
52
53
54 return content;
55}
56
57QFile *QgsNetworkContentFetcherRegistry::localFile( const QString &filePathOrUrl )
58{
59 QFile *file = nullptr;
60 const QString path = filePathOrUrl;
61
62 if ( !QUrl::fromUserInput( filePathOrUrl ).isLocalFile() )
63 {
64 if ( mFileRegistry.contains( path ) )
65 {
66 const QgsFetchedContent *content = mFileRegistry.value( path );
67 if ( content && content->status() == QgsFetchedContent::Finished && content->file() )
68 {
69 file = content->file();
70 }
71 else
72 {
73 // if the file is not downloaded yet or has failed, return nullptr
74 }
75 }
76 else
77 {
78 // if registry doesn't contain the URL, return nullptr
79 }
80 }
81 else
82 {
83 file = new QFile( filePathOrUrl );
84 }
85 return file;
86}
87
88QString QgsNetworkContentFetcherRegistry::localPath( const QString &filePathOrUrl )
89{
90 QString path = filePathOrUrl;
91
92 if ( !QUrl::fromUserInput( filePathOrUrl ).isLocalFile() )
93 {
94 if ( mFileRegistry.contains( path ) )
95 {
96 const QgsFetchedContent *content = mFileRegistry.value( path );
97 if ( content->status() == QgsFetchedContent::Finished && !content->filePath().isEmpty() )
98 {
99 path = content->filePath();
100 }
101 else
102 {
103 // if the file is not downloaded yet or has failed, return empty string
104 path = QString();
105 }
106 }
107 else
108 {
109 // if registry doesn't contain the URL, keep path unchanged
110 }
111 }
112 return path;
113}
114
115
116
117
118void QgsFetchedContent::download( bool redownload )
119{
120
121 if ( redownload && status() == QgsFetchedContent::Downloading )
122 {
123 {
124 if ( mFetchingTask )
125 disconnect( mFetchingTask, &QgsNetworkContentFetcherTask::taskCompleted, this, &QgsFetchedContent::taskCompleted );
126 }
127 cancel();
128 }
129 if ( redownload ||
132 {
133 mFetchingTask = new QgsNetworkContentFetcherTask( mUrl, mAuthConfig );
134 // use taskCompleted which is main thread rather than fetched signal in worker thread
135 connect( mFetchingTask, &QgsNetworkContentFetcherTask::taskCompleted, this, &QgsFetchedContent::taskCompleted );
136 connect( mFetchingTask, &QgsNetworkContentFetcherTask::taskTerminated, this, &QgsFetchedContent::taskCompleted );
138 QgsApplication::taskManager()->addTask( mFetchingTask );
140 }
141
142}
143
145{
146 if ( mFetchingTask && mFetchingTask->canCancel() )
147 {
148 mFetchingTask->cancel();
149 mStatus = ContentStatus::NotStarted;
150 }
151}
152
153
154void QgsFetchedContent::taskCompleted()
155{
156 if ( !mFetchingTask || !mFetchingTask->reply() )
157 {
158 // if no reply, it has been canceled
160 mError = QNetworkReply::OperationCanceledError;
161 mFilePath = QString();
162 }
163 else
164 {
165 QNetworkReply *reply = mFetchingTask->reply();
166 if ( reply->error() == QNetworkReply::NoError )
167 {
168
169 // keep or guess extension, it can be useful when guessing file content
170 // (when loading this file in a Qt WebView for instance)
171
172 // extension from file name
173 QString extension = QFileInfo( reply->request().url().fileName() ).completeSuffix();
174
175 // extension from contentType header if not found from file name
176 const QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString();
177 if ( extension.isEmpty() && !contentType.isEmpty() )
178 {
179 const QList<QMimeType> mimeTypes = QMimeDatabase().allMimeTypes();
180 auto it = std::find_if( mimeTypes.constBegin(), mimeTypes.constEnd(), [ = ]( QMimeType mimeType )
181 {
182 return mimeType.name() == contentType;
183 } );
184 if ( it != mimeTypes.constEnd() )
185 {
186 extension = ( *it ).preferredSuffix();
187 }
188 }
189
190 QTemporaryFile *tf = new QTemporaryFile( extension.isEmpty() ? QString( "XXXXXX" ) :
191 QString( "%1/XXXXXX.%2" ).arg( QDir::tempPath(), extension ) );
192 mFile = tf;
193 tf->open();
194 mFile->write( reply->readAll() );
195 // Qt docs notes that on some system if fileName is not called before close, file might get deleted
196 mFilePath = tf->fileName();
197 tf->close();
199 }
200 else
201 {
203 mError = reply->error();
204 mFilePath = QString();
205 }
206 }
207
208 emit fetched();
209}
ActionStart
Enum to determine when an operation would begin.
Definition: qgis.h:875
@ Immediate
Action will start immediately.
static QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling.
FetchedContent holds useful information about a network content being fetched.
QFile * file() const
Returns a pointer to the local file, or nullptr if the file is not accessible yet.
ContentStatus status() const
Returns the status of the download.
void download(bool redownload=false)
Start the download.
const QString filePath() const
Returns the path to the local file, an empty string if the file is not accessible yet.
void errorOccurred(QNetworkReply::NetworkError code, const QString &errorMsg)
Emitted when an error with code error occurred while processing the request errorMsg is a textual des...
@ Finished
Download finished and successful.
@ NotStarted
No download started for such URL.
@ Downloading
Currently downloading.
void fetched()
Emitted when the file is fetched and accessible.
void cancel()
Cancel the download operation.
QString localPath(const QString &filePathOrUrl)
Returns the path to a local file or to a temporary file previously fetched by the registry.
QFile * localFile(const QString &filePathOrUrl)
Returns a QFile from a local file or to a temporary file previously fetched by the registry.
QgsFetchedContent * fetch(const QString &url, Qgis::ActionStart fetchingMode=Qgis::ActionStart::Deferred, const QString &authConfig=QString())
Initialize a download for the given URL.
Handles HTTP network content fetching in a background task.
void errorOccurred(QNetworkReply::NetworkError code, const QString &errorMsg)
Emitted when an error with code error occurred while processing the request errorMsg is a textual des...
long addTask(QgsTask *task, int priority=0)
Adds a task to the manager.
void taskCompleted()
Will be emitted by task to indicate its successful completion.
void taskTerminated()
Will be emitted by task if it has terminated for any reason other then completion (e....