Skip to content

Commit

Permalink
TgBot++: socket: Refactor code 2
Browse files Browse the repository at this point in the history
- Namespace generalizations
- Two-step upload with dry procedure
  • Loading branch information
Royna2544 committed Jun 3, 2024
1 parent 78e2a6e commit 200211e
Show file tree
Hide file tree
Showing 24 changed files with 735 additions and 413 deletions.
6 changes: 2 additions & 4 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,7 @@ if (USE_UNIX_SOCKETS)
extend_set(SRC_LIST
src/ChatObserver.cpp
${SOCKET_SRC_INTERFACE}/impl/bot/SocketDataHandler.cpp
${SOCKET_SRC_INTERFACE}/impl/bot/TgBotSocketInterface.cpp
${SOCKET_SRC_INTERFACE}/impl/bot/TgBotSocketFileHelper.cpp)
${SOCKET_SRC_INTERFACE}/impl/bot/TgBotSocketInterface.cpp)
if (UNIX)
set(SOCKET_SRC_LIST
${SOCKET_SRC_INTERFACE}/impl/SocketPosix.cpp
Expand Down Expand Up @@ -333,8 +332,7 @@ if (USE_UNIX_SOCKETS)
endif()
target_link_libraries(TgBotSocket TgBotUtils)
add_executable(${SOCKET_CLI_NAME}
src/socket/TgBotSocketClient.cpp
${SOCKET_SRC_INTERFACE}/impl/bot/TgBotSocketFileHelper.cpp)
src/socket/TgBotSocketClient.cpp)

target_link_libraries(${SOCKET_CLI_NAME} TgBotSocket TgBotLogInit)
target_link_lib_if_windows(${SOCKET_CLI_NAME} Ws2_32)
Expand Down
10 changes: 5 additions & 5 deletions src/SpamBlocker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ using TgBot::ChatPermissions;

#ifdef SOCKET_CONNECTION
#include <socket/TgBotSocket.h>
CtrlSpamBlock gSpamBlockCfg = CTRL_ON;
TgBotSocket::data::CtrlSpamBlock gSpamBlockCfg = CtrlSpamBlock::CTRL_ON;
#endif

template <class Container, class Type>
Expand Down Expand Up @@ -143,7 +143,7 @@ void SpamBlockBase::addMessage(const Message::Ptr &message) {

#ifdef SOCKET_CONNECTION
// Global cfg
if (gSpamBlockCfg == CTRL_OFF) {
if (gSpamBlockCfg == CtrlSpamBlock::CTRL_OFF) {
return;
}
#endif
Expand Down Expand Up @@ -203,14 +203,14 @@ void SpamBlockManager::handleUserAndMessagePair(PerChatHandleConstRef e,
bool enforce = false;
#ifdef SOCKET_CONNECTION
switch (gSpamBlockCfg) {
case CTRL_ENFORCE:
case CtrlSpamBlock::CTRL_ENFORCE:
enforce = true;
[[fallthrough]];
case CTRL_ON: {
case CtrlSpamBlock::CTRL_ON: {
_deleteAndMuteCommon(it, e, threshold, name, enforce);
break;
}
case CTRL_LOGGING_ONLY_ON:
case CtrlSpamBlock::CTRL_LOGGING_ONLY_ON:
if (isEntryOverThreshold(e, threshold))
_logSpamDetectCommon(e, name);
break;
Expand Down
11 changes: 6 additions & 5 deletions src/database/utils/SendMediaToChat.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <impl/bot/ClientBackend.hpp>
#include <iostream>
#include <string>
#include "TgBotCommandExport.hpp"


[[noreturn]] static void usage(const char* argv0, const int exitCode) {
Expand All @@ -18,7 +19,7 @@

int main(int argc, char* const* argv) {
ChatId chatId = 0;
TgBotCommandData::SendFileToChatId data = {};
TgBotSocket::data::SendFileToChatId data = {};
const auto _usage = [capture0 = argv[0]](auto&& PH1) {
usage(capture0, std::forward<decltype(PH1)>(PH1));
};
Expand All @@ -43,10 +44,10 @@ int main(int argc, char* const* argv) {
LOG(INFO) << "Found, sending (fileid " << info->mediaId << ") to chat "
<< chatId;
}
strncpy(data.filepath, info->mediaId.c_str(), sizeof(data.filepath) - 1);
data.id = chatId;
data.type = TgBotCommandData::TYPE_DOCUMENT;
strncpy(data.filePath.data(), info->mediaId.c_str(), data.filePath.size());
data.chat = chatId;
data.fileType = TgBotSocket::data::FileType::TYPE_DOCUMENT;

struct TgBotCommandPacket pkt(CMD_SEND_FILE_TO_CHAT_ID, data);
struct TgBotSocket::Packet pkt(TgBotSocket::Command::CMD_SEND_FILE_TO_CHAT_ID, data);
getClientBackend()->writeAsClientToSocket(pkt.toSocketData());
}
2 changes: 1 addition & 1 deletion src/include/SpamBlock.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
#include <mutex>

#ifdef SOCKET_CONNECTION
using namespace TgBotCommandData;
using namespace TgBotSocket::data;
extern CtrlSpamBlock gSpamBlockCfg;
#endif

Expand Down
56 changes: 33 additions & 23 deletions src/socket/TgBotCommandMap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,52 +4,61 @@
#include <mutex>
#include <sstream>

#include "TgBotCommandExport.hpp"
#include "TgBotSocket.h"

#define ARGUMENT_SIZE(enum, len) array_helpers::make_elem(enum, len)
#define ARGUMENT_SIZE(enum, len) array_helpers::make_elem(Command::enum, len)

#undef ENUM_AND_STR
#define ENUM_AND_STR(e) \
array_helpers::make_elem<Command, const char*>(Command::e, #e)

using namespace TgBotSocket;

constexpr int MAX_LEN = static_cast<int>(Command::CMD_CLIENT_MAX);

constexpr auto kTgBotCommandStrMap =
array_helpers::make<CMD_CLIENT_MAX, TgBotCommand, const char*>(
array_helpers::make<MAX_LEN, TgBotSocket::Command, const char*>(
ENUM_AND_STR(CMD_WRITE_MSG_TO_CHAT_ID),
ENUM_AND_STR(CMD_CTRL_SPAMBLOCK), ENUM_AND_STR(CMD_OBSERVE_CHAT_ID),
ENUM_AND_STR(CMD_SEND_FILE_TO_CHAT_ID),
ENUM_AND_STR(CMD_OBSERVE_ALL_CHATS),
ENUM_AND_STR(CMD_DELETE_CONTROLLER_BY_ID),
ENUM_AND_STR(CMD_GET_UPTIME),
ENUM_AND_STR(CMD_UPLOAD_FILE),
ENUM_AND_STR(CMD_DOWNLOAD_FILE));
ENUM_AND_STR(CMD_DELETE_CONTROLLER_BY_ID), ENUM_AND_STR(CMD_GET_UPTIME),
ENUM_AND_STR(CMD_UPLOAD_FILE), ENUM_AND_STR(CMD_DOWNLOAD_FILE),
ENUM_AND_STR(CMD_UPLOAD_FILE_DRY));

const auto kTgBotCommandArgsCount =
array_helpers::make<CMD_CLIENT_MAX, TgBotCommand, int>(
array_helpers::make<MAX_LEN - 1, TgBotSocket::Command, int>(
ARGUMENT_SIZE(CMD_WRITE_MSG_TO_CHAT_ID, 2), // chatid, msg
ARGUMENT_SIZE(CMD_CTRL_SPAMBLOCK, 1), // policy
ARGUMENT_SIZE(CMD_OBSERVE_CHAT_ID, 2), // chatid, policy
ARGUMENT_SIZE(CMD_SEND_FILE_TO_CHAT_ID, 3), // chatid, type, filepath
ARGUMENT_SIZE(CMD_OBSERVE_ALL_CHATS, 1), // policy
ARGUMENT_SIZE(CMD_DELETE_CONTROLLER_BY_ID, 1), // id
ARGUMENT_SIZE(CMD_DELETE_CONTROLLER_BY_ID, 1), // id
ARGUMENT_SIZE(CMD_GET_UPTIME, 0),
ARGUMENT_SIZE(CMD_UPLOAD_FILE, 2), // source, dest filepath
ARGUMENT_SIZE(CMD_DOWNLOAD_FILE, 2)); // source, dest filepath
ARGUMENT_SIZE(CMD_UPLOAD_FILE, 2), // source, dest filepath
ARGUMENT_SIZE(CMD_DOWNLOAD_FILE, 2)); // source, dest filepath

namespace TgBotCmd {
std::string toStr(TgBotCommand cmd) {
const auto *const it = array_helpers::find(kTgBotCommandStrMap, cmd);
namespace TgBotSocket::CommandHelpers {

std::string toStr(Command cmd) {
const auto* const it = array_helpers::find(kTgBotCommandStrMap, cmd);
LOG_IF(FATAL, it == kTgBotCommandStrMap.end())
<< "Couldn't find cmd " << cmd << " in map";
<< "Couldn't find cmd " << static_cast<int>(cmd) << " in map";
return it->second;
}

int toCount(TgBotCommand cmd) {
int toCount(Command cmd) {
const auto* const it = array_helpers::find(kTgBotCommandArgsCount, cmd);
LOG_IF(FATAL, it == kTgBotCommandArgsCount.end())
<< "Couldn't find cmd " << cmd << " in map";
<< "Couldn't find cmd " << static_cast<int>(cmd) << " in map";
return it->second;
}

bool isClientCommand(TgBotCommand cmd) { return cmd < CMD_CLIENT_MAX; }
bool isClientCommand(Command cmd) { return cmd < Command::CMD_CLIENT_MAX; }

bool isInternalCommand(TgBotCommand cmd) {
return cmd >= CMD_SERVER_INTERNAL_START;
bool isInternalCommand(Command cmd) {
return cmd >= Command::CMD_SERVER_INTERNAL_START;
}

std::string getHelpText() {
Expand All @@ -61,10 +70,10 @@ std::string getHelpText() {
for (const auto& ent : kTgBotCommandStrMap) {
int count = 0;

count = TgBotCmd::toCount(ent.first);
count = toCount(ent.first);

help << ent.second << ": value " << ent.first << ", Requires "
<< count << " argument";
help << ent.second << ": value " << static_cast<int>(ent.first)
<< ", Requires " << count << " argument";
if (count > 1) {
help << "s";
}
Expand All @@ -74,4 +83,5 @@ std::string getHelpText() {
});
return helptext;
}
} // namespace TgBotCmd

} // namespace TgBotSocket::CommandHelpers
60 changes: 27 additions & 33 deletions src/socket/TgBotSocket.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,61 +6,53 @@
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <string>
#include <type_traits>

#include "SharedMalloc.hpp"

inline std::filesystem::path getSocketPath() {
static auto spath = std::filesystem::temp_directory_path() / "tgbot.sock";
return spath;
}

#define TGBOT_NAMESPACE_BEGIN namespace TgBotCommandData {
#define TGBOT_NAMESPACE_END }
#include "TgBotCommandExport.hpp"

namespace TgBotCmd {
namespace TgBotSocket {
namespace CommandHelpers {
/**
* @brief Convert TgBotCommand to string
*
* @param cmd TgBotCommand to convert
* @return std::string string representation of TgBotCommand enum
* @param cmd Command to convert
* @return std::string string representation of Command enum
*/
std::string toStr(TgBotCommand cmd);
std::string toStr(Command cmd);

/**
* @brief Get count of TgBotCommand
* @brief Get count of Command
*
* @param cmd TgBotCommand to get arg count of
* @return required arg count of TgBotCommand
* @param cmd Command to get arg count of
* @return required arg count of Command
*/
int toCount(TgBotCommand cmd);
int toCount(Command cmd);

/**
* @brief Check if given command is a client command
*
* @param cmd TgBotCommand to check
* @param cmd Command to check
* @return true if given command is a client command, false otherwise
*/
bool isClientCommand(TgBotCommand cmd);
bool isClientCommand(Command cmd);

/**
* @brief Check if given command is an internal command
*
* @param cmd TgBotCommand to check
* @param cmd Command to check
* @return true if given command is an internal command, false otherwise
*/
bool isInternalCommand(TgBotCommand cmd);
bool isInternalCommand(Command cmd);

/**
* @brief Get help text for TgBotCommand
* @brief Get help text for Command
*
* @return std::string help text for TgBotCommand
* @return std::string help text for Command
*/
std::string getHelpText(void);
} // namespace TgBotCmd
} // namespace CommandHelpers

/**
* @brief Packet for sending commands to the server
Expand All @@ -72,29 +64,29 @@ std::string getHelpText(void);
* It contains a header, which contains the magic value, the command, and the
* size of the data. The data is then followed by the actual data.
*/
struct TgBotCommandPacket {
static constexpr auto hdr_sz = sizeof(TgBotCommandPacketHeader);
using header_type = TgBotCommandPacketHeader;
struct Packet {
static constexpr auto hdr_sz = sizeof(PacketHeader);
using header_type = PacketHeader;
header_type header{};
SharedMalloc data;

explicit TgBotCommandPacket(header_type::length_type length)
explicit Packet(header_type::length_type length)
: data(length) {
header.magic = header_type::MAGIC_VALUE;
header.data_size = length;
}

// Constructor that takes malloc
template <typename T>
explicit TgBotCommandPacket(TgBotCommand cmd, T data)
: TgBotCommandPacket(cmd, &data, sizeof(T)) {
explicit Packet(Command cmd, T data)
: Packet(cmd, &data, sizeof(T)) {
static_assert(!std::is_pointer_v<T>,
"This constructor should not be used with a pointer");
}

// Constructor that takes pointer, uses malloc but with size
template <typename T>
explicit TgBotCommandPacket(TgBotCommand cmd, T in_data, std::size_t size)
explicit Packet(Command cmd, T in_data, std::size_t size)
: data(size) {
boost::crc_32_type crc;

Expand All @@ -112,8 +104,10 @@ struct TgBotCommandPacket {
SharedMalloc toSocketData() {
data->size = hdr_sz + header.data_size;
data->alloc();
memmove(static_cast<char*>(data.get()) + hdr_sz, data.get(), header.data_size);
memmove(static_cast<char*>(data.get()) + hdr_sz, data.get(),
header.data_size);
memcpy(data.get(), &header, hdr_sz);
return data;
}
};
};
} // namespace TgBotSocket
Loading

0 comments on commit 200211e

Please sign in to comment.