2020-06-25 18:05:16 +00:00
|
|
|
class Facebook::SendOnFacebookService < Base::SendOnChannelService
|
2019-12-28 17:44:09 +00:00
|
|
|
private
|
2019-08-30 22:38:00 +00:00
|
|
|
|
2020-06-25 18:05:16 +00:00
|
|
|
def channel_class
|
|
|
|
Channel::FacebookPage
|
2019-12-28 17:44:09 +00:00
|
|
|
end
|
2019-08-30 22:38:00 +00:00
|
|
|
|
2020-06-25 18:05:16 +00:00
|
|
|
def perform_reply
|
2021-01-06 12:26:29 +00:00
|
|
|
send_message_to_facebook fb_text_message_params if message.content.present?
|
|
|
|
send_message_to_facebook fb_attachment_message_params if message.attachments.present?
|
2020-09-29 19:42:32 +00:00
|
|
|
rescue Facebook::Messenger::FacebookError => e
|
|
|
|
Rails.logger.info e
|
|
|
|
channel.authorization_error!
|
2019-12-28 17:44:09 +00:00
|
|
|
end
|
2019-08-30 22:38:00 +00:00
|
|
|
|
2021-01-06 12:26:29 +00:00
|
|
|
def send_message_to_facebook(delivery_params)
|
2021-06-07 08:28:01 +00:00
|
|
|
result = Facebook::Messenger::Bot.deliver(delivery_params, page_id: channel.page_id)
|
2021-01-06 12:26:29 +00:00
|
|
|
message.update!(source_id: JSON.parse(result)['message_id'])
|
|
|
|
end
|
|
|
|
|
2020-03-28 06:13:02 +00:00
|
|
|
def fb_text_message_params
|
2019-12-28 17:44:09 +00:00
|
|
|
{
|
|
|
|
recipient: { id: contact.get_source_id(inbox.id) },
|
|
|
|
message: { text: message.content }
|
|
|
|
}
|
|
|
|
end
|
2019-08-30 22:38:00 +00:00
|
|
|
|
2020-03-28 06:13:02 +00:00
|
|
|
def fb_attachment_message_params
|
2020-07-16 19:02:32 +00:00
|
|
|
attachment = message.attachments.first
|
2020-03-28 06:13:02 +00:00
|
|
|
{
|
|
|
|
recipient: { id: contact.get_source_id(inbox.id) },
|
|
|
|
message: {
|
|
|
|
attachment: {
|
2020-07-16 19:02:32 +00:00
|
|
|
type: attachment_type(attachment),
|
2020-03-28 06:13:02 +00:00
|
|
|
payload: {
|
2020-07-16 19:02:32 +00:00
|
|
|
url: attachment.file_url
|
2020-03-28 06:13:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
2020-07-16 19:02:32 +00:00
|
|
|
def attachment_type(attachment)
|
|
|
|
return attachment.file_type if %w[image audio video file].include? attachment.file_type
|
|
|
|
|
|
|
|
'file'
|
|
|
|
end
|
|
|
|
|
2020-03-28 06:13:02 +00:00
|
|
|
def fb_message_params
|
2020-04-17 15:45:20 +00:00
|
|
|
if message.attachments.blank?
|
2020-03-28 06:13:02 +00:00
|
|
|
fb_text_message_params
|
|
|
|
else
|
|
|
|
fb_attachment_message_params
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-03-17 15:39:20 +00:00
|
|
|
def sent_first_outgoing_message_after_24_hours?
|
2019-12-28 17:44:09 +00:00
|
|
|
# we can send max 1 message after 24 hour window
|
2020-03-17 15:39:20 +00:00
|
|
|
conversation.messages.outgoing.where('id > ?', last_incoming_message.id).count == 1
|
|
|
|
end
|
|
|
|
|
|
|
|
def last_incoming_message
|
|
|
|
conversation.messages.incoming.last
|
2019-08-30 22:38:00 +00:00
|
|
|
end
|
|
|
|
end
|