summaryrefslogtreecommitdiffstats
path: root/rbutil/rbutilqt/base/httpget.cpp
blob: 4b08faf33b530c8bd364f47e065702d5603d5dfa (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 *
 *   Copyright (C) 2013 by Dominik Riebeling
 *
 * All files in this archive are subject to the GNU General Public License.
 * See the file COPYING in the source tree root for full license agreement.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

#include <QtNetwork>
#include <QtDebug>

#include <QNetworkAccessManager>
#include <QNetworkRequest>

#include "httpget.h"
#include "Logger.h"

QString HttpGet::m_globalUserAgent; //< globally set user agent for requests
QDir HttpGet::m_globalCache; //< global cach path value for new objects
QNetworkProxy HttpGet::m_globalProxy;

HttpGet::HttpGet(QObject *parent)
    : QObject(parent)
{
    m_mgr = new QNetworkAccessManager(this);
    m_cache = NULL;
    m_cachedir = m_globalCache;
    setCache(true);
    connect(m_mgr, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(requestFinished(QNetworkReply*)));
    m_outputFile = NULL;
    m_lastServerTimestamp = QDateTime();
    m_proxy = QNetworkProxy::NoProxy;
    m_reply = NULL;
}


//! @brief set cache path
//  @param d new directory to use as cache path
void HttpGet::setCache(const QDir& d)
{
    if(m_cache && m_cachedir == d.absolutePath())
        return;
    m_cachedir = d.absolutePath();
    setCache(true);
}


/** @brief enable / disable cache useage
 *  @param c set cache usage
 */
void HttpGet::setCache(bool c)
{
    // don't change cache if it's already (un)set.
    if(c && m_cache) return;
    if(!c && !m_cache) return;
    // don't delete the old cache directly, it might still be in use. Just
    // instruct it to delete itself later.
    if(m_cache) m_cache->deleteLater();
    m_cache = NULL;

    QString path = m_cachedir.absolutePath();

    if(!c || m_cachedir.absolutePath().isEmpty()) {
        LOG_INFO() << "disabling download cache";
    }
    else {
        // append the cache path to make it unique in case the path points to
        // the system temporary path. In that case using it directly might
        // cause problems. Extra path also used in configure dialog.
        path += "/rbutil-cache";
        LOG_INFO() << "setting cache folder to" << path;
        m_cache = new QNetworkDiskCache(this);
        m_cache->setCacheDirectory(path);
    }
    m_mgr->setCache(m_cache);
}


/** @brief read all downloaded data into a buffer
 *  @return data
 */
QByteArray HttpGet::readAll()
{
    return m_data;
}


void HttpGet::setProxy(const QUrl &proxy)
{
    LOG_INFO() << "Proxy set to" << proxy;
    m_proxy.setType(QNetworkProxy::HttpProxy);
    m_proxy.setHostName(proxy.host());
    m_proxy.setPort(proxy.port());
    m_proxy.setUser(proxy.userName());
    m_proxy.setPassword(proxy.password());
    m_mgr->setProxy(m_proxy);
}


void HttpGet::setProxy(bool enable)
{
    if(enable) m_mgr->setProxy(m_proxy);
    else m_mgr->setProxy(QNetworkProxy::NoProxy);
}


void HttpGet::setFile(QFile *file)
{
    m_outputFile = file;
}


void HttpGet::abort()
{
    if(m_reply) m_reply->abort();
}


void HttpGet::requestFinished(QNetworkReply* reply)
{
    m_lastStatusCode
        = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    LOG_INFO() << "Request finished, status code:" << m_lastStatusCode;
    m_lastServerTimestamp
        = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toLocalTime();
    LOG_INFO() << "Data from cache:"
             << reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
    m_lastRequestCached =
        reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
    if(reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid()) {
        // handle relative URLs using QUrl::resolved()
        QUrl org = reply->request().url();
        QUrl url = QUrl(org).resolved(
                reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl());
        // reconstruct query
#if QT_VERSION < 0x050000
        QList<QPair<QByteArray, QByteArray> > qitms = org.encodedQueryItems();
        for(int i = 0; i < qitms.size(); ++i)
            url.addEncodedQueryItem(qitms.at(i).first, qitms.at(i).second);
#else
        url.setQuery(org.query());
#endif
        LOG_INFO() << "Redirected to" << url;
        startRequest(url);
        return;
    }
    else if(m_lastStatusCode == 200) {
        m_data = reply->readAll();
        if(m_outputFile && m_outputFile->open(QIODevice::WriteOnly)) {
            m_outputFile->write(m_data);
            m_outputFile->close();
        }
        emit done(false);
    }
    else {
        m_data.clear();
        emit done(true);
    }
    reply->deleteLater();
    m_reply = NULL;
}


void HttpGet::downloadProgress(qint64 received, qint64 total)
{
    emit dataReadProgress((int)received, (int)total);
}


void HttpGet::startRequest(QUrl url)
{
    LOG_INFO() << "Request started";
    QNetworkRequest req(url);
    if(!m_globalUserAgent.isEmpty())
        req.setRawHeader("User-Agent", m_globalUserAgent.toLatin1());

    m_reply = m_mgr->get(req);
    connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(networkError(QNetworkReply::NetworkError)));
    connect(m_reply, SIGNAL(downloadProgress(qint64, qint64)),
            this, SLOT(downloadProgress(qint64, qint64)));
}


void HttpGet::networkError(QNetworkReply::NetworkError error)
{
    LOG_ERROR() << "NetworkError occured:" << error << m_reply->errorString();
    m_lastErrorString = m_reply->errorString();
}


bool HttpGet::getFile(const QUrl &url)
{
    LOG_INFO() << "Get URI" << url.toString();
    m_data.clear();
    startRequest(url);

    return false;
}


QString HttpGet::errorString(void)
{
    return m_lastErrorString;
}


int HttpGet::httpResponse(void)
{
    return m_lastStatusCode;
}