1 #include "cachedhttp.h"
2 #include "localcache.h"
4 CachedHttpReply::CachedHttpReply(const QByteArray &body, const HttpRequest &req)
5 : bytes(body), req(req) {
6 QTimer::singleShot(0, this, SLOT(emitSignals()));
9 QByteArray CachedHttpReply::body() const {
13 void CachedHttpReply::emitSignals() {
19 WrappedHttpReply::WrappedHttpReply(LocalCache *cache, const QByteArray &key, HttpReply *httpReply)
20 : HttpReply(httpReply), cache(cache), key(key), httpReply(httpReply) {
21 connect(httpReply, SIGNAL(data(QByteArray)), SIGNAL(data(QByteArray)));
22 connect(httpReply, SIGNAL(error(QString)), SIGNAL(error(QString)));
23 connect(httpReply, SIGNAL(finished(HttpReply)), SLOT(originFinished(HttpReply)));
26 void WrappedHttpReply::originFinished(const HttpReply &reply) {
27 qDebug() << reply.statusCode() << reply.url();
28 if (reply.isSuccessful()) cache->insert(key, reply.body());
32 CachedHttp::CachedHttp(Http &http, const char *name)
33 : http(http), cache(LocalCache::instance(name)), cachePostRequests(false) {}
35 void CachedHttp::setMaxSeconds(uint seconds) {
36 cache->setMaxSeconds(seconds);
39 void CachedHttp::setMaxSize(uint maxSize) {
40 cache->setMaxSize(maxSize);
43 HttpReply *CachedHttp::request(const HttpRequest &req) {
44 bool cacheable = req.operation == QNetworkAccessManager::GetOperation ||
45 (cachePostRequests && req.operation == QNetworkAccessManager::PostOperation);
47 qDebug() << "Not cacheable" << req.url;
48 return http.request(req);
50 const QByteArray key = requestHash(req);
51 const QByteArray value = cache->value(key);
52 if (!value.isNull()) {
53 qDebug() << "HIT" << key << req.url;
54 return new CachedHttpReply(value, req);
56 qDebug() << "MISS" << key << req.url;
57 return new WrappedHttpReply(cache, key, http.request(req));
60 QByteArray CachedHttp::requestHash(const HttpRequest &req) {
65 s = (req.url.scheme() + sep + req.url.path() + sep + req.url.query()).toUtf8();
67 s = req.url.toEncoded();
69 s += sep + req.body + sep + QByteArray::number(req.offset);
70 if (req.operation == QNetworkAccessManager::PostOperation) {
74 return LocalCache::hash(s);