Module: FGraph

Includes:
HTTParty
Defined in:
lib/fgraph.rb,
lib/fgraph/client.rb,
lib/fgraph/rails/fgraph_helper.rb,
lib/fgraph/rails/fgraph_tag_helper.rb

Defined Under Namespace

Modules: Rails Classes: Client, Collection, FacebookError, GraphMethodError, OAuthAccessTokenError, OAuthError, QueryParseError

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.configObject

Returns the value of attribute config.



78
79
80
# File 'lib/fgraph.rb', line 78

def config
  @config
end

Class Method Details

.format_url(path, options = {}) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/fgraph.rb', line 342

def format_url(path, options={})
  url = self.base_uri.dup
  url << path
  unless options.blank?
    url << "?"
  
    option_count = 0
  
    stringified_options = {}
    options.each do |key, value|
      stringified_options[key.to_s] = value
    end
    options = stringified_options
  
    options.each do |option|
      next unless option[0]
      url << "&" if option_count > 0
      url << "#{option[0]}=#{CGI.escape(option[1].to_s)}"
      option_count += 1
    end
  end
  url
end

.get_id(id) ⇒ Object

Return ID if ID is a hash object



395
396
397
398
399
# File 'lib/fgraph.rb', line 395

def get_id(id)
  return unless id
  id = id['id'] || id[:id] if id.is_a?(Hash)
  id
end

.handle_response(response) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/fgraph.rb', line 322

def handle_response(response)
  unless response['error']
    return FGraph::Collection.new(response) if response['data']
    response
  else
    case response['error']['type']
      when 'QueryParseException'
        raise QueryParseError, response['error']
      when 'GraphMethodException'
        raise GraphMethodError, response['error']
      when 'OAuthException'
        raise OAuthError, response['error']
      when 'OAuthAccessTokenException'
        raise OAuthAccessTokenError, response['error']
      else
        raise FacebookError, response['error']
    end
  end
end

.insights(client_id, app_access_token, options = {}) ⇒ Object

Download insights data for your application.

# https://graph.facebook.com/[client_id]/insights?access_token=...
FGraph.insights('[client_id]', '[app_access_token]')

# https://graph.facebook.com/[client_id]/insights/application_api_call/day?access_token=...
FGraph.insights('[client_id]', '[app_access_token]', :metric_path => 'application_api_call/day')

Options

  • metric_path - e.g. application_api_calls/day

  • since - since (a unix timestamp or any date accepted by strtotime, e.g. yesterday)

  • until - until (a unix timestamp or any date accepted by strtotime, e.g. yesterday)



299
300
301
302
303
304
305
306
307
308
# File 'lib/fgraph.rb', line 299

def insights(client_id, app_access_token, options={})
  metric_path = options.delete(:metric_path)

  path = "/#{client_id}/insights"
  path += "/#{metric_path}" if metric_path
  
  self.perform_get(path, {
    :access_token => app_access_token
  }.merge(options || {}))
end

.me(*args) ⇒ Object

call-seq:

FGraph.me(category)
FGraph.me(category, options_hash)

Returns current user object details.

category - friends|home|feed|likes|movies|books|notes|photos|videos|events|groups

# Current user: https://graph.facebook.com/me?access_token=...
FGraph.me(:access_token => '...')

# Current user's friends: https://graph.facebook.com/me/friends?access_token=...
FGraph.me('friends', :access_token => '...')
FGraph.me_friends(:access_token => '...')


144
145
146
147
148
149
150
151
# File 'lib/fgraph.rb', line 144

def me(*args)
  options = args.last.is_a?(Hash) ? args.pop : {}
  category = args.shift

  path = "me"
  path += "/#{category}" unless category.blank?
  self.object(path, options)
end

.method_missing(name, *args, &block) ⇒ Object



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/fgraph.rb', line 366

def method_missing(name, *args, &block)
  names = name.to_s.split('_')
  super unless names.length > 1

  case names.shift
    when 'object'
      # object_photos
      self.object("#{args[0]}/#{names[0]}", args[1])
    when 'me'
      # me_photos
      self.me(names[0], args[0])
    when 'publish'
      # publish_feed(id)
      self.publish("#{args[0]}/#{names[0]}", args[1])
    when 'remove'
      # remove_feed(id)
      self.remove("#{args[0]}/#{names[0]}", args[1])
    when 'search'
      # search_user(query)
      options = args[1] || {}
      options[:type] = names[0]
      self.search(args[0], options)
    else
      super
  end
end

.oauth_access_token(client_id, client_secret, options = {}) ⇒ Object

Return OAuth access_token. There are two types of access token, user access token and application access token.

User access_token requires code and and redirect_uri options. code is the autorization code appended as query string to redirect URI when accessing oauth authorization URL.

# https://graph.facebook.com/oauth/access_token?
#   client_id=...&
#   client_secret=...&
#   redirect_uri=http://www.example.com/oauth_redirect&
#   code=...
FGraph.oauth_access_token('[client id]', '[client secret]', 
   :redirect_uri => 'http://www.example.com/oauth_redirect', 
   :code => '[authorization code]')

Application access token requires <tt>:type => ‘client_cred’</td> option. Used to access application insights data.

# https://graph.facebook.com/oauth/access_token?
#   client_id=...&
#   client_secret=...&
#   type=client_cred
FGraph.oauth_access_token('[client id]', '[client secret]', :type => 'client_cred')


206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/fgraph.rb', line 206

def oauth_access_token(client_id, client_secret, options={})
  url = self.format_url('/oauth/access_token', {
    :client_id => client_id,
    :client_secret => client_secret,
    :redirect_uri => ''
  }.merge(options || {}))

  response = self.perform_get(url)
  response_hash = {}
  response.split('&').each do |value|
    value_pair = value.split('=')
    response_hash[value_pair[0]] = value_pair[1]
  end
  response_hash
end

.oauth_app_access_token(client_id, client_secret) ⇒ Object

Shortcut to retrieve application access token.



223
224
225
# File 'lib/fgraph.rb', line 223

def oauth_app_access_token(client_id, client_secret)
  self.oauth_access_token(client_id, client_secret, :type => 'client_cred')
end

.oauth_authorize_url(client_id, redirect_uri, options = {}) ⇒ Object

Request authorization from Facebok to fetch private data in the profile or permission to publish on a user’s behalf. Returns Oauth Authorization URL, redirect to this URL to allow user to authorize your application from Facebook.

client_id - Application ID redirect_uri - Needs to begin with your app’s Connect URL. For instance, if your Connect URL is www.example.com then your redirect URI could be www.example.com/oauth_redirect. scope (optional) -

Options

  • scope - Extended permission required to fetch private data or request permision to

publish to Facebook on a user’s behalf.



175
176
177
178
179
180
# File 'lib/fgraph.rb', line 175

def oauth_authorize_url(client_id, redirect_uri, options={})
  self.format_url('/oauth/authorize', {
    :client_id => client_id,
    :redirect_uri => redirect_uri
  }.merge(options))
end

.object(id, options = {}) ⇒ Object

Single object query.

# Users: https://graph.facebook.com/btaylor  (Bret Taylor)
FGraph.object('btaylor')

# Pages: https://graph.facebook.com/cocacola (Coca-Cola page)
FGraph.object('cocacola')

# Fields selection with metadata
FGraph.object('btaylor', :fields => 'id,name,picture', :metadata => 1)

# Page photos
FGraph.object('/cocacola/photos')
photos = FGraph.object_photos('cocacola')

# Support id from object hash
friend = { 'name' => 'Mark Zuckerberg', 'id' => '4'}
friend_details = FGraph.object(friend)


98
99
100
101
# File 'lib/fgraph.rb', line 98

def object(id, options={})
  id = self.get_id(id)
  perform_get("/#{id}", options)
end

.objects(*args) ⇒ Object

call-seq:

FGraph.objects(id, id)
FGraph.objects(id, id, options_hash)

Multiple objects query.

# Multiple users select: https://graph.facebook.com?ids=arjun,vernal
FGraph.objects('arjun', 'vernel')

# Filter fields: https://graph.facebook.com?ids=arjun,vernal&fields=id,name,picture
FGraph.objects('arjun', 'vernel', :fields => 'id,name,picture')


115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/fgraph.rb', line 115

def objects(*args)
  options = args.last.is_a?(Hash) ? args.pop : {}

  # If first input before option is an array
  if args.length == 1 and args.first.is_a?(Array)
    args = args.first.map do |arg|
      self.get_id(arg)
    end
  end

  options = options.merge(:ids => args.join(','))
  perform_get("/", options)
end

.perform_delete(uri, options = {}) ⇒ Object



318
319
320
# File 'lib/fgraph.rb', line 318

def perform_delete(uri, options = {})
  handle_response(delete(uri, {:body => options}))
end

.perform_get(uri, options = {}) ⇒ Object



310
311
312
# File 'lib/fgraph.rb', line 310

def perform_get(uri, options = {})
  handle_response(get(uri, {:query => options}))
end

.perform_post(uri, options = {}) ⇒ Object



314
315
316
# File 'lib/fgraph.rb', line 314

def perform_post(uri, options = {})
  handle_response(post(uri, {:body => options}))
end

.publish(id, options = {}) ⇒ Object

Publish to Facebook, you would need to be authorized and provide access token.

# Post to user's feed.
#   curl -F 'access_token=...' \
#     -F 'message=Hello, Arjun. I like this new API.' \
#     https://graph.facebook.com/arjun/feed
FGraph.publish('arjun/feed', :message => 'Hello, Arjun. I like this new API.', 
  :access_token => '...')
FGraph.publish_feed('arjun', :message => '...', :access_token => '...')
FGraph.publish_feed('me', ':message => '...', :access_token => '...')

Options

Method                Description                             Options
-------------------------------------------------------------------------------------
/PROFILE_ID/feed      write to the given profile's feed/wall  :message, :picture, 
                                                              :link, :name, description
/POST_ID/comments     comment on the given post               :message
/POST_ID/likes        like the given post                     none
/PROFILE_ID/notes     write a note on the given profile       :message, :subject
/PROFILE_ID/links     write a link on the given profile       :link, :message
/EVENT_ID/attending   attend the given event                  none
/EVENT_ID/maybe       maybe attend the given event            none
/EVENT_ID/declined    decline the given event                 none


252
253
254
255
# File 'lib/fgraph.rb', line 252

def publish(id, options={})
  id = self.get_id(id)
  self.perform_post("/#{id}", options)
end

.remove(id, options = {}) ⇒ Object

Delete objects in the graph.

# DELETE https://graph.facebook.com/ID?access_token=... HTTP/1.1

FGraph.remove('[ID]')
FGraph.remove('[ID]/likes')
FGraph.remove_likes('[ID]')


265
266
267
268
# File 'lib/fgraph.rb', line 265

def remove(id, options={})
  id = self.get_id(id)
  self.perform_delete("/#{id}", options)
end

.search(query, options = {}) ⇒ Object

Search over all public objects in the social graph.

# https://graph.facebook.com/search?q=watermelon&type=post
FGraph.search('watermelon', :type => 'post')
FGraph.search_post('watermelon')

Options

  • type - album|event|group|link|note|page|photo|post|status|user|video

  • limit - max no of records

  • offset - offset

  • until - since (a unix timestamp or any date accepted by strtotime, e.g. yesterday)



281
282
283
284
285
# File 'lib/fgraph.rb', line 281

def search(query, options={})
  self.perform_get("/search", {
    :q => query
  }.merge(options|| {}))
end