Migrate core infrastructure to VoidLibrary
This commit is contained in:
1 parent
53801f2b53
commit
2bdb63766d
65 files changed
+16109
-12011
No files matched your search
+478
-430
@@ -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
|
||||
Reference in new issue
Block a user