palidanx-koala 0.9.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,192 @@
1
+ module Koala
2
+ module Facebook
3
+ GRAPH_SERVER = "graph.facebook.com"
4
+
5
+ class GraphCollection < Array
6
+ #This class is a light wrapper for collections returned
7
+ #from the Graph API.
8
+ #
9
+ #It extends Array to allow direct access to the data colleciton
10
+ #which should allow it to drop in seamlessly.
11
+ #
12
+ #It also allows access to paging information and the
13
+ #ability to get the next/previous page in the collection
14
+ #by calling next_page or previous_page.
15
+ attr_reader :paging
16
+ attr_reader :api
17
+
18
+ def initialize(response, api)
19
+ super response["data"]
20
+ @paging = response["paging"]
21
+ @api = api
22
+ end
23
+
24
+ # defines methods for NEXT and PREVIOUS pages
25
+ %w{next previous}.each do |this|
26
+
27
+ # def next_page
28
+ # def previous_page
29
+ define_method "#{this.to_sym}_page" do
30
+ base, args = send("#{this}_page_params")
31
+ base ? @api.get_page([base, args]) : nil
32
+ end
33
+
34
+ # def next_page_params
35
+ # def previous_page_params
36
+ define_method "#{this.to_sym}_page_params" do
37
+ return nil unless @paging and @paging[this]
38
+ parse_page_url(@paging[this])
39
+ end
40
+ end
41
+
42
+ def parse_page_url(url)
43
+ match = url.match(/.com\/(.*)\?(.*)/)
44
+ base = match[1]
45
+ args = match[2]
46
+ params = CGI.parse(args)
47
+ new_params = {}
48
+ params.each_pair do |key,value|
49
+ new_params[key] = value.join ","
50
+ end
51
+ [base,new_params]
52
+ end
53
+
54
+ end
55
+
56
+
57
+
58
+ module GraphAPIMethods
59
+ # A client for the Facebook Graph API.
60
+ #
61
+ # See http://developers.facebook.com/docs/api for complete documentation
62
+ # for the API.
63
+ #
64
+ # The Graph API is made up of the objects in Facebook (e.g., people, pages,
65
+ # events, photos) and the connections between them (e.g., friends,
66
+ # photo tags, and event RSVPs). This client provides access to those
67
+ # primitive types in a generic way. For example, given an OAuth access
68
+ # token, this will fetch the profile of the active user and the list
69
+ # of the user's friends:
70
+ #
71
+ # graph = Koala::Facebook::GraphAPI.new(access_token)
72
+ # user = graph.get_object("me")
73
+ # friends = graph.get_connections(user["id"], "friends")
74
+ #
75
+ # You can see a list of all of the objects and connections supported
76
+ # by the API at http://developers.facebook.com/docs/reference/api/.
77
+ #
78
+ # You can obtain an access token via OAuth or by using the Facebook
79
+ # JavaScript SDK. See http://developers.facebook.com/docs/authentication/
80
+ # for details.
81
+ #
82
+ # If you are using the JavaScript SDK, you can use the
83
+ # Koala::Facebook::OAuth.get_user_from_cookie() method below to get the OAuth access token
84
+ # for the active user from the cookie saved by the SDK.
85
+
86
+ def get_object(id, args = {})
87
+ # Fetchs the given object from the graph.
88
+ graph_call(id, args)
89
+ end
90
+
91
+ def get_objects(ids, args = {})
92
+ # Fetchs all of the given object from the graph.
93
+ # We return a map from ID to object. If any of the IDs are invalid,
94
+ # we raise an exception.
95
+ graph_call("", args.merge("ids" => ids.join(",")))
96
+ end
97
+
98
+ def get_page(params)
99
+ result = graph_call(*params)
100
+ result ? GraphCollection.new(result, self) : nil # when facebook is down nil can be returned
101
+ end
102
+
103
+ def get_connections(id, connection_name, args = {})
104
+ # Fetchs the connections for given object.
105
+ result = graph_call("#{id}/#{connection_name}", args)
106
+ result ? GraphCollection.new(result, self) : nil # when facebook is down nil can be returned
107
+ end
108
+
109
+
110
+ def get_picture(object, args = {})
111
+ result = graph_call("#{object}/picture", args, "get", :http_component => :headers)
112
+ result["Location"]
113
+ end
114
+
115
+ def put_object(parent_object, connection_name, args = {})
116
+ # Writes the given object to the graph, connected to the given parent.
117
+ #
118
+ # For example,
119
+ #
120
+ # graph.put_object("me", "feed", :message => "Hello, world")
121
+ #
122
+ # writes "Hello, world" to the active user's wall. Likewise, this
123
+ # will comment on a the first post of the active user's feed:
124
+ #
125
+ # feed = graph.get_connections("me", "feed")
126
+ # post = feed["data"][0]
127
+ # graph.put_object(post["id"], "comments", :message => "First!")
128
+ #
129
+ # See http://developers.facebook.com/docs/api#publishing for all of
130
+ # the supported writeable objects.
131
+ #
132
+ # Most write operations require extended permissions. For example,
133
+ # publishing wall posts requires the "publish_stream" permission. See
134
+ # http://developers.facebook.com/docs/authentication/ for details about
135
+ # extended permissions.
136
+
137
+ raise APIError.new({"type" => "KoalaMissingAccessToken", "message" => "Write operations require an access token"}) unless @access_token
138
+ graph_call("#{parent_object}/#{connection_name}", args, "post")
139
+ end
140
+
141
+ def put_wall_post(message, attachment = {}, profile_id = "me")
142
+ # Writes a wall post to the given profile's wall.
143
+ #
144
+ # We default to writing to the authenticated user's wall if no
145
+ # profile_id is specified.
146
+ #
147
+ # attachment adds a structured attachment to the status message being
148
+ # posted to the Wall. It should be a dictionary of the form:
149
+ #
150
+ # {"name": "Link name"
151
+ # "link": "http://www.example.com/",
152
+ # "caption": "{*actor*} posted a new review",
153
+ # "description": "This is a longer description of the attachment",
154
+ # "picture": "http://www.example.com/thumbnail.jpg"}
155
+
156
+ self.put_object(profile_id, "feed", attachment.merge({:message => message}))
157
+ end
158
+
159
+ def put_comment(object_id, message)
160
+ # Writes the given comment on the given post.
161
+ self.put_object(object_id, "comments", {:message => message})
162
+ end
163
+
164
+ def put_like(object_id)
165
+ # Likes the given post.
166
+ self.put_object(object_id, "likes")
167
+ end
168
+
169
+ def delete_object(id)
170
+ # Deletes the object with the given ID from the graph.
171
+ graph_call(id, {}, "delete")
172
+ end
173
+
174
+ def search(search_terms, args = {})
175
+ # Searches for a given term
176
+ result = graph_call("search", args.merge({:q => search_terms}))
177
+ result ? GraphCollection.new(result, self) : nil # when facebook is down nil can be returned
178
+ end
179
+
180
+ def graph_call(*args)
181
+ response = api(*args) do |response|
182
+ # check for Graph API-specific errors
183
+ if response.is_a?(Hash) && error_details = response["error"]
184
+ raise APIError.new(error_details)
185
+ end
186
+ end
187
+
188
+ response
189
+ end
190
+ end
191
+ end
192
+ end
@@ -0,0 +1,71 @@
1
+ module Koala
2
+ class Response
3
+ attr_reader :status, :body, :headers
4
+ def initialize(status, body, headers)
5
+ @status = status
6
+ @body = body
7
+ @headers = headers
8
+ end
9
+ end
10
+
11
+ module NetHTTPService
12
+ # this service uses Net::HTTP to send requests to the graph
13
+ def self.included(base)
14
+ base.class_eval do
15
+ require 'net/http' unless defined?(Net::HTTP)
16
+ require 'net/https'
17
+
18
+ def self.make_request(path, args, verb, options = {})
19
+ # We translate args to a valid query string. If post is specified,
20
+ # we send a POST request to the given path with the given arguments.
21
+
22
+ # if the verb isn't get or post, send it as a post argument
23
+ args.merge!({:method => verb}) && verb = "post" if verb != "get" && verb != "post"
24
+
25
+ server = options[:rest_api] ? Facebook::REST_SERVER : Facebook::GRAPH_SERVER
26
+ http = Net::HTTP.new(server, 443)
27
+ http.use_ssl = true
28
+ # we turn off certificate validation to avoid the
29
+ # "warning: peer certificate won't be verified in this SSL session" warning
30
+ # not sure if this is the right way to handle it
31
+ # see http://redcorundum.blogspot.com/2008/03/ssl-certificates-and-nethttps.html
32
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
33
+
34
+ result = http.start { |http|
35
+ response, body = (verb == "post" ? http.post(path, encode_params(args)) : http.get("#{path}?#{encode_params(args)}"))
36
+ Koala::Response.new(response.code.to_i, body, response)
37
+ }
38
+ end
39
+
40
+ protected
41
+ def self.encode_params(param_hash)
42
+ # unfortunately, we can't use to_query because that's Rails, not Ruby
43
+ # if no hash (e.g. no auth token) return empty string
44
+ ((param_hash || {}).collect do |key_and_value|
45
+ key_and_value[1] = key_and_value[1].to_json if key_and_value[1].class != String
46
+ "#{key_and_value[0].to_s}=#{CGI.escape key_and_value[1]}"
47
+ end).join("&")
48
+ end
49
+ end
50
+ end
51
+ end
52
+
53
+ module TyphoeusService
54
+ # this service uses Typhoeus to send requests to the graph
55
+ def self.included(base)
56
+ base.class_eval do
57
+ require 'typhoeus' unless defined?(Typhoeus)
58
+ include Typhoeus
59
+
60
+ def self.make_request(path, args, verb, options = {})
61
+ # if the verb isn't get or post, send it as a post argument
62
+ args.merge!({:method => verb}) && verb = "post" if verb != "get" && verb != "post"
63
+ server = options[:rest_api] ? Facebook::REST_SERVER : Facebook::GRAPH_SERVER
64
+ typhoeus_options = {:params => args}.merge(options[:typhoeus_options] || {})
65
+ response = self.send(verb, "https://#{server}#{path}", typhoeus_options)
66
+ Koala::Response.new(response.code, response.body, response.headers_hash)
67
+ end
68
+ end # class_eval
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,95 @@
1
+ require 'koala'
2
+
3
+ module Koala
4
+ module Facebook
5
+ module RealtimeUpdateMethods
6
+ # note: to subscribe to real-time updates, you must have an application access token
7
+
8
+ def self.included(base)
9
+ # make the attributes readable
10
+ base.class_eval do
11
+ attr_reader :app_id, :app_access_token, :secret
12
+
13
+ # parses the challenge params and makes sure the call is legitimate
14
+ # returns the challenge string to be sent back to facebook if true
15
+ # returns false otherwise
16
+ # this is a class method, since you don't need to know anything about the app
17
+ # saves a potential trip fetching the app access token
18
+ def self.meet_challenge(params, verify_token = nil, &verification_block)
19
+ if params["hub.mode"] == "subscribe" &&
20
+ # you can make sure this is legitimate through two ways
21
+ # if your store the token across the calls, you can pass in the token value
22
+ # and we'll make sure it matches
23
+ (verify_token && params["hub.verify_token"] == verify_token) ||
24
+ # alternately, if you sent a specially-constructed value (such as a hash of various secret values)
25
+ # you can pass in a block, which we'll call with the verify_token sent by Facebook
26
+ # if it's legit, return anything that evaluates to true; otherwise, return nil or false
27
+ (verification_block && yield(params["hub.verify_token"]))
28
+ params["hub.challenge"]
29
+ else
30
+ false
31
+ end
32
+ end
33
+ end
34
+ end
35
+
36
+ def initialize(options = {})
37
+ @app_id = options[:app_id]
38
+ @app_access_token = options[:app_access_token]
39
+ @secret = options[:secret]
40
+ unless @app_id && (@app_access_token || @secret) # make sure we have what we need
41
+ raise ArgumentError, "Initialize must receive a hash with :app_id and either :app_access_token or :secret! (received #{options.inspect})"
42
+ end
43
+
44
+ # fetch the access token if we're provided a secret
45
+ if @secret && !@app_access_token
46
+ oauth = Koala::Facebook::OAuth.new(@app_id, @secret)
47
+ @app_access_token = oauth.get_app_access_token
48
+ end
49
+ end
50
+
51
+ # subscribes for realtime updates
52
+ # your callback_url must be set up to handle the verification request or the subscription will not be set up
53
+ # http://developers.facebook.com/docs/api/realtime
54
+ def subscribe(object, fields, callback_url, verify_token)
55
+ args = {
56
+ :object => object,
57
+ :fields => fields,
58
+ :callback_url => callback_url,
59
+ :verify_token => verify_token
60
+ }
61
+ # a subscription is a success if Facebook returns a 200 (after hitting your server for verification)
62
+ api(subscription_path, args, 'post', :http_component => :status) == 200
63
+ end
64
+
65
+ # removes subscription for object
66
+ # if object is nil, it will remove all subscriptions
67
+ def unsubscribe(object = nil)
68
+ args = {}
69
+ args[:object] = object if object
70
+ api(subscription_path, args, 'delete', :http_component => :status) == 200
71
+ end
72
+
73
+ def list_subscriptions
74
+ api(subscription_path)["data"]
75
+ end
76
+
77
+ def api(*args) # same as GraphAPI
78
+ response = super(*args) do |response|
79
+ # check for subscription errors
80
+ if response.is_a?(Hash) && error_details = response["error"]
81
+ raise APIError.new(error_details)
82
+ end
83
+ end
84
+
85
+ response
86
+ end
87
+
88
+ protected
89
+
90
+ def subscription_path
91
+ @subscription_path ||= "#{@app_id}/subscriptions"
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,23 @@
1
+ module Koala
2
+ module Facebook
3
+ REST_SERVER = "api.facebook.com"
4
+
5
+ module RestAPIMethods
6
+ def fql_query(fql)
7
+ rest_call('fql.query', 'query' => fql)
8
+ end
9
+
10
+ def rest_call(method, args = {})
11
+ response = api("method/#{method}", args.merge('format' => 'json'), 'get', :rest_api => true) do |response|
12
+ # check for REST API-specific errors
13
+ if response.is_a?(Hash) && response["error_code"]
14
+ raise APIError.new("type" => response["error_code"], "message" => response["error_msg"])
15
+ end
16
+ end
17
+
18
+ response
19
+ end
20
+ end
21
+
22
+ end # module Facebook
23
+ end # module Koala
@@ -0,0 +1,129 @@
1
+ Koala
2
+ ====
3
+ Koala (<a href="http://github.com/arsduo/koala" target="_blank">http://github.com/arsduo/koala</a>) is a new Facebook library for Ruby, supporting the Graph API, the old REST API, realtime updates, and OAuth validation. We wrote Koala with four goals:
4
+
5
+ * Lightweight: Koala should be as light and simple as Facebook’s own new libraries, providing API accessors and returning simple JSON. (We clock in, with comments, just over 500 lines of code.)
6
+ * Fast: Koala should, out of the box, be quick. In addition to supporting the vanilla Ruby networking libraries, it natively supports Typhoeus, our preferred gem for making fast HTTP requests. Of course, That brings us to our next topic:
7
+ * Flexible: Koala should be useful to everyone, regardless of their current configuration. (We have no dependencies beyond the JSON gem. Koala also has a built-in mechanism for using whichever HTTP library you prefer to make requests against the graph.)
8
+ * Tested: Koala should have complete test coverage, so you can rely on it. (Our complete test coverage can be run against either mocked responses or the live Facebook servers.)
9
+
10
+ Graph API
11
+ ----
12
+ The Graph API is the simple, slick new interface to Facebook's data. Using it with Koala is quite straightforward:
13
+
14
+ graph = Koala::Facebook::GraphAPI.new(oauth_access_token)
15
+ profile = graph.get_object("me")
16
+ friends = graph.get_connections("me", "friends")
17
+ graph.put_object("me", "feed", :message => "I am writing on my wall!")
18
+
19
+ The response of most requests is the JSON data returned from the Facebook servers as a Hash.
20
+
21
+ When retrieving data that returns an array of results (for example, when calling GraphAPI#get_connections or GraphAPI#search) a GraphCollection object (a sub-class of Array) will be returned, which contains added methods for getting the next and previous page of results:
22
+
23
+ # Returns the feed items for the currently logged-in user as a GraphCollection
24
+ feed = graph.get_connections("me", "feed")
25
+
26
+ # GraphCollection is a sub-class of Array, so you can use it as a usual Array
27
+ first_entry = feed[0]
28
+ last_entry = feed.last
29
+
30
+ # Returns the next page of results (also as a GraphCollection)
31
+ next_feed = feed.next_page
32
+
33
+ # Returns an array describing the URL for the next page: [path, arguments]
34
+ # This is useful for paging across multiple requests
35
+ next_path, next_args = feed.next_page_params
36
+
37
+ # You can use those params to easily get the next (or prevous) page
38
+ page = graph.get_page(feed.next_page_params)
39
+
40
+ Check out the wiki for more examples.
41
+
42
+ The old-school REST API
43
+ -----
44
+ Where the Graph API and the old REST API overlap, you should choose the Graph API. Unfortunately, that overlap is far from complete, and there are many important API calls that can't yet be done via the Graph.
45
+
46
+ Koala now supports the old-school REST API using OAuth access tokens; to use this, instantiate your class using the RestAPI class:
47
+
48
+ @rest = Koala::Facebook::RestAPI.new(oauth_access_token)
49
+ @rest.fql_query(my_fql_query) # convenience method
50
+ @rest.rest_call("stream.publish", arguments_hash) # generic version
51
+
52
+ We reserve the right to expand the built-in REST API coverage to additional convenience methods in the future, depending on how fast Facebook moves to fill in the gaps.
53
+
54
+ (If you want the power of both APIs in the palm of your hand, try out the GraphAndRestAPI class.)
55
+
56
+ OAuth
57
+ -----
58
+ You can use the Graph and REST APIs without an OAuth access token, but the real magic happens when you provide Facebook an OAuth token to prove you're authenticated. Koala provides an OAuth class to make that process easy:
59
+ @oauth = Koala::Facebook::OAuth.new(app_id, code, callback_url)
60
+
61
+ If your application uses Koala and the Facebook [JavaScript SDK](http://github.com/facebook/connect-js) (formerly Facebook Connect), you can use the OAuth class to parse the cookies:
62
+ @oauth.get_user_from_cookie(cookies)
63
+
64
+ And if you have to use the more complicated [redirect-based OAuth process](http://developers.facebook.com/docs/authentication/), Koala helps out there, too:
65
+ # generate authenticating URL
66
+ @oauth.url_for_oauth_code
67
+ # fetch the access token once you have the code
68
+ @oauth.get_access_token(code)
69
+
70
+ You can also get your application's own access token, which can be used without a user session for subscriptions and certain other requests:
71
+ @oauth.get_app_access_token
72
+
73
+ That's it! It's pretty simple once you get the hang of it. If you're new to OAuth, though, check out the wiki and the OAuth Playground example site (see below).
74
+
75
+ *Signed Requests:* Excited to try out the new signed request authentication scheme? Good news! Koala now supports parsing those parameters:
76
+ @oauth.parse_signed_request(request)
77
+
78
+ *Exchanging session keys:* Stuck building tab applications on Facebook? Wishing you had an OAuth token so you could use the Graph API? You're in luck! Koala now allows you to exchange session keys for OAuth access tokens:
79
+ @oauth.get_token_from_session_key(session_key)
80
+ @oauth.get_tokens_from_session_keys(array_of_session_keys)
81
+
82
+ Real-time Updates
83
+ -----
84
+ The Graph API now allows your application to subscribe to real-time updates for certain objects in the graph.
85
+
86
+ Currently, Facebook only supports subscribing to users, permissions and errors. On top of that, there are limitations on what attributes and connections for each of these objects you can subscribe to updates for. Check the [official Facebook documentation](http://developers.facebook.com/docs/api/realtime) for more details.
87
+
88
+ Koala makes it easy to interact with your applications using the RealtimeUpdates class:
89
+
90
+ @updates = Koala::Facebook::RealtimeUpdates.new(:app_id => app_id, :secret => secret)
91
+
92
+ You can do just about anything with your real-time update subscriptions using the RealtimeUpdates class:
93
+
94
+ # Add/modify a subscription to updates for when the first_name or last_name fields of any of your users is changed
95
+ @updates.subscribe("user", "first_name, last_name", callback_token, verify_token)
96
+
97
+ # Get an array of your current subscriptions (one hash for each object you've subscribed to)
98
+ @updates.list_subscriptions
99
+
100
+ # Unsubscribe from updates for an object
101
+ @updates.unsubscribe("user")
102
+
103
+ And to top it all off, RealtimeUpdates provides a static method to respond to Facebook servers' verification of your callback URLs:
104
+
105
+ # Returns the hub.challenge parameter in params if the verify token in params matches verify_token
106
+ Koala::Facebook::RealtimeUpdates.meet_challenge(params, your_verify_token)
107
+
108
+ For more information about meet_challenge and the RealtimeUpdates class, check out the Real-Time Updates page on the wiki.
109
+
110
+ See examples, ask questions
111
+ -----
112
+ Some resources to help you as you play with Koala and the Graph API:
113
+
114
+ * Complete Koala documentation <a href="http://wiki.github.com/arsduo/koala/">on the wiki</a>
115
+ * The <a href="http://groups.google.com/group/koala-users">Koala users group</a> on Google Groups, the place for your Koala and API questions
116
+ * The Koala-powered <a href="http://oauth.twoalex.com" target="_blank">OAuth Playground</a>, where you can easily generate OAuth access tokens and any other data needed to test out the APIs or OAuth
117
+
118
+ Testing
119
+ -----
120
+
121
+ Unit tests are provided for all of Koala's methods. By default, these tests run against mock responses and hence are ready out of the box:
122
+ # From the spec directory
123
+ spec koala_spec.rb
124
+
125
+ You can also run live tests against Facebook's servers:
126
+ # Again from the spec directory
127
+ spec koala_spec_without_mocks.rb
128
+
129
+ Important Note: to run the live tests, you have to provide some of your own data: a valid OAuth access token with publish\_stream and read\_stream permissions and an OAuth code that can be used to generate an access token. You can get these data at the OAuth Playground; if you want to use your own app, remember to swap out the app ID, secret, and other values. (The file also provides valid values for other tests, which you're welcome to swap out for data specific to your own application.)