2020-06-13 09:28:08 +00:00
|
|
|
#include <QTimer>
|
2020-06-13 11:57:29 +00:00
|
|
|
#include <QJsonDocument>
|
2020-06-13 09:28:08 +00:00
|
|
|
|
|
|
|
#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:45:08 +00:00
|
|
|
connect(&mWebSocket, &QWebSocket::textMessageReceived, this, &WsClient::onMessage);
|
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";
|
2020-06-13 12:14:01 +00:00
|
|
|
|
|
|
|
emit connected();
|
2020-06-13 09:28:08 +00:00
|
|
|
}
|
2020-06-13 09:45:08 +00:00
|
|
|
|
|
|
|
void WsClient::onMessage(const QString &msg)
|
|
|
|
{
|
|
|
|
qDebug() << "WS message: " << msg;
|
2020-06-13 11:57:29 +00:00
|
|
|
|
|
|
|
auto obj = QJsonDocument::fromJson(msg.toUtf8()).object();
|
|
|
|
auto title = obj.value("title").toString();
|
|
|
|
auto value = obj.value("data").toInt(-1);
|
|
|
|
|
|
|
|
if(title == "number_notifs")
|
|
|
|
emit newNumberNotifs(value);
|
|
|
|
|
|
|
|
else if(title == "number_unread_conversations")
|
|
|
|
emit newNumberConvs(value);
|
2020-06-13 09:45:08 +00:00
|
|
|
}
|