UsenetSearch/src/Database.cpp

73 lines
1.7 KiB
C++

#include <filesystem>
#include <fstream>
#include <string>
#include <vector>
#include "usenetsearch/StringUtils.h"
#include "usenetsearch/UsenetClient.h"
#include "usenetsearch/Database.h"
namespace usenetsearch {
Database::~Database()
{
if (m_newsGroupFileInput.is_open())
{
m_newsGroupFileInput.close();
}
if (m_newsGroupFileOutput.is_open())
{
m_newsGroupFileOutput.close();
}
}
void Database::Open(std::filesystem::path dbPath)
{
m_databasePath = dbPath;
if (!std::filesystem::exists(dbPath))
{
std::filesystem::create_directory(dbPath);
}
OpenNewsGroupFile();
}
void Database::OpenNewsGroupFile()
{
if (m_newsGroupFileInput.is_open() && m_newsGroupFileOutput.is_open())
{
return;
}
const std::filesystem::path newsGroupFilePath =
m_databasePath / "newsgroups.db";
if (!m_newsGroupFileInput.is_open())
{
m_newsGroupFileInput.open(newsGroupFilePath, std::ios::binary);
}
if (!m_newsGroupFileOutput.is_open())
{
m_newsGroupFileOutput.open(newsGroupFilePath, std::ios::binary);
}
}
void Database::UpdateNewsgroupList(const std::vector<NntpListEntry>& list)
{
OpenNewsGroupFile();
m_newsGroupFileOutput.write(
reinterpret_cast<const char*>(&m_databaseVersion),
sizeof(m_databaseVersion)
);
const size_t newsGroupCount = list.size();
m_newsGroupFileOutput.write(
reinterpret_cast<const char*>(&newsGroupCount),
sizeof(newsGroupCount)
);
for (const auto& entry: list)
{
m_newsGroupFileOutput << entry;
}
m_newsGroupFileOutput.flush();
}
} // namespace usenetsearch