-
Notifications
You must be signed in to change notification settings - Fork 2
/
QmlJsonRpcProvider.cpp
58 lines (47 loc) · 2.04 KB
/
QmlJsonRpcProvider.cpp
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
#include "QmlJsonRpcProvider.hpp"
#include <QDebug>
QmlJsonRpcProvider::QmlJsonRpcProvider(QObject* parent)
: QObject(parent) {}
QJSValue QmlJsonRpcProvider::call(QString method, QVariantList params) {
if (!m_socket)
return QJSValue::NullValue;
QJsonObject call {
{"jsonrpc", "2.0"},
{"method", method},
{"params", QJsonValue::fromVariant(params)},
{"id", qint64(nextQueryId)}
};
QString jsonCall = QJsonDocument(call).toJson(QJsonDocument::JsonFormat::Compact);
qDebug() << "Making call:" << jsonCall;
QMetaObject::invokeMethod(m_socket, "sendTextMessage", Q_ARG(QString, jsonCall));
return *pendingRequests.emplace(std::make_pair(nextQueryId++,
std::unique_ptr<QmlPromise>(new QmlPromise(this)))).first->second;
}
void QmlJsonRpcProvider::messageReceived(QString message) {
qDebug() << "Got response:" << message;
QJsonParseError error;
auto response = QJsonDocument::fromJson(message.toLocal8Bit(), &error).object();
if (error.error != QJsonParseError::ParseError::NoError || !response.contains("id") ||
(!response.contains("error") && !response.contains("result"))) {
qWarning() << "Got unrecognizeable message back from Bitshares wallet" << message;
return;
}
auto itr = pendingRequests.find(response["id"].toVariant().toLongLong());
if (itr == pendingRequests.end()) {
qWarning() << "Got response from Bitshares wallet, but the ID doesn't match any outstanding call:" << message;
return;
}
if (response.contains("result"))
itr->second->resolve(response["result"].toVariant());
else
itr->second->reject(response["error"].toVariant());
pendingRequests.erase(itr);
}
void QmlJsonRpcProvider::setSocket(QObject* socket) {
if (m_socket == socket)
return;
m_socket = socket;
if (m_socket)
connect(m_socket, SIGNAL(textMessageReceived(QString)), this, SLOT(messageReceived(QString)));
emit socketChanged(socket);
}