Skip to content
Repos

DevPlaceApp

C++ 10.7 KB337 lines Opens in site

Directory Raw Download

#include "screens/conversation/ConversationModel.hpp"

#include <algorithm>
#include <chrono>

#include "core/Log.hpp"
#include "core/TextCount.hpp"
#include "core/Timer.hpp"
#include "core/Uuid.hpp"
#include "screens/components/AlertPresenter.hpp"
#include "spec/ModelLimits.hpp"
#include "spec/SocialSpec.hpp"
#include "store/AppState.hpp"

namespace dp {

namespace {
double steadySeconds() {
  return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
}  // namespace

ConversationModel::ConversationModel(User otherUser, DevPlaceApi& api, AlertSink alertSink, SocketFactory socketFactory, Clock clock)
    : otherUser_(std::move(otherUser)),
      api_(api),
      alertSink_(alertSink ? std::move(alertSink) : [](const AlertMessage& m) { AlertPresenter::show(m); }),
      socketFactory_(socketFactory ? std::move(socketFactory)
                                   : [this](const std::string& uid) { return api_.makeMessagesSocket(uid); }),
      clock_(clock ? std::move(clock) : Clock(steadySeconds)) {}

ConversationModel::~ConversationModel() {
  *alive_ = false;
  if (typingTimer_) typingTimer_->cancel();
  if (restTimer_) restTimer_->cancel();
  if (socket_) {
    socket_->setEventHandler(nullptr);
    socket_->disconnect();
  }
}

int ConversationModel::draftCount() const { return TextCount::utf16(draft_); }

bool ConversationModel::canSend() const {
  if (isSending_ || pendingSends_.size() >= spec::SocialLimits::kMaxPendingSends) return false;
  const int count = draftCount();
  return count >= minCharacterCount() && count <= static_cast<int>(spec::ModelLimits::kMaxDirectMessageLength);
}

void ConversationModel::setDraft(const std::string& text) {
  if (text == draft_) return;
  draft_ = text;
  userIsTyping();
}

void ConversationModel::sortMessages() {
  std::stable_sort(messages_.begin(), messages_.end(),
                   [](const Message& a, const Message& b) { return a.data.createdAt < b.data.createdAt; });
  if (messages_.size() > spec::SocialLimits::kMaxMessages) {
    messages_.erase(messages_.begin(), messages_.begin() + static_cast<std::ptrdiff_t>(messages_.size() - spec::SocialLimits::kMaxMessages));
  }
}

// ---- load / reload ----

void ConversationModel::load(std::function<void()> done) { fetch(false, std::move(done)); }

void ConversationModel::reload() {
  if (isReloading_) return;
  isReloading_ = true;
  fetch(true, nullptr);
}

void ConversationModel::fetch(bool reloading, std::function<void()> done) {
  ++pending_;
  api_.messages(std::optional<std::string>(otherUser_.id), [this, alive = alive_, reloading, done](Result<MessagesInbox> r) {
    if (!*alive) return;
    if (r.ok()) {
      inbox_ = r.value();
      seedMessages(*inbox_);
      AppState::instance().loadUnreadCounts(api_, [this, alive, reloading, done] {
        if (!*alive) return;
        --pending_;
        if (reloading) isReloading_ = false;
        if (done) done();
      });
    } else {
      --pending_;
      if (reloading) isReloading_ = false;
      alertSink_(AlertMessage::presentedError(r.error()));
      if (done) done();
    }
  });
}

void ConversationModel::seedMessages(const MessagesInbox& inbox) {
  std::vector<Message> merged = inbox.messages;
  for (const Message& m : messages_) {
    if (!pendingSends_.count(m.data.id)) continue;
    const bool present = std::any_of(merged.begin(), merged.end(), [&](const Message& x) { return x.data.id == m.data.id; });
    if (!present) merged.push_back(m);
  }
  messages_ = std::move(merged);
  sortMessages();
}

// ---- send ----

void ConversationModel::send(std::function<void(bool)> done) {
  if (!canSend()) {
    if (done) done(false);
    return;
  }
  const std::string content = draft_;
  const std::vector<UploadResponse> toSend = attachments_;
  const std::string clientId = Uuid::random();
  isSending_ = true;
  setDraft("");
  attachments_.clear();
  appendOptimistic(content, toSend, clientId);

  if (isSocketConnected_ && socket_) {
    pendingSends_[clientId] = PendingSend{content, toSend};
    std::vector<std::string> uids;
    for (const auto& a : toSend) uids.push_back(a.id);
    socket_->send(content, uids, clientId);
    isSending_ = false;
    if (done) done(true);
    return;
  }
  restFallback(content, toSend, clientId, std::move(done));
}

void ConversationModel::restFallback(const std::string& content, const std::vector<UploadResponse>& toSend,
                                     const std::string& clientId, std::function<void(bool)> done) {
  api_.sendMessage(otherUser_.id, content, toSend, [this, alive = alive_, content, toSend, clientId, done](Result<Unit> r) {
    if (!*alive) return;
    auto fail = [this, content, toSend, clientId, done](const Error& e) {
      removeOptimistic(clientId);
      isSending_ = false;
      setDraft(content);
      attachments_ = toSend;
      alertSink_(AlertMessage::presentedError(e));
      if (done) done(false);
    };
    if (!r.ok()) return fail(r.error());
    restTimer_ = Timer::after(spec::SocialTiming::kRestFallbackDelayMs, [this, alive, clientId, fail, done] {
      if (!*alive) return;
      api_.messages(std::optional<std::string>(otherUser_.id), [this, alive, clientId, fail, done](Result<MessagesInbox> m) {
        if (!*alive) return;
        if (!m.ok()) return fail(m.error());
        inbox_ = m.value();
        removeOptimistic(clientId);
        seedMessages(*inbox_);
        AppState::instance().loadUnreadCounts(api_, [this, alive, done] {
          if (!*alive) return;
          isSending_ = false;
          if (done) done(true);
        });
      });
    });
  });
}

void ConversationModel::appendOptimistic(const std::string& content, const std::vector<UploadResponse>& uploads,
                                         const std::string& clientId) {
  const auto& me = AppState::instance().currentUser();
  Message m;
  m.data.id = clientId;
  m.data.senderId = me ? me->id : "";
  m.data.receiverId = otherUser_.id;
  m.data.content = content;
  m.data.read = false;
  m.data.createdAt = DateCodec::now();
  m.sender = me ? *me : otherUser_;
  m.isMine = true;
  for (const UploadResponse& u : uploads) {
    Attachment a;
    a.id = u.id;
    a.filename = u.filename;
    a.url = u.url;
    a.size = u.size;
    a.isImage = u.isImage;
    a.isVideo = u.isVideo;
    a.mimeType = u.mimeType;
    a.createdAt = DateCodec::now();
    a.canModify = true;
    m.attachments.push_back(std::move(a));
  }
  messages_.push_back(std::move(m));
  sortMessages();
}

void ConversationModel::removeOptimistic(const std::string& clientId) {
  messages_.erase(std::remove_if(messages_.begin(), messages_.end(), [&](const Message& m) { return m.data.id == clientId; }),
                  messages_.end());
  pendingSends_.erase(clientId);
}

// ---- typing, attachments ----

void ConversationModel::userIsTyping() {
  if (!isSocketConnected_ || !socket_) return;
  const double now = clock_();
  if (lastTypingSentAt_ && now - *lastTypingSentAt_ < spec::SocialTiming::kTypingThrottleSeconds) return;
  lastTypingSentAt_ = now;
  socket_->sendTyping();
}

void ConversationModel::deleteUnsubmittedAttachments() {
  const std::vector<UploadResponse> unsubmitted = attachments_;
  attachments_.clear();
  for (const UploadResponse& a : unsubmitted) {
    const std::string uid = a.id;
    api_.deleteAttachment(uid, [uid](Result<Unit> r) {
      if (!r.ok()) Log::warn("Failed to delete unsubmitted message attachment " + uid + ": " + r.error().message);
    });
  }
}

// ---- realtime ----

void ConversationModel::startRealtime() {
  if (socket_) return;
  socket_ = socketFactory_(otherUser_.id);
  if (!socket_) return;
  socket_->setEventHandler([this, alive = alive_](const ChatSocketEvent& e) {
    if (*alive) handle(e);
  });
  socket_->connect();
}

void ConversationModel::stopRealtime() {
  isSocketConnected_ = false;
  isOtherTyping_ = false;
  if (typingTimer_) typingTimer_->cancel();
  typingTimer_.reset();
  if (socket_) {
    socket_->setEventHandler(nullptr);
    socket_->disconnect();
    socket_.reset();
  }
}

void ConversationModel::handle(const ChatSocketEvent& e) {
  using T = ChatSocketEvent::Type;
  switch (e.type) {
    case T::Ready:
      isSocketConnected_ = true;
      sendRead();
      break;
    case T::Message:
      if (e.message) upsertIncoming(*e.message);
      break;
    case T::Typing:
      if (e.fromUid == otherUser_.id) showOtherTyping();
      break;
    case T::Read:
      if (e.byUid == otherUser_.id) markMyMessagesRead();
      break;
    case T::Failed:
      handleSendFailure(e.clientId, e.text);
      break;
    case T::Disconnected:
      isSocketConnected_ = false;
      break;
  }
}

Message ConversationModel::makeMessage(const ChatSocketIncomingMessage& in) const {
  const auto& me = AppState::instance().currentUser();
  const bool mine = me && in.senderUid == me->id;
  Message m;
  m.data.id = in.uid;
  m.data.senderId = in.senderUid;
  m.data.receiverId = in.receiverUid;
  m.data.content = in.content;
  m.data.read = false;
  m.data.createdAt = in.createdAt;
  m.sender = mine ? *me : otherUser_;
  m.isMine = mine;
  m.attachments = in.attachments;
  return m;
}

void ConversationModel::upsertIncoming(const ChatSocketIncomingMessage& in) {
  if (in.senderUid != otherUser_.id && in.receiverUid != otherUser_.id) return;
  Message m = makeMessage(in);
  auto byId = [&](const std::string& id) {
    return std::find_if(messages_.begin(), messages_.end(), [&](const Message& x) { return x.data.id == id; });
  };
  bool replaced = false;
  if (in.clientId) {
    auto it = byId(*in.clientId);
    if (it != messages_.end()) {
      *it = m;
      pendingSends_.erase(*in.clientId);
      replaced = true;
    }
  }
  if (!replaced) {
    auto it = byId(m.data.id);
    if (it != messages_.end()) *it = m;
    else messages_.push_back(m);
  }
  sortMessages();
  if (!m.isMine) {
    sendRead();
    AppState::instance().loadUnreadCounts(api_);
  }
}

void ConversationModel::showOtherTyping() {
  isOtherTyping_ = true;
  if (typingTimer_) typingTimer_->cancel();
  typingTimer_ = Timer::after(spec::SocialTiming::kTypingClearMs, [this, alive = alive_] {
    if (*alive) isOtherTyping_ = false;
  });
}

void ConversationModel::markMyMessagesRead() {
  for (Message& m : messages_) {
    if (m.isMine && !m.data.read) m.data.read = true;
  }
}

void ConversationModel::handleSendFailure(const std::optional<std::string>& clientId, const std::string& text) {
  // Swift quirk kept (ViewModel.handleSendFailure): removeOptimistic() clears pendingSends[clientId] first, so the
  // "restore draft and attachments" branch that follows it can never run. Only the bubble goes and the alert shows.
  if (clientId) removeOptimistic(*clientId);
  alertSink_(AlertMessage::presentedError(text));
}

void ConversationModel::sendRead() {
  if (socket_) socket_->sendRead(otherUser_.id);
}

}  // namespace dp
36.6ms