2020-02-09 10:17:48 +00:00
|
|
|
class Twitter::TweetParserService < Twitter::WebhooksBaseService
|
|
|
|
pattr_initialize [:payload]
|
|
|
|
|
|
|
|
def perform
|
|
|
|
set_inbox
|
2020-11-16 05:16:53 +00:00
|
|
|
return if message_already_exist? || user_has_blocked?
|
2020-03-05 20:17:37 +00:00
|
|
|
|
|
|
|
create_message
|
2020-02-09 10:17:48 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def message_type
|
|
|
|
user['id'] == profile_id ? :outgoing : :incoming
|
|
|
|
end
|
|
|
|
|
|
|
|
def tweet_text
|
|
|
|
tweet_data['truncated'] ? tweet_data['extended_tweet']['full_text'] : tweet_data['text']
|
|
|
|
end
|
|
|
|
|
|
|
|
def tweet_create_events_params
|
|
|
|
payload['tweet_create_events']
|
|
|
|
end
|
|
|
|
|
|
|
|
def tweet_data
|
|
|
|
tweet_create_events_params.first
|
|
|
|
end
|
|
|
|
|
|
|
|
def user
|
|
|
|
tweet_data['user']
|
|
|
|
end
|
|
|
|
|
2020-03-05 20:17:37 +00:00
|
|
|
def tweet_id
|
|
|
|
tweet_data['id'].to_s
|
|
|
|
end
|
|
|
|
|
2020-11-16 05:16:53 +00:00
|
|
|
def user_has_blocked?
|
|
|
|
payload['user_has_blocked'] == true
|
|
|
|
end
|
|
|
|
|
2020-02-09 10:17:48 +00:00
|
|
|
def parent_tweet_id
|
|
|
|
tweet_data['in_reply_to_status_id_str'].nil? ? tweet_data['id'].to_s : tweet_data['in_reply_to_status_id_str']
|
|
|
|
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: 'tweet',
|
|
|
|
tweet_id: parent_tweet_id,
|
|
|
|
tweet_source: tweet_data['source']
|
|
|
|
}
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_conversation
|
|
|
|
tweet_conversations = @contact_inbox.conversations.where("additional_attributes ->> 'tweet_id' = ?", parent_tweet_id)
|
|
|
|
@conversation = tweet_conversations.first
|
|
|
|
return if @conversation
|
|
|
|
|
|
|
|
tweet_message = @inbox.messages.find_by(source_id: parent_tweet_id)
|
|
|
|
@conversation = tweet_message.conversation if tweet_message
|
|
|
|
return if @conversation
|
|
|
|
|
|
|
|
@conversation = ::Conversation.create!(conversation_params)
|
|
|
|
end
|
2020-03-05 20:17:37 +00:00
|
|
|
|
|
|
|
def message_already_exist?
|
|
|
|
@inbox.messages.find_by(source_id: tweet_id)
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_message
|
|
|
|
find_or_create_contact(user)
|
|
|
|
set_conversation
|
|
|
|
@conversation.messages.create(
|
|
|
|
account_id: @inbox.account_id,
|
2020-06-27 16:04:53 +00:00
|
|
|
sender: @contact,
|
2020-03-05 20:17:37 +00:00
|
|
|
content: tweet_text,
|
|
|
|
inbox_id: @inbox.id,
|
|
|
|
message_type: message_type,
|
|
|
|
source_id: tweet_id
|
|
|
|
)
|
|
|
|
end
|
2020-02-09 10:17:48 +00:00
|
|
|
end
|