jay/component/router.cpp

58 lines
1.5 KiB
C++

// SPDX-FileCopyrightText: 2024 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "router.h"
#include "module/module.h"
Router::Router():
actors(),
defaultGroup("Stranger")
{}
void Router::registerModule(const std::string& key, const std::shared_ptr<Module::Module>& module) {
modules[key] = module;
}
void Router::registerActor(const std::string& key, const std::string& group) {
if (key == "default") {
defaultGroup = group;
return;
}
Actors::iterator act = actors.find(key);
if (act == actors.end())
actors.emplace(key, std::make_shared<Actor>(key, group));
else
act->second->setGroup(group);
}
void Router::routeMessage(const std::string& sender, const std::string& body) {
Actors::iterator aItr = actors.find(sender);
if (aItr == actors.end())
aItr = actors.emplace(sender, std::make_shared<Actor>(sender, defaultGroup)).first;
std::vector<std::string> args = Module::Module::split(body);
Modules::iterator mItr = modules.find(args[0]);
if (mItr == modules.end())
return;
std::shared_ptr<Module::Module> module = mItr->second.lock();
if (!module)
return;
args.erase(args.begin());
module->message(aItr->second, args);
}
std::map<std::string, std::string> Router::getActors() const {
std::map<std::string, std::string> result;
for (const std::pair<const std::string, std::shared_ptr<Actor>>& pair : actors)
result.emplace(pair.first, pair.second->getGroup());
return result;
}