transfer_receiver.cpp 1.54 KB
Newer Older
1
#include <logging/logging.hpp>
louiz’'s avatar
louiz’ committed
2
#include <network/transfer_receiver.hpp>
3 4
#include <network/message_handler.hpp>
#include <network/tls_socket.hpp>
louiz’'s avatar
louiz’ committed
5

6 7
using namespace std::string_literals;

8
static const boost::filesystem::path FILES_TO_RECEIVE_DIRECTORY("./receive/");
9

10
TransferReceiver::TransferReceiver(MessageHandler<TLSSocket>* client,
11 12
                                   const std::string& sid,
                                   const std::string& filename,
13 14
                                   int length,
                                   std::function<void(const TransferReceiver*)>&& end_callback):
louiz’'s avatar
louiz’ committed
15 16
  client(client),
  id(sid),
17
  filename(FILES_TO_RECEIVE_DIRECTORY / filename),
louiz’'s avatar
louiz’ committed
18
  length(length),
19 20
  received_length(0),
  end_callback(end_callback)
louiz’'s avatar
louiz’ committed
21
{
22 23
  this->client->install_callback("TRANSFER_"s + sid, std::bind(&TransferReceiver::get_next_chunk, this, std::placeholders::_1));
  this->file.open(this->filename, std::ofstream::binary);
louiz’'s avatar
louiz’ committed
24 25 26 27 28 29 30 31
}

TransferReceiver::~TransferReceiver()
{
  log_debug("Deleting transfer of " << this->filename << ": " << this->id);
  this->file.close();
}

32
void TransferReceiver::get_next_chunk(Message* received_message)
louiz’'s avatar
louiz’ committed
33 34 35 36
{
  if (!this->file.good())
    {
      log_warning("Could not write data to file " << this->filename << ". Stopping transfer");
37
      this->stop();
louiz’'s avatar
louiz’ committed
38 39
      return ;
    }
40
  if (received_message->body_size == 0)
41
    this->stop();
louiz’'s avatar
louiz’ committed
42
  else
43
    this->file.write(received_message->body, received_message->body_size);
44
}
louiz’'s avatar
louiz’ committed
45

46 47
void TransferReceiver::stop()
{
48
  this->client->remove_callback("TRANSFER_"s + this->id);
49
  this->end_callback(this);
louiz’'s avatar
louiz’ committed
50
}