UsenetSearch/src/Configuration.cpp

123 lines
3.0 KiB
C++

#include <filesystem>
#include <fstream>
#include <string>
#include "usenetsearch/StringUtils.h"
#include "usenetsearch/Configuration.h"
namespace usenetsearch {
std::filesystem::path Configuration::DatabasePath() const
{
return m_databasePath;
}
std::string Configuration::NNTPServerHost() const
{
return m_nntpServerHost;
}
std::string Configuration::NNTPServerPassword() const
{
return m_nntpServerPassword;
}
int Configuration::NNTPServerPort() const
{
return m_nntpServerPort;
}
bool Configuration::NNTPServerSSL() const
{
return m_nntpServerSSL;
}
std::string Configuration::NNTPServerUser() const
{
return m_nntpServerUser;
}
void Configuration::Open(const std::string& filename)
{
std::string line;
std::ifstream fin(filename.c_str());
if (!fin.is_open())
{
throw ConfigurationException(EINVAL,
"Could not open configuration file: " + filename
);
}
int line_nr = 0;
while(std::getline(fin,line))
{
line_nr++;
line = StringTrim(line);
// Immediately skip blank lines.
if (line == "") continue;
// Skip comments.
if (StringStartsWith("#",line)==true) continue;
// Split line in key-value pair.
const auto kvp = StringSplit(line, std::string{":"}, 2);
if (kvp.size() != 2)
{
fin.close();
throw ConfigurationException(EINVAL,
std::string("Invalid configuration in ")
+ filename + std::string(" line ")
+ std::to_string(line_nr)
);
}
const std::string key = StringToLower(kvp[0]);
const std::string value = StringTrim(kvp[1]);
if (key == "database_path")
{
m_databasePath = value;
}
else if (key == "nntp_server_host")
{
m_nntpServerHost = value;
}
else if (key == "nntp_server_pass")
{
m_nntpServerPassword = value;
}
else if (key == "nntp_server_port")
{
m_nntpServerPort = atoi(value.c_str());
}
else if (key == "nntp_server_use_ssl")
{
try
{
m_nntpServerSSL = StringToBoolean(value);
}
catch (const StringException& e)
{
fin.close();
throw ConfigurationException(EINVAL,
std::string("Invalid configuration in ")
+ filename + std::string(" line ")
+ std::to_string(line_nr) + " - " + e.what()
);
}
}
else if (key == "nntp_server_user")
{
m_nntpServerUser = value;
}
else
{
fin.close();
throw ConfigurationException(EINVAL,
std::string("Invalid configuration in ")
+ filename + std::string(" line ")
+ std::to_string(line_nr)
);
}
}
fin.close();
}
} // namespace usenetsearch