#include #include #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); connect(&mWebSocket, &QWebSocket::textMessageReceived, this, &WsClient::onMessage); startConnect(); } 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"; emit connected(); } void WsClient::onMessage(const QString &msg) { qDebug() << "WS message: " << msg; 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); }