Created
March 3, 2020 05:16
-
-
Save theareba/0cb6127c5a93e980abb635b45643825b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
METRICS = %w[post_impressions_organic_unique] | |
METRIC_ID_REGEX = %r{\/insights\/(\S+)\/lifetime} | |
facebook_handlers = [Activity::FacebookMessage, Activity::FacebookPhoto, Activity::FacebookVideo, Activity::FacebookReShare] | |
eligible_message_statuses = SMS.shared.joins(:message) | |
.where.not(share_id: nil) | |
.where(messages: { handler_type: facebook_handlers }) | |
.where(SMS.arel_table[:shared_at].gteq('1/1/2019'.to_datetime)) | |
queued_smses = [] | |
eligible_message_statuses.find_each do |sms| | |
next unless sms.corresponding_authentication.is_a?(FacebookPage) | |
next unless sms.corresponding_authentication.read_insights? | |
queued_smses << sms | |
end | |
def facebook_share_id(sms) | |
posting_object_uid = sms.posting_object_uid | |
posting_object_uid ||= sms.corresponding_authentication.uid | |
# return the share_id if posting_object_uid is already present as a prefix | |
return sms.share_id if sms.share_id.to_s.starts_with?(posting_object_uid.to_s) | |
[posting_object_uid, sms.share_id].select(&:present?).join('_') | |
end | |
def dig_metric(metric_hash) | |
metric = metric_hash.dig('id').scan(METRIC_ID_REGEX).flatten.first | |
value = metric_hash.dig 'values', 0, 'value' | |
[metric, value] | |
rescue StandardError => e | |
[0, 0] | |
end | |
FacebookAuthentication.app_client.batch do |api| | |
queued_smses.each do |sms| | |
api.get_connections(facebook_share_id(sms), 'insights', { fields: 'values', metric: METRICS }, | |
access_token: sms.corresponding_authentication.access_token) do |result| | |
if result.is_a?(Koala::KoalaError) || result.is_a?(Koala::Facebook::AuthenticationError) || !result | |
nil | |
elsif result.present? | |
metrics_hash_mapping = Hash[result.map { |metric_hash| dig_metric(metric_hash) }] | |
metric_params = { metric: "facebook_post_impressions_organic_unique", message_id: sms.message_id } | |
value = metrics_hash_mapping.dig('post_impressions_organic_unique') | |
metric = sms.metrics.where(metric_params).first_or_initialize | |
return if metric.new_record? && value.to_i.zero? | |
metric.value = value | |
metric.save | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment