Class: Koala::Facebook::API

Inherits:
Object
  • Object
show all
Includes:
GraphAPIMethods
Defined in:
lib/koala/api.rb,
lib/koala/api/graph_collection.rb

Defined Under Namespace

Classes: GraphCollection

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from GraphAPIMethods

#batch, #debug_token, #delete_connections, #delete_like, #delete_object, #get_connection, #get_object, #get_object_metadata, #get_objects, #get_page, #get_page_access_token, #get_picture, #get_picture_data, #get_user_picture_data, #put_comment, #put_connections, #put_like, #put_object, #put_picture, #put_video, #put_wall_post, #search, #set_app_restrictions

Constructor Details

#initialize(access_token = Koala.config.access_token, app_secret = Koala.config.app_secret, rate_limit_hook = Koala.config.rate_limit_hook) ⇒ Koala::Facebook::API

Note:

If no access token is provided, you can only access some public information.

Creates a new API client.

Parameters:

  • access_token (String) (defaults to: Koala.config.access_token)

    access token

  • app_secret (String) (defaults to: Koala.config.app_secret)

    app secret, for tying your access tokens to your app secret If you provide an app secret, your requests will be signed by default, unless you pass appsecret_proof: false as an option to the API call. (See developers.facebook.com/docs/graph-api/securing-requests/)

  • rate_limit_hook (Block) (defaults to: Koala.config.rate_limit_hook)

    block called with limits received in facebook response headers



19
20
21
22
23
# File 'lib/koala/api.rb', line 19

def initialize(access_token = Koala.config.access_token, app_secret = Koala.config.app_secret, rate_limit_hook = Koala.config.rate_limit_hook)
  @access_token = access_token
  @app_secret = app_secret
  @rate_limit_hook = rate_limit_hook
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



25
26
27
# File 'lib/koala/api.rb', line 25

def access_token
  @access_token
end

#app_secretObject (readonly)

Returns the value of attribute app_secret.



25
26
27
# File 'lib/koala/api.rb', line 25

def app_secret
  @app_secret
end

#rate_limit_hookObject (readonly)

Returns the value of attribute rate_limit_hook.



25
26
27
# File 'lib/koala/api.rb', line 25

def rate_limit_hook
  @rate_limit_hook
end

Instance Method Details

#api(path, args = {}, verb = "get", options = {}) ⇒ Object

Note:

You’ll rarely need to call this method directly.

Makes a request to the appropriate Facebook API.

Parameters:

  • path

    the server path for this request (leading / is prepended if not present)

  • args (defaults to: {})

    arguments to be sent to Facebook

  • verb (defaults to: "get")

    the HTTP method to use

  • options (defaults to: {})

    request-related options for Koala and Faraday. See github.com/arsduo/koala/wiki/HTTP-Services for additional options.

Options Hash (options):

  • :http_component (Symbol)

    which part of the response (headers, body, or status) to return

  • :format (Symbol)

    which request format to use. Currently, :json is supported

  • :preserve_form_arguments (Symbol)

    preserve arrays in arguments, which are expected by certain FB APIs (see the ads API in particular, developers.facebook.com/docs/marketing-api/adgroup/v2.4)

  • :beta (Boolean)

    use Facebook’s beta tier

  • :use_ssl (Boolean)

    force SSL for this request, even if it’s tokenless. (All API requests with access tokens use SSL.)

Returns:

  • a Koala::HTTPService::Response object representing the returned Facebook data

Raises:

See Also:

  • GraphAPIMethods#graph_call


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
129
# File 'lib/koala/api.rb', line 101

def api(path, args = {}, verb = "get", options = {})
  # we make a copy of args so the modifications (added access_token & appsecret_proof)
  # do not affect the received argument
  args = args.dup

  # If a access token is explicitly provided, use that
  # This is explicitly needed in batch requests so GraphCollection
  # results preserve any specific access tokens provided
  args["access_token"] ||= @access_token || @app_access_token if @access_token || @app_access_token

  if options.delete(:appsecret_proof) && args["access_token"] && @app_secret
    args["appsecret_proof"] = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha256"), @app_secret, args["access_token"])
  end

  # Translate any arrays in the params into comma-separated strings
  args = sanitize_request_parameters(args) unless preserve_form_arguments?(options)

  # add a leading / if needed...
  path = "/#{path}" unless path.to_s =~ /^\//

  # make the request via the provided service
  result = Koala.make_request(path, args, verb, options)

  if result.status.to_i >= 500
    raise Koala::Facebook::ServerError.new(result.status.to_i, result.body)
  end

  result
end

#graph_call(path, args = {}, verb = "get", options = {}) { ... } ⇒ Object

Make a call directly to the Graph API. (See any of the other methods for example invocations.)

Parameters:

  • path

    the Graph API path to query (no leading / needed)

  • verb (defaults to: "get")

    the type of HTTP request to make (get, post, delete, etc.)

Yields:

  • response when making a batch API call, you can pass in a block that parses the results, allowing for cleaner code. The block’s return value is returned in the batch results. See the code for GraphAPIMethods#get_picture for examples. (Not needed in regular calls; you’ll probably rarely use this.)

Returns:

  • the result from Facebook

Raises:



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
# File 'lib/koala/api.rb', line 46

def graph_call(path, args = {}, verb = "get", options = {}, &post_processing)
  # enable appsecret_proof by default
  options = {:appsecret_proof => true}.merge(options) if @app_secret
  response = api(path, args, verb, options)

  error = GraphErrorChecker.new(response.status, response.body, response.headers).error_if_appropriate
  raise error if error

  # if we want a component other than the body (e.g. redirect header for images), provide that
  http_component = options[:http_component]
  desired_data = if options[:http_component]
    http_component == :response ? response : response.send(http_component)
  else
    # turn this into a GraphCollection if it's pageable
    API::GraphCollection.evaluate(response, self)
  end

  if rate_limit_hook
    limits = %w(x-business-use-case-usage x-ad-account-usage x-app-usage).each_with_object({}) do |key, hash|
      value = response.headers.fetch(key, nil)
      next unless value
      hash[key] = JSON.parse(response.headers[key])
    rescue JSON::ParserError => e
      Koala::Utils.logger.error("#{e.class}: #{e.message} while parsing #{key} = #{value}")
    end

    rate_limit_hook.call(limits) if limits.keys.any?
  end

  # now process as appropriate for the given call (get picture header, etc.)
  post_processing ? post_processing.call(desired_data) : desired_data
end