mirror of
https://gitlab.com/comunic/comunicwatcher
synced 2024-10-22 22:53:24 +00:00
48 lines
1.2 KiB
C++
48 lines
1.2 KiB
C++
|
#include <QTimer>
|
||
|
|
||
|
#include "apirequest.h"
|
||
|
#include "wsclient.h"
|
||
|
#include "config.h"
|
||
|
|
||
|
WsClient::WsClient(QObject *parent) : QObject(parent)
|
||
|
{
|
||
|
startConnect();
|
||
|
|
||
|
connect(&mWebSocket, &QWebSocket::connected, this, &WsClient::onConnected);
|
||
|
connect(&mWebSocket, &QWebSocket::disconnected, this, &WsClient::onConnectionError);
|
||
|
}
|
||
|
|
||
|
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";
|
||
|
}
|