2019-11-30 13:39:55 +00:00
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: channel_facebook_pages
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# page_access_token :string not null
|
|
|
|
# user_access_token :string not null
|
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
|
|
|
# account_id :integer not null
|
2021-10-05 09:05:32 +00:00
|
|
|
# instagram_id :string
|
2019-11-30 13:39:55 +00:00
|
|
|
# page_id :string not null
|
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
2019-12-05 07:50:04 +00:00
|
|
|
# index_channel_facebook_pages_on_page_id (page_id)
|
|
|
|
# index_channel_facebook_pages_on_page_id_and_account_id (page_id,account_id) UNIQUE
|
2019-11-30 13:39:55 +00:00
|
|
|
#
|
|
|
|
|
2020-01-09 07:36:40 +00:00
|
|
|
class Channel::FacebookPage < ApplicationRecord
|
2021-09-10 20:01:17 +00:00
|
|
|
include Channelable
|
2020-09-29 19:42:32 +00:00
|
|
|
include Reauthorizable
|
|
|
|
|
2021-09-10 20:01:17 +00:00
|
|
|
self.table_name = 'channel_facebook_pages'
|
2019-10-20 10:49:12 +00:00
|
|
|
|
2021-09-10 20:01:17 +00:00
|
|
|
validates :page_id, uniqueness: { scope: :account_id }
|
2019-10-20 10:49:12 +00:00
|
|
|
|
2020-05-17 18:14:50 +00:00
|
|
|
after_create_commit :subscribe
|
2020-01-09 07:36:40 +00:00
|
|
|
before_destroy :unsubscribe
|
2019-10-20 10:49:12 +00:00
|
|
|
|
2020-09-04 13:43:47 +00:00
|
|
|
def name
|
|
|
|
'Facebook'
|
|
|
|
end
|
|
|
|
|
2020-07-25 17:24:45 +00:00
|
|
|
def has_24_hour_messaging_window?
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2021-10-05 09:05:32 +00:00
|
|
|
def create_contact_inbox(instagram_id, name)
|
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
contact = inbox.account.contacts.create!(name: name)
|
|
|
|
::ContactInbox.create(
|
|
|
|
contact_id: contact.id,
|
|
|
|
inbox_id: inbox.id,
|
|
|
|
source_id: instagram_id
|
|
|
|
)
|
|
|
|
rescue StandardError => e
|
2022-03-28 12:44:30 +00:00
|
|
|
Rails.logger.error e
|
2021-10-05 09:05:32 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-05-17 18:14:50 +00:00
|
|
|
def subscribe
|
|
|
|
# ref https://developers.facebook.com/docs/messenger-platform/reference/webhook-events
|
|
|
|
response = Facebook::Messenger::Subscriptions.subscribe(
|
|
|
|
access_token: page_access_token,
|
|
|
|
subscribed_fields: %w[
|
|
|
|
messages message_deliveries message_echoes message_reads
|
|
|
|
]
|
|
|
|
)
|
|
|
|
rescue => e
|
2021-08-03 14:41:52 +00:00
|
|
|
Rails.logger.debug { "Rescued: #{e.inspect}" }
|
2020-05-17 18:14:50 +00:00
|
|
|
true
|
|
|
|
end
|
2019-10-20 10:49:12 +00:00
|
|
|
|
2020-01-09 07:36:40 +00:00
|
|
|
def unsubscribe
|
|
|
|
Facebook::Messenger::Subscriptions.unsubscribe(access_token: page_access_token)
|
|
|
|
rescue => e
|
2021-08-03 14:41:52 +00:00
|
|
|
Rails.logger.debug { "Rescued: #{e.inspect}" }
|
2020-01-09 07:36:40 +00:00
|
|
|
true
|
2019-10-20 10:49:12 +00:00
|
|
|
end
|
|
|
|
end
|