BugFix: Filter duplicate DMs in Twitter Integration (#468)

BugFix: Filter duplicate DMs in Twitter Integration
This commit is contained in:
Pranav Raj S
2020-02-05 18:50:38 +05:30
committed by GitHub
parent 607fc25723
commit 7b1fdc5fcd
4 changed files with 106 additions and 63 deletions

View File

@@ -0,0 +1,74 @@
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,
message_type: outgoing_message? ? :outgoing : :incoming
)
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
@conversation = @contact_inbox.conversations.first
return if @conversation
@conversation = ::Conversation.create!(conversation_params)
end
def outgoing_message?
message_create_data['sender_id'] == @inbox.channel.profile_id
end
end

View File

@@ -0,0 +1,27 @@
class Twitter::WebhooksBaseService
private
def profile_id
payload[:for_user_id]
end
def set_inbox
twitter_profile = ::Channel::TwitterProfile.find_by(profile_id: profile_id)
@inbox = ::Inbox.find_by!(channel: twitter_profile)
end
def find_or_create_contact(user)
@contact_inbox = @inbox.contact_inboxes.where(source_id: user['id']).first
@contact = @contact_inbox.contact if @contact_inbox
return if @contact
@contact_inbox = @inbox.channel.create_contact_inbox(user['id'], user['name'])
@contact = @contact_inbox.contact
avatar_resource = LocalResource.new(user['profile_image_url'])
@contact.avatar.attach(
io: avatar_resource.file,
filename: avatar_resource.tmp_filename,
content_type: avatar_resource.encoding
)
end
end