test test test
[kugel-rb.git] / rbutil / rbutilqt / base / httpget.cpp
blobdab93d1b198c1f69e425b49b6206c548186aed2e
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
9 * Copyright (C) 2007 by Dominik Riebeling
10 * $Id$
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
20 #include <QtCore>
21 #include <QtNetwork>
22 #include <QtDebug>
24 #include "httpget.h"
26 QDir HttpGet::m_globalCache; //< global cach path value for new objects
27 QUrl HttpGet::m_globalProxy; //< global proxy value for new objects
28 bool HttpGet::m_globalDumbCache = false; //< globally set cache "dumb" mode
29 QString HttpGet::m_globalUserAgent; //< globally set user agent for requests
31 HttpGet::HttpGet(QObject *parent)
32 : QObject(parent)
34 outputToBuffer = true;
35 m_cached = false;
36 m_dumbCache = m_globalDumbCache;
37 getRequest = -1;
38 headRequest = -1;
39 // if a request is cancelled before a reponse is available return some
40 // hint about this in the http response instead of nonsense.
41 m_response = -1;
42 m_useproxy = false;
44 // default to global proxy / cache if not empty.
45 // proxy is automatically enabled, disable it by setting an empty proxy
46 // cache is enabled to be in line, can get disabled with setCache(bool)
47 if(!m_globalProxy.isEmpty())
48 setProxy(m_globalProxy);
49 m_usecache = false;
50 m_cachedir = m_globalCache;
52 m_serverTimestamp = QDateTime();
54 connect(&http, SIGNAL(done(bool)), this, SLOT(httpDone(bool)));
55 connect(&http, SIGNAL(dataReadProgress(int, int)),
56 this, SIGNAL(dataReadProgress(int, int)));
57 connect(&http, SIGNAL(requestFinished(int, bool)),
58 this, SLOT(httpFinished(int, bool)));
59 connect(&http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader&)),
60 this, SLOT(httpResponseHeader(const QHttpResponseHeader&)));
61 // connect(&http, SIGNAL(stateChanged(int)), this, SLOT(httpState(int)));
62 connect(&http, SIGNAL(requestStarted(int)), this, SLOT(httpStarted(int)));
64 connect(&http, SIGNAL(readyRead(const QHttpResponseHeader&)),
65 this, SLOT(httpResponseHeader(const QHttpResponseHeader&)));
66 connect(this, SIGNAL(headerFinished()), this, SLOT(getFileFinish()));
71 //! @brief set cache path
72 // @param d new directory to use as cache path
73 void HttpGet::setCache(const QDir& d)
75 m_cachedir = d;
76 bool result;
77 result = initializeCache(d);
78 m_usecache = result;
82 /** @brief enable / disable cache useage
83 * @param c set cache usage
85 void HttpGet::setCache(bool c)
87 m_usecache = c;
88 // make sure cache is initialized
89 if(c)
90 m_usecache = initializeCache(m_cachedir);
94 bool HttpGet::initializeCache(const QDir& d)
96 bool result;
97 QString p = d.absolutePath() + "/rbutil-cache";
98 if(QFileInfo(d.absolutePath()).isDir())
100 if(!QFileInfo(p).isDir())
101 result = d.mkdir("rbutil-cache");
102 else
103 result = true;
105 else
106 result = false;
108 return result;
113 /** @brief read all downloaded data into a buffer
114 * @return data
116 QByteArray HttpGet::readAll()
118 return dataBuffer;
122 /** @brief get http error
123 * @return http error
125 QHttp::Error HttpGet::error()
127 return http.error();
131 void HttpGet::setProxy(const QUrl &proxy)
133 m_proxy = proxy;
134 m_useproxy = true;
135 http.setProxy(m_proxy.host(), m_proxy.port(),
136 m_proxy.userName(), m_proxy.password());
140 void HttpGet::setProxy(bool enable)
142 if(enable) {
143 m_useproxy = true;
144 http.setProxy(m_proxy.host(), m_proxy.port(),
145 m_proxy.userName(), m_proxy.password());
147 else {
148 m_useproxy = false;
149 http.setProxy("", 0);
154 void HttpGet::setFile(QFile *file)
156 outputFile = file;
157 outputToBuffer = false;
161 void HttpGet::abort()
163 qDebug() << "[HTTP] Aborting requests, pending:" << http.hasPendingRequests();
164 http.abort();
165 if(!outputToBuffer)
166 outputFile->close();
170 bool HttpGet::getFile(const QUrl &url)
172 if (!url.isValid()) {
173 qDebug() << "[HTTP] Error: Invalid URL" << endl;
174 return false;
177 if (url.scheme() != "http") {
178 qDebug() << "[HTTP] Error: URL must start with 'http:'" << endl;
179 return false;
182 if (url.path().isEmpty()) {
183 qDebug() << "[HTTP] Error: URL has no path" << endl;
184 return false;
186 m_serverTimestamp = QDateTime();
187 // if no output file was set write to buffer
188 if(!outputToBuffer) {
189 if (!outputFile->open(QIODevice::ReadWrite)) {
190 qDebug() << "[HTTP] Error: Cannot open " << qPrintable(outputFile->fileName())
191 << " for writing: " << qPrintable(outputFile->errorString());
192 return false;
195 else {
196 // output to buffer. Make sure buffer is empty so no old data gets
197 // returned in case the object is reused.
198 dataBuffer.clear();
200 qDebug() << "[HTTP] GET URI" << url.toEncoded();
201 // create request
202 http.setHost(url.host(), url.port(80));
203 // construct query (if any)
204 QList<QPair<QString, QString> > qitems = url.queryItems();
205 if(url.hasQuery()) {
206 m_query = "?";
207 for(int i = 0; i < qitems.size(); i++)
208 m_query += QUrl::toPercentEncoding(qitems.at(i).first, "/") + "="
209 + QUrl::toPercentEncoding(qitems.at(i).second, "/") + "&";
212 // create hash used for caching
213 m_hash = QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Md5).toHex();
214 // RFC2616: the absoluteURI form must get used when the request is being
215 // sent to a proxy.
216 m_path.clear();
217 if(m_useproxy)
218 m_path = url.scheme() + "://" + url.host();
219 m_path += QString(QUrl::toPercentEncoding(url.path(), "/"));
221 // construct request header
222 m_header.setValue("Host", url.host());
223 m_header.setValue("User-Agent", m_globalUserAgent);
224 m_header.setValue("Connection", "Keep-Alive");
226 if(m_dumbCache || !m_usecache) {
227 getFileFinish();
229 else {
230 // schedule HTTP header request
231 m_header.setRequest("HEAD", m_path + m_query);
232 headRequest = http.request(m_header);
233 qDebug() << "[HTTP] HEAD scheduled: " << headRequest;
236 return true;
240 void HttpGet::getFileFinish()
242 m_cachefile = m_cachedir.absolutePath() + "/rbutil-cache/" + m_hash;
243 if(m_usecache) {
244 // check if the file is present in cache
245 QFileInfo cachefile = QFileInfo(m_cachefile);
246 if(cachefile.isReadable()
247 && cachefile.size() > 0
248 && cachefile.lastModified() > m_serverTimestamp) {
250 qDebug() << "[HTTP] Cache: up-to-date file found:" << m_cachefile;
252 getRequest = -1;
253 QFile c(m_cachefile);
254 if(!outputToBuffer) {
255 qDebug() << "[HTTP] Cache: copying file to output"
256 << outputFile->fileName();
257 c.open(QIODevice::ReadOnly);
258 outputFile->open(QIODevice::ReadWrite);
259 outputFile->write(c.readAll());
260 outputFile->close();
261 c.close();
263 else {
264 qDebug() << "[HTTP] Cache: reading file into buffer";
265 c.open(QIODevice::ReadOnly);
266 dataBuffer = c.readAll();
267 c.close();
269 m_response = 200; // fake "200 OK" HTTP response
270 m_cached = true;
271 httpDone(false); // we're done now. Handle http "done" signal.
272 return;
274 else {
275 // unlink old cache file
276 if(cachefile.isReadable()) {
277 QFile(m_cachefile).remove();
278 qDebug() << "[HTTP] Cache: outdated, timestamp:"
279 << cachefile.lastModified();
281 qDebug() << "[HTTP] Cache: caching as" << m_cachefile;
285 else {
286 qDebug() << "[HTTP] cache DISABLED";
288 // schedule GET request
290 m_header.setRequest("GET", m_path + m_query);
291 if(outputToBuffer) {
292 qDebug() << "[HTTP] downloading to buffer.";
293 getRequest = http.request(m_header);
295 else {
296 qDebug() << "[HTTP] downloading to file:"
297 << qPrintable(outputFile->fileName());
298 getRequest = http.request(m_header, 0, outputFile);
300 qDebug() << "[HTTP] GET scheduled: " << getRequest;
302 return;
306 void HttpGet::httpDone(bool error)
308 if (error) {
309 qDebug() << "[HTTP] Error:" << qPrintable(http.errorString()) << httpResponse();
311 if(!outputToBuffer)
312 outputFile->close();
314 if(m_usecache && !m_cached && !error) {
315 qDebug() << "[HTTP] creating cache file" << m_cachefile;
316 QFile c(m_cachefile);
317 c.open(QIODevice::ReadWrite);
318 if(!outputToBuffer) {
319 outputFile->open(QIODevice::ReadOnly | QIODevice::Truncate);
320 c.write(outputFile->readAll());
321 outputFile->close();
323 else
324 c.write(dataBuffer);
326 c.close();
328 // take care of concurring requests. If there is still one running,
329 // don't emit done(). That request will call this slot again.
330 if(http.currentId() == 0 && !http.hasPendingRequests())
331 emit done(error);
335 void HttpGet::httpFinished(int id, bool error)
337 qDebug() << "[HTTP] Request finished:" << id << "Error:" << error
338 << "pending requests:" << http.hasPendingRequests();
339 if(id == getRequest) {
340 dataBuffer = http.readAll();
341 emit requestFinished(id, error);
344 if(id == headRequest) {
345 QHttpResponseHeader h = http.lastResponse();
347 QString date = h.value("Last-Modified").simplified();
348 if(date.isEmpty()) {
349 m_serverTimestamp = QDateTime(); // no value = invalid
350 emit headerFinished();
351 return;
353 // to successfully parse the date strip weekday and timezone
354 date.remove(0, date.indexOf(" ") + 1);
355 if(date.endsWith("GMT"))
356 date.truncate(date.indexOf(" GMT"));
357 // distinguish input formats (see RFC1945)
358 // RFC 850
359 if(date.contains("-"))
360 m_serverTimestamp = QDateTime::fromString(date, "dd-MMM-yy hh:mm:ss");
361 // asctime format
362 else if(date.at(0).isLetter())
363 m_serverTimestamp = QDateTime::fromString(date, "MMM d hh:mm:ss yyyy");
364 // RFC 822
365 else
366 m_serverTimestamp = QDateTime::fromString(date, "dd MMM yyyy hh:mm:ss");
367 qDebug() << "[HTTP] HEAD finished, server date:" << date << ", parsed:" << m_serverTimestamp;
368 emit headerFinished();
369 return;
371 if(id == getRequest)
372 emit requestFinished(id, error);
375 void HttpGet::httpStarted(int id)
377 qDebug() << "[HTTP] Request started: " << id << "Header req:"
378 << headRequest << "Get req:" << getRequest;
382 QString HttpGet::errorString()
384 return http.errorString();
388 void HttpGet::httpResponseHeader(const QHttpResponseHeader &resp)
390 // if there is a network error abort all scheduled requests for
391 // this download
392 m_response = resp.statusCode();
393 if(m_response != 200) {
394 // abort old request first.
395 http.abort();
397 // 301 -- moved permanently
398 // 302 -- found
399 // 303 -- see other
400 // 307 -- moved temporarily
401 // in all cases, header: location has the correct address so we can follow.
402 if(m_response == 301 || m_response == 302 || m_response == 303 || m_response == 307) {
403 // start new request with new url
404 qDebug() << "[HTTP] response =" << m_response << "- following";
405 getFile(resp.value("location") + m_query);
407 else if(m_response != 200) {
408 // all other errors are fatal.
409 qDebug() << "[HTTP] Response error:" << m_response << resp.reasonPhrase();
415 int HttpGet::httpResponse()
417 return m_response;
421 void HttpGet::httpState(int state)
423 QString s[] = {"Unconnected", "HostLookup", "Connecting", "Sending",
424 "Reading", "Connected", "Closing"};
425 if(state <= 6)
426 qDebug() << "[HTTP] State:" << s[state];
427 else qDebug() << "[HTTP] State:" << state;