2020-02-05 13:20:38 +00:00
|
|
|
class Twitter::DirectMessageParserService < Twitter::WebhooksBaseService
|
|
|
|
pattr_initialize [:payload]
|
|
|
|
|
|
|
|
def perform
|
|
|
|
return if source_app_id == parent_app_id
|
|
|
|
|
|
|
|
set_inbox
|
|
|
|
ensure_contacts
|
|
|
|
set_conversation
|
|
|
|
@conversation.messages.create(
|
|
|
|
content: message_create_data['message_data']['text'],
|
|
|
|
account_id: @inbox.account_id,
|
|
|
|
inbox_id: @inbox.id,
|
2020-03-05 20:17:37 +00:00
|
|
|
message_type: outgoing_message? ? :outgoing : :incoming,
|
2020-06-27 16:04:53 +00:00
|
|
|
sender: @contact,
|
2020-03-05 20:17:37 +00:00
|
|
|
source_id: direct_message_data['id']
|
2020-02-05 13:20:38 +00:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def direct_message_events_params
|
|
|
|
payload['direct_message_events']
|
|
|
|
end
|
|
|
|
|
|
|
|
def direct_message_data
|
|
|
|
direct_message_events_params.first
|
|
|
|
end
|
|
|
|
|
|
|
|
def message_create_data
|
|
|
|
direct_message_data['message_create']
|
|
|
|
end
|
|
|
|
|
|
|
|
def source_app_id
|
|
|
|
message_create_data['source_app_id']
|
|
|
|
end
|
|
|
|
|
|
|
|
def parent_app_id
|
|
|
|
ENV.fetch('TWITTER_APP_ID', '')
|
|
|
|
end
|
|
|
|
|
|
|
|
def users
|
|
|
|
payload[:users]
|
|
|
|
end
|
|
|
|
|
|
|
|
def ensure_contacts
|
|
|
|
users.each do |key, user|
|
|
|
|
next if key == profile_id
|
|
|
|
|
|
|
|
find_or_create_contact(user)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def conversation_params
|
|
|
|
{
|
|
|
|
account_id: @inbox.account_id,
|
|
|
|
inbox_id: @inbox.id,
|
|
|
|
contact_id: @contact.id,
|
|
|
|
contact_inbox_id: @contact_inbox.id,
|
|
|
|
additional_attributes: {
|
|
|
|
type: 'direct_message'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_conversation
|
2020-06-09 18:24:35 +00:00
|
|
|
@conversation = @contact_inbox.conversations.where("additional_attributes ->> 'type' = 'direct_message'").first
|
2020-02-05 13:20:38 +00:00
|
|
|
return if @conversation
|
|
|
|
|
|
|
|
@conversation = ::Conversation.create!(conversation_params)
|
|
|
|
end
|
|
|
|
|
|
|
|
def outgoing_message?
|
|
|
|
message_create_data['sender_id'] == @inbox.channel.profile_id
|
|
|
|
end
|
|
|
|
end
|