fgraph

Description

Facebook Graph Ruby API implementation with Ruby magic (graph.facebook.com).

Installation

sudo gem install fgraph

Rails Plugin Installation

Gem Plugin installation:

sudo gem install fgraph

# Edit [RAILS_ROOT]/config/environment.rb
config.gem 'fgraph', :version => ">=0.2.0"

# Edit [RAILS_ROOT]/Rakefile
require 'tasks/fgraph'

# Create fgraph.yml config in [RAILS_ROOT]/config
rake fgraph:setup

Normal Plugin Installation:

script/plugin install http://github.com/jugend/fgraph.git

Facebook Graph Cheat Sheet

sudo gem install cheat
cheat fbgraph

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')
FGraph.object_photos('cocacola')

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

# 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 => '...')

Multiple objects query

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

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

# Passing hash objects
FGraph.objects([{:name => 'Arjun Banker', :id => 'arjun'}, {:name => 'Herryanto Siatono', :id => 'herryanto'}])

Collection Response

friends = FGraph.me_friends(:limit => 5, :access_token => '...')
friends.each do |friend|
  puts friend['name']
  puts friend['id']
end

# Other convenient methods
friends.next?
friends.next_url
friends.next_options

OAuth

OAuth authorization URL:

# https://graph.facebook.com/oauth/authorize?
#   client_id=...&
#   redirect_uri=http://www.example.com/oauth_redirect&
#   scope=publish_stream
FGraph.oauth_authorize_url('[client id]', 'http://www.example.com/oauth_redirect', :scope => 
  'publish_stream')

OAuth Access Token:

# 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]')

OAuth Application Access Token, required to access application anlytics 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')

Publish to Facebook Graph

# 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 n  ew API.', 
  :access_token => '...')
FGraph.publish_feed('arjun', :message => '...', :access_token => '...  ')
FGraph.publish_feed('me', :message => '...', :access_token => '...')

Remove from Facebook Graph

# DELETE https://graph.facebook.com/ID?access_token=... HTTP/1.1
FGraph.remove('[ID]')
FGraph.remove('[ID]/likes')
FGraph.remove_likes('[ID]')
# https://graph.facebook.com/search?q=watermelon&type=post
FGraph.search('watermelon', :type => 'post')
FGraph.search_post('watermelon')

Insights

# 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')

FGraph::Client

# Initialize with default options
fg_client = FGraph::Client.new(:client_id => '...', :client_secret => '...')
fg_client.oauth_authorize_url('[redirect uri]', :scope => 'publish_stream')
fg_client.oauth_access_token('[redirect uri]', '[authorization code]')

# Intialize with access token
fg_client = FGraph::Client.new(:access_token => '...')
fg_client.me
fg.client.publish_feed('herryanto', :message => 'Cool!')

Pagination Options

  • limit - max no of records

  • offset - offset

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

Rails Helper

Sample codes:

<%= fgraph_javascript_init_tag %>
<script type="text/javascript">
  FB.Event.subscribe('auth.sessionChange', function(response) {
    if (response.session) {
      // A user has logged in, and a new cookie has been saved
    } else {
      // The user has logged out, and the cookie has been cleared
    }
  });
</script>

<!-- Facebook Login Button -->
<fb:login-button autologoutlink="true" scope="email,publish_stream"></fb:login-button>

<% if fgraph_logged_in? %>
  <br>Hello <%= fgraph_user['name'] %>,
  <br><%= fgraph_image_tag(fgraph_user, 'large') %>
<% end %>

For Asynchronous load, use window.afterFbAsyncInit:

<script type="text/javascript">
  window.afterFbAsyncInit = function() {
    FB.Event.subscribe('auth.sessionChange', function(response) {
      if (response.session) {
        // A user has logged in, and a new cookie has been saved
      } else {
        // The user has logged out, and the cookie has been cleared
      }
    });
  }
</script>
<%= fgraph_javascript_init_tag :async => true %>

Facebook invalidates session token when you log out from facebook.com, and fgraph_logged_in? does not check if the session is still valid on Facebook server. The trick is you have to catch FGraph::OAuthError in ApplicationController:

rescue_from FGraph::OAuthError do
  # Delete existing invalid cookies
  cookies.delete "fbs_#{FGraph.config['app_id']}"

  # Redirect to referrer page
  redirect_to request.env['REQUEST_PATH']
end

License

(The MIT License)

Copyright © 2010 Herryanto Siatono www.pluitsolutions.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.