discord-rpc/src/discord-rpc.cpp

89 lines
2.4 KiB
C++
Raw Normal View History

2017-06-30 23:18:54 +00:00
#include "discord-rpc.h"
2017-07-17 16:28:54 +00:00
#include "rpc_connection.h"
2017-06-30 23:18:54 +00:00
#include "yolojson.h"
2017-07-13 15:32:08 +00:00
#include "rapidjson/document.h"
2017-06-30 23:18:54 +00:00
#include <stdio.h>
2017-06-30 23:18:54 +00:00
static RpcConnection* MyConnection = nullptr;
static char ApplicationId[64]{};
static DiscordEventHandlers Handlers{};
static bool WasJustConnected = false;
static bool WasJustDisconnected = false;
static int LastErrorCode = 0;
2017-07-13 15:32:08 +00:00
static char LastErrorMessage[256];
2017-06-30 23:18:54 +00:00
2017-07-07 21:00:29 +00:00
extern "C" void Discord_Initialize(const char* applicationId, DiscordEventHandlers* handlers)
2017-06-30 23:18:54 +00:00
{
if (handlers) {
Handlers = *handlers;
}
else {
Handlers = {};
}
2017-07-10 22:25:47 +00:00
MyConnection = RpcConnection::Create(applicationId);
MyConnection->onConnect = []() { WasJustConnected = true; };
2017-07-17 16:28:54 +00:00
MyConnection->onDisconnect = [](int err, const char* message) {
LastErrorCode = err;
StringCopy(LastErrorMessage, message, sizeof(LastErrorMessage));
WasJustDisconnected = true;
};
2017-06-30 23:18:54 +00:00
MyConnection->Open();
}
2017-07-07 21:00:29 +00:00
extern "C" void Discord_Shutdown()
2017-06-30 23:18:54 +00:00
{
Handlers = {};
2017-07-13 15:32:08 +00:00
MyConnection->onConnect = nullptr;
MyConnection->onDisconnect = nullptr;
2017-06-30 23:18:54 +00:00
MyConnection->Close();
RpcConnection::Destroy(MyConnection);
}
2017-07-07 21:00:29 +00:00
extern "C" void Discord_UpdatePresence(const DiscordRichPresence* presence)
2017-06-30 23:18:54 +00:00
{
auto frame = MyConnection->GetNextFrame();
frame->opcode = OPCODE::FRAME;
2017-06-30 23:18:54 +00:00
char* jsonWrite = frame->message;
JsonWriteRichPresenceObj(jsonWrite, presence);
2017-07-10 22:25:47 +00:00
frame->length = jsonWrite - frame->message;
2017-06-30 23:18:54 +00:00
MyConnection->WriteFrame(frame);
}
2017-07-07 16:41:20 +00:00
2017-07-07 21:00:29 +00:00
extern "C" void Discord_Update()
2017-07-07 16:41:20 +00:00
{
while (auto frame = MyConnection->Read()) {
2017-07-13 15:32:08 +00:00
rapidjson::Document d;
if (frame->length > 0) {
d.ParseInsitu(frame->message);
}
switch (frame->opcode) {
case OPCODE::HANDSHAKE:
// does this happen?
break;
case OPCODE::CLOSE:
LastErrorCode = d["code"].GetInt();
StringCopy(LastErrorMessage, d["code"].GetString(), sizeof(LastErrorMessage));
MyConnection->Close();
break;
case OPCODE::FRAME:
// todo
break;
}
}
2017-07-07 16:41:20 +00:00
// fire callbacks
if (WasJustDisconnected && Handlers.disconnected) {
WasJustDisconnected = false;
Handlers.disconnected(LastErrorCode, LastErrorMessage);
2017-07-07 16:41:20 +00:00
}
if (WasJustConnected && Handlers.ready) {
WasJustConnected = false;
2017-07-07 16:41:20 +00:00
Handlers.ready();
}
}