/
client.rb
306 lines (270 loc) · 11.1 KB
/
client.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
79
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
227
228
229
230
231
232
233
234
235
236
237
238
239
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
module Grackle
#Returned by methods which retrieve data from the API
class TwitterStruct < OpenStruct
attr_accessor :id
end
#Raised by methods which call the API if a non-200 response status is received
class TwitterError < StandardError
attr_accessor :method, :request_uri, :status, :response_body, :response_object
def initialize(method, request_uri, status, response_body, msg=nil)
self.method = method
self.request_uri = request_uri
self.status = status
self.response_body = response_body
super(msg||"#{self.method} #{self.request_uri} => #{self.status}: #{self.response_body}")
end
end
# The Client is the public interface to Grackle. You build Twitter API calls using method chains. See the README for details
# and new for information on valid options.
#
# ==Authentication
# Twitter is migrating to OAuth as the preferred mechanism for authentication (over HTTP basic auth). Grackle supports both methods.
# Typically you will supply Grackle with authentication information at the time you create your Grackle::Client via the :auth parameter.
# ===Basic Auth
# client = Grackle.Client.new(:auth=>{:type=>:basic,:username=>'twitteruser',:password=>'secret'})
# Please note that the original way of specifying basic authentication still works but is deprecated
# client = Grackle.Client.new(:username=>'twitteruser',:password=>'secret') #deprecated
#
# ===OAuth
# OAuth is a relatively complex topic. For more information on OAuth applications see the official OAuth site at http://oauth.net and the
# OAuth specification at http://oauth.net/core/1.0. For authentication using OAuth, you will need do the following:
# - Acquire a key and token for your application ("Consumer" in OAuth terms) from Twitter. Learn more here: http://apiwiki.twitter.com/OAuth-FAQ
# - Acquire an access token and token secret for the user that will be using OAuth to authenticate into Twitter
# The process of acquiring the access token and token secret are outside the scope of Grackle and will need to be coded on a per-application
# basis. Grackle comes into play once you've acquired all of the above pieces of information. To create a Grackle::Client that uses OAuth once
# you've got all the necessary tokens and keys:
# client = Grackle::Client.new(:auth=>{
# :type=>:oauth,
# :consumer_key=>'SOMECONSUMERKEYFROMTWITTER, :consumer_secret=>'SOMECONSUMERTOKENFROMTWITTER',
# :token=>'ACCESSTOKENACQUIREDONUSERSBEHALF', :token_secret=>'SUPERSECRETACCESSTOKENSECRET'
# })
class Client
class Request #:nodoc:
attr_accessor :client, :path, :method, :api, :ssl, :params
def initialize(client,api=:rest,ssl=true)
self.client = client
self.api = api
self.ssl = ssl
self.path = ''
end
def <<(path)
self.path << path
end
def path?
path.length > 0
end
def url
"#{scheme}://#{host}#{path}"
end
def host
client.api_hosts[api]
end
def scheme
ssl ? 'https' :'http'
end
def params
@params ||= {}
end
end
VALID_FORMATS = [:json,:xml,:atom,:rss]
# Contains the mapping of API name symbols to actual host (and path)
# prefixes to use with requests. You can add your own to this hash and
# refer to it wherever Grackle::Client uses an API symbol. You may wish
# to do this when Twitter introduces API versions greater than 1.
TWITTER_API_HOSTS = {
:search=>'search.twitter.com', :v1=>'api.twitter.com/1'
}
TWITTER_API_HOSTS[:rest] = TWITTER_API_HOSTS[:v1]
# Contains the response headers from twitter
DEFAULT_RESPONSE_HEADERS =[
'x-ratelimit-limit',
'x-ratelimit-remaining',
'x-ratelimit-reset'
]
#Basic OAuth information needed to communicate with Twitter
TWITTER_OAUTH_SPEC = {
:request_token_path=>'/oauth/request_token',
:access_token_path=>'/oauth/access_token',
:authorize_path=>'/oauth/authorize'
}
attr_accessor :auth, :handlers, :default_format, :headers, :ssl, :api,
:transport, :request, :api_hosts, :timeout, :auto_append_ids,
:auto_append_format, :response_headers, :response
# Arguments (all are optional):
# - :username - Twitter username to authenticate with (deprecated in favor of :auth arg)
# - :password - Twitter password to authenticate with (deprecated in favor of :auth arg)
# - :handlers - Hash of formats to Handler instances (e.g. {:json=>CustomJSONHandler.new})
# - :default_format - Symbol of format to use when no format is specified in an API call (e.g. :json, :xml)
# - :headers - Hash of string keys and values for headers to pass in the HTTP request to twitter
# - :ssl - true or false to turn SSL on or off. Default is off (i.e. http://)
# - :api - one of :rest, :search or :v1. :v1 is the default and :rest is now deprecated
# - :auth - Hash of authentication type and credentials. Must have :type key with value one of :basic or :oauth
# - :type=>:basic - Include :username and :password keys
# - :type=>:oauth - Include :consumer_key, :consumer_secret, :token and :token_secret keys
# - :auto_append_format - true or false to include format in URI (e.g. /test.json). Default is true
# - :response_headers - array of headers to return from the response
def initialize(options={})
self.transport = Transport.new
self.handlers = {:json=>Handlers::JSONHandler.new,:xml=>Handlers::XMLHandler.new,:unknown=>Handlers::StringHandler.new}
self.handlers.merge!(options[:handlers]||{})
self.default_format = options[:default_format] || :json
self.auto_append_format = options[:auto_append_format] == false ? false : true
self.headers = {"User-Agent"=>"Grackle/#{Grackle::VERSION}"}.merge!(options[:headers]||{})
self.ssl = options[:ssl] == true
self.api = options[:api] || :v1
self.api_hosts = TWITTER_API_HOSTS.clone
self.timeout = options[:timeout] || 60
self.auto_append_ids = options[:auto_append_ids] == false ? false : true
self.auth = {}
self.response_headers = options[:response_headers] || DEFAULT_RESPONSE_HEADERS
if options.has_key?(:username) || options.has_key?(:password)
#Use basic auth if :username and :password args are passed in
self.auth.merge!({:type=>:basic,:username=>options[:username],:password=>options[:password]})
end
#Handle auth mechanism that permits basic or oauth
if options.has_key?(:auth)
self.auth = options[:auth]
if auth[:type] == :oauth
self.auth = TWITTER_OAUTH_SPEC.merge(auth)
end
end
end
def method_missing(name,*args,&block)
if block_given?
return request_with_http_method_block(name,&block)
end
append(name,*args)
end
# Used to toggle APIs for a particular request without setting the Client's default API
# client[:rest].users.show.hayesdavis?
def [](api_name)
request.api = api_name
self
end
#Clears any pending request built up by chained methods but not executed
def clear
self.request = nil
end
#Deprecated in favor of using the auth attribute.
def username
if auth[:type] == :basic
auth[:username]
end
end
#Deprecated in favor of using the auth attribute.
def username=(value)
unless auth[:type] == :basic
auth[:type] = :basic
end
auth[:username] = value
end
#Deprecated in favor of using the auth attribute.
def password
if auth[:type] == :basic
auth[:password]
end
end
#Deprecated in favor of using the auth attribute.
def password=(value)
unless auth[:type] == :basic
auth[:type] = :basic
end
auth[:password] = value
end
def append(name,*args)
name = name.to_s.to_sym
#The args will be a hash, store them if they're specified
self.request.params = args.first
#If method is a format name, execute using that format
if format_invocation?(name)
return call_with_format(name)
end
#If method ends in ! or ? use that to determine post or get
if name.to_s =~ /^(.*)(!|\?)$/
name = $1.to_sym
#! is a post, ? is a get - only set this if the method hasn't been set
self.request.method ||= ($2 == '!' ? :post : :get)
if format_invocation?(name)
return call_with_format(name)
else
self.request << "/#{$1}"
return call_with_format(self.default_format)
end
end
#Else add to the request path
self.request << "/#{name}"
self
end
alias_method :_, :append
protected
def call_with_format(format)
if auto_append_ids
id = request.params.delete(:id)
request << "/#{id}" if id
end
if auto_append_format
request << ".#{format}"
end
res = send_request
process_response(format,res)
ensure
clear
end
def send_request
begin
http_method = (
request.params.delete(:__method) or request.method or :get
)
@response = transport.request(
http_method, request.url,
:auth=>auth,:headers=>headers,
:params=>request.params,:timeout=>timeout,
:response_headers=>response_headers
)
rescue => e
puts e
raise TwitterError.new(request.method,request.url,nil,nil,"Unexpected failure making request: #{e}")
end
end
def process_response(format,res)
fmt_handler = handler(format)
begin
unless res.status == 200
handle_error_response(res,fmt_handler)
else
fmt_handler.decode_response(res.body)
end
rescue TwitterError => e
raise e
rescue => e
raise TwitterError.new(res.method,res.request_uri,res.status,res.body,"Unable to decode response: #{e}")
end
end
def request
@request ||= Request.new(self,api,ssl)
end
def handler(format)
handlers[format] || handlers[:unknown]
end
def handle_error_response(res,handler)
err = TwitterError.new(res.method,res.request_uri,res.status,res.body)
err.response_object = handler.decode_response(err.response_body)
raise err
end
def format_invocation?(name)
self.request.path? && VALID_FORMATS.include?(name)
end
def pending_request?
!@request.nil?
end
def request_with_http_method_block(method,&block)
request.method = method
response = instance_eval(&block)
if pending_request?
call_with_format(self.default_format)
else
response
end
end
end
end