/
qgsnetworkcontentfetcherregistry.cpp
93 lines (79 loc) · 2.96 KB
/
qgsnetworkcontentfetcherregistry.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/***************************************************************************
qgsnetworkcontentfetcherregistry.cpp
-------------------
begin : April, 2018
copyright : (C) 2018 by Denis Rouzaud
email : denis.rouzaud@gmail.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsnetworkcontentfetcherregistry.h"
#include "qgsapplication.h"
#include "qgsnetworkcontentfetchertask.h"
QgsNetworkContentFetcherRegistry::QgsNetworkContentFetcherRegistry()
: QObject()
{
}
QgsNetworkContentFetcherRegistry::~QgsNetworkContentFetcherRegistry()
{
QMap<QUrl, FetchedContent>::const_iterator it = mFileRegistry.constBegin();
for ( ; it != mFileRegistry.constEnd(); ++it )
{
it.value().mFile->deleteLater();
}
}
const QgsNetworkContentFetcherTask *QgsNetworkContentFetcherRegistry::fetch( const QUrl &url, const bool reload )
{
if ( mFileRegistry.contains( url ) )
{
if ( !reload )
{
return mFileRegistry.value( url ).mFetchingTask;
}
else
{
FetchedContent content = mFileRegistry.take( url );
if ( content.mFetchingTask )
{
content.mFetchingTask->cancel();
}
if ( content.mFile )
{
content.mFile->deleteLater();
}
}
}
QgsNetworkContentFetcherTask *fetcher = new QgsNetworkContentFetcherTask( url );
QgsApplication::instance()->taskManager()->addTask( fetcher );
mFileRegistry.insert( url,
FetchedContent( nullptr,
QgsNetworkContentFetcherRegistry::Downloading ) );
QObject::connect( fetcher, &QgsNetworkContentFetcherTask::fetched, this, [ = ]()
{
QNetworkReply *reply = fetcher->reply();
FetchedContent content = mFileRegistry.take( url );
if ( reply->error() == QNetworkReply::NoError )
{
content.setFile( new QTemporaryFile( QStringLiteral( "XXXXXX" ) ) );
content.mFile->write( reply->readAll() );
content.setStatus( Finished );
}
else
{
content.setStatus( Failed );
content.setError( reply->error() );
}
mFileRegistry.insert( url, content );
} );
return fetcher;
}
QgsNetworkContentFetcherRegistry::FetchedContent QgsNetworkContentFetcherRegistry::file( const QUrl &url )
{
return mFileRegistry.value( url );
}