summaryrefslogtreecommitdiff
path: root/rockworkd/libpebble/jskit/jskitxmlhttprequest.cpp
blob: 5948683ff3a147cd7696351421e936df591387ae (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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#include <QBuffer>
#include <QAuthenticator>
#include <QEventLoop>

#include "jskitxmlhttprequest.h"
#include "jskitmanager.h"

JSKitXMLHttpRequest::JSKitXMLHttpRequest(QJSEngine *engine) :
    QObject(engine),
    l(metaObject()->className()),
    m_engine(engine),
    m_net(new QNetworkAccessManager(this)),
    m_timeout(0),
    m_reply(0)
{
    connect(m_net, &QNetworkAccessManager::authenticationRequired,
            this, &JSKitXMLHttpRequest::handleAuthenticationRequired);
}

void JSKitXMLHttpRequest::open(const QString &method, const QString &url, bool async, const QString &username, const QString &password)
{
    if (m_reply) {
        m_reply->deleteLater();
        m_reply = 0;
    }

    m_username = username;
    m_password = password;
    m_request = QNetworkRequest(QUrl(url));
    m_verb = method;
    m_async = async;

    qCDebug(l) << "opened to URL" << m_request.url().toString() << "Async:" << async;
}

void JSKitXMLHttpRequest::setRequestHeader(const QString &header, const QString &value)
{
    qCDebug(l) << "setRequestHeader" << header << value;
    m_request.setRawHeader(header.toLatin1(), value.toLatin1());
}

void JSKitXMLHttpRequest::send(const QJSValue &data)
{
    QByteArray byteData;

    if (data.isUndefined() || data.isNull()) {
        // Do nothing, byteData is empty.
    } else if (data.isString()) {
        byteData = data.toString().toUtf8();
    } else if (data.isObject()) {
        if (data.hasProperty("byteLength")) {
            // Looks like an ArrayView or an ArrayBufferView!
            QJSValue buffer = data.property("buffer");
            if (buffer.isUndefined()) {
                // We must assume we've been passed an ArrayBuffer directly
                buffer = data;
            }

            QJSValue array = data.property("_bytes");
            int byteLength = data.property("byteLength").toInt();

            if (array.isArray()) {
                byteData.reserve(byteLength);

                for (int i = 0; i < byteLength; i++) {
                    byteData.append(array.property(i).toInt());
                }

                qCDebug(l) << "passed an ArrayBufferView of" << byteData.length() << "bytes";
            } else {
                qCWarning(l) << "passed an unknown/invalid ArrayBuffer" << data.toString();
            }
        } else {
            qCWarning(l) << "passed an unknown object" << data.toString();
        }

    }

    QBuffer *buffer;
    if (!byteData.isEmpty()) {
        buffer = new QBuffer;
        buffer->setData(byteData);
    } else {
        buffer = 0;
    }

    qCDebug(l) << "sending" << m_verb << "to" << m_request.url() << "with" << QString::fromUtf8(byteData);
    m_reply = m_net->sendCustomRequest(m_request, m_verb.toLatin1(), buffer);

    connect(m_reply, &QNetworkReply::finished,
            this, &JSKitXMLHttpRequest::handleReplyFinished);
    connect(m_reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
            this, &JSKitXMLHttpRequest::handleReplyError);

    if (buffer) {
        // So that it gets deleted alongside the reply object.
        buffer->setParent(m_reply);
    }

    if (!m_async) {
        QEventLoop loop; //Hacky way to get QNetworkReply be synchronous

        connect(m_reply, &QNetworkReply::finished,
                &loop, &QEventLoop::quit);
        connect(m_reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
                &loop, &QEventLoop::quit);

        loop.exec();
    }
}

void JSKitXMLHttpRequest::abort()
{
    if (m_reply) {
        m_reply->deleteLater();
        m_reply = 0;
    }
}

QJSValue JSKitXMLHttpRequest::onload() const
{
    return m_onload;
}

void JSKitXMLHttpRequest::setOnload(const QJSValue &value)
{
    m_onload = value;
}

QJSValue JSKitXMLHttpRequest::onreadystatechange() const
{
    return m_onreadystatechange;
}

void JSKitXMLHttpRequest::setOnreadystatechange(const QJSValue &value)
{
    m_onreadystatechange = value;
}

QJSValue JSKitXMLHttpRequest::ontimeout() const
{
    return m_ontimeout;
}

void JSKitXMLHttpRequest::setOntimeout(const QJSValue &value)
{
    m_ontimeout = value;
}

QJSValue JSKitXMLHttpRequest::onerror() const
{
    return m_onerror;
}

void JSKitXMLHttpRequest::setOnerror(const QJSValue &value)
{
    m_onerror = value;
}

uint JSKitXMLHttpRequest::readyState() const
{
    if (!m_reply) {
        return UNSENT;
    } else if (m_reply->isFinished()) {
        return DONE;
    } else {
        return LOADING;
    }
}

uint JSKitXMLHttpRequest::timeout() const
{
    return m_timeout;
}

void JSKitXMLHttpRequest::setTimeout(uint value)
{
    m_timeout = value;
    // TODO Handle fetch in-progress.
}

uint JSKitXMLHttpRequest::status() const
{
    if (!m_reply || !m_reply->isFinished()) {
        return 0;
    } else {
        return m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();
    }
}

QString JSKitXMLHttpRequest::statusText() const
{
    if (!m_reply || !m_reply->isFinished()) {
        return QString();
    } else {
        return m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    }
}

QString JSKitXMLHttpRequest::responseType() const
{
    return m_responseType;
}

void JSKitXMLHttpRequest::setResponseType(const QString &type)
{
    qCDebug(l) << "response type set to" << type;
    m_responseType = type;
}

QJSValue JSKitXMLHttpRequest::response() const
{
    if (m_responseType.isEmpty() || m_responseType == "text") {
        return m_engine->toScriptValue(QString::fromUtf8(m_response));
    } else if (m_responseType == "arraybuffer") {
        QJSValue arrayBufferProto = m_engine->globalObject().property("ArrayBuffer").property("prototype");
        QJSValue arrayBuf = m_engine->newObject();

        if (!arrayBufferProto.isUndefined()) {
            arrayBuf.setPrototype(arrayBufferProto);
            arrayBuf.setProperty("byteLength", m_engine->toScriptValue<uint>(m_response.size()));

            QJSValue array = m_engine->newArray(m_response.size());
            for (int i = 0; i < m_response.size(); i++) {
                array.setProperty(i, m_engine->toScriptValue<int>(m_response[i]));
            }

            arrayBuf.setProperty("_bytes", array);
            qCDebug(l) << "returning ArrayBuffer of" << m_response.size() << "bytes";
        } else {
            qCWarning(l) << "Cannot find proto of ArrayBuffer";
        }

        return arrayBuf;
    } else {
        qCWarning(l) << "unsupported responseType:" << m_responseType;
        return m_engine->toScriptValue<void*>(0);
    }
}

QString JSKitXMLHttpRequest::responseText() const
{
    return QString::fromUtf8(m_response);
}

void JSKitXMLHttpRequest::handleReplyFinished()
{
    if (!m_reply) {
        qCDebug(l) << "reply finished too late";
        return;
    }

    m_response = m_reply->readAll();
    qCDebug(l) << "reply finished, reply text:" << QString::fromUtf8(m_response) << "status:" << status();

    emit readyStateChanged();
    emit statusChanged();
    emit statusTextChanged();
    emit responseChanged();
    emit responseTextChanged();

    if (m_onload.isCallable()) {
        qCDebug(l) << "going to call onload handler:" << m_onload.toString();

        QJSValue result = m_onload.callWithInstance(m_engine->newQObject(this));
        if (result.isError()) {
            qCWarning(l) << "JS error on onload handler:" << JSKitManager::describeError(result);
        }
    } else {
        qCDebug(l) << "No onload set";
    }

    if (m_onreadystatechange.isCallable()) {
        qCDebug(l) << "going to call onreadystatechange handler:" << m_onreadystatechange.toString();
        QJSValue result = m_onreadystatechange.callWithInstance(m_engine->newQObject(this));
        if (result.isError()) {
            qCWarning(l) << "JS error on onreadystatechange handler:" << JSKitManager::describeError(result);
        }
    }
}

void JSKitXMLHttpRequest::handleReplyError(QNetworkReply::NetworkError code)
{
    if (!m_reply) {
        qCDebug(l) << "reply error too late";
        return;
    }

    qCDebug(l) << "reply error" << code;

    emit readyStateChanged();
    emit statusChanged();
    emit statusTextChanged();

    if (m_onerror.isCallable()) {
        qCDebug(l) << "going to call onerror handler:" << m_onload.toString();
        QJSValue result = m_onerror.callWithInstance(m_engine->newQObject(this));
        if (result.isError()) {
            qCWarning(l) << "JS error on onerror handler:" << JSKitManager::describeError(result);
        }
    }
}

void JSKitXMLHttpRequest::handleAuthenticationRequired(QNetworkReply *reply, QAuthenticator *auth)
{
    if (m_reply == reply) {
        qCDebug(l) << "authentication required";

        if (!m_username.isEmpty() || !m_password.isEmpty()) {
            qCDebug(l) << "using provided authorization:" << m_username;

            auth->setUser(m_username);
            auth->setPassword(m_password);
        } else {
            qCDebug(l) << "no username or password provided";
        }
    }
}