jay/jay.cpp

91 lines
2.3 KiB
C++

// SPDX-FileCopyrightText: 2024 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "jay.h"
#include "module/actor.h"
static const std::map<std::string, std::function<std::shared_ptr<Module::Module>(const std::shared_ptr<gloox::Client>)>> moduleNames = {
{"actor", [](const std::shared_ptr<gloox::Client> client) { return std::make_shared<Module::Actor>(client); }}
};
Jay::Jay(const std::string& configPath):
runMutex(),
config(std::make_shared<Config>(configPath)),
router(std::make_unique<Router>()),
client(),
messageHandler(),
connectionHandler(),
modules(),
loggers()
{}
Jay::~Jay() {}
bool Jay::isConfigValid() const {
return config->isValid();
}
void Jay::run() {
std::lock_guard lock(runMutex);
initialize();
client->connect(true);
}
void Jay::initialize() {
createClient();
if (!messageHandler)
messageHandler = std::make_unique<Message>(
config,
client,
std::bind(&Router::routeMessage, router.get(), std::placeholders::_1, std::placeholders::_2)
);
if (!connectionHandler)
connectionHandler = std::make_unique<Connection>(config, client);
createModules();
createActors();
}
void Jay::createClient() {
if (client)
return;
client = std::make_shared<gloox::Client>(config->getFullJID(), config->getPassword());
addLogger(config->getLogLevel());
gloox::Disco* disco = client->disco();
disco->setVersion("Jay", "0.0.1");
disco->setIdentity("client", "bot");
client->setTls(config->getTLSPolicy());
client->setSASLMechanisms(gloox::SaslMechAll);
client->setStreamManagement(true, true);
}
void Jay::createActors() {
for (const std::pair<const std::string, std::string>& pair : config->getOwners())
router->registerActor(pair.first, pair.second);
}
void Jay::createModules() {
for (const auto& pair : moduleNames) {
Config::Module conf = config->getModuleConfig(pair.first);
if (!conf.enabled)
continue;
modules.emplace_back(pair.second(client));
router->registerModule(pair.first, modules.back());
}
}
void Jay::addLogger(gloox::LogLevel level) {
loggers.emplace_back(std::make_unique<Logger>(client->logInstance(), level));
}