This commit is contained in:
fluttershy 2025-01-29 16:06:47 +05:00
parent 90ddcff78b
commit 2e54a17b5d
19 changed files with 242 additions and 213 deletions

View File

@ -2,6 +2,8 @@ cmake_minimum_required(VERSION 3.10)
project(sparkle)
#target_precompile_headers(${PROJECT_NAME} PRIVATE pch.h)
include(GoogleTest)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
@ -49,11 +51,11 @@ message(STATUS "${CMAKE_BUILD_TYPE}")
add_executable(${PROJECT_NAME} ${SOURCE} ${NETWORK_SOURCES} ${WEBSOCKET_SOURCES})
#add_library(sparkles STATIC ${SOURCE})
add_executable(tests ${TESTS}/tests.cpp)
#add_executable(tests ${TESTS}/tests.cpp)
enable_testing()
#enable_testing()
add_test(NAME NetworkManagerTest COMMAND tests)
#add_test(NAME NetworkManagerTest COMMAND tests)
target_include_directories(${PROJECT_NAME} PRIVATE
${LIBS}
@ -67,15 +69,15 @@ target_link_libraries(${PROJECT_NAME} PRIVATE
${CURL_LIBRARIES}
)
target_include_directories(tests PRIVATE
${LIBS}
${INCLUDE}
${IXWEBSOCKET_INCLUDE_DIR}
${CURL_INCLUDE_DIRS}
)
#target_include_directories(tests PRIVATE
# ${LIBS}
# ${INCLUDE}
# ${IXWEBSOCKET_INCLUDE_DIR}
# ${CURL_INCLUDE_DIRS}
#)
target_link_libraries(tests gtest
${IXWEBSOCKET_LIBRARIES}
${CURL_LIBRARIES}
gtest_main
)
#target_link_libraries(tests gtest
# ${IXWEBSOCKET_LIBRARIES}
# ${CURL_LIBRARIES}
# gtest_main
#)

View File

@ -1,10 +1,10 @@
#ifndef INCLUDE_API_HPP_
#define INCLUDE_API_HPP_
#include <api/Author.hpp>
#include <api/Message.hpp>
#include <api/Channel.hpp>
#include <api/Embed.hpp>
#include <api/Bot.hpp>
#include <api/User.hpp>
#include <api/Guild.hpp>
#ifndef INCLUDE_INTERFACE_HPP_
#define INCLUDE_INTERFACE_HPP_
#include <interface/Author.hpp>
#include <interface/Message.hpp>
#include <interface/Channel.hpp>
#include <interface/Embed.hpp>
#include <interface/Bot.hpp>
#include <interface/User.hpp>
#include <interface/Guild.hpp>
#endif

View File

@ -1,6 +1,6 @@
#ifndef INCLUDE_INCLUDES_HPP_
#define INCLUDE_INCLUDES_HPP_
#include <utils/types.hpp>
//#include <utils/types.hpp>
#include <utils/json.hpp>
#include <utils/log.hpp>
#include <utils/enums.hpp>

View File

@ -1,5 +1,5 @@
#ifndef INCLUDE_NET_HPP_
#define INCLUDE_NET_HPP_
#include <gateway/websocket.hpp>
#include <network/websocket.hpp>
#include <network/network.hpp>
#endif

3
libs/api/Activity.hpp Normal file
View File

@ -0,0 +1,3 @@
#ifndef API_ACTIVITY_HPP_
#define API_ACTIVITY_HPP_
#endif

View File

@ -1,154 +0,0 @@
#ifndef GATEWAY_WEBSOCKET_HPP_
#define GATEWAY_WEBSOCKET_HPP_
#include <includes.hpp>
#include <ixwebsocket/IXNetSystem.h>
#include <ixwebsocket/IXWebSocket.h>
class EventEmitter {
private:
using eventHandlers = std::function<void(const nlohmann::json&)>;
std::unordered_map<std::string, std::vector<eventHandlers>> handlers;
protected:
void emit(const std::string& event, const nlohmann::json& data) {
if (handlers.find(event) != handlers.end()) {
for (const auto& handler : handlers[event]) {
handler(data);
}
}
}
public:
void getEvents() {
Log::create(CRITICAL, WEBSOCKET, "Event list");
for (const auto& handler : handlers) {
Log::create(INFO, WEBSOCKET, handler.first);
}
Log::create(CRITICAL, WEBSOCKET, "End of list");
}
void start() {
while (1) std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
void on(const std::string& event, eventHandlers handler) {
handlers[event].emplace_back(handler);
}
void once(const std::string& event, eventHandlers handler) {
auto wrappedHandler = [this, event, handler](const nlohmann::json& data) {
handler(data);
off(event, handler);
};
handlers[event].emplace_back(wrappedHandler);
}
void off(const std::string& event, eventHandlers handler) {
if (handlers.find(event) != handlers.end()) {
auto& vec = handlers[event];
vec.erase(std::remove_if(vec.begin(), vec.end(), [&handler](const eventHandlers& h) {
return h.target<eventHandlers>() == handler.target<eventHandlers>();
}), vec.end());
}
}
};
class WebSocket : public EventEmitter {
private:
std::string token;
int intents;
bool isBot;
ix::WebSocket webSocket;
const nlohmann::json payload = { {"op", GatewayOpcodes::Heartbeat}, {"d", nullptr} };
WebSocket& operator=(const WebSocket&) = delete;
WebSocket& operator=(WebSocket&&) = delete;
WebSocket(WebSocket&&) = delete;
WebSocket(const WebSocket&) = delete;
WebSocket(const std::string& token, const int& intents, const bool& isBot) : token(token), intents(intents), isBot(isBot) {
nlohmann::json id = {
{"op", GatewayOpcodes::Identify},
{"d", {
{"token", token},
{"intents", intents},
{"properties", {
{"os", "linux"},
{"browser", "firefox"},
{"device", "firefox"}
}},
{"compress", 1},
{"presence", {
{"activities", nlohmann::json::array({
{
{"name", "meow"},
{"type", 2}
}
})},
{"status", "idle"},
{"since", 91879201},
{"afk", false}
}}
}}
};
ix::initNetSystem();
webSocket.setUrl("wss://gateway.discord.gg/?v=10&encoding=json");
webSocket.disableAutomaticReconnection();
Log::create(INFO, WEBSOCKET, "ixwebsocket init");
webSocket.setOnMessageCallback([this, res = nlohmann::json(), heartbeat_interval = 0, connected = false, id](const ix::WebSocketMessagePtr& msg) mutable {
switch (msg->type) {
case ix::WebSocketMessageType::Message:
res = nlohmann::json::parse(msg->str);
Log::create(INFO, WEBSOCKET, std::to_string(res["op"].get<int>()) + " " + res["t"].dump());
switch (res["op"].get<GatewayOpcodes>()) {
case GatewayOpcodes::Hello:
heartbeat_interval = res["d"]["heartbeat_interval"].get<int>();
!connected ? connected = true, webSocket.send(id.dump()) : 0;
std::thread([this, &heartbeat_interval, &connected]() {
while (connected && heartbeat_interval != -1) {
Log::create(INFO, WEBSOCKET, "Heartbeat " + std::to_string(heartbeat_interval));
std::this_thread::sleep_for(std::chrono::milliseconds(heartbeat_interval));
webSocket.send(payload.dump());
}
}).detach();
break;
case GatewayOpcodes::Dispatch:
Log::force_create(INFO, WEBSOCKET, res.dump());
emit(res["t"].get<std::string>(), res);
break;
default:
break;
}
break;
case ix::WebSocketMessageType::Error:
Log::force_create(ERROR, WEBSOCKET, msg->errorInfo.reason);
exit(-1);
break;
default:
break;
}
});
webSocket.start();
}
public:
[[maybe_unused]]
void sendPresenceUpdate(const int& statusType, const std::string& activityName) {
nlohmann::json prsUpdate = {
{"op", 3},
{"d", {
{"since", 0},
{"activities", nlohmann::json::array({{"name", activityName}, {"type", 2}})},
{"status", statusType == 1 ? "online" : "idle"},
{"afk", false}
}}
};
webSocket.send(prsUpdate.dump());
}
static WebSocket& getInstance(const std::string& token = "", const int& intents = 0, const bool& bot = true) {
Log::create(INFO, WEBSOCKET, "Instance event");
static WebSocket instance(token, intents, bot);
return instance;
}
~WebSocket() {
webSocket.close();
ix::uninitNetSystem();
}
std::string getToken() const {
return isBot ? std::string("Bot " + WebSocket::token) : WebSocket::token;
}
int getIntents() const {
return WebSocket::intents;
}
};
#endif

View File

@ -1,7 +1,7 @@
#ifndef API_AUTHOR_HPP_
#define API_AUTHOR_HPP_
#ifndef INTERFACE_AUTHOR_HPP_
#define INTERFACE_AUTHOR_HPP_
#include <includes.hpp>
#include <net.hpp>
#include <network.hpp>
class Author {
private:
const nlohmann::json& data;
@ -35,7 +35,8 @@ public:
discriminator(functions::testValue<std::string>(data, { "d", "author", "discriminator" }).value_or("")),
message_id(functions::testValue<std::string>(data, { "d", "id" }).value_or("")),
isPinned(functions::testValue<bool>(data, { "d", "pinned" }).value_or(false)),
isBot(functions::testValue<bool>(data, { "d", "author", "bot" }).value_or(false)) {}
isBot(functions::testValue<bool>(data, { "d", "author", "bot" }).value_or(false)) {
}
std::string send(const nlohmann::json& msg) {
return req.request(HttpMethods::POST, DiscordEndpoints::details::latest + "/channels/" + data["d"]["channel_id"].get<std::string>() + "/messages", msg.dump());
}

View File

@ -1,5 +1,5 @@
#ifndef API_BOT_HPP_
#define API_BOT_HPP_
#ifndef INTERFACE_BOT_HPP_
#define INTERFACE_BOT_HPP_
#include <includes.hpp>
template<typename...Args>
class Discord {

View File

@ -1,7 +1,7 @@
#ifndef API_CHANNEL_HPP_
#define API_CHANNEL_HPP_
#ifndef INTERFACE_CHANNEL_HPP_
#define INTERFACE_CHANNEL_HPP_
#include <includes.hpp>
#include <net.hpp>
#include <network.hpp>
class Channel {
private:
const nlohmann::json& data;

View File

@ -1,5 +1,5 @@
#ifndef API_EMBED_HPP_
#define API_EMBED_HPP_
#ifndef INTERFACE_EMBED_HPP_
#define INTERFACE_EMBED_HPP_
#include <includes.hpp>
class EmbedBuilder {
private:

View File

@ -1,7 +1,7 @@
#ifndef API_GUILD_HPP_
#define API_GUILD_HPP_
#ifndef INTERFACE_GUILD_HPP_
#define INTERFACE_GUILD_HPP_
#include <includes.hpp>
#include <net.hpp>
#include <network.hpp>
class Guild {
private:
nlohmann::json data;

View File

@ -1,7 +1,7 @@
#ifndef API_MESSAGE_HPP_
#define API_MESSAGE_HPP_
#ifndef INTERFACE_MESSAGE_HPP_
#define INTERFACE_MESSAGE_HPP_
#include <includes.hpp>
#include <net.hpp>
#include <network.hpp>
class Message {
private:
const nlohmann::json& data;

View File

@ -1,7 +1,7 @@
#ifndef API_USER_HPP_
#define API_USER_HPP_
#ifndef INTERFACE_USER_HPP_
#define INTERFACE_USER_HPP_
#include <includes.hpp>
#include <net.hpp>
#include <network.hpp>
#include <vector>
class User {
private:
@ -17,7 +17,6 @@ public:
}
}
bool isBot;
/*
nlohmann::json extract(const std::vector<std::string>& keys) {
std::vector<std::string> d = { "d" };
d.insert(d.end(), keys.begin(), keys.end());
@ -31,7 +30,6 @@ public:
}
return current;
};
*/
std::string me() {
return req.request(HttpMethods::GET, DiscordEndpoints::details::latest + "/users/@me");
}

View File

@ -1,7 +1,7 @@
#ifndef TLS_NETWORK_HPP_
#define TLS_NETWORK_HPP_
#include <includes.hpp>
#include <gateway/websocket.hpp>
#include <network/websocket.hpp>
#include <curl/curl.h>
class NetworkManager {
private:

130
libs/network/websocket.cpp Normal file
View File

@ -0,0 +1,130 @@
#include "websocket.hpp"
void EventEmitter::emit(const std::string& event, const nlohmann::json& data) {
if (handlers.find(event) != handlers.end()) {
for (const auto& handler : handlers[event]) {
handler(data);
}
}
}
void EventEmitter::getEvents() {
Log::create(CRITICAL, WEBSOCKET, "Event list");
for (const auto& handler : handlers) {
Log::create(INFO, WEBSOCKET, handler.first);
}
Log::create(CRITICAL, WEBSOCKET, "End of list");
}
void EventEmitter::start() {
while (1) std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
void EventEmitter::on(const std::string& event, eventHandlers handler) {
handlers[event].emplace_back(handler);
}
void EventEmitter::once(const std::string& event, eventHandlers handler) {
auto wrappedHandler = [this, event, handler](const nlohmann::json& data) {
handler(data);
off(event, handler);
};
handlers[event].emplace_back(wrappedHandler);
}
void EventEmitter::off(const std::string& event, eventHandlers handler) {
if (handlers.find(event) != handlers.end()) {
auto& vec = handlers[event];
vec.erase(std::remove_if(vec.begin(), vec.end(), [&handler](const eventHandlers& h) {
return h.target<eventHandlers>() == handler.target<eventHandlers>();
}), vec.end());
}
}
WebSocket::WebSocket(const std::string& token, const int& intents, const bool& isBot) : token(token), intents(intents), isBot(isBot) {
nlohmann::json id = {
{"op", GatewayOpcodes::Identify},
{"d", {
{"token", token},
{"intents", intents},
//{"shard", {{0}}},
{"properties", {
{"os", "linux"},
{"browser", "firefox"},
{"device", "firefox"}
}},
{"compress", 1},
{"presence", {
{"activities", nlohmann::json::array({
{
{"name", "meow"},
{"type", 2}
}
})},
{"status", "idle"},
{"since", 91879201},
{"afk", false}
}}
}}
};
ix::initNetSystem();
webSocket.setUrl("wss://gateway.discord.gg/?v=10&encoding=json");
webSocket.disableAutomaticReconnection();
Log::create(INFO, WEBSOCKET, "ixwebsocket init");
webSocket.setOnMessageCallback([this, res = nlohmann::json(), heartbeat_interval = 0, connected = false, id](const ix::WebSocketMessagePtr& msg) mutable {
switch (msg->type) {
case ix::WebSocketMessageType::Message:
res = nlohmann::json::parse(msg->str);
Log::create(INFO, WEBSOCKET, std::to_string(res["op"].get<int>()) + " " + res["t"].dump());
switch (res["op"].get<GatewayOpcodes>()) {
case GatewayOpcodes::Hello:
heartbeat_interval = res["d"]["heartbeat_interval"].get<int>();
!connected ? connected = true, webSocket.send(id.dump()) : 0;
std::thread([this, &heartbeat_interval, &connected]() {
while (connected && heartbeat_interval != -1) {
Log::create(INFO, WEBSOCKET, "Heartbeat " + std::to_string(heartbeat_interval));
std::this_thread::sleep_for(std::chrono::milliseconds(heartbeat_interval));
webSocket.send(payload.dump());
}
}).detach();
break;
case GatewayOpcodes::Dispatch:
Log::create(INFO, WEBSOCKET, res.dump());
emit(res["t"].get<std::string>(), res);
break;
default:
break;
}
break;
case ix::WebSocketMessageType::Error:
Log::force_create(ERROR, WEBSOCKET, msg->errorInfo.reason);
exit(-1);
break;
default:
break;
}
});
webSocket.start();
}
WebSocket& WebSocket::getInstance(const std::string& token, const int& intents, const bool& bot) {
Log::create(INFO, WEBSOCKET, "Instance event");
static WebSocket instance(token, intents, bot);
return instance;
}
WebSocket::~WebSocket() {
webSocket.close();
ix::uninitNetSystem();
}
std::string WebSocket::getToken() const {
return isBot ? std::string("Bot " + WebSocket::token) : WebSocket::token;
}
int WebSocket::getIntents() const {
return WebSocket::intents;
}
[[maybe_unused]]
void WebSocket::sendPresenceUpdate(const char* statusType, const std::string& activityName, const int& activityType) {
nlohmann::json prsUpdate = {
{"op", 3},
{"d", {
{"since", 0},
{"activities", nlohmann::json::array({{"name", activityName}, {"type", activityType}})},
{"status", statusType},
{"afk", false}
}}
};
webSocket.send(prsUpdate.dump());
}

View File

@ -0,0 +1,39 @@
#ifndef NETWORK_WEBSOCKET_HPP_
#define NETWORK_WEBSOCKET_HPP_
#include <includes.hpp>
#include <ixwebsocket/IXNetSystem.h>
#include <ixwebsocket/IXWebSocket.h>
class EventEmitter {
private:
using eventHandlers = std::function<void(const nlohmann::json&)>;
std::unordered_map<std::string, std::vector<eventHandlers>> handlers;
protected:
void emit(const std::string& event, const nlohmann::json& data);
public:
void getEvents();
void start();
void on(const std::string& event, eventHandlers handler);
void once(const std::string& event, eventHandlers handler);
void off(const std::string& event, eventHandlers handler);
};
class WebSocket : public EventEmitter {
private:
std::string token;
int intents;
bool isBot;
ix::WebSocket webSocket;
const nlohmann::json payload = { {"op", GatewayOpcodes::Heartbeat}, {"d", nullptr} };
WebSocket& operator=(const WebSocket&) = delete;
WebSocket& operator=(WebSocket&&) = delete;
WebSocket(WebSocket&&) = delete;
WebSocket(const WebSocket&) = delete;
WebSocket(const std::string& token, const int& intents, const bool& isBot);
public:
[[maybe_unused]]
void sendPresenceUpdate(const char* statusType, const std::string& activityName, const int& activityType);
static WebSocket& getInstance(const std::string& token = "", const int& intents = 0, const bool& bot = true);
~WebSocket();
std::string getToken() const;
int getIntents() const;
};
#endif

View File

@ -103,6 +103,21 @@ struct DiscordEndpoints {
static const inline std::string latest = DiscordEndpoints::discord + ApiVersion::latest;
};
};
struct StatusType {
static inline const char* Offline = "offline";
static inline const char* Online = "online";
static inline const char* Idle = "idle";
static inline const char* DND = "dnd";
static inline const char* Invisible = "invisible";
};
enum ActivityType {
Playing,
Streaming,
Listening,
Watching,
Custom,
Competing
};
enum GatewayIntents {
AutoModerationConfiguration = 1048576,
AutoModerationExecution = 2097152,
@ -129,14 +144,6 @@ enum GatewayIntents {
MessageContent = 32768,
AllIntents = 131071
};
enum UserStatus {
Offline,
Online,
Idle,
AFK,
DoNotDisturb,
Invisible
};
enum DiscordTime {
Epoch = 1420070400000,
};

View File

@ -36,8 +36,11 @@ int main(int argc, char* argv[]) {
bot->on(GatewayEvents::MESSAGE_CREATE, [bot](const Discord<Message, User, Author>& msg) {
auto& [message, user, author] = msg.ctx();
message->send("939957962972229634", message->pack("content", std::to_string(user->isBot)));
bot->getEvents();
if (!author->isBot) {
message->send("939957962972229634", message->pack("content", std::to_string(user->isBot)));
bot->getEvents();
bot->sendPresenceUpdate(StatusType::DND, "meow", ActivityType::Streaming);
}
});
bot->start();
return 0;

View File

@ -1,7 +1,7 @@
/*
#include <gtest/gtest.h>
#include <includes.hpp>
#include <net.hpp>
#include <network.hpp>
TEST(NetworkManagerTest, RequestReturnsExpectedValue) {
NetworkManager& networkManager = NetworkManager::getInstance();
EXPECT_FALSE(networkManager.request(HttpMethods::POST, DiscordEndpoints::details::latest + "/channels/939957962972229634/messages", { "content", "test" }).empty());