2020-06-13 09:28:08 +00:00
|
|
|
#include <QTimer>
|
|
|
|
|
|
|
|
#include "apirequest.h"
|
|
|
|
#include "wsclient.h"
|
|
|
|
#include "config.h"
|
|
|
|
|
|
|
|
WsClient::WsClient(QObject *parent) : QObject(parent)
|
|
|
|
{
|
|
|
|
connect(&mWebSocket, &QWebSocket::connected, this, &WsClient::onConnected);
|
|
|
|
connect(&mWebSocket, &QWebSocket::disconnected, this, &WsClient::onConnectionError);
|
2020-06-13 09:40:39 +00:00
|
|
|
|
|
|
|
startConnect();
|
2020-06-13 09:28:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void WsClient::startConnect()
|
|
|
|
{
|
|
|
|
// First, get an access token
|
|
|
|
APIRequest *r = new APIRequest("ws/token");
|
|
|
|
r->exec();
|
|
|
|
connect(r, &APIRequest::done, this, &WsClient::getTokenCallBack);
|
|
|
|
}
|
|
|
|
|
|
|
|
void WsClient::onConnectionError()
|
|
|
|
{
|
|
|
|
qWarning("Connection error, trying again in 30 seconds...");
|
|
|
|
QTimer::singleShot(30000, this, &WsClient::startConnect);
|
|
|
|
}
|
|
|
|
|
|
|
|
void WsClient::getTokenCallBack(APIResponse res)
|
|
|
|
{
|
|
|
|
if(res.isError()) {
|
|
|
|
onConnectionError();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Determine WebSocket URL
|
|
|
|
const auto token = res.getObject().value("token").toString();
|
|
|
|
const auto ws_url = QString(QString(API_SERVER_SCHEME) == "https" ? "wss" : "ws") + "://" + API_HOST + API_BASE_PATH + "ws?token=" + token;
|
|
|
|
qDebug() << "Connecting to " << ws_url;
|
|
|
|
|
|
|
|
mWebSocket.open(ws_url);
|
|
|
|
}
|
|
|
|
|
|
|
|
void WsClient::onConnected()
|
|
|
|
{
|
|
|
|
qDebug() << "Connected to WebSocket";
|
|
|
|
}
|