summaryrefslogtreecommitdiff
path: root/src/commandHandler.cpp
diff options
context:
space:
mode:
authorlittleblack111 <littleblack11111@gmail.com>2025-03-20 22:38:46 +0800
committerlittleblack111 <littleblack11111@gmail.com>2025-03-22 15:02:46 +0800
commitf25eec7a0ba4a8a868eb87c76ec8b88f76f3a124 (patch)
treea3f7c6e07b895327beee62d5f83602b6b083df33 /src/commandHandler.cpp
parent45ca296a55332a4d79319f8a706f332aa8feb336 (diff)
feat: inputManager and commandHandler (#7)
server now have ability to send chat like any clients. can also run commands(registered in commands.cpp)
Diffstat (limited to 'src/commandHandler.cpp')
-rw-r--r--src/commandHandler.cpp58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/commandHandler.cpp b/src/commandHandler.cpp
new file mode 100644
index 0000000..12b51dc
--- /dev/null
+++ b/src/commandHandler.cpp
@@ -0,0 +1,58 @@
+#include "commandHandler.hpp"
+#include "log.hpp"
+#include <algorithm>
+
+CCommandHandler::CCommandHandler() {
+ log(LOG, "CommandHandler: initialized");
+}
+
+CCommandHandler::~CCommandHandler() {
+ log(SYS, "CommandHandler: bye");
+ m_vCommands.clear();
+}
+
+bool CCommandHandler::isCommand(const std::string &str) const {
+ return !str.empty() && str.front() == '/';
+};
+
+bool CCommandHandler::validCommand(const std::string &command) const {
+ return std::ranges::any_of(m_vCommands, [&command](const SCommand &cmd) {
+ return cmd.name == command;
+ });
+}
+
+bool CCommandHandler::registerCommand(const SCommand &command) {
+ if (command.name.empty() || !command.exe || !command.parser)
+ return false;
+
+ m_vCommands.push_back(command);
+ return true;
+}
+
+const CCommandHandler::SCommand *CCommandHandler::getCommand(const std::string &command) const {
+ auto it = std::ranges::find_if(m_vCommands, [&command](const SCommand &cmd) { return cmd.name == command; });
+
+ if (it != m_vCommands.end())
+ return &*it;
+
+ return nullptr;
+}
+
+CCommandHandler::SResult CCommandHandler::exeCommand(const SCommand &command, const std::string &args) const {
+ const auto [parsed, good] = command.parser(args);
+ if (!good)
+ try {
+ return {.result = std::any_cast<std::string>(parsed), .good = false};
+ } catch (const std::bad_any_cast &) {
+ return {.result = "", .good = false};
+ }
+
+ return command.exe(parsed);
+}
+
+CCommandHandler::SResult CCommandHandler::newCommand(const std::string &command, const std::string &args) const {
+ if (!validCommand(command))
+ return {.result = "Invalid command", .good = false};
+
+ return exeCommand(*getCommand(command), args);
+}