Class: RbFacebook::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/rb_facebook.rb

Constant Summary collapse

STATS_METRICS =
["impressions", "clicks", "spent", "social_impressions", "social_clicks", "social_spent", "actions", "unique_impressions", "social_unique_impressions", "unique_clicks", "social_unique_clicks", "connections"]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Api

Returns a new instance of Api.



136
137
138
# File 'lib/rb_facebook.rb', line 136

def initialize(args = {})
  load_tokens
end

Instance Attribute Details

#access_tokenObject

Returns the value of attribute access_token.



6
7
8
# File 'lib/rb_facebook.rb', line 6

def access_token
  @access_token
end

#app_idObject

Returns the value of attribute app_id.



6
7
8
# File 'lib/rb_facebook.rb', line 6

def app_id
  @app_id
end

#app_secretObject

Returns the value of attribute app_secret.



6
7
8
# File 'lib/rb_facebook.rb', line 6

def app_secret
  @app_secret
end

#graph_api_hostObject

Returns the value of attribute graph_api_host.



6
7
8
# File 'lib/rb_facebook.rb', line 6

def graph_api_host
  @graph_api_host
end

#rest_api_hostObject

Returns the value of attribute rest_api_host.



6
7
8
# File 'lib/rb_facebook.rb', line 6

def rest_api_host
  @rest_api_host
end

Class Method Details

.format_targeting(targeting) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/rb_facebook.rb', line 282

def self.format_targeting(targeting)
  Rails.logger.warn '-0-0-0-0-0-0-0-0-0-0-'
  Rails.logger.warn 'ABOUT TO FORMAT TARGETING'
  Rails.logger.warn targeting.inspect
  Rails.logger.warn '-0-0-0-0-0-0-0-0-0-0-'
  
  begin
    
    formatted_targeting = []
    targeting = targeting.dup
    Rails.logger.warn(targeting.inspect)
    adgroup_id = targeting.delete('adgroup_id')
    
    genders = targeting.delete('genders')
    if genders.nil? or genders.length == 2
      gender = 'People'
    elsif genders == ['1']
      gender = 'Men'
    else
      gender = 'Women'
    end
    
    #education_statuses =
    
    age_min = targeting.delete('age_min')
    age_max = targeting.delete('age_max')
    if age_min and age_max
      formatted_targeting << "#{gender} between #{age_min} and #{age_max} years of age"
    elsif age_min
      formatted_targeting << "#{gender} #{age_min} years of age and older"
    elsif age_max
      formatted_targeting << "#{gender} #{age_max} years of age and younger"
    elsif gender != 'People'
      formatted_targeting << "#{gender} only"
    end
    
    relationship_statuses = targeting.delete('relationship_statuses')
    if relationship_statuses and !relationship_statuses.include?('0') #0 indicates ALL
      ref = {'1' => 'single', '2' => 'in a relationship', '3' => 'married', '4' => 'engaged'}
      formatted_targeting << "Are #{relationship_statuses.map{|s|ref[s]}.join(' or ')}"
    end

    education_statuses = targeting.delete('education_statuses')
    if education_statuses and !education_statuses.include?('0') #0 indicates ALL
      ref = {'1' => 'in high school', '2' => 'in college', '3' => 'college graduates'}
      formatted_targeting << "Are #{education_statuses.map{|s|ref[s]}.join(' or ')}"
    end

    #puts "remaining keys: #{targeting.keys.inspect}"
    targeting.each do |target_name, target_data|
      target_string = "#{target_name}: "
      target_data = target_data.map{|t|t['name']} if target_data.first.is_a?(Hash)
      target_string << [target_data].flatten.join(', ')
      formatted_targeting << target_string
    end
    
    return formatted_targeting
  rescue => ex
    
    Rails.logger.warn "ERROR FORMATTING TARGETING"
    Rails.logger.warn ex.backtrace
    return ["There was an error formatting the following raw targeting", targeting.inspect]
  end
  
end

Instance Method Details

#ad_groups(args = {}) ⇒ Object



129
130
131
132
133
134
# File 'lib/rb_facebook.rb', line 129

def ad_groups(args = {})
  params = {:account_id => args[:account_id], :include_deleted => args[:include_deleted] || false}
  params[:campaign_ids] = args[:campaign_ids] if args[:campaign_ids]
  params[:campaign_ids] = "[#{args[:campaign_id]}]" if args[:campaign_id]
  rest_api_parse('ads.getAdGroups', :params => params, :log_call_url => true)
end

#ads_accountsObject



14
15
16
# File 'lib/rb_facebook.rb', line 14

def ads_accounts
  rest_api_parse('ads.getAccounts')
end

#ads_campaign_stats(args = {}) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/rb_facebook.rb', line 80

def ads_campaign_stats(args = {})
   = args[:account_id]
  campaign_id = args[:campaign_id]
  include_deleted = args[:include_deleted]
  start_date = args[:start_date]
  end_date = args[:end_date]
  period = args[:interval]
  
  data_calls = []
  metrics_data = {}
  
  current_date = start_date
  
  while current_date <= end_date
    metrics_data[current_date] = {}
    data_calls << {
      :start_date => current_date.strftime('%s'),
      :end_date => (current_date + period).strftime('%s'),
      :date => current_date
    }
    current_date += period
  end
  
  data_calls.each_slice(50) do |call_slice|
    call_slice.map do |call|
      Thread.new do 
        date_param = {"time_range" => {"time_start" => call[:start_date], "time_stop" => call[:end_date]}}.to_json
        result = rest_api_parse('ads.getCampaignStats', :params => {
          :account_id => ,
          :campaign_ids => "[#{campaign_id}]",
          :time_ranges => date_param,
          :include_deleted => include_deleted
        })
        Thread.exclusive do
          #Rails.logger.warn(result.inspect)
          result.first['stats'].each do |id, stats|
            stats.each do |metric, value|
              next if metric == 'id'
              metrics_data[call[:date]][metric] = metrics_data[call[:date]][metric].to_f + value.to_f
            end
          end
        end
      end
    end.each(&:join)
  end
  
  metrics_data
end

#ads_campaigns(args = {}) ⇒ Object



22
23
24
25
26
27
# File 'lib/rb_facebook.rb', line 22

def ads_campaigns(args = {})
   = args[:account_id]
  params = {'account_id' => }
  params[:campaign_ids] = "[#{args[:campaign_ids].join(',')}]" if args[:campaign_ids]
  rest_api_parse('ads.getCampaigns', :params => params, :log_call_url => true)
end

#api_fetch(api_base_url, method_name, api_params, use_access_token, log_call_url, args = {}) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/rb_facebook.rb', line 238

def api_fetch(api_base_url, method_name, api_params, use_access_token, log_call_url, args = {})
  
  api_params["access_token"] = self.access_token if use_access_token
  
  params_fragment = api_params.map{|k,v|"#{k}=#{URI.escape("#{v}", Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}"}.join('&')
  
  call_url = ['https:/', api_base_url, method_name].join('/')
  call_url << "?#{params_fragment}" unless params_fragment.blank? or args[:mp_post]
  
  Rails.logger.warn("About to fetch: #{call_url}") if log_call_url
  Rails.logger.warn("Parameters: #{api_params.inspect}") if log_call_url
  
  #tries = 0
  #while tries < 5
    #tries += 1
    #begin          
      uri = URI.parse(call_url)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true
      if args[:mp_post]
        mp_post = args[:mp_post]
        api_params[mp_post[:name]] = UploadIO.new(mp_post[:file], mp_post[:mime], mp_post[:name])
        post = Net::HTTP::Post::Multipart.new(
          uri.request_uri,
          api_params
        )
        response = http.request(post)
      else
        response = http.request(Net::HTTP::Get.new(uri.request_uri))
      end
    #rescue Exception => ex
    #  if tries > 5
    #    raise
    #  end
    #else
    #  tries = 5
    #end
  #end
  
  Rails.logger.warn("And returned #{response.inspect}: #{response.body}") if log_call_url
  
  response
end

#authenticate(args) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/rb_facebook.rb', line 157

def authenticate(args)
  load_tokens
  response = graph_api_fetch(
    "oauth/access_token", 
    :params => {
      :client_id => app_id,
      :client_secret => app_secret,
      :code => args[:code],
      :redirect_uri => args[:url]
    },
    :no_access_token => true
  )
  
  self.access_token = CGI.parse(response.body)['access_token'].first
end

#check_authObject



178
179
180
181
182
183
184
185
# File 'lib/rb_facebook.rb', line 178

def check_auth
  if self.access_token
    response = graph_api_fetch('me')
    if response.code != '200'
      self.access_token = nil
    end
  end
end

#graph_api_fetch(method_name, args = {}) ⇒ Object



191
192
193
194
195
196
197
# File 'lib/rb_facebook.rb', line 191

def graph_api_fetch(method_name, args = {})
  api_params = args[:params] || {}
  use_access_token = !args[:no_access_token]
  log_call_url = args[:log_call_url]
  
  api_fetch(self.graph_api_host, method_name, api_params, use_access_token, log_call_url)
end

#graph_api_parse(method_name, args = {}) ⇒ Object



187
188
189
# File 'lib/rb_facebook.rb', line 187

def graph_api_parse(method_name, args = {})
  ActiveSupport::JSON.decode(graph_api_fetch(method_name, args).body)
end

#insight_metrics(args = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rb_facebook.rb', line 29

def insight_metrics(args = {})
  
  metrics = args[:metrics]
  object_id = args[:object_id]
  start_date = args[:start_date]
  end_date = args[:end_date]
  
  data_calls = []
  metrics_data = {}
  
  metrics.each do |metric|
    metrics_data[metric] = {}
    current_date = start_date + 1.day
    period = 1.day.seconds
    while current_date <= end_date
      data_calls << {
        :fql_query => 
          "SELECT object_id, metric, end_time, period, value FROM insights 
          WHERE object_id = #{object_id}
          AND metric = '#{metric}'
          AND end_time = end_time_date('#{current_date.strftime("%Y-%m-%d")}')
          AND period = #{period}",
        :metric => metric,
        :date => current_date - 1.day
      }
      current_date += 1.day
    end
  end
  
  data_calls.each_slice(50) do |call_slice|
    call_slice.map do |call|
      Thread.new do 
        #Rails.logger.warn(call)
        result = rest_api_parse('fql.query', :params => {:query => call[:fql_query]})
        #Rails.logger.warn(result)
        Thread.exclusive do
          begin
            #Rails.logger.warn "RESULT: #{result.inspect}"
            metrics_data[call[:metric]][call[:date]] = (result.first || {})['value'] || 0
          rescue
            Rails.logger.warn "ERROR THROWN: #{result.inspect}"
            raise
          end
        end
      end
    end.each(&:join)
  end
  
  metrics_data
end

#load_tokensObject



140
141
142
143
144
145
146
147
# File 'lib/rb_facebook.rb', line 140

def load_tokens
  tokens = YAML.load(File.open(File.join(Rails.root, 'config', 'facebook.yml')))
  self.app_secret = tokens[:APP_SECRET]
  self.app_id = tokens[:APP_ID]
  self.rest_api_host = tokens[:REST_API_HOST] || 'api.facebook.com'
  self.graph_api_host = tokens[:GRAPH_API_HOST] || 'graph.facebook.com'

end

#logged_in?Boolean

Returns:

  • (Boolean)


173
174
175
176
# File 'lib/rb_facebook.rb', line 173

def logged_in?
  check_auth
  !self.access_token.nil?
end

#logged_in_userObject



10
11
12
# File 'lib/rb_facebook.rb', line 10

def logged_in_user
  graph_api_parse('me', :log_call_url => true)
end

#login_url(current_url, permissions = [:read_insights,:ads_management,:offline_access]) ⇒ Object



149
150
151
# File 'lib/rb_facebook.rb', line 149

def (current_url, permissions=[:read_insights,:ads_management,:offline_access])
  "https://www.facebook.com/dialog/oauth?client_id=#{self.app_id}&scope=#{permissions.join(',')}&redirect_uri=#{URI.escape(current_url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}"
end

#logout_url(current_url) ⇒ Object



153
154
155
# File 'lib/rb_facebook.rb', line 153

def logout_url(current_url)
  "https://www.facebook.com/logout.php?next=#{URI.escape(current_url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}&access_token=#{URI.escape(self.access_token, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}"
end

#rest_api_fetch(method_name, args = {}) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
# File 'lib/rb_facebook.rb', line 226

def rest_api_fetch(method_name, args = {})
  api_params = args[:params] || {}
  use_access_token = !args[:no_access_token]
  log_call_url = args[:log_call_url]
  multipart_post = args[:mp_post]
  
  api_params["format"] = 'json-strings'

  api_fetch("#{self.rest_api_host}/method", method_name, api_params, use_access_token, log_call_url, :mp_post => multipart_post)
  
end

#rest_api_parse(method_name, args = {}) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/rb_facebook.rb', line 199

def rest_api_parse(method_name, args = {})
  results = []
  result = [:dummy]
  previous_result = []
  
  page = 0
  per_page = 10
  
  until result.empty? or result.is_a?(Hash) or result == previous_result
    if method_name =~ /^ads./
      args[:params] = {} unless args[:params]
      args[:params][:limit] = per_page 
      args[:params][:offset] = per_page * page
      #args[:params][:include_count] = 1
    end
    
    previous_result = result
    result = ActiveSupport::JSON.decode(rest_api_fetch(method_name, args).body)
    
    page += 1
    results << result unless result == previous_result
    
    result = [] unless method_name =~ /^ads\./
  end
  results.flatten
end

#user_accountsObject



18
19
20
# File 'lib/rb_facebook.rb', line 18

def user_accounts
  graph_api_parse('me/accounts')['data']
end