Updated documentation on User-Agent.
[arvados.git] / lib / google / api_client.rb
1 # Copyright 2010 Google Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 require 'httpadapter'
17 require 'json'
18 require 'stringio'
19
20 require 'google/api_client/errors'
21 require 'google/api_client/environment'
22 require 'google/api_client/discovery'
23
24 module Google
25   # TODO(bobaman): Document all this stuff.
26
27
28   ##
29   # This class manages APIs communication.
30   class APIClient
31     ##
32     # Creates a new Google API client.
33     #
34     # @param [Hash] options The configuration parameters for the client.
35     # @option options [Symbol, #generate_authenticated_request] :authorization
36     #   (:oauth_1)
37     #   The authorization mechanism used by the client.  The following
38     #   mechanisms are supported out-of-the-box:
39     #   <ul>
40     #     <li><code>:two_legged_oauth_1</code></li>
41     #     <li><code>:oauth_1</code></li>
42     #     <li><code>:oauth_2</code></li>
43     #   </ul>
44     # @option options [String] :host ("www.googleapis.com")
45     #   The API hostname used by the client.  This rarely needs to be changed.
46     # @option options [String] :application_name
47     #   The name and version of the application using the client. This should
48     #   be given in the form `"{name}/{version}"`.
49     # @option options [String] :user_agent
50     #   ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
51     #   The user agent used by the client.  Most developers will want to
52     #   leave this value alone and use the `:application_name` option instead.
53     def initialize(options={})
54       # Normalize key to String to allow indifferent access.
55       options = options.inject({}) do |accu, (key, value)|
56         accu[key.to_s] = value
57         accu
58       end
59       # Almost all API usage will have a host of 'www.googleapis.com'.
60       self.host = options["host"] || 'www.googleapis.com'
61       # Most developers will want to leave this value alone and use the
62       # application_name option.
63       self.user_agent = options["user_agent"] || (
64         (options["application_name"] || '')
65         'google-api-ruby-client/' + VERSION::STRING +
66         ' ' + ENV::OS_VERSION
67       ).strip
68       # This is mostly a default for the sake of convenience.
69       # Unlike most other options, this one may be nil, so we check for
70       # the presence of the key rather than checking the value.
71       if options.has_key?("parser")
72         self.parser = options["parser"]
73       else
74         require 'google/api_client/parsers/json_parser'
75         # NOTE: Do not rely on this default value, as it may change
76         self.parser = Google::APIClient::JSONParser
77       end
78       # The writer method understands a few Symbols and will generate useful
79       # default authentication mechanisms.
80       self.authorization = options["authorization"] || :oauth_2
81       # The HTTP adapter controls all of the HTTP traffic the client generates.
82       # By default, Net::HTTP is used, but adding support for other clients
83       # is trivial.
84       if options["http_adapter"]
85         self.http_adapter = options["http_adapter"]
86       else
87         require 'httpadapter/adapters/net_http'
88         # NOTE: Do not rely on this default value, as it may change
89         self.http_adapter = HTTPAdapter::NetHTTPAdapter.new
90       end
91       @discovery_uris = {}
92       @discovery_documents = {}
93       @discovered_apis = {}
94       return self
95     end
96
97
98     ##
99     # Returns the parser used by the client.
100     #
101     # @return [#serialize, #parse]
102     #   The parser used by the client.  Any object that implements both a
103     #   <code>#serialize</code> and a <code>#parse</code> method may be used.
104     #   If <code>nil</code>, no parsing will be done.
105     attr_reader :parser
106
107     ##
108     # Sets the parser used by the client.
109     #
110     # @param [#serialize, #parse] new_parser
111     #   The parser used by the client.  Any object that implements both a
112     #   <code>#serialize</code> and a <code>#parse</code> method may be used.
113     #   If <code>nil</code>, no parsing will be done.
114     def parser=(new_parser)
115       if new_parser &&
116           !new_parser.respond_to?(:serialize) &&
117           !new_parser.respond_to?(:parse)
118         raise TypeError,
119           'Expected parser object to respond to #serialize and #parse.'
120       end
121       @parser = new_parser
122     end
123
124     ##
125     # Returns the authorization mechanism used by the client.
126     #
127     # @return [#generate_authenticated_request] The authorization mechanism.
128     attr_reader :authorization
129
130     ##
131     # Sets the authorization mechanism used by the client.
132     #
133     # @param [#generate_authenticated_request] new_authorization
134     #   The new authorization mechanism.
135     def authorization=(new_authorization)
136       case new_authorization
137       when :oauth_1, :oauth
138         require 'signet/oauth_1/client'
139         # NOTE: Do not rely on this default value, as it may change
140         new_authorization = Signet::OAuth1::Client.new(
141           :temporary_credential_uri =>
142             'https://www.google.com/accounts/OAuthGetRequestToken',
143           :authorization_uri =>
144             'https://www.google.com/accounts/OAuthAuthorizeToken',
145           :token_credential_uri =>
146             'https://www.google.com/accounts/OAuthGetAccessToken',
147           :client_credential_key => 'anonymous',
148           :client_credential_secret => 'anonymous'
149         )
150       when :two_legged_oauth_1, :two_legged_oauth
151         require 'signet/oauth_1/client'
152         # NOTE: Do not rely on this default value, as it may change
153         new_authorization = Signet::OAuth1::Client.new(
154           :client_credential_key => nil,
155           :client_credential_secret => nil,
156           :two_legged => true
157         )
158       when :oauth_2
159         require 'signet/oauth_2/client'
160         # NOTE: Do not rely on this default value, as it may change
161         new_authorization = Signet::OAuth2::Client.new(
162           :authorization_uri =>
163             'https://accounts.google.com/o/oauth2/auth',
164           :token_credential_uri =>
165             'https://accounts.google.com/o/oauth2/token'
166         )
167       when nil
168         # No authorization mechanism
169       else
170         if !new_authorization.respond_to?(:generate_authenticated_request)
171           raise TypeError,
172             'Expected authorization mechanism to respond to ' +
173             '#generate_authenticated_request.'
174         end
175       end
176       @authorization = new_authorization
177       return @authorization
178     end
179
180     ##
181     # Returns the HTTP adapter used by the client.
182     #
183     # @return [HTTPAdapter]
184     #   The HTTP adapter object.  The object must include the
185     #   HTTPAdapter module and conform to its interface.
186     attr_reader :http_adapter
187
188     ##
189     # Returns the HTTP adapter used by the client.
190     #
191     # @return [HTTPAdapter]
192     #   The HTTP adapter object.  The object must include the
193     #   HTTPAdapter module and conform to its interface.
194     def http_adapter=(new_http_adapter)
195       if new_http_adapter.kind_of?(HTTPAdapter)
196         @http_adapter = new_http_adapter
197       else
198         raise TypeError, "Expected HTTPAdapter, got #{new_http_adapter.class}."
199       end
200     end
201
202     ##
203     # The API hostname used by the client.
204     #
205     # @return [String]
206     #   The API hostname.  Should almost always be 'www.googleapis.com'.
207     attr_accessor :host
208
209     ##
210     # The user agent used by the client.
211     #
212     # @return [String]
213     #   The user agent string used in the User-Agent header.
214     attr_accessor :user_agent
215
216     ##
217     # Returns the URI for the directory document.
218     #
219     # @return [Addressable::URI] The URI of the directory document.
220     def directory_uri
221       template = Addressable::Template.new(
222         "https://{host}/discovery/v0.3/directory"
223       )
224       return template.expand({
225         "host" => self.host
226       })
227     end
228
229     ##
230     # Manually registers a URI as a discovery document for a specific version
231     # of an API.
232     #
233     # @param [String, Symbol] api The service name.
234     # @param [String] version The desired version of the service.
235     # @param [Addressable::URI] uri The URI of the discovery document.
236     def register_discovery_uri(api, version, uri)
237       api = api.to_s
238       version = version || 'v1'
239       @discovery_uris["#{api}:#{version}"] = uri
240     end
241
242     ##
243     # Returns the URI for the discovery document.
244     #
245     # @param [String, Symbol] api The service name.
246     # @param [String] version The desired version of the service.
247     # @return [Addressable::URI] The URI of the discovery document.
248     def discovery_uri(api, version=nil)
249       api = api.to_s
250       version = version || 'v1'
251       return @discovery_uris["#{api}:#{version}"] ||= (begin
252         template = Addressable::Template.new(
253           "https://{host}/discovery/v0.3/describe/" +
254           "{api}/{version}"
255         )
256         template.expand({
257           "host" => self.host,
258           "api" => api,
259           "version" => version
260         })
261       end)
262     end
263
264     ##
265     # Manually registers a pre-loaded discovery document for a specific version
266     # of an API.
267     #
268     # @param [String, Symbol] api The service name.
269     # @param [String] version The desired version of the service.
270     # @param [String, StringIO] discovery_document
271     #   The contents of the discovery document.
272     def register_discovery_document(api, version, discovery_document)
273       api = api.to_s
274       version = version || 'v1'
275       if discovery_document.kind_of?(StringIO)
276         discovery_document.rewind
277         discovery_document = discovery_document.string
278       elsif discovery_document.respond_to?(:to_str)
279         discovery_document = discovery_document.to_str
280       else
281         raise TypeError,
282           "Expected String or StringIO, got #{discovery_document.class}."
283       end
284       @discovery_documents["#{api}:#{version}"] =
285         JSON.parse(discovery_document)
286     end
287
288     ##
289     # Returns the parsed directory document.
290     #
291     # @return [Hash] The parsed JSON from the directory document.
292     def directory_document
293       return @directory_document ||= (begin
294         request_uri = self.directory_uri
295         request = ['GET', request_uri, [], []]
296         response = self.transmit_request(request)
297         status, headers, body = response
298         if status == 200 # TODO(bobaman) Better status code handling?
299           merged_body = StringIO.new
300           body.each do |chunk|
301             merged_body.write(chunk)
302           end
303           merged_body.rewind
304           JSON.parse(merged_body.string)
305         else
306           raise TransmissionError,
307             "Could not retrieve discovery document at: #{request_uri}"
308         end
309       end)
310     end
311
312     ##
313     # Returns the parsed discovery document.
314     #
315     # @param [String, Symbol] api The service name.
316     # @param [String] version The desired version of the service.
317     # @return [Hash] The parsed JSON from the discovery document.
318     def discovery_document(api, version=nil)
319       api = api.to_s
320       version = version || 'v1'
321       return @discovery_documents["#{api}:#{version}"] ||= (begin
322         request_uri = self.discovery_uri(api, version)
323         request = ['GET', request_uri, [], []]
324         response = self.transmit_request(request)
325         status, headers, body = response
326         if status == 200 # TODO(bobaman) Better status code handling?
327           merged_body = StringIO.new
328           body.each do |chunk|
329             merged_body.write(chunk)
330           end
331           merged_body.rewind
332           JSON.parse(merged_body.string)
333         else
334           raise TransmissionError,
335             "Could not retrieve discovery document at: #{request_uri}"
336         end
337       end)
338     end
339
340     ##
341     # Returns all APIs published in the directory document.
342     #
343     # @return [Array] The list of available APIs.
344     def discovered_apis
345       @directory_apis ||= (begin
346         document_base = self.directory_uri
347         if self.directory_document && self.directory_document['items']
348           self.directory_document['items'].map do |discovery_document|
349             ::Google::APIClient::API.new(
350               document_base,
351               discovery_document
352             )
353           end
354         else
355           []
356         end
357       end)
358     end
359
360     ##
361     # Returns the service object for a given service name and service version.
362     #
363     # @param [String, Symbol] api The service name.
364     # @param [String] version The desired version of the service.
365     #
366     # @return [Google::APIClient::API] The service object.
367     def discovered_api(api, version=nil)
368       if !api.kind_of?(String) && !api.kind_of?(Symbol)
369         raise TypeError,
370           "Expected String or Symbol, got #{api.class}."
371       end
372       api = api.to_s
373       version = version || 'v1'
374       return @discovered_apis["#{api}:#{version}"] ||= begin
375         document_base = self.discovery_uri(api, version)
376         discovery_document = self.discovery_document(api, version)
377         if document_base && discovery_document
378           ::Google::APIClient::API.new(
379             document_base,
380             discovery_document
381           )
382         else
383           nil
384         end
385       end
386     end
387
388     ##
389     # Returns the method object for a given RPC name and service version.
390     #
391     # @param [String, Symbol] rpc_name The RPC name of the desired method.
392     # @param [String] version The desired version of the service.
393     #
394     # @return [Google::APIClient::Method] The method object.
395     def discovered_method(rpc_name, api, version=nil)
396       if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
397         raise TypeError,
398           "Expected String or Symbol, got #{rpc_name.class}."
399       end
400       rpc_name = rpc_name.to_s
401       api = api.to_s
402       version = version || 'v1'
403       service = self.discovered_api(api, version)
404       if service.to_h[rpc_name]
405         return service.to_h[rpc_name]
406       else
407         return nil
408       end
409     end
410
411     ##
412     # Returns the service object with the highest version number.
413     #
414     # @note <em>Warning</em>: This method should be used with great care.
415     # As APIs are updated, minor differences between versions may cause
416     # incompatibilities. Requesting a specific version will avoid this issue.
417     #
418     # @param [String, Symbol] api The name of the service.
419     #
420     # @return [Google::APIClient::API] The service object.
421     def preferred_version(api)
422       if !api.kind_of?(String) && !api.kind_of?(Symbol)
423         raise TypeError,
424           "Expected String or Symbol, got #{api.class}."
425       end
426       api = api.to_s
427       # TODO(bobaman): Update to use directory API.
428       return self.discovered_apis.detect do |a|
429         a.name == api && a.preferred == true
430       end
431     end
432
433     ##
434     # Generates a request.
435     #
436     # @param [Google::APIClient::Method, String] api_method
437     #   The method object or the RPC name of the method being executed.
438     # @param [Hash, Array] parameters
439     #   The parameters to send to the method.
440     # @param [String] body The body of the request.
441     # @param [Hash, Array] headers The HTTP headers for the request.
442     # @param [Hash] options
443     #   The configuration parameters for the request.
444     #   - <code>:version</code> — 
445     #     The service version.  Only used if <code>api_method</code> is a
446     #     <code>String</code>.  Defaults to <code>'v1'</code>.
447     #   - <code>:parser</code> — 
448     #     The parser for the response.
449     #   - <code>:authorization</code> — 
450     #     The authorization mechanism for the response.  Used only if
451     #     <code>:authenticated</code> is <code>true</code>.
452     #   - <code>:authenticated</code> — 
453     #     <code>true</code> if the request must be signed or otherwise
454     #     authenticated, <code>false</code>
455     #     otherwise.  Defaults to <code>true</code> if an authorization
456     #     mechanism has been set, <code>false</code> otherwise.
457     #
458     # @return [Array] The generated request.
459     #
460     # @example
461     #   request = client.generate_request(
462     #     'chili.activities.list',
463     #     {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
464     #   )
465     #   method, uri, headers, body = request
466     def generate_request(
467         api_method, parameters={}, body='', headers=[], options={})
468       options={
469         :parser => self.parser,
470         :version => 'v1',
471         :authorization => self.authorization
472       }.merge(options)
473       # The default value for the :authenticated option depends on whether an
474       # authorization mechanism has been set.
475       if options[:authorization]
476         options = {:authenticated => true}.merge(options)
477       else
478         options = {:authenticated => false}.merge(options)
479       end
480       if api_method.kind_of?(String) || api_method.kind_of?(Symbol)
481         api_method = api_method.to_s
482         # This method of guessing the API is unreliable. This will fail for
483         # APIs where the first segment of the RPC name does not match the
484         # service name. However, this is a fallback mechanism anyway.
485         # Developers should be passing in a reference to the method, rather
486         # than passing in a string or symbol. This should raise an error
487         # in the case of a mismatch.
488         api = api_method[/^([^.]+)\./, 1]
489         api_method = self.discovered_method(
490           api_method, api, options[:version]
491         )
492       elsif !api_method.kind_of?(::Google::APIClient::Method)
493         raise TypeError,
494           "Expected String, Symbol, or Google::APIClient::Method, " +
495           "got #{api_method.class}."
496       end
497       unless api_method
498         raise ArgumentError, "API method could not be found."
499       end
500       request = api_method.generate_request(parameters, body, headers)
501       if options[:authenticated]
502         request = self.generate_authenticated_request(:request => request)
503       end
504       return request
505     end
506
507     ##
508     # Generates a request and transmits it.
509     #
510     # @param [Google::APIClient::Method, String] api_method
511     #   The method object or the RPC name of the method being executed.
512     # @param [Hash, Array] parameters
513     #   The parameters to send to the method.
514     # @param [String] body The body of the request.
515     # @param [Hash, Array] headers The HTTP headers for the request.
516     # @param [Hash] options
517     #   The configuration parameters for the request.
518     #   - <code>:version</code> — 
519     #     The service version.  Only used if <code>api_method</code> is a
520     #     <code>String</code>.  Defaults to <code>'v1'</code>.
521     #   - <code>:adapter</code> — 
522     #     The HTTP adapter.
523     #   - <code>:parser</code> — 
524     #     The parser for the response.
525     #   - <code>:authorization</code> — 
526     #     The authorization mechanism for the response.  Used only if
527     #     <code>:authenticated</code> is <code>true</code>.
528     #   - <code>:authenticated</code> — 
529     #     <code>true</code> if the request must be signed or otherwise
530     #     authenticated, <code>false</code>
531     #     otherwise.  Defaults to <code>true</code>.
532     #
533     # @return [Array] The response from the API.
534     #
535     # @example
536     #   response = client.execute(
537     #     'chili.activities.list',
538     #     {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
539     #   )
540     #   status, headers, body = response
541     def execute(api_method, parameters={}, body='', headers=[], options={})
542       request = self.generate_request(
543         api_method, parameters, body, headers, options
544       )
545       return self.transmit_request(
546         request,
547         options[:adapter] || self.http_adapter
548       )
549     end
550
551     ##
552     # Transmits the request using the current HTTP adapter.
553     #
554     # @param [Array] request The request to transmit.
555     # @param [#transmit] adapter The HTTP adapter.
556     #
557     # @return [Array] The response from the server.
558     def transmit_request(request, adapter=self.http_adapter)
559       if self.user_agent != nil
560         # If there's no User-Agent header, set one.
561         method, uri, headers, body = request
562         unless headers.kind_of?(Enumerable)
563           # We need to use some Enumerable methods, relying on the presence of
564           # the #each method.
565           class <<headers
566             include Enumerable
567           end
568         end
569         if self.user_agent.kind_of?(String)
570           unless headers.any? { |k, v| k.downcase == 'User-Agent'.downcase }
571             headers = headers.to_a.insert(0, ['User-Agent', self.user_agent])
572           end
573         elsif self.user_agent != nil
574           raise TypeError,
575             "Expected User-Agent to be String, got #{self.user_agent.class}"
576         end
577       end
578       adapter.transmit([method, uri, headers, body])
579     end
580
581     ##
582     # Signs a request using the current authorization mechanism.
583     #
584     # @param [Hash] options The options to pass through.
585     #
586     # @return [Array] The signed or otherwise authenticated request.
587     def generate_authenticated_request(options={})
588       return authorization.generate_authenticated_request(options)
589     end
590   end
591 end
592
593 require 'google/api_client/version'