-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachemanager.cpp
82 lines (67 loc) · 1.96 KB
/
cachemanager.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
#include "cachemanager.h"
#include <QtCore/QCryptographicHash>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtGui/QDesktopServices>
#include <QtNetwork/QNetworkReply>
#include "networkaccessmanager.h"
#include <QtCore/QDebug>
CacheManager::CacheManager(QObject *parent)
: QObject(parent)
, m_networkAccessManager(NetworkAccessManager::createN9NetworkAccessManager(this))
{
}
CacheManager::~CacheManager()
{
foreach (QString path, m_cachedFiles) {
QFile file (path);
file.remove();
}
}
bool CacheManager::contains(const QUrl &url)
{
return m_cachedFiles.contains(url);
}
QString CacheManager::cachedFile(const QUrl &url)
{
return m_cachedFiles.value(url);
}
void CacheManager::request(const QUrl &url)
{
if (contains(url)) {
emit requestFinished(url, cachedFile(url));
return;
}
QNetworkReply *reply = m_networkAccessManager->get(QNetworkRequest(url));
connect(reply, SIGNAL(finished()), this, SLOT(slotFinished()));
}
void CacheManager::slotFinished()
{
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
if (!reply) {
return;
}
QUrl url = reply->url();
if (reply->error() != QNetworkReply::NoError) {
emit requestFinished(url, QString());
return;
}
QString cachePath = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
if (!QDir::root().mkpath(cachePath)) {
emit requestFinished(url, QString());
return;
}
QString name = QCryptographicHash::hash(url.toString().toLocal8Bit(),
QCryptographicHash::Md5).toHex();
QDir cacheDir (cachePath);
QString path = cacheDir.absoluteFilePath(name);
QFile file (path);
if (!file.open(QIODevice::WriteOnly)) {
emit requestFinished(url, QString());
return;
}
file.write(reply->readAll());
file.close();
m_cachedFiles.insert(url, path);
emit requestFinished(url, path);
}