Bump version numbers for 3.13
[maemo-rb.git] / rbutil / rbutilqt / base / httpget.cpp
blobe6b9eb4d3c057c8c18a5229096c8ee3ab5ad620a
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
9 * Copyright (C) 2013 by Dominik Riebeling
11 * All files in this archive are subject to the GNU General Public License.
12 * See the file COPYING in the source tree root for full license agreement.
14 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
15 * KIND, either express or implied.
17 ****************************************************************************/
19 #include <QtNetwork>
20 #include <QtDebug>
22 #include <QNetworkAccessManager>
23 #include <QNetworkRequest>
25 #include "httpget.h"
27 QString HttpGet::m_globalUserAgent; //< globally set user agent for requests
28 QDir HttpGet::m_globalCache; //< global cach path value for new objects
29 QNetworkProxy HttpGet::m_globalProxy;
31 HttpGet::HttpGet(QObject *parent)
32 : QObject(parent)
34 m_mgr = new QNetworkAccessManager(this);
35 m_cache = NULL;
36 m_cachedir = m_globalCache;
37 setCache(true);
38 connect(m_mgr, SIGNAL(finished(QNetworkReply*)),
39 this, SLOT(requestFinished(QNetworkReply*)));
40 m_outputFile = NULL;
41 m_lastServerTimestamp = QDateTime();
42 m_proxy = QNetworkProxy::NoProxy;
43 m_reply = NULL;
47 //! @brief set cache path
48 // @param d new directory to use as cache path
49 void HttpGet::setCache(const QDir& d)
51 if(m_cache && m_cachedir == d.absolutePath())
52 return;
53 m_cachedir = d.absolutePath();
54 setCache(true);
58 /** @brief enable / disable cache useage
59 * @param c set cache usage
61 void HttpGet::setCache(bool c)
63 // don't change cache if it's already (un)set.
64 if(c && m_cache) return;
65 if(!c && !m_cache) return;
66 // don't delete the old cache directly, it might still be in use. Just
67 // instruct it to delete itself later.
68 if(m_cache) m_cache->deleteLater();
69 m_cache = NULL;
71 QString path = m_cachedir.absolutePath();
73 if(!c || m_cachedir.absolutePath().isEmpty()) {
74 qDebug() << "[HttpGet] disabling download cache";
76 else {
77 // append the cache path to make it unique in case the path points to
78 // the system temporary path. In that case using it directly might
79 // cause problems. Extra path also used in configure dialog.
80 path += "/rbutil-cache";
81 qDebug() << "[HttpGet] setting cache folder to" << path;
82 m_cache = new QNetworkDiskCache(this);
83 m_cache->setCacheDirectory(path);
85 m_mgr->setCache(m_cache);
89 /** @brief read all downloaded data into a buffer
90 * @return data
92 QByteArray HttpGet::readAll()
94 return m_data;
98 void HttpGet::setProxy(const QUrl &proxy)
100 qDebug() << "[HttpGet] Proxy set to" << proxy;
101 m_proxy.setType(QNetworkProxy::HttpProxy);
102 m_proxy.setHostName(proxy.host());
103 m_proxy.setPort(proxy.port());
104 m_proxy.setUser(proxy.userName());
105 m_proxy.setPassword(proxy.password());
106 m_mgr->setProxy(m_proxy);
110 void HttpGet::setProxy(bool enable)
112 if(enable) m_mgr->setProxy(m_proxy);
113 else m_mgr->setProxy(QNetworkProxy::NoProxy);
117 void HttpGet::setFile(QFile *file)
119 m_outputFile = file;
123 void HttpGet::abort()
125 if(m_reply) m_reply->abort();
129 void HttpGet::requestFinished(QNetworkReply* reply)
131 m_lastStatusCode
132 = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
133 qDebug() << "[HttpGet] Request finished, status code:" << m_lastStatusCode;
134 m_lastServerTimestamp
135 = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toLocalTime();
136 qDebug() << "[HttpGet] Data from cache:"
137 << reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
138 m_lastRequestCached =
139 reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
140 if(reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid()) {
141 // handle relative URLs using QUrl::resolved()
142 QUrl org = reply->request().url();
143 QUrl url = QUrl(org).resolved(
144 reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl());
145 // reconstruct query
146 #if QT_VERSION < 0x050000
147 QList<QPair<QByteArray, QByteArray> > qitms = org.encodedQueryItems();
148 for(int i = 0; i < qitms.size(); ++i)
149 url.addEncodedQueryItem(qitms.at(i).first, qitms.at(i).second);
150 #else
151 url.setQuery(org.query());
152 #endif
153 qDebug() << "[HttpGet] Redirected to" << url;
154 startRequest(url);
155 return;
157 else if(m_lastStatusCode == 200) {
158 m_data = reply->readAll();
159 if(m_outputFile && m_outputFile->open(QIODevice::WriteOnly)) {
160 m_outputFile->write(m_data);
161 m_outputFile->close();
163 emit done(false);
165 else {
166 m_data.clear();
167 emit done(true);
169 reply->deleteLater();
170 m_reply = NULL;
174 void HttpGet::downloadProgress(qint64 received, qint64 total)
176 emit dataReadProgress((int)received, (int)total);
180 void HttpGet::startRequest(QUrl url)
182 qDebug() << "[HttpGet] Request started";
183 QNetworkRequest req(url);
184 if(!m_globalUserAgent.isEmpty())
185 req.setRawHeader("User-Agent", m_globalUserAgent.toLatin1());
187 m_reply = m_mgr->get(req);
188 connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
189 this, SLOT(networkError(QNetworkReply::NetworkError)));
190 connect(m_reply, SIGNAL(downloadProgress(qint64, qint64)),
191 this, SLOT(downloadProgress(qint64, qint64)));
195 void HttpGet::networkError(QNetworkReply::NetworkError error)
197 qDebug() << "[HttpGet] NetworkError occured:"
198 << error << m_reply->errorString();
199 m_lastErrorString = m_reply->errorString();
203 bool HttpGet::getFile(const QUrl &url)
205 qDebug() << "[HttpGet] Get URI" << url.toString();
206 m_data.clear();
207 startRequest(url);
209 return false;
213 QString HttpGet::errorString(void)
215 return m_lastErrorString;
219 int HttpGet::httpResponse(void)
221 return m_lastStatusCode;