QGIS API Documentation 3.30.0-'s-Hertogenbosch (f186b8efe0)
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 }
150 if ( mFile )
151 {
152 mFile->deleteLater();
153 mFilePath = QString();
154 }
155}
156
157
158void QgsFetchedContent::taskCompleted()
159{
160 if ( !mFetchingTask || !mFetchingTask->reply() )
161 {
162 // if no reply, it has been canceled
164 mError = QNetworkReply::OperationCanceledError;
165 mFilePath = QString();
166 }
167 else
168 {
169 QNetworkReply *reply = mFetchingTask->reply();
170 if ( reply->error() == QNetworkReply::NoError )
171 {
172
173 // keep or guess extension, it can be useful when guessing file content
174 // (when loading this file in a Qt WebView for instance)
175
176 // extension from file name
177 QString extension = QFileInfo( reply->request().url().fileName() ).completeSuffix();
178
179 // extension from contentType header if not found from file name
180 const QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString();
181 if ( extension.isEmpty() && !contentType.isEmpty() )
182 {
183 const QList<QMimeType> mimeTypes = QMimeDatabase().allMimeTypes();
184 auto it = std::find_if( mimeTypes.constBegin(), mimeTypes.constEnd(), [ = ]( QMimeType mimeType )
185 {
186 return mimeType.name() == contentType;
187 } );
188 if ( it != mimeTypes.constEnd() )
189 {
190 extension = ( *it ).preferredSuffix();
191 }
192 }
193
194 QTemporaryFile *tf = new QTemporaryFile( extension.isEmpty() ? QString( "XXXXXX" ) :
195 QString( "%1/XXXXXX.%2" ).arg( QDir::tempPath(), extension ) );
196 mFile = tf;
197 tf->open();
198 mFile->write( reply->readAll() );
199 // Qt docs notes that on some system if fileName is not called before close, file might get deleted
200 mFilePath = tf->fileName();
201 tf->close();
203 }
204 else
205 {
207 mError = reply->error();
208 mFilePath = QString();
209 }
210 }
211
212 emit fetched();
213}
ActionStart
Enum to determine when an operation would begin.
Definition: qgis.h:692
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.
QNetworkReply * reply()
Returns the network reply.
void cancel() override
Notifies the task that it should terminate.
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....
bool canCancel() const
Returns true if the task can be canceled.