Class: CollavreSlack::SlackChannelSyncJob

Inherits:
ApplicationJob
  • Object
show all
Defined in:
app/jobs/collavre_slack/slack_channel_sync_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(slack_channel_link_id) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/jobs/collavre_slack/slack_channel_sync_job.rb', line 5

def perform(slack_channel_link_id)
  link = SlackChannelLink.find(slack_channel_link_id)
  client = SlackClient.new(access_token: link..access_token)
  oldest = link.last_synced_at&.to_f
  newest_ts = nil
  cursor = nil

  loop do
    response = client.list_messages(channel: link.channel_id, oldest: oldest, cursor: cursor)
    break unless response[:ok]

    messages = Array(response[:messages])
    break if messages.empty?

    # Track the newest message timestamp (messages are returned newest first)
    newest_ts ||= messages.first[:ts]

    # Process messages in chronological order (oldest first)
    messages.reverse.each do |message|
      next if message[:subtype].present?

      user = link..slack_user_mappings.find_by(slack_user_id: message[:user])&.collavre_user
      user ||= link.created_by
      next unless user

      content = MentionMapping.from_slack(message[:text].to_s, link.)
      SlackInboundMessageJob.perform_later({ creative_id: link.creative_id, user_id: user.id, content: content })
    end

    # Check for more pages
    cursor = response.dig(:response_metadata, :next_cursor)
    break if cursor.blank?
  end

  # Update last_synced_at to the newest processed message timestamp
  if newest_ts.present?
    link.update!(last_synced_at: Time.at(newest_ts.to_f))
  end
end