summaryrefslogtreecommitdiff
path: root/discord/websocket.cpp
blob: 8232ac6f18f283a622c9edcd21463a7e8b018417 (plain)
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
#include "websocket.hpp"
#include <functional>
#include <nlohmann/json.hpp>

Websocket::Websocket() {}

void Websocket::StartConnection(std::string url) {
    m_websocket.setUrl(url);
    m_websocket.setOnMessageCallback(std::bind(&Websocket::OnMessage, this, std::placeholders::_1));
    m_websocket.start();
}

void Websocket::Stop() {
    m_websocket.stop();
}

bool Websocket::IsOpen() const {
    auto state = m_websocket.getReadyState();
    return state == ix::ReadyState::Open;
}

void Websocket::SetJSONCallback(JSONCallback_t func) {
    m_json_callback = func;
}

void Websocket::Send(const std::string &str) {
    printf("sending %s\n", str.c_str());
    m_websocket.sendText(str);
}

void Websocket::Send(const nlohmann::json &j) {
    Send(j.dump());
}

void Websocket::OnMessage(const ix::WebSocketMessagePtr &msg) {
    switch (msg->type) {
        case ix::WebSocketMessageType::Message: {
            //if (msg->str.size() > 1000)
            //    printf("%s\n", msg->str.substr(0, 1000).c_str());
            //else
            //    printf("%s\n", msg->str.c_str());
            nlohmann::json obj;
            try {
                obj = nlohmann::json::parse(msg->str);
            } catch (std::exception &e) {
                printf("Error decoding JSON. Discarding message: %s\n", e.what());
                return;
            }
            if (m_json_callback)
                m_json_callback(obj);
        } break;
    }
}