Had to rewrite this entire bitch.

This commit is contained in:
Nicolás Ortega Froysa
2018-09-01 19:40:04 +02:00
parent b53556599f
commit 45c1879880
6 changed files with 55 additions and 233 deletions

@ -18,96 +18,33 @@
#include "neocomm/node.hpp"
#include <iostream>
#include <fstream>
#include <stdexcept>
using namespace neocomm;
neocomm::node::node(unsigned short port) {
#ifdef WOE32
gnutls_global_init();
#endif
try {
dht_node.run(port,
dht::crypto::generateIdentity(), true);
}
catch(const std::exception &e)
{
// rethrow exception
throw e;
}
node::node(unsigned short port) {
// TODO: see about preserving an identity
network.run(port, dht::crypto::generateIdentity(), true);
}
neocomm::node::node(const std::string &node_file,
unsigned short port) {
#ifdef WOE32
gnutls_global_init();
#endif
try {
dht_node.run(port,
dht::crypto::generateIdentity(), true);
}
catch(const std::exception &e)
{
// rethrow exception
throw e;
}
import_nodes(node_file);
node::~node() {
network.join();
}
neocomm::node::~node() {
dht_node.join();
#ifdef WOE32
gnutls_global_deinit();
#endif
void node::join_channel(const std::string &name) {
if(get_channel(name))
return;
channels[name].key = dht::InfoHash::get(name);
channels[name].token = network.listen<std::string>(
channels[name].key,
[&](std::string &&msg) {
channels[name].messages.push_back(msg);
return true;
});
}
void neocomm::node::connect(const std::string &address,
unsigned short port) {
if(not dht_node.isRunning())
throw std::runtime_error("Node is not yet running.");
dht_node.bootstrap(address, std::to_string(port));
}
void neocomm::node::import_nodes(
const std::string &node_file) {
if(not dht_node.isRunning())
throw std::runtime_error("Node is not yet running.");
msgpack::unpacker upak;
{
std::ifstream import_file(node_file, std::ios::binary
bitor std::ios::ate);
if(not import_file.is_open())
{
throw std::runtime_error("Failed to open file " +
node_file);
}
auto file_size = import_file.tellg();
import_file.seekg(0, std::ios::beg);
upak.reserve_buffer(file_size);
import_file.read(upak.buffer(), file_size);
}
msgpack::object_handle obj_handler;
while(upak.next(obj_handler))
{
auto imported_nodes =
obj_handler.get().as<
std::vector<dht::NodeExport>>();
dht_node.bootstrap(imported_nodes);
}
}
void neocomm::node::export_nodes(
const std::string &node_file) {
if(not dht_node.isRunning())
throw std::runtime_error("Node is not yet running.");
std::ofstream export_file(node_file, std::ios::binary);
if(not export_file.is_open())
{
throw std::runtime_error("Failed to open file " +
node_file);
}
msgpack::pack(export_file, dht_node.exportNodes());
void node::leave_channel(const std::string &name) {
if(!get_channel(name))
return;
network.cancelListen(channels[name].key,
channels[name].token.get());
channels.erase(name);
}