Skip to content
Repos

DevPlaceApp

C++ 1.5 KB57 lines Opens in site

Directory Raw Download

#include "screens/messages/MessagesModel.hpp"

#include "screens/components/AlertPresenter.hpp"
#include "spec/SocialSpec.hpp"
#include "store/AppState.hpp"

namespace dp {

MessagesModel::MessagesModel(DevPlaceApi& api, AlertSink alertSink)
    : api_(api), alertSink_(alertSink ? std::move(alertSink) : [](const AlertMessage& m) { AlertPresenter::show(m); }) {}

const std::vector<Conversation>& MessagesModel::conversations() const {
  static const std::vector<Conversation> kEmpty;
  return inbox_ ? inbox_->conversations : kEmpty;
}

void MessagesModel::load() {
  if (!AppState::instance().isLoggedIn()) {
    inbox_.reset();
    return;
  }
  fetch(false);
}

void MessagesModel::reload() {
  if (!AppState::instance().isLoggedIn()) {
    inbox_.reset();
    return;
  }
  if (isReloading_) return;
  isReloading_ = true;
  fetch(true);
}

void MessagesModel::fetch(bool reloading) {
  ++pending_;
  api_.messages([this, alive = alive_, reloading](Result<MessagesInbox> r) {
    if (!*alive) return;
    if (r.ok()) {
      inbox_ = r.value();
      if (inbox_->conversations.size() > spec::SocialLimits::kMaxConversations) {
        inbox_->conversations.resize(spec::SocialLimits::kMaxConversations);
      }
      AppState::instance().loadUnreadCounts(api_, [this, alive, reloading] {
        if (!*alive) return;
        --pending_;
        if (reloading) isReloading_ = false;
      });
    } else {
      --pending_;
      if (reloading) isReloading_ = false;
      alertSink_(AlertMessage::presentedError(r.error()));
    }
  });
}

}  // namespace dp
36.8ms