Class: InstagramConnect::Conversation

Inherits:
ApplicationRecord show all
Defined in:
app/models/instagram_connect/conversation.rb

Overview

One DM thread — a connected account talking to one Instagram user (igsid). Threads are shared across the host's operators; ownership lives on the account, not per-operator.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.locate(account:, igsid:) ⇒ Object

Race-safe find-or-create on the unique [account_id, igsid] pair.



18
19
20
21
22
# File 'app/models/instagram_connect/conversation.rb', line 18

def self.locate(account:, igsid:)
  find_or_create_by!(account_id: .id, igsid: igsid)
rescue ActiveRecord::RecordNotUnique
  find_by!(account_id: .id, igsid: igsid)
end

Instance Method Details

#register_message(message) ⇒ Object

Denormalizes the thread summary + unread count atomically (SQL-side) so concurrent inbound writes can't lose an unread increment.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/models/instagram_connect/conversation.rb', line 26

def register_message(message)
  stamp = message.created_at || Time.current
  if message.inbound?
    self.class.where(id: id).update_all([
      "last_message_at = ?, last_message_preview = ?, last_inbound_at = ?, " \
      "unread_count = unread_count + 1, updated_at = ?",
      stamp, message.preview, stamp, Time.current
    ])
  else
    self.class.where(id: id).update_all([
      "last_message_at = ?, last_message_preview = ?, updated_at = ?",
      stamp, message.preview, Time.current
    ])
  end
  reload
end