Migrate core infrastructure to VoidLibrary

This commit is contained in:
faumaray committed 2026-06-22 15:53:23 +03:00
1 parent 53801f2b53
commit 2bdb63766d
65 files changed
+16109 -12011

No files matched your search

+704 -570
View File
File diff suppressed because it is too large. Load diff
-46
View File
@@ -1,46 +0,0 @@
#include "echoion/api/Cache.hpp"
#include "echoion/core/Logger.hpp"
namespace Echoion::Api {
CacheManager& CacheManager::instance() {
static CacheManager instance;
return instance;
}
void CacheManager::initialize() {
ECHOION_LOG_INFO("CacheManager initialized");
}
void CacheManager::shutdown() {
clearAll();
ECHOION_LOG_INFO("CacheManager shutdown");
}
void CacheManager::purgeAllExpired() {
size_t totalPurged = 0;
totalPurged += httpCache_.purgeExpired();
totalPurged += trackCache_.purgeExpired();
totalPurged += metadataCache_.purgeExpired();
if (totalPurged > 0) {
ECHOION_LOG_INFO(std::format("Purged {} expired cache entries", totalPurged));
}
}
void CacheManager::clearAll() {
httpCache_.clear();
trackCache_.clear();
metadataCache_.clear();
ECHOION_LOG_INFO("All caches cleared");
}
std::unordered_map<std::string, CacheStats> CacheManager::getAllStats() const {
return {
{"http", httpCache_.getStats()},
{"track", trackCache_.getStats()},
{"metadata", metadataCache_.getStats()}
};
}
} // namespace Echoion::Api
+478 -430
View File
@@ -1,468 +1,516 @@
#include "echoion/api/ConfigTypes.hpp"
#include "echoion/core/CommandManager.hpp"
#include "echoion/core/Logger.hpp"
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/commands/Command.hpp"
#include <ConfigTypes.hpp>
#include <algorithm>
#include <echoion/core/commands/Commands.hpp>
#include <format>
#include <sstream>
namespace Echoion::Core {
namespace Echoion::Core
{
// --- Internal Help Command ---
class CommandManager::HelpCommand : public Command {
CommandManager& manager_;
// --- Internal Help Command ---
class CommandManager::HelpCommand : public Command
{
CommandManager& manager_;
public:
explicit HelpCommand(CommandManager& mgr) : manager_(mgr) {}
public:
void execute(const CommandContext& ctx) override {
try {
auto prefix = manager_.getPrefix();
std::string helpMsg = std::format("\xf0\x9f\x8e\xb5 **Echoion Bot Help**\n\n");
helpMsg += std::format("Prefix: `{}`\n\n", prefix);
explicit HelpCommand(CommandManager& mgr) : manager_(mgr) {}
// Get commands visible to this client
auto visibleCommands = manager_.getVisibleCommands(ctx.clientId);
void execute(const CommandContext& ctx) override
{
try {
auto prefix = manager_.getPrefix();
// Group commands by category
std::map<CommandCategory, std::vector<std::pair<std::string, CommandPtr>>> grouped;
for (const auto& [name, cmd] : visibleCommands) {
grouped[cmd->getCategory()].push_back({name, cmd});
}
std::string helpMsg = std::format(
"\xf0\x9f\x8e\xb5 **Echoion Bot Help**\n\n");
helpMsg += std::format("Prefix: `{}`\n\n", prefix);
for (const auto& [cat, cmds] : grouped) {
helpMsg += std::format("**{} Commands**\n", toString(cat));
// Get commands visible to this client
auto visibleCommands =
manager_.getVisibleCommands(ctx.clientId);
for (const auto& [name, cmd] : cmds) {
// Format: prefix!command usage
if (!cmd->getUsage().empty()) {
helpMsg += std::format("`{}{}` {}\n", prefix, name, cmd->getUsage());
} else {
helpMsg += std::format("`{}{}`\n", prefix, name);
}
// Group commands by category
std::map<CommandCategory,
std::vector<std::pair<std::string, CommandPtr>>>
grouped;
// Description
helpMsg += std::format("> {}\n", cmd->getDescription());
for (const auto& [name, cmd] : visibleCommands) {
grouped[cmd->getCategory()].push_back({name, cmd});
}
// Aliases
auto aliases = cmd->getAliases();
if (!aliases.empty()) {
helpMsg += "> Aliases: ";
for (size_t i = 0; i < aliases.size(); ++i) {
helpMsg += std::format("`{}{}`", prefix, aliases[i]);
if (i < aliases.size() - 1) {
helpMsg += ", ";
}
}
helpMsg += "\n";
}
for (const auto& [cat, cmds] : grouped) {
helpMsg +=
std::format("**{} Commands**\n", toString(cat));
helpMsg += "\n";
}
}
for (const auto& [name, cmd] : cmds) {
// Format: prefix!command usage
if (!cmd->getUsage().empty()) {
helpMsg += std::format("`{}{}` {}\n",
prefix,
name,
cmd->getUsage());
} else {
helpMsg +=
std::format("`{}{}`\n", prefix, name);
}
ctx.reply(helpMsg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Help command exception: {}", e.what()));
ctx.reply("Couldn't generate help. Please try again.");
}
}
// Description
helpMsg +=
std::format("> {}\n", cmd->getDescription());
std::string_view getDescription() const override {
return "Shows this help message with all available commands.";
}
// Aliases
auto aliases = cmd->getAliases();
if (!aliases.empty()) {
helpMsg += "> Aliases: ";
for (size_t i = 0; i < aliases.size(); ++i) {
helpMsg += std::format(
"`{}{}`", prefix, aliases[i]);
if (i < aliases.size() - 1) {
helpMsg += ", ";
}
}
helpMsg += "\n";
}
std::string_view getUsage() const override { return "[command]"; }
CommandCategory getCategory() const override { return CommandCategory::Utility; }
helpMsg += "\n";
}
}
std::vector<std::string_view> getAliases() const override {
return {"h", "?", "commands"};
}
};
ctx.reply(helpMsg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Help command exception: {}", e.what()));
ctx.reply("Couldn't generate help. Please try again.");
}
}
// --- Manager Implementation ---
std::string_view getDescription() const override
{
return "Shows this help message with all available commands.";
}
CommandManager::CommandManager() {
registerBuiltinCommands();
registerHelpCommand();
startThreadPool();
}
std::string_view getUsage() const override { return "[command]"; }
CommandManager::~CommandManager() {
shutdown();
}
CommandCategory getCategory() const override
{
return CommandCategory::Utility;
}
void CommandManager::shutdown() {
{
std::lock_guard<std::mutex> lock(queueMutex_);
shutdown_ = true;
}
queueCv_.notify_all();
for (auto& thread : workerThreads_) {
if (thread.joinable()) {
thread.join();
}
}
workerThreads_.clear();
}
std::vector<std::string_view> getAliases() const override
{
return {"h", "?", "commands"};
}
};
void CommandManager::startThreadPool() {
for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) {
workerThreads_.emplace_back([this]() {
processCommandQueue();
});
}
ECHOION_LOG_INFO(std::format("CommandManager thread pool started with {} workers", THREAD_POOL_SIZE));
}
// --- Manager Implementation ---
void CommandManager::processCommandQueue() {
while (true) {
CommandTask task;
{
std::unique_lock<std::mutex> lock(queueMutex_);
queueCv_.wait(lock, [this] { return shutdown_ || !commandQueue_.empty(); });
if (shutdown_ && commandQueue_.empty()) {
return;
}
task = std::move(commandQueue_.front());
commandQueue_.pop();
}
// Execute the command
executeCommandAsync(std::move(task));
}
}
void CommandManager::executeCommandAsync(CommandTask task) {
try {
// Re-parse the command (same logic as dispatch)
std::string_view message = task.message;
if (!message.starts_with(prefix_)) {
return;
}
// Skip prefix and trim
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) return;
input = input.substr(start);
// Split command and args
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
std::string argsStr;
if (spacePos != std::string_view::npos) {
size_t argStart = input.find_first_not_of(" \t", spacePos);
if (argStart != std::string_view::npos) {
argsStr = std::string(input.substr(argStart));
}
}
std::string cmdKey(cmdName);
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return;
}
command = it->second;
}
// Check permissions
if (!canExecuteCommand(task.clientId, command)) {
task.replyFunc("You don't have permission to use this command.");
return;
}
// Execute command
CommandContext ctx{
.clientId = task.clientId,
.prefix = prefix_,
.args = std::move(argsStr),
.invokerName = task.invokerName,
.musicManager = task.musicManager,
.replyCallback = std::move(task.replyFunc)
};
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Async command execution error: {}", e.what()));
try {
task.replyFunc("An error occurred while executing the command.");
} catch (...) {}
}
}
bool CommandManager::dispatch(
uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager> musicManager,
std::function<void(std::string_view)> replyFunc,
std::string_view invokerName) {
if (!message.starts_with(prefix_)) {
return false;
}
// Skip prefix and trim leading whitespace
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) {
return false;
}
input = input.substr(start);
// Split command and arguments
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
// Convert to lowercase for lookup
std::string cmdKey(cmdName);
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
// Check if command exists
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return false;
}
command = it->second;
}
// Check permissions synchronously (fast check)
if (!canExecuteCommand(clientId, command)) {
replyFunc("You don't have permission to use this command.");
return true; // Command was found but not allowed
}
// Queue the command for async execution
CommandTask task{
.clientId = clientId,
.message = std::string(message),
.musicManager = musicManager,
.replyFunc = std::move(replyFunc),
.invokerName = std::string(invokerName)
};
{
std::lock_guard<std::mutex> lock(queueMutex_);
if (shutdown_) {
return false;
}
commandQueue_.push(std::move(task));
}
queueCv_.notify_one();
return true;
}
bool CommandManager::dispatchSync(
uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager> musicManager,
std::function<void(std::string_view)> replyFunc,
std::string_view invokerName) {
if (!message.starts_with(prefix_)) {
return false;
}
// Skip prefix and trim leading whitespace
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) {
return false;
}
input = input.substr(start);
// Split command and arguments
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
std::string argsStr;
if (spacePos != std::string_view::npos) {
size_t argStart = input.find_first_not_of(" \t", spacePos);
if (argStart != std::string_view::npos) {
argsStr = std::string(input.substr(argStart));
}
}
// Convert to lowercase for lookup
std::string cmdKey(cmdName);
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return false;
}
command = it->second;
}
// Check permissions
if (!canExecuteCommand(clientId, command)) {
replyFunc("You don't have permission to use this command.");
return true;
}
CommandContext ctx{
.clientId = clientId,
.prefix = prefix_,
.args = std::move(argsStr),
.invokerName = invokerName,
.musicManager = musicManager,
.replyCallback = std::move(replyFunc)
};
try {
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Command execution error [{}]: {}", cmdKey, e.what()));
ctx.reply("An unexpected error occurred. Our team has been notified.");
}
return true;
}
bool CommandManager::hasCommand(std::string_view name) const {
std::lock_guard<std::mutex> lock(mutex_);
return commands_.contains(std::string(name));
}
std::optional<CommandPtr> CommandManager::getCommand(std::string_view name) const {
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(std::string(name));
if (it != commands_.end()) {
return it->second;
}
return std::nullopt;
}
std::vector<std::pair<std::string, CommandPtr>> CommandManager::getAllCommands() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::pair<std::string, CommandPtr>> result;
result.reserve(uniqueCommands_.size());
for (const auto& entry : uniqueCommands_) {
result.emplace_back(entry.primaryName, entry.instance);
}
return result;
}
std::vector<std::pair<std::string, CommandPtr>> CommandManager::getVisibleCommands(uint64_t clientId) const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::pair<std::string, CommandPtr>> result;
for (const auto& entry : uniqueCommands_) {
// Only include if client can execute it
if (canExecuteCommand(clientId, entry.instance)) {
result.emplace_back(entry.primaryName, entry.instance);
}
}
return result;
}
bool CommandManager::canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const {
if (!cmd->requiresAdmin()) {
return true; // Non-admin commands are always allowed
}
// If no server config is set, deny admin commands
if (!serverConfig_.has_value()) {
return false;
}
// If no admin groups configured, deny everyone
if (serverConfig_->server.adminGroups.empty()) {
return false;
}
// Check permission via callback if set
if (permissionCheck_ && (cmd->requiresAdmin() ||
cmd->getCategory() == CommandCategory::Admin)) {
return permissionCheck_(clientId, cmd->getCategory());
CommandManager::CommandManager()
{
registerBuiltinCommands();
registerHelpCommand();
startThreadPool();
}
// Default: deny admin commands if no checker configured
return false;
}
CommandManager::~CommandManager() { shutdown(); }
void CommandManager::setPrefix(std::string_view prefix) {
prefix_ = prefix;
}
void CommandManager::shutdown()
{
{
std::lock_guard<std::mutex> lock(queueMutex_);
shutdown_ = true;
}
queueCv_.notify_all();
void CommandManager::setPermissionCheckFunc(PermissionCheckFunc func) {
std::lock_guard<std::mutex> lock(mutex_);
permissionCheck_ = std::move(func);
}
for (auto& thread : workerThreads_) {
if (thread.joinable()) {
thread.join();
}
}
workerThreads_.clear();
}
void CommandManager::setServerConfig(const Api::AppConfig& config) {
std::lock_guard<std::mutex> lock(mutex_);
serverConfig_ = config;
}
void CommandManager::startThreadPool()
{
for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) {
workerThreads_.emplace_back([this]() { processCommandQueue(); });
}
ECHOION_LOG_INFO(
std::format("CommandManager thread pool started with {} workers",
THREAD_POOL_SIZE));
}
void CommandManager::registerBuiltinCommands() {
registerCommand<PlayCommand>("play");
registerCommand<SelectCommand>("select");
registerCommand<PauseCommand>("pause");
registerCommand<ResumeCommand>("resume");
registerCommand<StopCommand>("stop");
registerCommand<SkipCommand>("skip");
// registerCommand<SeekCommand>("seek");
registerCommand<VolumeCommand>("volume");
registerCommand<QueueCommand>("queue");
registerCommand<RemoveCommand>("remove");
registerCommand<ClearCommand>("clear");
registerCommand<MoveCommand>("move");
registerCommand<ShuffleCommand>("shuffle");
registerCommand<RepeatCommand>("repeat");
registerCommand<PlaylistCommand>("playlist");
registerCommand<NowPlayingCommand>("np");
registerCommand<SearchCommand>("search");
registerCommand<ReloadCommand>("reload");
registerCommand<ReloadConfigCommand>("reloadconfig");
registerCommand<SubscribeCommand>("subscribe");
registerCommand<UnsubscribeCommand>("unsubscribe");
registerCommand<SubscribersCommand>("subscribers");
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
}
void CommandManager::processCommandQueue()
{
while (true) {
CommandTask task;
{
std::unique_lock<std::mutex> lock(queueMutex_);
queueCv_.wait(lock, [this] {
return shutdown_ || !commandQueue_.empty();
});
void CommandManager::registerHelpCommand() {
auto helpCmd = std::make_shared<HelpCommand>(*this);
std::lock_guard<std::mutex> lock(mutex_);
commands_["help"] = helpCmd;
uniqueCommands_.push_back({"help", helpCmd});
for (auto alias : helpCmd->getAliases()) {
commands_[std::string(alias)] = helpCmd;
}
}
if (shutdown_ && commandQueue_.empty()) {
return;
}
task = std::move(commandQueue_.front());
commandQueue_.pop();
}
// Execute the command
executeCommandAsync(std::move(task));
}
}
void CommandManager::executeCommandAsync(CommandTask task)
{
try {
// Re-parse the command (same logic as dispatch)
std::string_view message = task.message;
if (!message.starts_with(prefix_)) {
return;
}
// Skip prefix and trim
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) {
return;
}
input = input.substr(start);
// Split command and args
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
std::string argsStr;
if (spacePos != std::string_view::npos) {
size_t argStart = input.find_first_not_of(" \t", spacePos);
if (argStart != std::string_view::npos) {
argsStr = std::string(input.substr(argStart));
}
}
std::string cmdKey(cmdName);
std::transform(
cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return;
}
command = it->second;
}
// Check permissions
if (!canExecuteCommand(task.clientId, command)) {
task.replyFunc(
"You don't have permission to use this command.");
return;
}
// Execute command
CommandContext ctx{.clientId = task.clientId,
.prefix = prefix_,
.args = std::move(argsStr),
.invokerName = task.invokerName,
.musicManager = task.musicManager,
.replyCallback = std::move(task.replyFunc)};
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Async command execution error: {}", e.what()));
try {
task.replyFunc(
"An error occurred while executing the command.");
} catch (...) {
}
}
}
bool CommandManager::dispatch(uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager>
musicManager,
std::function<void(std::string_view)>
replyFunc,
std::string_view invokerName)
{
if (!message.starts_with(prefix_)) {
return false;
}
// Skip prefix and trim leading whitespace
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) {
return false;
}
input = input.substr(start);
// Split command and arguments
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
// Convert to lowercase for lookup
std::string cmdKey(cmdName);
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
// Check if command exists
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return false;
}
command = it->second;
}
// Check permissions synchronously (fast check)
if (!canExecuteCommand(clientId, command)) {
replyFunc("You don't have permission to use this command.");
return true; // Command was found but not allowed
}
// Queue the command for async execution
CommandTask task{.clientId = clientId,
.message = std::string(message),
.musicManager = musicManager,
.replyFunc = std::move(replyFunc),
.invokerName = std::string(invokerName)};
{
std::lock_guard<std::mutex> lock(queueMutex_);
if (shutdown_) {
return false;
}
commandQueue_.push(std::move(task));
}
queueCv_.notify_one();
return true;
}
bool CommandManager::dispatchSync(uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager>
musicManager,
std::function<void(std::string_view)>
replyFunc,
std::string_view invokerName)
{
if (!message.starts_with(prefix_)) {
return false;
}
// Skip prefix and trim leading whitespace
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) {
return false;
}
input = input.substr(start);
// Split command and arguments
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
std::string argsStr;
if (spacePos != std::string_view::npos) {
size_t argStart = input.find_first_not_of(" \t", spacePos);
if (argStart != std::string_view::npos) {
argsStr = std::string(input.substr(argStart));
}
}
// Convert to lowercase for lookup
std::string cmdKey(cmdName);
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return false;
}
command = it->second;
}
// Check permissions
if (!canExecuteCommand(clientId, command)) {
replyFunc("You don't have permission to use this command.");
return true;
}
CommandContext ctx{.clientId = clientId,
.prefix = prefix_,
.args = std::move(argsStr),
.invokerName = invokerName,
.musicManager = musicManager,
.replyCallback = std::move(replyFunc)};
try {
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
"Command execution error [{}]: {}", cmdKey, e.what()));
ctx.reply(
"An unexpected error occurred. Our team has been notified.");
}
return true;
}
bool CommandManager::hasCommand(std::string_view name) const
{
std::lock_guard<std::mutex> lock(mutex_);
return commands_.contains(std::string(name));
}
std::optional<CommandPtr>
CommandManager::getCommand(std::string_view name) const
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(std::string(name));
if (it != commands_.end()) {
return it->second;
}
return std::nullopt;
}
std::vector<std::pair<std::string, CommandPtr>>
CommandManager::getAllCommands() const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::pair<std::string, CommandPtr>> result;
result.reserve(uniqueCommands_.size());
for (const auto& entry : uniqueCommands_) {
result.emplace_back(entry.primaryName, entry.instance);
}
return result;
}
std::vector<std::pair<std::string, CommandPtr>>
CommandManager::getVisibleCommands(uint64_t clientId) const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::pair<std::string, CommandPtr>> result;
for (const auto& entry : uniqueCommands_) {
// Only include if client can execute it
if (canExecuteCommand(clientId, entry.instance)) {
result.emplace_back(entry.primaryName, entry.instance);
}
}
return result;
}
bool CommandManager::canExecuteCommand(uint64_t clientId,
const CommandPtr& cmd) const
{
if (!cmd->requiresAdmin()) {
return true; // Non-admin commands are always allowed
}
// If no server config is set, deny admin commands
if (!serverConfig_.has_value()) {
return false;
}
// If no admin groups configured, deny everyone
if (serverConfig_->teamspeak.adminGroups.empty()) {
return false;
}
// Check permission via callback if set
if (permissionCheck_ &&
(cmd->requiresAdmin() ||
cmd->getCategory() == CommandCategory::Admin)) {
return permissionCheck_(clientId, cmd->getCategory());
}
// Default: deny admin commands if no checker configured
return false;
}
void CommandManager::setPrefix(std::string_view prefix)
{
prefix_ = prefix;
}
void CommandManager::setPermissionCheckFunc(PermissionCheckFunc func)
{
std::lock_guard<std::mutex> lock(mutex_);
permissionCheck_ = std::move(func);
}
void CommandManager::setServerConfig(const Api::AppConfig& config)
{
std::lock_guard<std::mutex> lock(mutex_);
serverConfig_ = config;
}
void CommandManager::registerBuiltinCommands()
{
registerCommand<PlayCommand>("play");
registerCommand<SelectCommand>("select");
registerCommand<PauseCommand>("pause");
registerCommand<ResumeCommand>("resume");
registerCommand<StopCommand>("stop");
registerCommand<SkipCommand>("skip");
// registerCommand<SeekCommand>("seek");
registerCommand<VolumeCommand>("volume");
registerCommand<QueueCommand>("queue");
registerCommand<RemoveCommand>("remove");
registerCommand<ClearCommand>("clear");
registerCommand<MoveCommand>("move");
registerCommand<ShuffleCommand>("shuffle");
registerCommand<RepeatCommand>("repeat");
registerCommand<PlaylistCommand>("playlist");
registerCommand<NowPlayingCommand>("np");
registerCommand<SearchCommand>("search");
registerCommand<ReloadCommand>("reload");
registerCommand<ReloadConfigCommand>("reloadconfig");
registerCommand<SubscribeCommand>("subscribe");
registerCommand<UnsubscribeCommand>("unsubscribe");
registerCommand<SubscribersCommand>("subscribers");
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
registerCommand<RpcInfoCommand>("rpc");
}
void CommandManager::registerHelpCommand()
{
auto helpCmd = std::make_shared<HelpCommand>(*this);
std::lock_guard<std::mutex> lock(mutex_);
commands_["help"] = helpCmd;
uniqueCommands_.push_back({"help", helpCmd});
for (auto alias : helpCmd->getAliases()) {
commands_[std::string(alias)] = helpCmd;
}
}
} // namespace Echoion::Core
+424 -369
View File
@@ -1,378 +1,433 @@
#include "LoggerInterface.hpp"
#include "Types.hpp"
#include "echoion/core/ConfigLoader.hpp"
#include "echoion/api/AudioTypes.hpp"
#include <glaze/glaze.hpp>
#include <fstream>
#include <AudioTypes.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <format>
#include <fstream>
#include <string>
namespace Echoion::Core {
// NOTE: The Echoion::Core::*Json mirror structs are plain reflectable
// aggregates whose member names are exactly the desired JSON keys, so
// Void::Json reflection (Json::to_json / Json::from_json) produces the same
// document the former glz::meta specializations did — no annotations needed.
// JSON structures for configuration
struct BotConfigJson {
std::string botName = "Echoion";
std::string commandPrefix = "!";
float defaultVolume = 0.5f;
bool autoReconnect = true;
uint32_t reconnectDelay = 5000;
uint32_t maxReconnectAttempts = 5;
std::optional<std::string> proxyHost;
std::optional<uint16_t> proxyPort;
std::optional<std::string> proxyUsername;
std::optional<std::string> proxyPassword;
std::optional<std::string> proxyType;
std::optional<std::string> youtubeApiKey;
std::string preferredQuality = "High";
bool allowPlaylistImports = true;
uint32_t maxQueueSize = 100;
uint32_t trackTimeout = 30000;
std::optional<std::string> youtubeCookiesPath;
std::optional<std::string> cookiesFromBrowser;
uint32_t ytDlpMaxConcurrent = 4;
bool ytDlpAsyncEnabled = true;
bool enableUrlShortening = true;
};
namespace Echoion::Core
{
struct ServerConfigJson {
std::string address;
uint16_t port = 9987;
std::string serverPassword = "";
std::string nickname = "EchoionBot";
std::optional<std::string> defaultChannelId;
std::optional<std::string> channelPassword;
std::vector<uint64_t> adminGroups;
std::vector<uint64_t> djGroups;
std::vector<uint64_t> bannedGroups;
};
Api::Result<Api::AppConfig>
ConfigLoader::loadFromFile(const std::filesystem::path& path)
{
if (!std::filesystem::exists(path)) {
return std::unexpected(
Api::Error(Api::ErrorCode::NotFound,
std::format("Configuration file not found: {}",
path.string())));
}
struct SecurityConfigJson {
bool requireAuthForAdmin = true;
uint32_t maxLoginAttempts = 5;
uint32_t lockoutDuration = 300000;
uint32_t sessionTimeout = 3600000;
bool enableAuditLog = true;
};
std::ifstream file(path);
if (!file.is_open()) {
return std::unexpected(
Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to open configuration file: {}",
path.string())));
}
struct AppConfigJson {
BotConfigJson bot;
ServerConfigJson server;
SecurityConfigJson security;
};
} // namespace Echoion::Core
// Glaze metadata for JSON serialization
template<> struct glz::meta<Echoion::Core::BotConfigJson> {
using T = Echoion::Core::BotConfigJson;
static constexpr auto value = object(
"botName", &T::botName,
"commandPrefix", &T::commandPrefix,
"defaultVolume", &T::defaultVolume,
"autoReconnect", &T::autoReconnect,
"reconnectDelay", &T::reconnectDelay,
"maxReconnectAttempts", &T::maxReconnectAttempts,
"proxyHost", &T::proxyHost,
"proxyPort", &T::proxyPort,
"proxyUsername", &T::proxyUsername,
"proxyPassword", &T::proxyPassword,
"proxyType", &T::proxyType,
"youtubeApiKey", &T::youtubeApiKey,
"preferredQuality", &T::preferredQuality,
"allowPlaylistImports", &T::allowPlaylistImports,
"maxQueueSize", &T::maxQueueSize,
"trackTimeout", &T::trackTimeout,
"youtubeCookiesPath", &T::youtubeCookiesPath,
"cookiesFromBrowser", &T::cookiesFromBrowser,
"ytDlpMaxConcurrent", &T::ytDlpMaxConcurrent,
"ytDlpAsyncEnabled", &T::ytDlpAsyncEnabled,
"enableUrlShortening", &T::enableUrlShortening
);
};
template<> struct glz::meta<Echoion::Core::ServerConfigJson> {
using T = Echoion::Core::ServerConfigJson;
static constexpr auto value = object(
"address", &T::address,
"port", &T::port,
"serverPassword", &T::serverPassword,
"nickname", &T::nickname,
"defaultChannelId", &T::defaultChannelId,
"channelPassword", &T::channelPassword,
"adminGroups", &T::adminGroups,
"djGroups", &T::djGroups,
"bannedGroups", &T::bannedGroups
);
};
template<> struct glz::meta<Echoion::Core::SecurityConfigJson> {
using T = Echoion::Core::SecurityConfigJson;
static constexpr auto value = object(
"requireAuthForAdmin", &T::requireAuthForAdmin,
"maxLoginAttempts", &T::maxLoginAttempts,
"lockoutDuration", &T::lockoutDuration,
"sessionTimeout", &T::sessionTimeout,
"enableAuditLog", &T::enableAuditLog
);
};
template<> struct glz::meta<Echoion::Core::AppConfigJson> {
using T = Echoion::Core::AppConfigJson;
static constexpr auto value = object(
"bot", &T::bot,
"server", &T::server,
"security", &T::security
);
};
namespace Echoion::Core {
Api::Result<Api::AppConfig> ConfigLoader::loadFromFile(const std::filesystem::path& path) {
if (!std::filesystem::exists(path)) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
std::format("Configuration file not found: {}", path.string())));
}
std::ifstream file(path);
if (!file.is_open()) {
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to open configuration file: {}", path.string())));
}
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
AppConfigJson jsonConfig;
auto ec = glz::read_json(jsonConfig, content);
if (ec) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Failed to parse configuration: {}", glz::format_error(ec, content))));
}
// Convert to API config
Api::AppConfig config;
// Bot config
config.bot.botName = jsonConfig.bot.botName;
config.bot.commandPrefix = jsonConfig.bot.commandPrefix;
config.bot.defaultVolume = jsonConfig.bot.defaultVolume;
config.bot.autoReconnect = jsonConfig.bot.autoReconnect;
config.bot.reconnectDelay = std::chrono::milliseconds(jsonConfig.bot.reconnectDelay);
config.bot.maxReconnectAttempts = jsonConfig.bot.maxReconnectAttempts;
config.bot.preferredQuality = parseQuality(jsonConfig.bot.preferredQuality);
config.bot.allowPlaylistImports = jsonConfig.bot.allowPlaylistImports;
config.bot.maxQueueSize = jsonConfig.bot.maxQueueSize;
config.bot.trackTimeout = std::chrono::milliseconds(jsonConfig.bot.trackTimeout);
// Proxy config
if (jsonConfig.bot.proxyHost.has_value() && jsonConfig.bot.proxyPort.has_value()) {
Api::ProxyConfig proxy;
proxy.host = *jsonConfig.bot.proxyHost;
proxy.port = *jsonConfig.bot.proxyPort;
proxy.username = jsonConfig.bot.proxyUsername;
proxy.password = jsonConfig.bot.proxyPassword;
// Parse proxy type (default to HTTP)
if (jsonConfig.bot.proxyType.has_value()) {
const auto& typeStr = *jsonConfig.bot.proxyType;
if (typeStr == "SOCKS5" || typeStr == "socks5") {
proxy.type = Api::ProxyType::SOCKS5;
} else {
proxy.type = Api::ProxyType::HTTP;
}
} else {
proxy.type = Api::ProxyType::HTTP;
}
config.bot.proxy = proxy;
}
// YouTube API key
if (jsonConfig.bot.youtubeApiKey.has_value()) {
config.bot.youtubeApiKey = jsonConfig.bot.youtubeApiKey;
}
// YouTube cookies
if (jsonConfig.bot.youtubeCookiesPath.has_value()) {
config.bot.youtubeCookiesPath = jsonConfig.bot.youtubeCookiesPath;
}
if (jsonConfig.bot.cookiesFromBrowser.has_value()) {
config.bot.cookiesFromBrowser = jsonConfig.bot.cookiesFromBrowser;
}
// yt-dlp settings
config.bot.ytDlpMaxConcurrent = std::min(static_cast<size_t>(jsonConfig.bot.ytDlpMaxConcurrent), size_t(8));
config.bot.ytDlpAsyncEnabled = jsonConfig.bot.ytDlpAsyncEnabled;
// URL shortening settings
config.bot.enableUrlShortening = jsonConfig.bot.enableUrlShortening;
// Server config
config.server.address = jsonConfig.server.address;
config.server.port = jsonConfig.server.port;
config.server.serverPassword = jsonConfig.server.serverPassword;
config.server.nickname = jsonConfig.server.nickname;
config.server.defaultChannelId = jsonConfig.server.defaultChannelId;
config.server.channelPassword = jsonConfig.server.channelPassword;
config.server.adminGroups = jsonConfig.server.adminGroups;
config.server.djGroups = jsonConfig.server.djGroups;
config.server.bannedGroups = jsonConfig.server.bannedGroups;
// Security config
config.security.requireAuthForAdmin = jsonConfig.security.requireAuthForAdmin;
config.security.maxLoginAttempts = jsonConfig.security.maxLoginAttempts;
config.security.lockoutDuration = std::chrono::milliseconds(jsonConfig.security.lockoutDuration);
config.security.sessionTimeout = std::chrono::milliseconds(jsonConfig.security.sessionTimeout);
config.security.enableAuditLog = jsonConfig.security.enableAuditLog;
ECHOION_LOG_INFO(std::format("Configuration loaded from {}", path.string()));
return config;
}
Api::Result<void> ConfigLoader::saveToFile(const std::filesystem::path& path, const Api::AppConfig& config) {
AppConfigJson jsonConfig;
// Bot config
jsonConfig.bot.botName = config.bot.botName;
jsonConfig.bot.commandPrefix = config.bot.commandPrefix;
jsonConfig.bot.defaultVolume = config.bot.defaultVolume;
jsonConfig.bot.autoReconnect = config.bot.autoReconnect;
jsonConfig.bot.reconnectDelay = static_cast<uint32_t>(config.bot.reconnectDelay.count());
jsonConfig.bot.maxReconnectAttempts = config.bot.maxReconnectAttempts;
jsonConfig.bot.preferredQuality = qualityToString(config.bot.preferredQuality);
jsonConfig.bot.allowPlaylistImports = config.bot.allowPlaylistImports;
jsonConfig.bot.maxQueueSize = config.bot.maxQueueSize;
jsonConfig.bot.trackTimeout = static_cast<uint32_t>(config.bot.trackTimeout.count());
// Proxy config
if (config.bot.proxy.has_value()) {
jsonConfig.bot.proxyHost = config.bot.proxy->host;
jsonConfig.bot.proxyPort = config.bot.proxy->port;
jsonConfig.bot.proxyUsername = config.bot.proxy->username;
jsonConfig.bot.proxyPassword = config.bot.proxy->password;
jsonConfig.bot.proxyType = config.bot.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5" : "HTTP";
}
// YouTube API key
if (config.bot.youtubeApiKey.has_value()) {
jsonConfig.bot.youtubeApiKey = *config.bot.youtubeApiKey;
}
// YouTube cookies
if (config.bot.youtubeCookiesPath.has_value()) {
jsonConfig.bot.youtubeCookiesPath = *config.bot.youtubeCookiesPath;
}
if (config.bot.cookiesFromBrowser.has_value()) {
jsonConfig.bot.cookiesFromBrowser = *config.bot.cookiesFromBrowser;
}
// yt-dlp settings
jsonConfig.bot.ytDlpMaxConcurrent = static_cast<uint32_t>(config.bot.ytDlpMaxConcurrent);
jsonConfig.bot.ytDlpAsyncEnabled = config.bot.ytDlpAsyncEnabled;
// URL shortening settings
jsonConfig.bot.enableUrlShortening = config.bot.enableUrlShortening;
// Server config
jsonConfig.server.address = config.server.address;
jsonConfig.server.port = config.server.port;
jsonConfig.server.serverPassword = config.server.serverPassword;
jsonConfig.server.nickname = config.server.nickname;
jsonConfig.server.defaultChannelId = config.server.defaultChannelId;
jsonConfig.server.channelPassword = config.server.channelPassword;
jsonConfig.server.adminGroups = config.server.adminGroups;
jsonConfig.server.djGroups = config.server.djGroups;
jsonConfig.server.bannedGroups = config.server.bannedGroups;
// Security config
jsonConfig.security.requireAuthForAdmin = config.security.requireAuthForAdmin;
jsonConfig.security.maxLoginAttempts = config.security.maxLoginAttempts;
jsonConfig.security.lockoutDuration = static_cast<uint32_t>(config.security.lockoutDuration.count());
jsonConfig.security.sessionTimeout = static_cast<uint32_t>(config.security.sessionTimeout.count());
jsonConfig.security.enableAuditLog = config.security.enableAuditLog;
auto json = glz::write_json(jsonConfig);
if (!json.has_value())
{
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Failed to serialize: {}", json.error().custom_error_message)));
}
std::ofstream file(path);
if (!file.is_open()) {
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to write configuration file: {}", path.string())));
}
file << json.value();
file.close();
ECHOION_LOG_INFO(std::format("Configuration saved to {}", path.string()));
return {};
}
std::filesystem::path ConfigLoader::getDefaultConfigPath() {
// Try to get config path from environment or use default
const char* configHome = std::getenv("XDG_CONFIG_HOME");
if (configHome) {
return std::filesystem::path(configHome) / "echoion" / "config.json";
}
const char* home = std::getenv("HOME");
if (home) {
return std::filesystem::path(home) / ".config" / "echoion" / "config.json";
}
// Fallback to current directory
return "echoion_config.json";
}
Api::AppConfig ConfigLoader::createDefaultConfig() {
Api::AppConfig config;
// Default bot config
config.bot.botName = "Echoion";
config.bot.commandPrefix = "!";
config.bot.defaultVolume = 0.5f;
config.bot.autoReconnect = true;
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
config.bot.maxReconnectAttempts = 5;
config.bot.preferredQuality = Api::AudioQuality::High;
config.bot.allowPlaylistImports = true;
config.bot.maxQueueSize = 100;
config.bot.trackTimeout = std::chrono::milliseconds(30000);
config.bot.ytDlpMaxConcurrent = 4;
config.bot.ytDlpAsyncEnabled = true;
config.bot.enableUrlShortening = true;
// Default server config
config.server.address = "localhost";
config.server.port = 9987;
config.server.nickname = "EchoionBot";
// Default security config
config.security.requireAuthForAdmin = true;
config.security.maxLoginAttempts = 5;
config.security.lockoutDuration = std::chrono::milliseconds(300000);
config.security.sessionTimeout = std::chrono::milliseconds(3600000);
config.security.enableAuditLog = true;
return config;
}
Api::AudioQuality ConfigLoader::parseQuality(const std::string& str) {
if (str == "Low") return Api::AudioQuality::Low;
if (str == "Medium") return Api::AudioQuality::Medium;
if (str == "High") return Api::AudioQuality::High;
if (str == "VeryHigh") return Api::AudioQuality::VeryHigh;
if (str == "Lossless") return Api::AudioQuality::Lossless;
return Api::AudioQuality::High; // Default
}
std::string ConfigLoader::qualityToString(Api::AudioQuality quality) {
switch (quality) {
case Api::AudioQuality::Low: return "Low";
case Api::AudioQuality::Medium: return "Medium";
case Api::AudioQuality::High: return "High";
case Api::AudioQuality::VeryHigh: return "VeryHigh";
case Api::AudioQuality::Lossless: return "Lossless";
default: return "High";
}
}
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
auto parsed = Void::Json::parse(content);
if (!parsed) {
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError,
std::format("Failed to parse configuration ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message)));
}
// Tolerant deserialization: unknown JSON fields are ignored and missing
// fields keep their default-initialized values (matches the former
// glz::opts{error_on_unknown_keys=false, error_on_missing_keys=false}).
auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed);
if (!jsonResult) {
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError,
std::format("Failed to parse configuration: field '{}': {}",
jsonResult.error().field,
jsonResult.error().message)));
}
AppConfigJson jsonConfig = std::move(*jsonResult);
// Convert to API config
Api::AppConfig config;
// Bot config
config.bot.botName = jsonConfig.bot.botName;
config.bot.commandPrefix = jsonConfig.bot.commandPrefix;
config.bot.defaultVolume = jsonConfig.bot.defaultVolume;
config.bot.maxQueueSize = jsonConfig.bot.maxQueueSize;
config.bot.trackTimeout =
std::chrono::milliseconds(jsonConfig.bot.trackTimeout);
config.bot.autoReconnect = jsonConfig.bot.autoReconnect;
config.bot.reconnectDelay =
std::chrono::milliseconds(jsonConfig.bot.reconnectDelay);
config.bot.maxReconnectAttempts = jsonConfig.bot.maxReconnectAttempts;
config.bot.preferredQuality =
parseQuality(jsonConfig.bot.preferredQuality);
config.bot.allowPlaylistImports = jsonConfig.bot.allowPlaylistImports;
// YouTube config
if (jsonConfig.youtube.youtubeApiKey.has_value()) {
config.youtube.youtubeApiKey = jsonConfig.youtube.youtubeApiKey;
}
if (jsonConfig.youtube.youtubeCookiesPath.has_value()) {
config.youtube.youtubeCookiesPath =
jsonConfig.youtube.youtubeCookiesPath;
}
if (jsonConfig.youtube.cookiesFromBrowser.has_value()) {
config.youtube.cookiesFromBrowser =
jsonConfig.youtube.cookiesFromBrowser;
}
config.youtube.ytDlpMaxConcurrent =
std::min(static_cast<size_t>(jsonConfig.youtube.ytDlpMaxConcurrent),
size_t(8));
config.youtube.ytDlpAsyncEnabled = jsonConfig.youtube.ytDlpAsyncEnabled;
config.youtube.enableUrlShortening =
jsonConfig.youtube.enableUrlShortening;
// Network config
if (jsonConfig.network.proxyHost.has_value() &&
jsonConfig.network.proxyPort.has_value()) {
Api::ProxyConfig proxy;
proxy.host = *jsonConfig.network.proxyHost;
proxy.port = *jsonConfig.network.proxyPort;
proxy.username = jsonConfig.network.proxyUsername;
proxy.password = jsonConfig.network.proxyPassword;
const auto& typeStr = jsonConfig.network.proxyType;
if (typeStr == "SOCKS5" || typeStr == "socks5") {
proxy.type = Api::ProxyType::SOCKS5;
} else {
proxy.type = Api::ProxyType::HTTP;
}
config.network.proxy = proxy;
}
config.network.rpcEnabled = jsonConfig.network.rpcEnabled;
config.network.rpcPort = jsonConfig.network.rpcPort;
config.network.rpcBindAddress = jsonConfig.network.rpcBindAddress;
// TeamSpeak config
config.teamspeak.address = jsonConfig.teamspeak.address;
config.teamspeak.port = jsonConfig.teamspeak.port;
config.teamspeak.serverPassword = jsonConfig.teamspeak.serverPassword;
config.teamspeak.nickname = jsonConfig.teamspeak.nickname;
config.teamspeak.defaultChannelId =
jsonConfig.teamspeak.defaultChannelId;
config.teamspeak.channelPassword = jsonConfig.teamspeak.channelPassword;
config.teamspeak.adminGroups = jsonConfig.teamspeak.adminGroups;
config.teamspeak.djGroups = jsonConfig.teamspeak.djGroups;
config.teamspeak.bannedGroups = jsonConfig.teamspeak.bannedGroups;
// Security config
config.security.requireAuthForAdmin =
jsonConfig.security.requireAuthForAdmin;
config.security.maxLoginAttempts = jsonConfig.security.maxLoginAttempts;
config.security.lockoutDuration =
std::chrono::milliseconds(jsonConfig.security.lockoutDuration);
config.security.sessionTimeout =
std::chrono::milliseconds(jsonConfig.security.sessionTimeout);
config.security.enableAuditLog = jsonConfig.security.enableAuditLog;
if (jsonConfig.security.apiKey.has_value()) {
config.security.apiKey = jsonConfig.security.apiKey;
}
config.security.allowCors = jsonConfig.security.allowCors;
config.security.corsOrigins = jsonConfig.security.corsOrigins;
// Features config
config.features.enableHotReload = jsonConfig.features.enableHotReload;
config.features.enableAutoReload = jsonConfig.features.enableAutoReload;
config.features.enableAutoUpdateCheck =
jsonConfig.features.enableAutoUpdateCheck;
config.features.autoStartOnSubscribe =
jsonConfig.features.autoStartOnSubscribe;
config.features.pauseOnEmptySubscribers =
jsonConfig.features.pauseOnEmptySubscribers;
config.features.resumeOnSubscriberReturn =
jsonConfig.features.resumeOnSubscriberReturn;
config.features.shuffleMode = jsonConfig.features.shuffleMode;
config.features.repeatMode = jsonConfig.features.repeatMode;
config.features.maxHistorySize = jsonConfig.features.maxHistorySize;
// Advanced config
config.advanced.sampleRate = jsonConfig.advanced.sampleRate;
config.advanced.channels = jsonConfig.advanced.channels;
config.advanced.bufferSize = jsonConfig.advanced.bufferSize;
config.advanced.commandThreadPoolSize =
jsonConfig.advanced.commandThreadPoolSize;
config.advanced.networkThreadPoolSize =
jsonConfig.advanced.networkThreadPoolSize;
config.advanced.decoderThreads = jsonConfig.advanced.decoderThreads;
config.advanced.cacheEnabled = jsonConfig.advanced.cacheEnabled;
config.advanced.cacheMaxSize = jsonConfig.advanced.cacheMaxSize;
config.advanced.cacheTTL = jsonConfig.advanced.cacheTTL;
config.advanced.tempCleanupInterval =
jsonConfig.advanced.tempCleanupInterval;
std::cout << std::format("[INFO] Configuration loaded from {}",
path.string())
<< std::endl;
return config;
}
Api::Result<void>
ConfigLoader::saveToFile(const std::filesystem::path& path,
const Api::AppConfig& config)
{
AppConfigJson jsonConfig;
// Bot config
jsonConfig.bot.botName = config.bot.botName;
jsonConfig.bot.commandPrefix = config.bot.commandPrefix;
jsonConfig.bot.defaultVolume = config.bot.defaultVolume;
jsonConfig.bot.maxQueueSize = config.bot.maxQueueSize;
jsonConfig.bot.trackTimeout =
static_cast<uint32_t>(config.bot.trackTimeout.count());
jsonConfig.bot.autoReconnect = config.bot.autoReconnect;
jsonConfig.bot.reconnectDelay =
static_cast<uint32_t>(config.bot.reconnectDelay.count());
jsonConfig.bot.maxReconnectAttempts = config.bot.maxReconnectAttempts;
jsonConfig.bot.preferredQuality =
qualityToString(config.bot.preferredQuality);
jsonConfig.bot.allowPlaylistImports = config.bot.allowPlaylistImports;
// YouTube config
if (config.youtube.youtubeApiKey.has_value()) {
jsonConfig.youtube.youtubeApiKey = *config.youtube.youtubeApiKey;
}
if (config.youtube.youtubeCookiesPath.has_value()) {
jsonConfig.youtube.youtubeCookiesPath =
*config.youtube.youtubeCookiesPath;
}
if (config.youtube.cookiesFromBrowser.has_value()) {
jsonConfig.youtube.cookiesFromBrowser =
*config.youtube.cookiesFromBrowser;
}
jsonConfig.youtube.ytDlpMaxConcurrent =
static_cast<uint32_t>(config.youtube.ytDlpMaxConcurrent);
jsonConfig.youtube.ytDlpAsyncEnabled = config.youtube.ytDlpAsyncEnabled;
jsonConfig.youtube.enableUrlShortening =
config.youtube.enableUrlShortening;
// Network config
if (config.network.proxy.has_value()) {
jsonConfig.network.proxyHost = config.network.proxy->host;
jsonConfig.network.proxyPort = config.network.proxy->port;
jsonConfig.network.proxyUsername = config.network.proxy->username;
jsonConfig.network.proxyPassword = config.network.proxy->password;
jsonConfig.network.proxyType =
config.network.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5"
: "HTTP";
}
jsonConfig.network.rpcEnabled = config.network.rpcEnabled;
jsonConfig.network.rpcPort = config.network.rpcPort;
jsonConfig.network.rpcBindAddress = config.network.rpcBindAddress;
// TeamSpeak config
jsonConfig.teamspeak.address = config.teamspeak.address;
jsonConfig.teamspeak.port = config.teamspeak.port;
jsonConfig.teamspeak.serverPassword = config.teamspeak.serverPassword;
jsonConfig.teamspeak.nickname = config.teamspeak.nickname;
jsonConfig.teamspeak.defaultChannelId =
config.teamspeak.defaultChannelId;
jsonConfig.teamspeak.channelPassword = config.teamspeak.channelPassword;
jsonConfig.teamspeak.adminGroups = config.teamspeak.adminGroups;
jsonConfig.teamspeak.djGroups = config.teamspeak.djGroups;
jsonConfig.teamspeak.bannedGroups = config.teamspeak.bannedGroups;
// Security config
jsonConfig.security.requireAuthForAdmin =
config.security.requireAuthForAdmin;
jsonConfig.security.maxLoginAttempts = config.security.maxLoginAttempts;
jsonConfig.security.lockoutDuration =
static_cast<uint32_t>(config.security.lockoutDuration.count());
jsonConfig.security.sessionTimeout =
static_cast<uint32_t>(config.security.sessionTimeout.count());
jsonConfig.security.enableAuditLog = config.security.enableAuditLog;
if (config.security.apiKey.has_value()) {
jsonConfig.security.apiKey = *config.security.apiKey;
}
jsonConfig.security.allowCors = config.security.allowCors;
jsonConfig.security.corsOrigins = config.security.corsOrigins;
// Features config
jsonConfig.features.enableHotReload = config.features.enableHotReload;
jsonConfig.features.enableAutoReload = config.features.enableAutoReload;
jsonConfig.features.enableAutoUpdateCheck =
config.features.enableAutoUpdateCheck;
jsonConfig.features.autoStartOnSubscribe =
config.features.autoStartOnSubscribe;
jsonConfig.features.pauseOnEmptySubscribers =
config.features.pauseOnEmptySubscribers;
jsonConfig.features.resumeOnSubscriberReturn =
config.features.resumeOnSubscriberReturn;
jsonConfig.features.shuffleMode = config.features.shuffleMode;
jsonConfig.features.repeatMode = config.features.repeatMode;
jsonConfig.features.maxHistorySize = config.features.maxHistorySize;
// Advanced config
jsonConfig.advanced.sampleRate = config.advanced.sampleRate;
jsonConfig.advanced.channels = config.advanced.channels;
jsonConfig.advanced.bufferSize = config.advanced.bufferSize;
jsonConfig.advanced.commandThreadPoolSize =
config.advanced.commandThreadPoolSize;
jsonConfig.advanced.networkThreadPoolSize =
config.advanced.networkThreadPoolSize;
jsonConfig.advanced.decoderThreads = config.advanced.decoderThreads;
jsonConfig.advanced.cacheEnabled = config.advanced.cacheEnabled;
jsonConfig.advanced.cacheMaxSize = config.advanced.cacheMaxSize;
jsonConfig.advanced.cacheTTL = config.advanced.cacheTTL;
jsonConfig.advanced.tempCleanupInterval =
config.advanced.tempCleanupInterval;
const std::string json = Void::Json::serialize(
Void::Json::to_json(jsonConfig), {.pretty = true});
std::ofstream file(path);
if (!file.is_open()) {
return std::unexpected(
Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to write configuration file: {}",
path.string())));
}
file << json;
file.close();
ECHOION_LOG_INFO(
std::format("Configuration saved to {}", path.string()));
return {};
}
std::filesystem::path ConfigLoader::getDefaultConfigPath()
{
// Try to get config path from environment or use default
const char* configHome = std::getenv("XDG_CONFIG_HOME");
if (configHome) {
return std::filesystem::path(configHome) / "echoion" /
"config.json";
}
const char* home = std::getenv("HOME");
if (home) {
return std::filesystem::path(home) / ".config" / "echoion" /
"config.json";
}
// Fallback to current directory
return "echoion_config.json";
}
Api::AppConfig ConfigLoader::createDefaultConfig()
{
Api::AppConfig config;
// Default bot config
config.bot.botName = "Echoion";
config.bot.commandPrefix = "!";
config.bot.defaultVolume = 0.5f;
config.bot.maxQueueSize = 100;
config.bot.trackTimeout = std::chrono::milliseconds(30000);
config.bot.autoReconnect = true;
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
config.bot.maxReconnectAttempts = 5;
config.bot.preferredQuality = Api::AudioQuality::High;
config.bot.allowPlaylistImports = true;
// Default YouTube config
config.youtube.ytDlpMaxConcurrent = 4;
config.youtube.ytDlpAsyncEnabled = true;
config.youtube.enableUrlShortening = true;
// Default network config
config.network.rpcEnabled = true;
config.network.rpcPort = 8765;
config.network.rpcBindAddress = "127.0.0.1";
// Default TeamSpeak config
config.teamspeak.address = "localhost";
config.teamspeak.port = 9987;
config.teamspeak.nickname = "EchoionBot";
// Default security config
config.security.requireAuthForAdmin = true;
config.security.maxLoginAttempts = 5;
config.security.lockoutDuration = std::chrono::milliseconds(300000);
config.security.sessionTimeout = std::chrono::milliseconds(3600000);
config.security.enableAuditLog = true;
config.security.allowCors = false;
// Default features config
config.features.enableHotReload = true;
config.features.enableAutoReload = false;
config.features.enableAutoUpdateCheck = true;
config.features.autoStartOnSubscribe = true;
config.features.pauseOnEmptySubscribers = true;
config.features.resumeOnSubscriberReturn = true;
config.features.shuffleMode = "random";
config.features.repeatMode = "off";
config.features.maxHistorySize = 50;
// Default advanced config
config.advanced.sampleRate = 192000;
config.advanced.channels = 2;
config.advanced.bufferSize = 7680;
config.advanced.commandThreadPoolSize = 4;
config.advanced.networkThreadPoolSize = 4;
config.advanced.decoderThreads = 2;
config.advanced.cacheEnabled = true;
config.advanced.cacheMaxSize = "1GB";
config.advanced.cacheTTL = 86400;
config.advanced.tempCleanupInterval = 3600;
return config;
}
Api::AudioQuality ConfigLoader::parseQuality(const std::string& str)
{
if (str == "Low") {
return Api::AudioQuality::Low;
}
if (str == "Medium") {
return Api::AudioQuality::Medium;
}
if (str == "High") {
return Api::AudioQuality::High;
}
if (str == "VeryHigh") {
return Api::AudioQuality::VeryHigh;
}
if (str == "Lossless") {
return Api::AudioQuality::Lossless;
}
return Api::AudioQuality::High; // Default
}
std::string ConfigLoader::qualityToString(Api::AudioQuality quality)
{
switch (quality) {
case Api::AudioQuality::Low:
return "Low";
case Api::AudioQuality::Medium:
return "Medium";
case Api::AudioQuality::High:
return "High";
case Api::AudioQuality::VeryHigh:
return "VeryHigh";
case Api::AudioQuality::Lossless:
return "Lossless";
default:
return "High";
}
}
} // namespace Echoion::Core
+178
View File
@@ -0,0 +1,178 @@
#include "ConfigManager.hpp"
#include "echoion/core/ConfigLoader.hpp"
#include <format>
#include <iostream>
namespace Echoion::Api
{
ConfigManager& ConfigManager::instance()
{
static ConfigManager instance;
return instance;
}
bool ConfigManager::initialize(const std::filesystem::path& configPath)
{
std::unique_lock lock(mutex_);
configPath_ = configPath;
bool success = loadFromFileInternal();
initialized_.store(success);
return success;
}
bool ConfigManager::initialize()
{
return initialize(getDefaultConfigPath());
}
AppConfig ConfigManager::getConfig() const
{
std::shared_lock lock(mutex_);
return config_;
}
const BotConfig& ConfigManager::getBot() const
{
std::shared_lock lock(mutex_);
return config_.bot;
}
const YouTubeConfig& ConfigManager::getYouTube() const
{
std::shared_lock lock(mutex_);
return config_.youtube;
}
const NetworkConfig& ConfigManager::getNetwork() const
{
std::shared_lock lock(mutex_);
return config_.network;
}
const TeamSpeakConfig& ConfigManager::getTeamSpeak() const
{
std::shared_lock lock(mutex_);
return config_.teamspeak;
}
const SecurityConfig& ConfigManager::getSecurity() const
{
std::shared_lock lock(mutex_);
return config_.security;
}
const FeaturesConfig& ConfigManager::getFeatures() const
{
std::shared_lock lock(mutex_);
return config_.features;
}
const AdvancedConfig& ConfigManager::getAdvanced() const
{
std::shared_lock lock(mutex_);
return config_.advanced;
}
bool ConfigManager::reload()
{
std::unique_lock lock(mutex_);
return loadFromFileInternal();
}
bool ConfigManager::save()
{
std::shared_lock lock(mutex_);
return saveToFileInternal();
}
void ConfigManager::updateConfig(const AppConfig& config, bool saveToFile)
{
{
std::unique_lock lock(mutex_);
config_ = config;
}
if (saveToFile) {
save();
}
notifyCallbacks();
}
bool ConfigManager::isInitialized() const { return initialized_.load(); }
std::filesystem::path ConfigManager::getConfigPath() const
{
std::shared_lock lock(mutex_);
return configPath_;
}
std::filesystem::path ConfigManager::getDefaultConfigPath()
{
const char* configHome = std::getenv("XDG_CONFIG_HOME");
if (configHome) {
return std::filesystem::path(configHome) / "echoion" /
"config.json";
}
const char* home = std::getenv("HOME");
if (home) {
return std::filesystem::path(home) / ".config" / "echoion" /
"config.json";
}
return "echoion_config.json";
}
void ConfigManager::onConfigChanged(ConfigChangedCallback callback)
{
std::unique_lock lock(callbackMutex_);
callbacks_.push_back(std::move(callback));
}
bool ConfigManager::createDefaultConfigIfNeeded()
{
if (!std::filesystem::exists(configPath_)) {
std::filesystem::create_directories(configPath_.parent_path());
return save();
}
return true;
}
void ConfigManager::notifyCallbacks()
{
std::shared_lock lock(mutex_);
std::shared_lock cbLock(callbackMutex_);
for (const auto& callback : callbacks_) {
callback(config_);
}
}
bool ConfigManager::loadFromFileInternal()
{
// Delegate to Core::ConfigLoader, which performs the JSON <-> AppConfig
// mapping (via the *Json mirror structs and Void::Json reflection).
auto result = Core::ConfigLoader::loadFromFile(configPath_);
if (!result) {
std::cerr << std::format("Failed to load config: {}\n",
result.error().toString());
return false;
}
config_ = std::move(*result);
return true;
}
bool ConfigManager::saveToFileInternal()
{
auto result = Core::ConfigLoader::saveToFile(configPath_, config_);
if (!result) {
std::cerr << std::format("Failed to save config: {}\n",
result.error().toString());
return false;
}
return true;
}
} // namespace Echoion::Api
+2080 -958
View File
File diff suppressed because it is too large. Load diff
+1091 -639
View File
File diff suppressed because it is too large. Load diff
+10 -181
View File
@@ -1,185 +1,14 @@
#include "echoion/api/EventBus.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <EventBus.hpp>
namespace Echoion::Api {
namespace Echoion::Api
{
// Global event bus instance
EventBus& GlobalEventBus::instance() {
static EventBus instance;
return instance;
}
EventBus::EventBus() = default;
EventBus::~EventBus() {
stop();
}
void EventBus::start() {
if (running_.exchange(true)) {
return; // Already running
}
stopRequested_ = false;
eventThread_ = std::jthread([this] { processEvents(); });
ECHOION_LOG_INFO("EventBus started");
}
void EventBus::stop() {
if (!running_.exchange(false)) {
return; // Not running
}
stopRequested_ = true;
queueCv_.notify_all();
if (eventThread_.joinable()) {
eventThread_.join();
}
ECHOION_LOG_INFO("EventBus stopped");
}
void EventBus::unsubscribe(const SubscriptionToken& token) {
if (!token.isValid()) {
return;
}
std::unique_lock<std::shared_mutex> lock(handlersMutex_);
auto it = handlers_.find(token.getType());
if (it != handlers_.end()) {
it->second.erase(token.getId());
if (it->second.empty()) {
handlers_.erase(it);
}
}
}
void EventBus::processOne() {
std::shared_ptr<IEvent> evt;
{
std::lock_guard<std::mutex> lock(queueMutex_);
if (eventQueue_.empty()) {
return;
}
evt = std::move(eventQueue_.front());
eventQueue_.pop();
}
// Get handlers for this event type
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
auto it = handlers_.find(evt->getType());
if (it != handlers_.end()) {
// Copy handlers to avoid holding lock during callback
auto handlers = it->second;
lock.unlock();
for (const auto& [id, handler] : handlers) {
try {
if (handler) {
(*handler)(evt);
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
}
}
}
}
bool EventBus::waitAndProcessOne(std::chrono::milliseconds timeout) {
std::shared_ptr<IEvent> evt;
{
std::unique_lock<std::mutex> lock(queueMutex_);
if (!queueCv_.wait_for(lock, timeout, [this] {
return !eventQueue_.empty() || stopRequested_.load();
})) {
return false; // Timeout
}
if (stopRequested_ || eventQueue_.empty()) {
return false;
}
evt = std::move(eventQueue_.front());
eventQueue_.pop();
}
// Get handlers for this event type
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
auto it = handlers_.find(evt->getType());
if (it != handlers_.end()) {
auto handlers = it->second;
lock.unlock();
for (const auto& [id, handler] : handlers) {
try {
if (handler) {
(*handler)(evt);
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
}
}
}
return true;
}
void EventBus::clearQueue() {
std::lock_guard<std::mutex> lock(queueMutex_);
std::queue<std::shared_ptr<IEvent>> empty;
std::swap(eventQueue_, empty);
}
size_t EventBus::getPendingEventCount() const {
std::lock_guard<std::mutex> lock(queueMutex_);
return eventQueue_.size();
}
void EventBus::processEvents() {
while (!stopRequested_) {
std::shared_ptr<IEvent> evt;
{
std::unique_lock<std::mutex> lock(queueMutex_);
queueCv_.wait(lock, [this] {
return !eventQueue_.empty() || stopRequested_.load();
});
if (stopRequested_) {
break;
}
if (eventQueue_.empty()) {
continue;
}
evt = std::move(eventQueue_.front());
eventQueue_.pop();
}
// Get handlers for this event type
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
auto it = handlers_.find(evt->getType());
if (it != handlers_.end()) {
// Copy handlers to avoid holding lock during callback
auto handlers = it->second;
lock.unlock();
for (const auto& [id, handler] : handlers) {
try {
if (handler) {
(*handler)(evt);
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
}
}
}
}
}
// Global event bus instance. The EventBus type is otherwise header-only
// (it delegates to Void::EventBus); only the singleton lives here.
EventBus& GlobalEventBus::instance()
{
static EventBus instance;
return instance;
}
} // namespace Echoion::Api
+10 -14
View File
@@ -1,23 +1,19 @@
#include "echoion/api/Export.hpp"
#include <Export.hpp>
#include "echoion/core/Core.hpp"
#include <memory>
namespace Echoion::Api {
namespace Echoion::Api
{
CoreInterfacePtr CreateCore() {
return std::make_shared<Core::Core>();
}
CoreInterfacePtr CreateCore() { return std::make_shared<Core::Core>(); }
void DestroyCore(ICoreInterface* core) {
delete core;
}
void DestroyCore(ICoreInterface* core) { delete core; }
const char* GetApiVersion() {
return VERSION_STRING;
}
const char* GetApiVersion() { return VERSION_STRING; }
bool IsApiCompatible(uint32_t major, uint32_t minor) {
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
}
bool IsApiCompatible(uint32_t major, uint32_t minor)
{
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
}
} // namespace Echoion::Api
+185 -353
View File
@@ -1,381 +1,213 @@
#include "echoion/core/Logger.hpp"
#include <iostream>
#include <format>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/Entry.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Level.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <algorithm>
#include <iostream>
namespace Echoion::Core {
namespace
{
[[nodiscard]] Void::Logging::Level toVoidLevel(Echoion::Api::LogLevel level)
{
using A = Echoion::Api::LogLevel;
using V = Void::Logging::Level;
switch (level) {
case A::Debug:
return V::Debug;
case A::Info:
return V::Info;
case A::Warning:
return V::Warning;
case A::Error:
return V::Error;
case A::Critical:
return V::Fatal;
}
return V::Info;
}
Logger::Logger(std::string_view logDir, std::string_view baseName)
: logDir_(logDir)
, baseName_(baseName) {
// Ensure log directory exists
std::error_code ec;
std::filesystem::create_directories(logDir_, ec);
// Ensure history directory exists
ensureHistoryDirExists();
// Open log files for each level
openLogFiles();
// Start worker thread
workerThread_ = std::thread(&Logger::logWorker, this);
}
[[nodiscard]] Echoion::Api::LogLevel fromVoidLevel(Void::Logging::Level level)
{
using A = Echoion::Api::LogLevel;
using V = Void::Logging::Level;
switch (level) {
case V::Trace:
case V::Debug:
return A::Debug;
case V::Info:
return A::Info;
case V::Warning:
return A::Warning;
case V::Error:
return A::Error;
case V::Fatal:
return A::Critical;
case V::Disabled:
return A::Debug;
}
return A::Info;
}
} // namespace
Logger::~Logger() {
running_ = false;
cv_.notify_all();
if (workerThread_.joinable()) {
workerThread_.join();
}
// Close all file streams
std::lock_guard<std::mutex> lock(fileMutex_);
for (auto& [level, info] : levelFiles_) {
if (info.stream.is_open()) {
info.stream.close();
}
}
if (combinedFile_.stream.is_open()) {
combinedFile_.stream.close();
}
}
namespace Echoion::Core
{
void Logger::ensureHistoryDirExists() {
std::error_code ec;
auto historyDir = logDir_ / "history";
std::filesystem::create_directories(historyDir, ec);
}
Logger::Logger(std::string_view logDir, std::string_view baseName)
: logDir_(logDir), baseName_(baseName)
{
std::error_code ec;
std::filesystem::create_directories(logDir_, ec);
rebuildSinks();
}
void Logger::openLogFiles() {
std::lock_guard<std::mutex> lock(fileMutex_);
// Open file for each log level
for (auto level : {Api::LogLevel::Debug, Api::LogLevel::Info,
Api::LogLevel::Warning, Api::LogLevel::Error, Api::LogLevel::Critical}) {
auto path = generateLogFilePath(level);
LogFileInfo info;
info.path = path;
info.stream.open(path, std::ios::app);
info.createdAt = std::chrono::system_clock::now();
// Get current file size
if (std::filesystem::exists(path)) {
info.size = std::filesystem::file_size(path);
}
levelFiles_[level] = std::move(info);
}
// Open combined log file
auto combinedPath = logDir_ / std::format("{}_all.log", baseName_);
combinedFile_.path = combinedPath;
combinedFile_.stream.open(combinedPath, std::ios::app);
combinedFile_.createdAt = std::chrono::system_clock::now();
if (std::filesystem::exists(combinedPath)) {
combinedFile_.size = std::filesystem::file_size(combinedPath);
}
}
Logger::~Logger()
{
std::lock_guard<std::mutex> lock(sinkMutex_);
if (sink_) {
sink_->flush();
sink_.reset();
}
}
std::filesystem::path Logger::generateLogFilePath(Api::LogLevel level) {
std::string levelStr;
switch (level) {
case Api::LogLevel::Debug: levelStr = "debug"; break;
case Api::LogLevel::Info: levelStr = "info"; break;
case Api::LogLevel::Warning: levelStr = "warning"; break;
case Api::LogLevel::Error: levelStr = "error"; break;
case Api::LogLevel::Critical: levelStr = "critical"; break;
default: levelStr = "unknown"; break;
}
return logDir_ / std::format("{}_{}.log", baseName_, levelStr);
}
void Logger::rebuildSinks()
{
namespace VL = Void::Logging;
void Logger::log(Api::LogLevel level, std::string_view message, std::source_location location) {
if (level < minLevel_.load()) {
return;
}
Api::LogEntry entry;
entry.timestamp = std::chrono::system_clock::now();
entry.level = level;
entry.message = std::string(message);
entry.sourceFile = location.file_name();
entry.sourceLine = location.line();
entry.function = location.function_name();
entry.threadId = std::this_thread::get_id();
{
std::lock_guard<std::mutex> lock(queueMutex_);
logQueue_.push(std::move(entry));
}
cv_.notify_one();
}
auto multi = std::make_shared<VL::MultiLogger>();
void Logger::logWorker() {
while (running_.load()) {
std::unique_lock<std::mutex> lock(queueMutex_);
cv_.wait(lock, [this] { return !logQueue_.empty() || !running_.load(); });
while (!logQueue_.empty()) {
auto entry = std::move(logQueue_.front());
logQueue_.pop();
lock.unlock();
// Format the log entry
std::string formatted = formatLogEntry(entry);
// Console output
if (consoleOutput_.load()) {
if (entry.level >= Api::LogLevel::Error) {
std::cerr << formatted << std::endl;
} else {
std::cout << formatted << std::endl;
}
}
// File output
if (fileOutput_.load()) {
rotateIfNeeded(entry.level);
writeToFile(entry.level, formatted);
}
// Callbacks
{
std::lock_guard<std::mutex> cbLock(callbackMutex_);
for (const auto& callback : callbacks_) {
callback(entry);
}
}
lock.lock();
}
}
}
// Shared layout approximating the previous Logger output:
// [2024-01-01 12:00:00.123] [INFO] [thread] file.cpp - message
auto formatter = std::make_shared<const VL::PatternFormatter>(
"[{time}] [{level}] [{thread}] {file} - {message}");
void Logger::writeToFile(Api::LogLevel level, const std::string& formattedEntry) {
std::lock_guard<std::mutex> lock(fileMutex_);
// Write to level-specific file
auto it = levelFiles_.find(level);
if (it != levelFiles_.end() && it->second.stream.is_open()) {
it->second.stream << formattedEntry << std::endl;
it->second.size += formattedEntry.size() + 1;
}
// Write to combined file
if (combinedFile_.stream.is_open()) {
combinedFile_.stream << formattedEntry << std::endl;
combinedFile_.size += formattedEntry.size() + 1;
}
}
if (consoleOutput_.load()) {
auto console = std::make_shared<VL::ConsoleLogger>(std::cout);
console->set_formatter(formatter);
multi->add(std::move(console));
}
void Logger::moveToHistory(const std::filesystem::path& filePath) {
ensureHistoryDirExists();
auto historyDir = logDir_ / "history";
auto fileName = filePath.filename().string();
// Generate timestamp for unique filename
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::tm tm;
localtime_r(&time_t, &tm);
std::string timestamp = std::format("{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
auto historyPath = historyDir / std::format("{}.{}", fileName, timestamp);
std::error_code ec;
std::filesystem::rename(filePath, historyPath, ec);
if (!ec) {
// Clean up old history files (keep last 30)
cleanupOldLogs();
}
}
if (fileOutput_.load()) {
VL::SplitFileOptions opts;
opts.combined = true; // also write <dir>/all.log
opts.max_bytes = static_cast<std::size_t>(maxFileSize_.load());
opts.max_files = static_cast<std::size_t>(maxFiles_.load());
if (auto fileSink = VL::SplitFileLogger::open(logDir_, opts)) {
(*fileSink)->set_formatter(formatter);
multi->add(std::shared_ptr<VL::Logger>(std::move(*fileSink)));
}
}
void Logger::cleanupOldLogs() {
ensureHistoryDirExists();
auto historyDir = logDir_ / "history";
if (!std::filesystem::exists(historyDir)) {
return;
}
// Get all files in history directory
std::vector<std::pair<std::filesystem::path, std::filesystem::file_time_type>> files;
for (const auto& entry : std::filesystem::directory_iterator(historyDir)) {
if (entry.is_regular_file()) {
files.emplace_back(entry.path(), entry.last_write_time());
}
}
// Sort by modification time (oldest first)
std::sort(files.begin(), files.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
// Keep only the most recent 30 files
const size_t maxHistoryFiles = 30;
if (files.size() > maxHistoryFiles) {
std::error_code ec;
for (size_t i = 0; i < files.size() - maxHistoryFiles; ++i) {
std::filesystem::remove(files[i].first, ec);
}
}
}
// Bridge Void entries back to the registered ILogger callbacks so
// existing log subscribers (e.g. RPC log streaming) keep receiving
// Api::LogEntry records, asynchronously as before.
multi->add(std::make_shared<VL::CallbackLogger>(
[this](const VL::Entry& entry) {
dispatchToCallbacks(fromVoidLevel(entry.level), entry.message,
entry.location.file_name(),
entry.location.line(),
entry.location.function_name());
}));
void Logger::rotateIfNeeded(Api::LogLevel level) {
std::lock_guard<std::mutex> lock(fileMutex_);
auto maxSize = maxFileSize_.load();
auto maxFiles = maxFiles_.load();
// Check level-specific file
auto it = levelFiles_.find(level);
if (it != levelFiles_.end() && it->second.size >= maxSize) {
it->second.stream.close();
auto basePath = it->second.path;
// Move oldest to history if at max files
auto oldestPath = std::format("{}.{}", basePath.string(), maxFiles);
if (std::filesystem::exists(oldestPath)) {
moveToHistory(oldestPath);
}
// Rotate: move .4 to .5, .3 to .4, etc.
for (int i = maxFiles - 1; i > 0; --i) {
auto oldPath = std::format("{}.{}", basePath.string(), i);
auto newPath = std::format("{}.{}", basePath.string(), i + 1);
if (std::filesystem::exists(oldPath)) {
std::filesystem::rename(oldPath, newPath);
}
}
// Move current to .1
if (std::filesystem::exists(basePath)) {
std::filesystem::rename(basePath, std::format("{}.1", basePath.string()));
}
// Reopen
it->second.stream.open(basePath, std::ios::app);
it->second.size = 0;
it->second.createdAt = std::chrono::system_clock::now();
}
// Check combined file
if (combinedFile_.size >= maxSize) {
combinedFile_.stream.close();
auto basePath = combinedFile_.path;
// Move oldest to history if at max files
auto oldestPath = std::format("{}.{}", basePath.string(), maxFiles);
if (std::filesystem::exists(oldestPath)) {
moveToHistory(oldestPath);
}
// Rotate: move .4 to .5, .3 to .4, etc.
for (int i = maxFiles - 1; i > 0; --i) {
auto oldPath = std::format("{}.{}", basePath.string(), i);
auto newPath = std::format("{}.{}", basePath.string(), i + 1);
if (std::filesystem::exists(oldPath)) {
std::filesystem::rename(oldPath, newPath);
}
}
// Move current to .1
if (std::filesystem::exists(basePath)) {
std::filesystem::rename(basePath, std::format("{}.1", basePath.string()));
}
combinedFile_.stream.open(basePath, std::ios::app);
combinedFile_.size = 0;
combinedFile_.createdAt = std::chrono::system_clock::now();
}
}
std::lock_guard<std::mutex> lock(sinkMutex_);
sink_ = std::move(multi);
}
std::string Logger::formatLogEntry(const Api::LogEntry& entry) {
return std::format("[{}] [{}] [{}] {} - {}",
formatTimestamp(entry.timestamp),
levelToString(entry.level),
entry.threadId,
entry.sourceFile.substr(entry.sourceFile.find_last_of("/\\") + 1),
entry.message);
}
void Logger::dispatchToCallbacks(Api::LogLevel level,
const std::string& message,
const std::string& file, uint32_t line,
const std::string& function)
{
std::lock_guard<std::mutex> lock(callbackMutex_);
if (callbacks_.empty()) {
return;
}
std::string Logger::levelToString(Api::LogLevel level) {
switch (level) {
case Api::LogLevel::Debug: return "DEBUG";
case Api::LogLevel::Info: return "INFO";
case Api::LogLevel::Warning: return "WARN";
case Api::LogLevel::Error: return "ERROR";
case Api::LogLevel::Critical: return "CRITICAL";
default: return "UNKNOWN";
}
}
Api::LogEntry entry;
entry.level = level;
entry.message = message;
entry.sourceFile = file;
entry.sourceLine = line;
entry.function = function;
entry.threadId = std::this_thread::get_id();
entry.timestamp = std::chrono::system_clock::now();
std::string Logger::formatTimestamp(const std::chrono::system_clock::time_point& tp) {
auto time_t = std::chrono::system_clock::to_time_t(tp);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
tp.time_since_epoch()) % 1000;
std::tm tm;
localtime_r(&time_t, &tm);
return std::format("{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:03d}",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
}
for (const auto& callback : callbacks_) {
callback(entry);
}
}
void Logger::setMinLevel(Api::LogLevel level) {
minLevel_.store(level);
}
void Logger::log(Api::LogLevel level, std::string_view message,
std::source_location location)
{
if (level < minLevel_.load()) {
return;
}
Api::LogLevel Logger::getMinLevel() const {
return minLevel_.load();
}
std::shared_ptr<Void::Logging::MultiLogger> sink;
{
std::lock_guard<std::mutex> lock(sinkMutex_);
sink = sink_;
}
if (sink) {
sink->log(toVoidLevel(level), message, location);
}
}
void Logger::registerCallback(const LogCallback& callback) {
std::lock_guard<std::mutex> lock(callbackMutex_);
callbacks_.push_back(callback);
}
void Logger::setMinLevel(Api::LogLevel level) { minLevel_.store(level); }
void Logger::unregisterCallback(const LogCallback& callback) {
std::lock_guard<std::mutex> lock(callbackMutex_);
callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(),
[&callback](const auto& cb) { return &cb == &callback; }), callbacks_.end());
}
Api::LogLevel Logger::getMinLevel() const { return minLevel_.load(); }
void Logger::flush() {
std::lock_guard<std::mutex> lock(fileMutex_);
for (auto& [level, info] : levelFiles_) {
if (info.stream.is_open()) {
info.stream.flush();
}
}
if (combinedFile_.stream.is_open()) {
combinedFile_.stream.flush();
}
}
void Logger::registerCallback(const LogCallback& callback)
{
std::lock_guard<std::mutex> lock(callbackMutex_);
callbacks_.push_back(callback);
}
void Logger::setConsoleOutput(bool enabled) {
consoleOutput_.store(enabled);
}
void Logger::unregisterCallback(const LogCallback& callback)
{
std::lock_guard<std::mutex> lock(callbackMutex_);
callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(),
[&callback](const auto& cb) {
return &cb == &callback;
}),
callbacks_.end());
}
void Logger::setFileOutput(bool enabled) {
fileOutput_.store(enabled);
}
void Logger::flush()
{
std::lock_guard<std::mutex> lock(sinkMutex_);
if (sink_) {
sink_->flush();
}
}
void Logger::setMaxFileSize(uint64_t bytes) {
maxFileSize_.store(bytes);
}
void Logger::setConsoleOutput(bool enabled)
{
consoleOutput_.store(enabled);
rebuildSinks();
}
void Logger::setMaxFiles(uint32_t count) {
maxFiles_.store(count);
}
void Logger::setFileOutput(bool enabled)
{
fileOutput_.store(enabled);
rebuildSinks();
}
void Logger::setMaxFileSize(uint64_t bytes)
{
maxFileSize_.store(bytes);
rebuildSinks();
}
void Logger::setMaxFiles(uint32_t count)
{
maxFiles_.store(count);
rebuildSinks();
}
} // namespace Echoion::Core
+50 -37
View File
@@ -1,47 +1,60 @@
#include "echoion/api/MemoryPool.hpp"
#include "echoion/core/Logger.hpp"
#include <MemoryPool.hpp>
#include <format>
#include <vector>
namespace Echoion::Api {
namespace Echoion::Api
{
AudioBufferPool& AudioBufferPool::instance() {
static AudioBufferPool instance;
return instance;
}
AudioBufferPool& AudioBufferPool::instance()
{
static AudioBufferPool instance;
return instance;
}
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize) {
bufferSize_ = bufferSize;
pool_ = std::make_unique<MemoryPool<int16_t>>(bufferSize, poolSize);
ECHOION_LOG_INFO(std::format("AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
poolSize, bufferSize, (bufferSize * poolSize * sizeof(int16_t)) / 1024));
}
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize)
{
bufferSize_ = bufferSize;
pool_ = std::make_unique<Void::BufferPool::BufferPool<int16_t>>();
void AudioBufferPool::shutdown() {
pool_.reset();
ECHOION_LOG_INFO("AudioBufferPool shutdown");
}
// Pre-warm the size-class bucket: acquire then immediately drop
// `poolSize` buffers so subsequent acquireBuffer() calls reuse storage.
{
std::vector<AudioSampleBuffer> warm;
warm.reserve(poolSize);
for (size_t i = 0; i < poolSize; ++i) {
warm.push_back(pool_->acquire(bufferSize));
}
} // buffers returned to the pool here
PooledPtr<int16_t> AudioBufferPool::acquireBuffer() {
if (!pool_) {
return PooledPtr<int16_t>();
}
int16_t* ptr = pool_->acquire();
if (!ptr) {
ECHOION_LOG_WARNING("AudioBufferPool exhausted - consider increasing pool size");
return PooledPtr<int16_t>();
}
return PooledPtr<int16_t>(ptr, pool_.get());
}
ECHOION_LOG_INFO(std::format(
"AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
poolSize, bufferSize,
(bufferSize * poolSize * sizeof(int16_t)) / 1024));
}
size_t AudioBufferPool::getAvailableBuffers() const {
if (!pool_) return 0;
return pool_->available();
}
void AudioBufferPool::shutdown()
{
pool_.reset();
ECHOION_LOG_INFO("AudioBufferPool shutdown");
}
size_t AudioBufferPool::getTotalBuffers() const {
if (!pool_) return 0;
return pool_->capacity();
}
AudioSampleBuffer AudioBufferPool::acquireBuffer()
{
if (!pool_) {
return AudioSampleBuffer{};
}
return pool_->acquire(bufferSize_);
}
size_t AudioBufferPool::getAvailableBuffers() const
{
return pool_ ? pool_->stats().pooled : 0;
}
size_t AudioBufferPool::getTotalBuffers() const
{
return pool_ ? static_cast<size_t>(pool_->stats().allocations) : 0;
}
} // namespace Echoion::Api
+2295 -1718
View File
File diff suppressed because it is too large. Load diff
+871 -755
View File
File diff suppressed because it is too large. Load diff
+410 -347
View File
@@ -1,400 +1,463 @@
#include "echoion/core/RpcServer.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include "echoion/core/RpcServer.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <algorithm>
#include <format>
namespace Echoion::Core {
namespace Echoion::Core
{
RpcServer::RpcServer() = default;
RpcServer::RpcServer() = default;
RpcServer::~RpcServer() {
stop();
}
RpcServer::~RpcServer() { stop(); }
Api::Result<void> RpcServer::start(uint16_t port) {
if (running_.exchange(true)) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "RPC server already running"));
}
Api::Result<void> RpcServer::start(uint16_t port)
{
if (running_.exchange(true)) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
"RPC server already running"));
}
port_ = port;
port_ = port;
try {
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
acceptor_.emplace(ioContext_);
acceptor_->open(endpoint.protocol());
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
acceptor_->bind(endpoint);
acceptor_->listen();
try {
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
acceptor_.emplace(ioContext_);
acceptor_->open(endpoint.protocol());
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
acceptor_->bind(endpoint);
acceptor_->listen();
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
ECHOION_LOG_INFO(std::format("RPC server started on port {}", port));
return {};
} catch (const std::exception& e) {
running_ = false;
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
std::format("Failed to start RPC server: {}", e.what())));
}
}
ECHOION_LOG_INFO(
std::format("RPC server started on port {}", port));
return {};
} catch (const std::exception& e) {
running_ = false;
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable,
std::format("Failed to start RPC server: {}", e.what())));
}
}
void RpcServer::stop() {
if (!running_.exchange(false)) {
return;
}
void RpcServer::stop()
{
if (!running_.exchange(false)) {
return;
}
try {
// Cancel any pending async operations
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->cancel(ec);
}
ioContext_.stop();
try {
// Cancel any pending async operations
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->cancel(ec);
}
// Close all client connections
{
std::lock_guard<std::mutex> lock(clientsMutex_);
for (auto& [id, ws] : clients_) {
if (ws->is_open()) {
beast::error_code ec;
ws->close(websocket::close_code::normal, ec);
}
}
clients_.clear();
}
ioContext_.stop();
// Wait for all client threads to finish (with timeout)
{
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
for (auto& thread : clientThreads_) {
if (thread.joinable()) {
thread.detach(); // Don't wait, just detach
}
}
clientThreads_.clear();
}
// Close all client connections
{
std::lock_guard<std::mutex> lock(clientsMutex_);
for (auto& [id, ws] : clients_) {
if (ws->is_open()) {
beast::error_code ec;
ws->close(websocket::close_code::normal, ec);
}
}
clients_.clear();
}
// Wait for server thread with timeout
if (serverThread_.joinable()) {
// Give it a moment to clean up
auto start = std::chrono::steady_clock::now();
while (serverThread_.joinable() &&
std::chrono::steady_clock::now() - start < std::chrono::seconds(2)) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
if (serverThread_.joinable()) {
serverThread_.detach(); // Force detach if still running
}
}
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->close(ec);
}
// Wait for all client threads to finish (with timeout)
{
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
for (auto& thread : clientThreads_) {
if (thread.joinable()) {
// Give each thread a short time to finish
auto start = std::chrono::steady_clock::now();
while (thread.joinable() &&
std::chrono::steady_clock::now() - start <
std::chrono::milliseconds(100)) {
std::this_thread::sleep_for(
std::chrono::milliseconds(10));
}
if (thread.joinable()) {
thread.detach(); // Only detach if still running
// after timeout
}
}
}
clientThreads_.clear();
}
ECHOION_LOG_INFO("RPC server stopped");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Error stopping RPC server: {}", e.what()));
}
}
// Wait for server thread with timeout
if (serverThread_.joinable()) {
// Give it a moment to clean up
auto start = std::chrono::steady_clock::now();
while (serverThread_.joinable() &&
std::chrono::steady_clock::now() - start <
std::chrono::seconds(2)) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
if (serverThread_.joinable()) {
serverThread_.detach(); // Force detach if still running
}
}
void RpcServer::acceptLoop() {
ECHOION_LOG_INFO("RPC server accept loop started");
while (running_.load()) {
try {
asio::ip::tcp::socket socket(ioContext_);
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
// Use async accept with cancellation support
std::atomic<bool> acceptComplete{false};
boost::system::error_code acceptEc;
acceptor_->async_accept(socket, [&](const boost::system::error_code& ec) {
acceptEc = ec;
acceptComplete = true;
});
// Poll until accept completes or we're stopped
while (!acceptComplete.load() && running_.load()) {
ioContext_.poll_one();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// Cancel pending operation if we're stopping
if (!running_.load()) {
acceptor_->cancel();
break;
}
if (acceptEc) {
throw std::runtime_error(acceptEc.message());
}
ECHOION_LOG_DEBUG(std::format("RPC server accepted TCP connection from {}:{}",
socket.remote_endpoint().address().to_string(),
socket.remote_endpoint().port()));
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->close(ec);
}
if (!running_.load()) break;
ECHOION_LOG_INFO("RPC server stopped");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Error stopping RPC server: {}", e.what()));
}
}
auto ws = std::make_shared<websocket::stream<asio::ip::tcp::socket>>(std::move(socket));
ws->accept();
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
void RpcServer::acceptLoop()
{
ECHOION_LOG_INFO("RPC server accept loop started");
while (running_.load()) {
try {
asio::ip::tcp::socket socket(ioContext_);
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
uint64_t clientId = nextClientId_++;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_[clientId] = ws;
}
// Use async accept with cancellation support
std::atomic<bool> acceptComplete{false};
boost::system::error_code acceptEc;
ECHOION_LOG_DEBUG(std::format("RPC client {} connected", clientId));
acceptor_->async_accept(
socket, [&](const boost::system::error_code& ec) {
acceptEc = ec;
acceptComplete = true;
});
// Handle client in separate thread
std::thread clientThread([this, clientId, ws]() {
handleClient(ws);
// Cleanup
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_.erase(clientId);
}
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
ECHOION_LOG_DEBUG(std::format("RPC client {} disconnected", clientId));
});
// Track the thread for proper cleanup
{
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
// Clean up any finished threads first
clientThreads_.erase(
std::remove_if(clientThreads_.begin(), clientThreads_.end(),
[](std::thread& t) {
if (!t.joinable()) return true;
return false;
}),
clientThreads_.end()
);
clientThreads_.push_back(std::move(clientThread));
}
// Poll until accept completes or we're stopped
while (!acceptComplete.load() && running_.load()) {
ioContext_.poll_one();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
} catch (const std::exception& e) {
// If we're shutting down, exit gracefully
if (!running_.load()) {
break;
}
ECHOION_LOG_ERROR(std::format("RPC accept error: {}", e.what()));
}
}
ECHOION_LOG_INFO("RPC server accept loop stopped");
}
// Cancel pending operation if we're stopping
if (!running_.load()) {
acceptor_->cancel();
break;
}
void RpcServer::handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws) {
beast::flat_buffer buffer;
if (acceptEc) {
throw std::runtime_error(acceptEc.message());
}
while (running_.load() && ws->is_open()) {
try {
beast::error_code ec;
ws->read(buffer, ec);
ECHOION_LOG_DEBUG(
std::format("RPC server accepted TCP connection from {}:{}",
socket.remote_endpoint().address().to_string(),
socket.remote_endpoint().port()));
if (ec == websocket::error::closed) {
break;
}
if (ec) {
ECHOION_LOG_ERROR(std::format("WebSocket read error: {}", ec.message()));
break;
}
if (!running_.load()) {
break;
}
std::string message = beast::buffers_to_string(buffer.data());
buffer.consume(buffer.size());
auto ws =
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
std::move(socket));
ws->accept();
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
// Find client ID
uint64_t clientId = 0;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
for (const auto& [id, clientWs] : clients_) {
if (clientWs.get() == ws.get()) {
clientId = id;
break;
}
}
}
uint64_t clientId = nextClientId_++;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_[clientId] = ws;
}
if (clientId != 0) {
processMessage(clientId, message);
}
ECHOION_LOG_DEBUG(
std::format("RPC client {} connected", clientId));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Client handling error: {}", e.what()));
break;
}
}
}
// Handle client in separate thread
std::thread clientThread([this, clientId, ws]() {
handleClient(ws);
void RpcServer::processMessage(uint64_t clientId, const std::string& message) {
try {
Api::RpcRequest request;
auto ec = glz::read_json(request, message);
if (ec) {
Api::RpcResponse response;
response.requestId = 0;
response.success = false;
response.error = "{\"code\":5,\"message\":\"Invalid JSON\",\"source\":\"RpcServer\"}";
response.success = false;
sendResponse(clientId, response);
return;
}
// Cleanup
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_.erase(clientId);
}
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
ECHOION_LOG_DEBUG(
std::format("RPC client {} disconnected", clientId));
});
// Check authentication (except for Authenticate method)
if (request.method != Api::RpcMethod::Authenticate) {
if (!isClientAuthenticated(clientId)) {
Api::RpcResponse response;
response.requestId = request.id;
response.success = false;
response.error = "{\"code\":10,\"message\":\"Not authenticated\",\"source\":\"RpcServer\"}";
response.success = false;
sendResponse(clientId, response);
return;
}
}
// Track the thread for proper cleanup
{
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
// Clean up any finished threads first
clientThreads_.erase(std::remove_if(clientThreads_.begin(),
clientThreads_.end(),
[](std::thread& t) {
if (!t.joinable()) {
return true;
}
return false;
}),
clientThreads_.end());
clientThreads_.push_back(std::move(clientThread));
}
// Find handler
std::string methodName = std::to_string(static_cast<int>(request.method));
CommandHandler handler;
{
std::lock_guard<std::mutex> lock(handlersMutex_);
auto it = handlers_.find(methodName);
if (it != handlers_.end()) {
handler = it->second;
}
}
} catch (const std::exception& e) {
// If we're shutting down, exit gracefully
if (!running_.load()) {
break;
}
ECHOION_LOG_ERROR(
std::format("RPC accept error: {}", e.what()));
}
}
ECHOION_LOG_INFO("RPC server accept loop stopped");
}
Api::RpcResponse response;
response.requestId = request.id;
response.timestamp = std::chrono::system_clock::now();
void RpcServer::handleClient(
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
{
beast::flat_buffer buffer;
if (handler) {
auto result = handler(request.params.value_or(""), clientId);
if (result) {
response.success = true;
response.result = *result;
} else {
response.success = false;
response.error = std::format("{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
static_cast<uint32_t>(result.error().code),
result.error().message,
result.error().source);
}
} else {
response.success = false;
response.error = "{\"code\":2,\"message\":\"Unknown method\",\"source\":\"RpcServer\"}";
}
while (running_.load() && ws->is_open()) {
try {
beast::error_code ec;
ws->read(buffer, ec);
sendResponse(clientId, response);
if (ec == websocket::error::closed) {
break;
}
if (ec) {
ECHOION_LOG_ERROR(
std::format("WebSocket read error: {}", ec.message()));
break;
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Message processing error: {}", e.what()));
}
}
std::string message = beast::buffers_to_string(buffer.data());
buffer.consume(buffer.size());
void RpcServer::sendResponse(uint64_t clientId, const Api::RpcResponse& response) {
std::lock_guard<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
// Find client ID
uint64_t clientId = 0;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
for (const auto& [id, clientWs] : clients_) {
if (clientWs.get() == ws.get()) {
clientId = id;
break;
}
}
}
try {
auto json = glz::write_json(response);
if (json) {
it->second->write(asio::buffer(*json));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
}
}
if (clientId != 0) {
processMessage(clientId, message);
}
void RpcServer::sendNotification(uint64_t clientId, const Api::RpcNotification& notification) {
std::lock_guard<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Client handling error: {}", e.what()));
break;
}
}
}
try {
auto json = glz::write_json(notification);
if (json) {
it->second->write(asio::buffer(*json));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Send notification error: {}", e.what()));
}
}
void RpcServer::processMessage(uint64_t clientId,
const std::string& message)
{
try {
Api::RpcRequest request;
bool decoded = false;
if (auto parsed = Void::Json::parse(message)) {
if (auto req = Void::Json::from_json<Api::RpcRequest>(*parsed)) {
request = std::move(*req);
decoded = true;
}
}
if (!decoded) {
Api::RpcResponse response;
response.requestId = 0;
response.success = false;
response.error = "{\"code\":5,\"message\":\"Invalid "
"JSON\",\"source\":\"RpcServer\"}";
response.success = false;
sendResponse(clientId, response);
return;
}
void RpcServer::broadcastEvent(const std::string& event, const std::string& data) {
Api::RpcNotification notification;
notification.event = event;
notification.data = data;
notification.timestamp = std::chrono::system_clock::now();
// Check authentication (except for Authenticate method)
if (request.method != Api::RpcMethod::Authenticate) {
if (!isClientAuthenticated(clientId)) {
Api::RpcResponse response;
response.requestId = request.id;
response.success = false;
response.error =
"{\"code\":10,\"message\":\"Not "
"authenticated\",\"source\":\"RpcServer\"}";
response.success = false;
sendResponse(clientId, response);
return;
}
}
std::lock_guard<std::mutex> lock(clientsMutex_);
for (const auto& [clientId, ws] : clients_) {
if (ws->is_open() && isClientAuthenticated(clientId)) {
try {
auto json = glz::write_json(notification);
if (json) {
ws->write(asio::buffer(*json));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Broadcast error: {}", e.what()));
}
}
}
}
// Find handler
std::string methodName =
std::to_string(static_cast<int>(request.method));
CommandHandler handler;
{
std::lock_guard<std::mutex> lock(handlersMutex_);
auto it = handlers_.find(methodName);
if (it != handlers_.end()) {
handler = it->second;
}
}
void RpcServer::sendEvent(uint64_t clientId, const std::string& event, const std::string& data) {
Api::RpcNotification notification;
notification.event = event;
notification.data = data;
notification.timestamp = std::chrono::system_clock::now();
sendNotification(clientId, notification);
}
Api::RpcResponse response;
response.requestId = request.id;
response.timestamp = std::chrono::system_clock::now();
void RpcServer::registerHandler(const std::string& method, CommandHandler handler) {
std::lock_guard<std::mutex> lock(handlersMutex_);
handlers_[method] = std::move(handler);
}
if (handler) {
auto result = handler(request.params.value_or(""), clientId);
if (result) {
response.success = true;
response.result = *result;
} else {
response.success = false;
response.error = std::format(
"{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
static_cast<uint32_t>(result.error().code),
result.error().message,
result.error().source);
}
} else {
response.success = false;
response.error = "{\"code\":2,\"message\":\"Unknown "
"method\",\"source\":\"RpcServer\"}";
}
void RpcServer::unregisterHandler(const std::string& method) {
std::lock_guard<std::mutex> lock(handlersMutex_);
handlers_.erase(method);
}
sendResponse(clientId, response);
void RpcServer::setAuthToken(const std::string& token) {
std::lock_guard<std::mutex> lock(authMutex_);
authToken_ = token;
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Message processing error: {}", e.what()));
}
}
bool RpcServer::authenticate(const std::string& token) {
std::lock_guard<std::mutex> lock(authMutex_);
return authToken_.empty() || token == authToken_;
}
void RpcServer::sendResponse(uint64_t clientId,
const Api::RpcResponse& response)
{
std::lock_guard<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
void RpcServer::addAuthenticatedClient(uint64_t clientId) {
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.insert(clientId);
}
try {
const std::string json =
Void::Json::serialize(Void::Json::to_json(response));
it->second->write(asio::buffer(json));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
}
}
void RpcServer::removeAuthenticatedClient(uint64_t clientId) {
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
void RpcServer::sendNotification(uint64_t clientId,
const Api::RpcNotification& notification)
{
std::lock_guard<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
bool RpcServer::isClientAuthenticated(uint64_t clientId) {
std::lock_guard<std::mutex> lock(authMutex_);
return authenticatedClients_.contains(clientId);
}
try {
const std::string json =
Void::Json::serialize(Void::Json::to_json(notification));
it->second->write(asio::buffer(json));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Send notification error: {}", e.what()));
}
}
void RpcServer::broadcastEvent(const std::string& event,
const std::string& data)
{
Api::RpcNotification notification;
notification.event = event;
notification.data = data;
notification.timestamp = std::chrono::system_clock::now();
std::lock_guard<std::mutex> lock(clientsMutex_);
for (const auto& [clientId, ws] : clients_) {
if (ws->is_open() && isClientAuthenticated(clientId)) {
try {
const std::string json = Void::Json::serialize(
Void::Json::to_json(notification));
ws->write(asio::buffer(json));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Broadcast error: {}", e.what()));
}
}
}
}
void RpcServer::sendEvent(uint64_t clientId, const std::string& event,
const std::string& data)
{
Api::RpcNotification notification;
notification.event = event;
notification.data = data;
notification.timestamp = std::chrono::system_clock::now();
sendNotification(clientId, notification);
}
void RpcServer::registerHandler(const std::string& method,
CommandHandler handler)
{
std::lock_guard<std::mutex> lock(handlersMutex_);
handlers_[method] = std::move(handler);
}
void RpcServer::unregisterHandler(const std::string& method)
{
std::lock_guard<std::mutex> lock(handlersMutex_);
handlers_.erase(method);
}
void RpcServer::setAuthToken(const std::string& token)
{
std::lock_guard<std::mutex> lock(authMutex_);
authToken_ = token;
}
bool RpcServer::authenticate(const std::string& token)
{
std::lock_guard<std::mutex> lock(authMutex_);
return authToken_.empty() || token == authToken_;
}
void RpcServer::addAuthenticatedClient(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.insert(clientId);
}
void RpcServer::removeAuthenticatedClient(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
bool RpcServer::isClientAuthenticated(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(authMutex_);
return authenticatedClients_.contains(clientId);
}
} // namespace Echoion::Core
+203
View File
@@ -0,0 +1,203 @@
#include "echoion/core/Logger.hpp"
#include "echoion/core/SessionManager.hpp"
#include <format>
#include <iomanip>
#include <random>
#include <sstream>
namespace Echoion::Core
{
SessionManager::SessionManager() = default;
SessionManager::SessionManager(const Config& config) : config_(config) {}
bool SessionManager::initialize()
{
running_ = true;
ECHOION_LOG_INFO(std::format(
"SessionManager initialized: max {} sessions, timeout {}s",
config_.maxSessions, config_.sessionTimeout.count()));
return true;
}
void SessionManager::shutdown()
{
running_ = false;
std::lock_guard<std::mutex> lock(mutex_);
sessions_.clear();
ECHOION_LOG_INFO("SessionManager shut down");
}
std::string SessionManager::createSession(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(mutex_);
// Check capacity
if (sessions_.size() >= config_.maxSessions) {
ECHOION_LOG_WARNING(
"Session capacity reached, rejecting new session");
return "";
}
// Generate unique token
std::string token = generateToken();
Session session;
session.clientId = clientId;
session.authToken = token;
session.lastActivity = std::chrono::steady_clock::now();
session.createdAt = session.lastActivity;
session.isAuthenticated = false;
sessions_[token] = std::move(session);
ECHOION_LOG_INFO(
std::format("Created session for client {}", clientId));
return token;
}
bool SessionManager::authenticateSession(const std::string& token)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = sessions_.find(token);
if (it == sessions_.end()) {
return false;
}
it->second.isAuthenticated = true;
it->second.lastActivity = std::chrono::steady_clock::now();
return true;
}
bool SessionManager::validateSession(const std::string& token)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = sessions_.find(token);
if (it == sessions_.end()) {
return false;
}
// Check timeout
auto elapsed =
std::chrono::steady_clock::now() - it->second.lastActivity;
if (elapsed > config_.sessionTimeout) {
sessions_.erase(it);
return false;
}
return it->second.isAuthenticated;
}
void SessionManager::updateActivity(const std::string& token)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = sessions_.find(token);
if (it != sessions_.end()) {
it->second.lastActivity = std::chrono::steady_clock::now();
}
}
std::optional<SessionManager::Session>
SessionManager::getSession(const std::string& token) const
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = sessions_.find(token);
if (it != sessions_.end()) {
return it->second;
}
return std::nullopt;
}
void SessionManager::endSession(const std::string& token)
{
std::lock_guard<std::mutex> lock(mutex_);
sessions_.erase(token);
}
void SessionManager::endSessionByClientId(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(mutex_);
for (auto it = sessions_.begin(); it != sessions_.end();) {
if (it->second.clientId == clientId) {
it = sessions_.erase(it);
} else {
++it;
}
}
}
std::vector<SessionManager::Session> SessionManager::getAllSessions() const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<Session> result;
result.reserve(sessions_.size());
for (const auto& [token, session] : sessions_) {
result.push_back(session);
}
return result;
}
size_t SessionManager::getSessionCount() const
{
std::lock_guard<std::mutex> lock(mutex_);
return sessions_.size();
}
size_t SessionManager::cleanupExpiredSessions()
{
std::lock_guard<std::mutex> lock(mutex_);
size_t cleaned = 0;
auto now = std::chrono::steady_clock::now();
for (auto it = sessions_.begin(); it != sessions_.end();) {
auto elapsed = now - it->second.lastActivity;
if (elapsed > config_.sessionTimeout) {
it = sessions_.erase(it);
cleaned++;
} else {
++it;
}
}
if (cleaned > 0) {
ECHOION_LOG_INFO(
std::format("Cleaned up {} expired sessions", cleaned));
}
return cleaned;
}
bool SessionManager::isAtCapacity() const
{
std::lock_guard<std::mutex> lock(mutex_);
return sessions_.size() >= config_.maxSessions;
}
std::string SessionManager::generateToken()
{
// Generate random 32-byte token
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dis(0, 255);
std::stringstream ss;
for (int i = 0; i < 32; ++i) {
ss << std::hex << std::setw(2) << std::setfill('0') << dis(gen);
}
return ss.str();
}
} // namespace Echoion::Core
+754 -671
View File
File diff suppressed because it is too large. Load diff
+198 -174
View File
@@ -1,192 +1,216 @@
#include "LoggerInterface.hpp"
#include "echoion/core/SubscriptionManager.hpp"
#include "echoion/core/Logger.hpp"
namespace Echoion::Core {
namespace Echoion::Core
{
SubscriptionManager::SubscriptionManager() = default;
SubscriptionManager::SubscriptionManager() = default;
SubscriptionManager::~SubscriptionManager() {
shutdown();
}
SubscriptionManager::~SubscriptionManager() { shutdown(); }
Api::Result<void> SubscriptionManager::initialize(std::shared_ptr<Api::Database> database) {
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
return {};
}
database_ = std::move(database);
if (!database_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Database not available"));
}
// Load existing subscriptions from database
auto result = database_->getAllSubscribers();
if (!result) {
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}", result.error().message));
// Not fatal - start with empty subscriptions
} else {
for (const auto& subscriber : *result) {
subscribedUids_.insert(subscriber.uid);
}
}
initialized_ = true;
ECHOION_LOG_INFO(std::format("SubscriptionManager initialized ({} subscribers)",
subscribedUids_.size()));
return {};
}
Api::Result<void>
SubscriptionManager::initialize(std::shared_ptr<Api::Database> database)
{
std::lock_guard<std::mutex> lock(mutex_);
void SubscriptionManager::shutdown() {
std::lock_guard<std::mutex> lock(mutex_);
if (!initialized_) {
return;
}
initialized_ = false;
database_.reset();
subscribedUids_.clear();
ECHOION_LOG_INFO("SubscriptionManager shutdown");
}
if (initialized_) {
return {};
}
bool SubscriptionManager::subscribe(const std::string& uid, const std::string& nickname) {
std::lock_guard<std::mutex> lock(mutex_);
// Check if already subscribed (ensures uniqueness)
if (subscribedUids_.contains(uid)) {
// Update nickname even if already subscribed
if (database_) {
database_->addSubscriber(uid, nickname);
}
return false; // Already subscribed
}
// Add to database first
if (database_) {
auto result = database_->addSubscriber(uid, nickname);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to add subscriber {} to database: {}",
uid, result.error().message));
return false;
}
}
subscribedUids_.insert(uid);
ECHOION_LOG_INFO(std::format("Client {} ({}) subscribed", nickname, uid));
return true;
}
database_ = std::move(database);
if (!database_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Database not available"));
}
bool SubscriptionManager::unsubscribe(const std::string& uid) {
std::lock_guard<std::mutex> lock(mutex_);
bool removed = subscribedUids_.erase(uid) > 0;
if (removed) {
// Remove from database
if (database_) {
auto result = database_->removeSubscriber(uid);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to remove subscriber {} from database: {}",
uid, result.error().message));
}
}
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid));
}
return removed;
}
// Load existing subscriptions from database
auto result = database_->getAllSubscribers();
if (!result) {
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}",
result.error().message));
// Not fatal - start with empty subscriptions
} else {
for (const auto& subscriber : *result) {
subscribedUids_.insert(subscriber.uid);
}
}
bool SubscriptionManager::isSubscribed(const std::string& uid) const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedUids_.contains(uid);
}
initialized_ = true;
ECHOION_LOG_INFO(
std::format("SubscriptionManager initialized ({} subscribers)",
subscribedUids_.size()));
return {};
}
std::vector<std::string> SubscriptionManager::getSubscribedUids() const {
std::lock_guard<std::mutex> lock(mutex_);
return std::vector<std::string>(subscribedUids_.begin(), subscribedUids_.end());
}
void SubscriptionManager::shutdown()
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<SubscriptionManager::Subscriber> SubscriptionManager::getSubscribers() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<Subscriber> result;
if (!database_) {
return result;
}
auto dbSubscribers = database_->getAllSubscribers();
if (dbSubscribers) {
for (const auto& info : *dbSubscribers) {
if (subscribedUids_.contains(info.uid)) {
result.push_back({info.uid, info.nickname});
}
}
}
return result;
}
if (!initialized_) {
return;
}
std::optional<std::string> SubscriptionManager::getSubscriberNickname(const std::string& uid) const {
std::lock_guard<std::mutex> lock(mutex_);
if (!subscribedUids_.contains(uid) || !database_) {
return std::nullopt;
}
auto subscribers = database_->getAllSubscribers();
if (subscribers) {
for (const auto& info : *subscribers) {
if (info.uid == uid) {
return info.nickname;
}
}
}
return std::nullopt;
}
initialized_ = false;
database_.reset();
subscribedUids_.clear();
ECHOION_LOG_INFO("SubscriptionManager shutdown");
}
bool SubscriptionManager::updateNickname(const std::string& uid, const std::string& nickname) {
std::lock_guard<std::mutex> lock(mutex_);
if (!subscribedUids_.contains(uid)) {
return false;
}
if (database_) {
auto result = database_->addSubscriber(uid, nickname);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to update nickname for {}: {}",
uid, result.error().message));
return false;
}
}
return true;
}
bool SubscriptionManager::subscribe(const std::string& uid,
const std::string& nickname)
{
std::lock_guard<std::mutex> lock(mutex_);
bool SubscriptionManager::hasSubscribers() const {
std::lock_guard<std::mutex> lock(mutex_);
return !subscribedUids_.empty();
}
// Check if already subscribed (ensures uniqueness)
if (subscribedUids_.contains(uid)) {
// Update nickname even if already subscribed
if (database_) {
database_->addSubscriber(uid, nickname);
}
return false; // Already subscribed
}
size_t SubscriptionManager::getSubscriberCount() const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedUids_.size();
}
// Add to database first
if (database_) {
auto result = database_->addSubscriber(uid, nickname);
if (!result) {
ECHOION_LOG_ERROR(
std::format("Failed to add subscriber {} to database: {}",
uid, result.error().message));
return false;
}
}
bool SubscriptionManager::clearAll() {
std::lock_guard<std::mutex> lock(mutex_);
if (database_) {
auto result = database_->clearAllSubscribers();
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to clear all subscribers: {}",
result.error().message));
return false;
}
}
subscribedUids_.clear();
ECHOION_LOG_INFO("All subscriptions cleared");
return true;
}
subscribedUids_.insert(uid);
ECHOION_LOG_INFO(
std::format("Client {} ({}) subscribed", nickname, uid));
return true;
}
bool SubscriptionManager::unsubscribe(const std::string& uid)
{
std::lock_guard<std::mutex> lock(mutex_);
bool removed = subscribedUids_.erase(uid) > 0;
if (removed) {
// Remove from database
if (database_) {
auto result = database_->removeSubscriber(uid);
if (!result) {
ECHOION_LOG_ERROR(std::format(
"Failed to remove subscriber {} from database: {}", uid,
result.error().message));
}
}
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid));
}
return removed;
}
bool SubscriptionManager::isSubscribed(const std::string& uid) const
{
std::lock_guard<std::mutex> lock(mutex_);
return subscribedUids_.contains(uid);
}
std::vector<std::string> SubscriptionManager::getSubscribedUids() const
{
std::lock_guard<std::mutex> lock(mutex_);
return std::vector<std::string>(subscribedUids_.begin(),
subscribedUids_.end());
}
std::vector<SubscriptionManager::Subscriber>
SubscriptionManager::getSubscribers() const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<Subscriber> result;
if (!database_) {
return result;
}
auto dbSubscribers = database_->getAllSubscribers();
if (dbSubscribers) {
for (const auto& info : *dbSubscribers) {
if (subscribedUids_.contains(info.uid)) {
result.push_back({info.uid, info.nickname});
}
}
}
return result;
}
std::optional<std::string>
SubscriptionManager::getSubscriberNickname(const std::string& uid) const
{
std::lock_guard<std::mutex> lock(mutex_);
if (!subscribedUids_.contains(uid) || !database_) {
return std::nullopt;
}
auto subscribers = database_->getAllSubscribers();
if (subscribers) {
for (const auto& info : *subscribers) {
if (info.uid == uid) {
return info.nickname;
}
}
}
return std::nullopt;
}
bool SubscriptionManager::updateNickname(const std::string& uid,
const std::string& nickname)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!subscribedUids_.contains(uid)) {
return false;
}
if (database_) {
auto result = database_->addSubscriber(uid, nickname);
if (!result) {
ECHOION_LOG_ERROR(
std::format("Failed to update nickname for {}: {}", uid,
result.error().message));
return false;
}
}
return true;
}
bool SubscriptionManager::hasSubscribers() const
{
std::lock_guard<std::mutex> lock(mutex_);
return !subscribedUids_.empty();
}
size_t SubscriptionManager::getSubscriberCount() const
{
std::lock_guard<std::mutex> lock(mutex_);
return subscribedUids_.size();
}
bool SubscriptionManager::clearAll()
{
std::lock_guard<std::mutex> lock(mutex_);
if (database_) {
auto result = database_->clearAllSubscribers();
if (!result) {
ECHOION_LOG_ERROR(
std::format("Failed to clear all subscribers: {}",
result.error().message));
return false;
}
}
subscribedUids_.clear();
ECHOION_LOG_INFO("All subscriptions cleared");
return true;
}
} // namespace Echoion::Core
+148 -131
View File
@@ -1,144 +1,161 @@
#include "echoion/core/UrlShortener.hpp"
#include "echoion/core/Logger.hpp"
#include "echoion/core/UrlShortener.hpp"
#include <Void/Data/Json.hpp>
#include <format>
#include <glaze/glaze.hpp>
namespace Echoion::Core {
namespace Echoion::Core
{
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)) {
}
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient))
{
}
UrlShortener::~UrlShortener() = default;
UrlShortener::~UrlShortener() = default;
Api::Result<std::string> UrlShortener::shortenYouTubeUrl(std::string_view videoId) {
std::string originalUrl = std::format("https://www.youtube.com/watch?v={}", videoId);
return shortenUrl(originalUrl);
}
Api::Result<std::string>
UrlShortener::shortenYouTubeUrl(std::string_view videoId)
{
std::string originalUrl =
std::format("https://www.youtube.com/watch?v={}", videoId);
return shortenUrl(originalUrl);
}
Api::Result<std::string> UrlShortener::shortenUrl(std::string_view originalUrl) {
// Check cache first
{
std::lock_guard<std::mutex> lock(cacheMutex_);
auto it = cache_.find(std::string(originalUrl));
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
ECHOION_LOG_DEBUG(std::format("URL cache hit: {} -> {}",
originalUrl, it->second.shortenedUrl));
return it->second.shortenedUrl;
}
// Expired, remove from cache
cache_.erase(it);
}
}
if (!networkClient_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Network client not available"));
}
// faumaray.ru API endpoint for URL shortening
// POST /shorten with JSON body {"longUrl": "https://..."}
// Response: {"shortUrl": "https://faumaray.ru/xxxxx"}
std::string apiUrl = "https://faumaray.ru/shorten";
// Build JSON request body - API expects "longUrl" field
std::string jsonBody = std::format(R"({{"longUrl":"{}"}})", originalUrl);
std::vector<Api::HttpHeader> headers = {
{"Content-Type", "application/json"},
{"User-Agent", "EchoionBot/1.0"}
};
ECHOION_LOG_DEBUG(std::format("Shortening URL via faumaray.ru: {}", originalUrl));
auto response = networkClient_->post(apiUrl, jsonBody, headers);
if (!response) {
ECHOION_LOG_WARNING(std::format("URL shortening failed: {}",
response.error().message));
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"Failed to shorten URL"));
}
if (!response->isSuccess()) {
ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}",
response->statusCode));
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("Shortening service returned HTTP {}", response->statusCode)));
}
try {
// Parse response - expecting {"shortUrl": "https://faumaray.ru/xxxxx"}
glz::generic json;
if (glz::read_json(json, response->body)) {
ECHOION_LOG_WARNING("Failed to parse URL shortening response");
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Failed to parse shortening response"));
}
std::string shortenedUrl;
if (json.contains("shortUrl")) {
shortenedUrl = json["shortUrl"].get<std::string>();
} else {
ECHOION_LOG_WARNING("No shortUrl field in response");
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"No shortUrl in response"));
}
// Cache the result
{
std::lock_guard<std::mutex> lock(cacheMutex_);
cache_[std::string(originalUrl)] = {
.shortenedUrl = shortenedUrl,
.timestamp = std::chrono::system_clock::now()
};
}
ECHOION_LOG_DEBUG(std::format("URL shortened: {} -> {}", originalUrl, shortenedUrl));
return shortenedUrl;
} catch (const std::exception& e) {
ECHOION_LOG_WARNING(std::format("Exception parsing shortening response: {}",
e.what()));
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Exception during URL shortening"));
}
}
Api::Result<std::string>
UrlShortener::shortenUrl(std::string_view originalUrl)
{
// Check cache first
{
std::lock_guard<std::mutex> lock(cacheMutex_);
auto it = cache_.find(std::string(originalUrl));
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
ECHOION_LOG_DEBUG(std::format("URL cache hit: {} -> {}",
originalUrl,
it->second.shortenedUrl));
return it->second.shortenedUrl;
}
// Expired, remove from cache
cache_.erase(it);
}
}
std::optional<std::string> UrlShortener::getCachedUrl(std::string_view originalUrl) const {
std::lock_guard<std::mutex> lock(cacheMutex_);
auto it = cache_.find(std::string(originalUrl));
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
return it->second.shortenedUrl;
}
}
return std::nullopt;
}
if (!networkClient_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Network client not available"));
}
void UrlShortener::clearCache() {
std::lock_guard<std::mutex> lock(cacheMutex_);
cache_.clear();
}
// faumaray.ru API endpoint for URL shortening
// POST /shorten with JSON body {"longUrl": "https://..."}
// Response: {"shortUrl": "https://faumaray.ru/xxxxx"}
std::string apiUrl = "https://faumaray.ru/shorten";
void UrlShortener::setCacheTtl(std::chrono::hours ttl) {
cacheTtl_ = ttl;
}
// Build JSON request body - API expects "longUrl" field
std::string jsonBody =
std::format(R"({{"longUrl":"{}"}})", originalUrl);
void UrlShortener::cleanExpiredCache() {
std::lock_guard<std::mutex> lock(cacheMutex_);
auto now = std::chrono::system_clock::now();
for (auto it = cache_.begin(); it != cache_.end();) {
if (now - it->second.timestamp >= cacheTtl_) {
it = cache_.erase(it);
} else {
++it;
}
}
}
std::vector<Api::HttpHeader> headers = {
{"Content-Type", "application/json"},
{"User-Agent", "EchoionBot/1.0"}};
ECHOION_LOG_DEBUG(
std::format("Shortening URL via faumaray.ru: {}", originalUrl));
auto response = networkClient_->post(apiUrl, jsonBody, headers);
if (!response) {
ECHOION_LOG_WARNING(std::format("URL shortening failed: {}",
response.error().message));
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"Failed to shorten URL"));
}
if (!response->isSuccess()) {
ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}",
response->statusCode));
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
std::format("Shortening service returned HTTP {}",
response->statusCode)));
}
try {
// Parse response - expecting {"shortUrl":
// "https://faumaray.ru/xxxxx"}
auto parsed = Void::Json::parse(response->body);
if (!parsed) {
ECHOION_LOG_WARNING("Failed to parse URL shortening response");
return std::unexpected(
Api::Error(Api::ErrorCode::ParseError,
"Failed to parse shortening response"));
}
std::string shortenedUrl;
const Void::Json::Value* shortUrl = parsed->find("shortUrl");
if (shortUrl && shortUrl->is_string()) {
shortenedUrl = shortUrl->as_string();
} else {
ECHOION_LOG_WARNING("No shortUrl field in response");
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"No shortUrl in response"));
}
// Cache the result
{
std::lock_guard<std::mutex> lock(cacheMutex_);
cache_[std::string(originalUrl)] = {
.shortenedUrl = shortenedUrl,
.timestamp = std::chrono::system_clock::now()};
}
ECHOION_LOG_DEBUG(std::format("URL shortened: {} -> {}",
originalUrl, shortenedUrl));
return shortenedUrl;
} catch (const std::exception& e) {
ECHOION_LOG_WARNING(std::format(
"Exception parsing shortening response: {}", e.what()));
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError, "Exception during URL shortening"));
}
}
std::optional<std::string>
UrlShortener::getCachedUrl(std::string_view originalUrl) const
{
std::lock_guard<std::mutex> lock(cacheMutex_);
auto it = cache_.find(std::string(originalUrl));
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
return it->second.shortenedUrl;
}
}
return std::nullopt;
}
void UrlShortener::clearCache()
{
std::lock_guard<std::mutex> lock(cacheMutex_);
cache_.clear();
}
void UrlShortener::setCacheTtl(std::chrono::hours ttl) { cacheTtl_ = ttl; }
void UrlShortener::cleanExpiredCache()
{
std::lock_guard<std::mutex> lock(cacheMutex_);
auto now = std::chrono::system_clock::now();
for (auto it = cache_.begin(); it != cache_.end();) {
if (now - it->second.timestamp >= cacheTtl_) {
it = cache_.erase(it);
} else {
++it;
}
}
}
} // namespace Echoion::Core
+1449 -1346
View File
File diff suppressed because it is too large. Load diff
+620 -627
View File
File diff suppressed because it is too large. Load diff
+109
View File
@@ -0,0 +1,109 @@
#include "echoion/core/NetworkClient.hpp"
#include "echoion/core/commands/RpcInfoCommand.hpp"
#include <ConfigManager.hpp>
#include <format>
#include <future>
#include <regex>
namespace Echoion::Core
{
std::string getPublicIpAddress()
{
// Try to get public IP from external services
static std::string cachedIp;
static std::chrono::steady_clock::time_point lastFetch;
// Cache IP for 5 minutes to avoid excessive API calls
auto now = std::chrono::steady_clock::now();
if (!cachedIp.empty() &&
std::chrono::duration_cast<std::chrono::minutes>(now - lastFetch)
.count() < 5) {
return cachedIp;
}
// List of services to try
const std::vector<std::string> ipServices = {
"https://api.ipify.org", "https://checkip.amazonaws.com",
"https://icanhazip.com", "https://ifconfig.me/ip"};
// Create a temporary network client for IP lookup
auto networkClient = std::make_shared<NetworkClient>();
auto initResult = networkClient->initialize();
if (!initResult) {
return cachedIp.empty() ? "127.0.0.1" : cachedIp;
}
for (const auto& service : ipServices) {
try {
auto result = networkClient->get(service);
if (result && result->isSuccess()) {
// Extract IP from response body (trim whitespace)
std::string ip = result->body;
// Remove whitespace and newlines
ip.erase(std::remove_if(ip.begin(), ip.end(),
[](unsigned char c) {
return std::isspace(c);
}),
ip.end());
// Validate IP format (basic check)
std::regex ipRegex(
R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)");
if (std::regex_match(ip, ipRegex)) {
cachedIp = ip;
lastFetch = now;
return cachedIp;
}
}
} catch (...) {
// Try next service
continue;
}
}
// Return cached IP or localhost if all services failed
return cachedIp.empty() ? "127.0.0.1" : cachedIp;
}
void RpcInfoCommand::execute(const CommandContext& ctx)
{
// Get RPC configuration from global ConfigManager
const auto& networkConfig = ECHOION_NETWORK;
uint16_t rpcPort = networkConfig.rpcPort;
std::string rpcBindAddress = networkConfig.rpcBindAddress;
// Determine the public IP to show
std::string publicIp = getPublicIpAddress();
// If bind address is not localhost, use it
if (rpcBindAddress != "127.0.0.1" && rpcBindAddress != "localhost") {
publicIp = rpcBindAddress;
}
// Format message using plain text (compatible with TS3 BBCode and TS6
// Markdown)
std::string message = std::format(
"**RPC Server Information**\n\n"
"The RPC server allows remote control via WebSocket API.\n\n"
"**Connection Details:**\n"
"Address: {}:{}\n"
"Protocol: WebSocket (ws://)\n\n"
"**To connect:**\n"
"1. Subscribe to the bot with !subscribe\n"
"2. Connect to ws://{}:{}\n"
"3. Send auth request with your nickname: "
"{{\"nickname\":\"YourName\"}}\n"
"4. Check your TeamSpeak PM for the token\n"
"5. Authenticate with: {{\"token\":\"YOUR_TOKEN\"}}\n\n"
"**Available endpoints:**\n"
"- Playback control (play, pause, skip, volume)\n"
"- Queue management\n"
"- Track information\n"
"- Real-time event updates",
publicIp, rpcPort, publicIp, rpcPort);
ctx.reply(message);
}
} // namespace Echoion::Core
+73
View File
@@ -0,0 +1,73 @@
#include "echoion/core/state/StateMigration.hpp"
#include "echoion/core/state/StateSerializer.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <format>
namespace Echoion::Core
{
Api::Result<StateV1> StateMigration::migrate(uint32_t fromVersion,
const std::string& jsonData)
{
// Migration chain: fromVersion -> ... -> CURRENT_VERSION
// For now, only V0 -> V1 is implemented
// Future: V1 -> V2, V2 -> V3, etc.
if (fromVersion == 0) {
auto parsed = Void::Json::parse(jsonData);
if (!parsed) {
return std::unexpected(Api::Error{Api::ErrorCode::ParseError,
"Failed to parse V0 state"});
}
auto v0 = Void::Json::from_json<StateV0>(*parsed);
if (!v0) {
return std::unexpected(Api::Error{Api::ErrorCode::ParseError,
"Failed to parse V0 state"});
}
return fromV0(*v0);
}
// Add more migrations here as versions evolve
// if (fromVersion == 1) { return fromV1(...); }
return std::unexpected(Api::Error{
Api::ErrorCode::IncompatibleVersion,
std::format("No migration path from version {}", fromVersion)});
}
StateV1 StateMigration::fromV0(const StateV0& v0)
{
StateV1 v1;
// Migrate queue
for (const auto& trackId : v0.trackIds) {
StateV1::QueueEntryState entry;
entry.track.id = trackId;
entry.track.title = "Unknown";
entry.track.artist = "Unknown";
v1.queue.push_back(std::move(entry));
}
// Migrate playback state
if (!v1.queue.empty()) {
StateV1::PlaybackState playback;
playback.currentTrack = v1.queue[0].track;
playback.volume = v0.volume;
v1.playback = std::move(playback);
v1.hasPlayback = true;
}
v1.version = 1;
v1.savedAt = StateSerializer::getCurrentTimestampISO8601();
return v1;
}
bool StateMigration::canMigrate(uint32_t fromVersion)
{
return fromVersion >= StateSerializer::getMinimumSupportedVersion() &&
fromVersion < StateSerializer::getCurrentVersion();
}
} // namespace Echoion::Core
+144
View File
@@ -0,0 +1,144 @@
// #include "echoion/api/base/StateBlob.hpp"
#include "echoion/core/state/StateMigration.hpp"
#include "echoion/core/state/StateSerializer.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <format>
#include <iomanip>
#include <sstream>
namespace Echoion::Core
{
Api::StateBlob StateSerializer::serialize(const StateV1& state)
{
// Serialize to JSON using Void::Json reflection
std::string jsonStr =
Void::Json::serialize(Void::Json::to_json(state));
// Convert to binary blob
std::vector<uint8_t> data(jsonStr.begin(), jsonStr.end());
return Api::StateBlob{.data = std::move(data),
.version = CURRENT_VERSION,
.timestamp = getCurrentTimestampISO8601()};
}
Api::Result<StateV1>
StateSerializer::deserialize(const Api::StateBlob& blob)
{
if (blob.data.empty()) {
return std::unexpected(Api::Error{Api::ErrorCode::InvalidArgument,
"Empty state blob"});
}
// Convert blob to string
std::string jsonStr(blob.data.begin(), blob.data.end());
// Extract version
uint32_t dataVersion = extractVersion(jsonStr);
// Check if version is supported
if (!isVersionSupported(dataVersion)) {
if (dataVersion > CURRENT_VERSION) {
return std::unexpected(Api::Error{
Api::ErrorCode::IncompatibleVersion,
std::format("State version {} is from a newer Core. "
"Please update/restart to load this state.",
dataVersion)});
} else {
return std::unexpected(Api::Error{
Api::ErrorCode::IncompatibleVersion,
std::format("State version {} is too old. "
"Maximum supported age is {} versions.",
dataVersion,
Api::MAX_SUPPORTED_STATE_VERSION_AGE)});
}
}
// If current version, parse directly
if (dataVersion == CURRENT_VERSION) {
auto parsed = Void::Json::parse(jsonStr);
if (!parsed) {
return std::unexpected(Api::Error{
Api::ErrorCode::ParseError,
std::format("Failed to parse state ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message)});
}
auto state = Void::Json::from_json<StateV1>(*parsed);
if (!state) {
return std::unexpected(Api::Error{
Api::ErrorCode::ParseError,
std::format("Failed to decode state: field '{}': {}",
state.error().field, state.error().message)});
}
return *state;
}
// Otherwise, migrate
return StateMigration::migrate(dataVersion, jsonStr);
}
bool StateSerializer::isVersionSupported(uint32_t version)
{
if (version > CURRENT_VERSION) {
return false; // Future version
}
uint32_t minVersion = getMinimumSupportedVersion();
return version >= minVersion && version <= CURRENT_VERSION;
}
uint32_t StateSerializer::getMinimumSupportedVersion()
{
// Support 10 versions back, but not below 1
return (CURRENT_VERSION > Api::MAX_SUPPORTED_STATE_VERSION_AGE)
? CURRENT_VERSION - Api::MAX_SUPPORTED_STATE_VERSION_AGE
: 1;
}
uint32_t StateSerializer::getCurrentVersion() { return CURRENT_VERSION; }
uint32_t StateSerializer::extractVersion(const std::string& jsonStr)
{
// Quick extraction without full parse
// Look for "version": N pattern
size_t pos = jsonStr.find("\"version\"");
if (pos != std::string::npos) {
pos = jsonStr.find(':', pos);
if (pos != std::string::npos) {
// Skip whitespace
pos++;
while (pos < jsonStr.size() &&
std::isspace(static_cast<unsigned char>(jsonStr[pos]))) {
pos++;
}
// Parse number
if (pos < jsonStr.size() &&
std::isdigit(static_cast<unsigned char>(jsonStr[pos]))) {
try {
return static_cast<uint32_t>(
std::stoul(jsonStr.substr(pos)));
} catch (...) {
return 0;
}
}
}
}
// Default to 0 (unknown/legacy)
return 0;
}
std::string StateSerializer::getCurrentTimestampISO8601()
{
auto now = std::chrono::system_clock::now();
auto time_t_now = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::gmtime(&time_t_now), "%Y-%m-%dT%H:%M:%SZ");
return ss.str();
}
} // namespace Echoion::Core