#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& MessagesModel::conversations() const { static const std::vector 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 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