Notifications.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include "../include/Notifications.h"
  2. #include <ctime>
  3. namespace Notifications {
  4. std::vector<std::pair<long int, std::string>> messages;
  5. std::map<std::string, long int> userTimeStamps;
  6. }; // namespace Notifications
  7. void Notifications::newNotification(const std::string &message) {
  8. long int timestamp = static_cast<long int>(time(0));
  9. messages.push_back(make_pair(timestamp, message));
  10. }
  11. std::vector<std::string> Notifications::getMessages(const std::string &user) {
  12. std::vector<std::string> ret;
  13. // first clean up
  14. long int latest = static_cast<long int>(time(0)) - 604800;
  15. for (int i = 0; i < messages.size(); i++) {
  16. if (messages.at(i).first < latest) {
  17. messages.erase(messages.begin() + i);
  18. }
  19. }
  20. auto it = userTimeStamps.find(user);
  21. if (it == userTimeStamps.end()) {
  22. // case user has no timestamp yet
  23. for (int i = 0; i < messages.size(); i++) {
  24. ret.push_back(messages.at(i).second);
  25. }
  26. userTimeStamps.insert(std::pair<std::string, long int>(user, static_cast<long int>(time(0))));
  27. } else {
  28. long int userTimeStamp = it->second;
  29. for (int i = 0; i < messages.size(); i++) {
  30. if (userTimeStamp <= messages.at(i).first) {
  31. ret.push_back(messages.at(i).second);
  32. }
  33. }
  34. // update user timestamp
  35. it->second = static_cast<long int>(time(0));
  36. }
  37. return ret;
  38. }