Queue.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "../include/Queue.h"
  2. #include "../include/Notifications.h"
  3. #include <algorithm>
  4. namespace Queue {
  5. std::deque<std::string> queue;
  6. std::mutex mtx;
  7. ChannelControls *channel;
  8. } // namespace Queue
  9. bool Queue::push(const std::string &file) {
  10. // Don't queue if no channel is available
  11. if (channel == nullptr) {
  12. return false;
  13. }
  14. mtx.lock();
  15. queue.push_back(file);
  16. mtx.unlock();
  17. Notifications::newNotification("File \"" + file + "\" queued.");
  18. if (curTransfer().compare("") == 0) {
  19. schedule();
  20. }
  21. return true;
  22. }
  23. bool Queue::remove(const std::string &file) {
  24. if (curTransfer().compare(file) == 0) {
  25. // Reset channel and remove from queue
  26. channel->reset();
  27. Notifications::newNotification("Transfer of file \"" + file + "\" was aborted.");
  28. return true;
  29. } else {
  30. mtx.lock();
  31. auto it = std::find(queue.begin(), queue.end(), file);
  32. if (it == queue.end()) {
  33. return false;
  34. }
  35. queue.erase(it);
  36. mtx.unlock();
  37. return true;
  38. }
  39. }
  40. void Queue::schedule() {
  41. if (!queue.empty()) {
  42. mtx.lock();
  43. std::string file = queue.front();
  44. queue.pop_front();
  45. // success is false if file could not be sent or found
  46. bool success = channel->sendFile(file);
  47. mtx.unlock();
  48. if (!success) {
  49. Notifications::newNotification("File \"" + file + "\" could not be sent.");
  50. schedule();
  51. }
  52. // don't wait until transer finished because schedule must be called again
  53. } else {
  54. mtx.lock();
  55. mtx.unlock();
  56. }
  57. }
  58. std::string Queue::curTransfer() {
  59. if (channel == nullptr || !channel->isTransferRunning()) {
  60. return "";
  61. }
  62. return channel->getFileName();
  63. }