Class: RbFacebook::Api
- Inherits:
-
Object
- Object
- RbFacebook::Api
- 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
-
#access_token ⇒ Object
Returns the value of attribute access_token.
-
#app_id ⇒ Object
Returns the value of attribute app_id.
-
#app_secret ⇒ Object
Returns the value of attribute app_secret.
-
#graph_api_host ⇒ Object
Returns the value of attribute graph_api_host.
-
#rest_api_host ⇒ Object
Returns the value of attribute rest_api_host.
Class Method Summary collapse
Instance Method Summary collapse
- #ad_groups(args = {}) ⇒ Object
- #ads_accounts ⇒ Object
- #ads_campaign_stats(args = {}) ⇒ Object
- #ads_campaigns(args = {}) ⇒ Object
- #api_fetch(api_base_url, method_name, api_params, use_access_token, log_call_url, args = {}) ⇒ Object
- #authenticate(args) ⇒ Object
- #check_auth ⇒ Object
- #graph_api_fetch(method_name, args = {}) ⇒ Object
- #graph_api_parse(method_name, args = {}) ⇒ Object
-
#initialize(args = {}) ⇒ Api
constructor
A new instance of Api.
- #insight_metrics(args = {}) ⇒ Object
- #load_tokens ⇒ Object
- #logged_in? ⇒ Boolean
- #logged_in_user ⇒ Object
- #login_url(current_url, permissions = [:read_insights,:ads_management,:offline_access]) ⇒ Object
- #logout_url(current_url) ⇒ Object
- #rest_api_fetch(method_name, args = {}) ⇒ Object
- #rest_api_parse(method_name, args = {}) ⇒ Object
- #user_accounts ⇒ Object
Constructor Details
#initialize(args = {}) ⇒ Api
Returns a new instance of Api.
137 138 139 |
# File 'lib/rb_facebook.rb', line 137 def initialize(args = {}) load_tokens end |
Instance Attribute Details
#access_token ⇒ Object
Returns the value of attribute access_token.
6 7 8 |
# File 'lib/rb_facebook.rb', line 6 def access_token @access_token end |
#app_id ⇒ Object
Returns the value of attribute app_id.
6 7 8 |
# File 'lib/rb_facebook.rb', line 6 def app_id @app_id end |
#app_secret ⇒ Object
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_host ⇒ Object
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_host ⇒ Object
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
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 347 348 |
# File 'lib/rb_facebook.rb', line 284 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
130 131 132 133 134 135 |
# File 'lib/rb_facebook.rb', line 130 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_accounts ⇒ Object
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 128 |
# File 'lib/rb_facebook.rb', line 80 def ads_campaign_stats(args = {}) account_id = 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 => 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' next if value.is_a?Hash 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 = {}) account_id = args[:account_id] params = {'account_id' => 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
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 281 282 |
# File 'lib/rb_facebook.rb', line 240 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
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
# File 'lib/rb_facebook.rb', line 158 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_auth ⇒ Object
179 180 181 182 183 184 185 186 |
# File 'lib/rb_facebook.rb', line 179 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
192 193 194 195 196 197 198 199 |
# File 'lib/rb_facebook.rb', line 192 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] multipart_post = args[:mp_post] api_fetch(self.graph_api_host, method_name, api_params, use_access_token, log_call_url, :mp_post => multipart_post) end |
#graph_api_parse(method_name, args = {}) ⇒ Object
188 189 190 |
# File 'lib/rb_facebook.rb', line 188 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_tokens ⇒ Object
141 142 143 144 145 146 147 148 |
# File 'lib/rb_facebook.rb', line 141 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
174 175 176 177 |
# File 'lib/rb_facebook.rb', line 174 def logged_in? check_auth !self.access_token.nil? end |
#logged_in_user ⇒ Object
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
150 151 152 |
# File 'lib/rb_facebook.rb', line 150 def login_url(current_url, =[:read_insights,:ads_management,:offline_access]) "https://www.facebook.com/dialog/oauth?client_id=#{self.app_id}&scope=#{.join(',')}&redirect_uri=#{URI.escape(current_url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}" end |
#logout_url(current_url) ⇒ Object
154 155 156 |
# File 'lib/rb_facebook.rb', line 154 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
228 229 230 231 232 233 234 235 236 237 238 |
# File 'lib/rb_facebook.rb', line 228 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
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/rb_facebook.rb', line 201 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_accounts ⇒ Object
18 19 20 |
# File 'lib/rb_facebook.rb', line 18 def user_accounts graph_api_parse('me/accounts')['data'] end |