You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
93 lines
3.0 KiB
93 lines
3.0 KiB
#include "PityTransport.hh"
|
|
#include "PityUnit.hh"
|
|
#include <pEp/std_utils.hh>
|
|
#include "iostream"
|
|
#include <random>
|
|
#include <fstream>
|
|
#include <memory>
|
|
|
|
|
|
namespace pEp {
|
|
namespace PityTest11 {
|
|
bool PityTransport::debug_log_enabled = false;
|
|
|
|
PityTransport::PityTransport(std::string inboxDir, Endpoints& endpoints) :
|
|
_inboxDir{ inboxDir }, _endpoints{ endpoints }
|
|
{
|
|
}
|
|
|
|
void PityTransport::sendMsg(const std::string nodename, const std::string& msg) const
|
|
{
|
|
pEpLogClass("Address: " + nodename + " msg: " + msg);
|
|
|
|
// HACK TODO
|
|
std::string nodename_normalized = AbstractPityUnit::_normalizeName(nodename);
|
|
|
|
bool found = false;
|
|
std::string dir;
|
|
try {
|
|
dir = _endpoints.at(nodename_normalized);
|
|
} catch (std::out_of_range&) {
|
|
throw std::runtime_error("no such nodename: " + nodename_normalized);
|
|
}
|
|
Utils::dir_ensure(dir);
|
|
std::stringstream filename;
|
|
// collision detect
|
|
do {
|
|
filename << dir << Utils::random_string(97, 122, 16) << ".pitymsg";
|
|
} while (Utils::path_exists(filename.str()));
|
|
// create
|
|
std::ofstream msgfile = Utils::file_create(filename.str());
|
|
// write
|
|
msgfile << msg;
|
|
}
|
|
|
|
bool PityTransport::hasMsg() const
|
|
{
|
|
bool ret = false;
|
|
pEpLogClass("called");
|
|
Utils::dir_ensure(_inboxDir);
|
|
auto msg_filenames = Utils::dir_list_files(_inboxDir);
|
|
ret = msg_filenames.size() > 0;
|
|
return ret;
|
|
}
|
|
|
|
std::string PityTransport::pollMsg() const
|
|
{
|
|
pEpLogClass("called");
|
|
std::string ret;
|
|
Utils::dir_ensure(_inboxDir);
|
|
auto msg_filenames = Utils::dir_list_files(_inboxDir);
|
|
if (!msg_filenames.empty()) {
|
|
std::string msg_filename = msg_filenames.at(0);
|
|
std::string msg_path = _inboxDir + "/" + msg_filename;
|
|
pEpLogClass("Reading file: " + msg_filename);
|
|
ret = Utils::file_read(msg_path);
|
|
Utils::path_delete(msg_path);
|
|
} else {
|
|
throw std::underflow_error("inbox empty: " + _inboxDir);
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
|
|
std::string PityTransport::receiveMsg(int poll_interval) const
|
|
{
|
|
pEpLogClass("called");
|
|
std::string ret;
|
|
bool retry = false;
|
|
do {
|
|
try {
|
|
ret = pollMsg();
|
|
retry = false;
|
|
} catch (const std::underflow_error&) {
|
|
pEpLogClass("polling again in [ms]: " + std::to_string(poll_interval) + "...");
|
|
Utils::sleep_millis(poll_interval);
|
|
retry = true;
|
|
}
|
|
} while (retry);
|
|
return ret;
|
|
}
|
|
|
|
} // namespace PityTest11
|
|
} // namespace pEp
|
|
|