node.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright © 2017 Simon Désaulniers
  3. * Author: Simon Désaulniers <sim.desaulniers@gmail.com>
  4. * Milisarge <milisarge@gmail.com>
  5. *
  6. * Bu program özgür yazılımdır:
  7. * Özgür Yazılım Vakfı(Free Software Foundation) tarafından yayımlanan
  8. * GNU Genel Kamu Lisansı’nın sürüm 3 veya
  9. * isteğinize bağlı olarak daha sonraki sürümlerinin hükümleri altında
  10. * yeniden dağıtabilir ve/veya değiştirebilirsiniz.
  11. * Bu program, yararlı olması umuduyla dağıtılmış olup, programın BİR TEMİNATI YOKTUR;
  12. * TİCARETİNİN YAPILABİLİRLİĞİNE VE ÖZEL BİR AMAÇ İÇİN UYGUNLUĞUNA dair bir teminat da vermez.
  13. * Ayrıntılar için GNU Genel Kamu Lisansı’na göz atınız.
  14. * Bu programla birlikte GNU Genel Kamu Lisansı’nın bir kopyasını elde etmiş olmanız gerekir.
  15. * Eğer elinize ulaşmadıysa <http://www.gnu.org/licenses/> adresine bakınız.
  16. */
  17. #include <algorithm>
  18. #include <random>
  19. #include <future>
  20. #include <opendht.h>
  21. #include "node.h"
  22. namespace Milis {
  23. bool Node::put(const std::string& code, dht::Blob&& blob, dht::DoneCallbackSimple&& cb) {
  24. auto v = std::make_shared<dht::Value>(std::forward<dht::Blob>(blob));
  25. auto hash = dht::InfoHash::get(code);
  26. if (cb) {
  27. node_.put(hash, v, cb);
  28. return true;
  29. } else {
  30. std::mutex mtx;
  31. std::condition_variable cv;
  32. std::unique_lock<std::mutex> lk(mtx);
  33. bool done, success_ {false};
  34. node_.put(hash, v, [&](bool success) {
  35. if (not success)
  36. std::cerr << OPERATION_FAILURE_MSG << std::endl;
  37. else
  38. success_ = true;
  39. {
  40. std::unique_lock<std::mutex> lk(mtx);
  41. done = true;
  42. }
  43. cv.notify_all();
  44. });
  45. cv.wait(lk, [&](){ return done; });
  46. return success_;
  47. }
  48. }
  49. void Node::get(const std::string& code, PastedCallback&& pcb) {
  50. auto blobs = std::make_shared<std::vector<dht::Blob>>();
  51. node_.get(dht::InfoHash::get(code),
  52. [blobs](std::shared_ptr<dht::Value> value) {
  53. blobs->emplace_back(value->data);
  54. return true;
  55. },
  56. [pcb,blobs](bool success) {
  57. if (not success)
  58. std::cerr << OPERATION_FAILURE_MSG << std::endl;
  59. else if (pcb)
  60. pcb(*blobs);
  61. });
  62. }
  63. std::vector<dht::Blob> Node::get(const std::string& code) {
  64. auto values = node_.get(dht::InfoHash::get(code)).get();
  65. std::vector<dht::Blob> blobs (values.size());
  66. std::transform(values.begin(), values.end(), blobs.begin(), [] (const decltype(values)::value_type& value) {
  67. return value->data;
  68. });
  69. return blobs;
  70. }
  71. }