Files
faumaray 39aff68d8d Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-15 19:49:57 +03:00

238 lines
7.7 KiB
C++

#pragma once
#include "commands/Command.hpp"
#include <ConfigTypes.hpp>
#include <PluginTypes.hpp>
#include <Types.hpp>
#include <Void/Async/ThreadPool.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <future>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
namespace Echoion::Core
{
class MusicManager;
// Function to check if client has permission (set by Core)
using PermissionCheckFunc =
std::function<bool(uint64_t clientId, CommandCategory category)>;
/**
* @brief Manages command registration and dispatch.
*
* Usage:
* CommandManager mgr;
* mgr.registerCommand<PlayCommand>("play");
* mgr.dispatch(clientId, "play song name", musicManager, replyFunc);
*/
class CommandManager
{
public:
CommandManager();
~CommandManager();
// Shutdown the command manager (stops thread pool)
void shutdown();
// Provide the service registry that command contexts resolve
// shared services from (non-owning; must outlive this manager).
void setServices(const Void::Service::ServiceRegistry* services)
{
services_ = services;
}
// Disable copy
CommandManager(const CommandManager&) = delete;
CommandManager& operator=(const CommandManager&) = delete;
// Enable move
CommandManager(CommandManager&&) = default;
CommandManager& operator=(CommandManager&&) = default;
/**
* @brief Registers a command class.
* @tparam T The command class (must inherit Command).
* @param primaryName The primary name/trigger (e.g., "play").
*/
template <typename T>
void registerCommand(const std::string& primaryName)
{
auto cmd = std::make_shared<T>();
std::lock_guard<std::mutex> lock(mutex_);
// Register primary name
commands_[primaryName] = cmd;
uniqueCommands_.push_back({primaryName, cmd});
// Register aliases automatically from the class itself
for (auto alias : cmd->getAliases()) {
commands_[std::string(alias)] = cmd;
}
}
/**
* @brief Dispatches a command message to the appropriate handler
* (ASYNC). Commands are executed in a thread pool, allowing
* multiple users to use the bot simultaneously without blocking.
* @param clientId The client ID who invoked the command.
* @param message The full message (including prefix, e.g., "!play
* song").
* @param musicManager Weak pointer to the MusicManager.
* @param replyFunc Function to call to send a reply.
* @param invokerName Name of the invoking user.
* @return true if a command was found and queued for execution,
* false otherwise.
*/
[[nodiscard]] bool
dispatch(uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager> musicManager,
std::function<void(std::string_view)> replyFunc,
std::string_view invokerName = "");
/**
* @brief Executes a command synchronously (for internal use).
* Prefer using dispatch() for normal command handling.
*/
[[nodiscard]] bool
dispatchSync(uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager> musicManager,
std::function<void(std::string_view)> replyFunc,
std::string_view invokerName = "");
[[nodiscard]] bool hasCommand(std::string_view name) const;
[[nodiscard]] std::optional<CommandPtr>
getCommand(std::string_view name) const;
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
getAllCommands() const;
[[nodiscard]] bool registerExternalCommand(
std::string owner, std::string primaryName, CommandPtr command);
void unregisterExternalCommands(std::string_view owner);
// Get commands visible to a specific client (for help)
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
getVisibleCommands(uint64_t clientId) const;
// Check if client can execute a command
[[nodiscard]] bool canExecuteCommand(uint64_t clientId,
const CommandPtr& cmd) const;
void setPrefix(std::string_view prefix);
[[nodiscard]] std::string_view getPrefix() const { return prefix_; }
// Set permission check function
void setPermissionCheckFunc(PermissionCheckFunc func);
// Set server config for permission checks
void setServerConfig(const Api::AppConfig& config);
private:
struct CommandEntry {
std::string primaryName;
CommandPtr instance;
};
void registerBuiltinCommands();
// Internal Help Command (defined in .cpp to access registry)
class HelpCommand;
void registerHelpCommand();
// Internal page-navigator command (!page/!next/!prev), defined in
// the .cpp so it can reach the paged-reply cache below.
class PageNavCommand;
void registerPageCommands();
// Resolve the language a client should be answered in: their stored
// per-user preference (kv_store "lang:<uid>") if any, else the
// configured bot default, else English.
[[nodiscard]] I18n::Language resolveLanguage(
uint64_t clientId,
const std::weak_ptr<MusicManager>& musicManager) const;
// --- Oversized-reply pagination -------------------------------
// Long replies (from any command except help / the navigator) are
// kept to a single message: page 1 is sent with a footer and the
// remaining pages are cached here for !page/!next/!prev.
struct PagedReply {
std::vector<std::string> pages;
std::size_t current = 0;
std::chrono::steady_clock::time_point ts{};
};
mutable std::mutex pagedMutex_;
std::unordered_map<uint64_t, PagedReply> pagedReplies_;
static constexpr std::size_t kPageLimitBytes = 700;
static constexpr std::chrono::minutes kPageTtl{10};
// Split `text` into pages, cache pages 2..N for `clientId`, and
// return page 1 (with a footer when there is more than one page).
// Replies that already fit one message pass through unchanged.
std::string paginateReply(uint64_t clientId, std::string text,
I18n::Language lang);
// Re-render a cached page for `clientId`. When `absolute` is set
// the current page jumps to it (1-based, clamped); otherwise it
// moves by `delta`. Returns std::nullopt when nothing is cached /
// expired.
std::optional<std::string>
renderCachedPage(uint64_t clientId,
std::optional<long> absolute, int delta,
I18n::Language lang);
std::string prefix_ = "!";
// Non-owning service registry threaded into each CommandContext
// so commands can resolve shared services by interface.
const Void::Service::ServiceRegistry* services_ = nullptr;
// Map for fast lookup: "play" -> PlayCommand
std::map<std::string, CommandPtr, std::less<>> commands_;
// List for generating help: {"play", PlayCommand}
std::vector<CommandEntry> uniqueCommands_;
std::map<std::string, std::vector<CommandPtr>, std::less<>>
externalCommands_;
mutable std::mutex mutex_;
// Permission checking
PermissionCheckFunc permissionCheck_;
std::optional<Api::AppConfig> serverConfig_;
// Async command execution
struct CommandTask {
uint64_t clientId;
std::string message;
std::weak_ptr<MusicManager> musicManager;
std::function<void(std::string_view)> replyFunc;
std::string invokerName;
};
void startThreadPool();
void executeCommandAsync(CommandTask task);
// Void worker pool backing async command execution (drains
// in-flight commands on shutdown via ~ThreadPool).
std::unique_ptr<Void::Concurrency::ThreadPool> pool_;
std::atomic<bool> shutdown_{false};
static constexpr size_t THREAD_POOL_SIZE =
4; // Handle up to 4 concurrent commands
}; // namespace Echoion::Core
} // namespace Echoion::Core