Updated to use v1 of the discovery API.
[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/v1/apis"
223       )
224       return template.expand({"host" => self.host})
225     end
226
227     ##
228     # Manually registers a URI as a discovery document for a specific version
229     # of an API.
230     #
231     # @param [String, Symbol] api The service name.
232     # @param [String] version The desired version of the service.
233     # @param [Addressable::URI] uri The URI of the discovery document.
234     def register_discovery_uri(api, version, uri)
235       api = api.to_s
236       version = version || 'v1'
237       @discovery_uris["#{api}:#{version}"] = uri
238     end
239
240     ##
241     # Returns the URI for the discovery document.
242     #
243     # @param [String, Symbol] api The service name.
244     # @param [String] version The desired version of the service.
245     # @return [Addressable::URI] The URI of the discovery document.
246     def discovery_uri(api, version=nil)
247       api = api.to_s
248       version = version || 'v1'
249       return @discovery_uris["#{api}:#{version}"] ||= (begin
250         template = Addressable::Template.new(
251           "https://{host}/discovery/v1/apis/" +
252           "{api}/{version}/rest"
253         )
254         template.expand({
255           "host" => self.host,
256           "api" => api,
257           "version" => version
258         })
259       end)
260     end
261
262     ##
263     # Manually registers a pre-loaded discovery document for a specific version
264     # of an API.
265     #
266     # @param [String, Symbol] api The service name.
267     # @param [String] version The desired version of the service.
268     # @param [String, StringIO] discovery_document
269     #   The contents of the discovery document.
270     def register_discovery_document(api, version, discovery_document)
271       api = api.to_s
272       version = version || 'v1'
273       if discovery_document.kind_of?(StringIO)
274         discovery_document.rewind
275         discovery_document = discovery_document.string
276       elsif discovery_document.respond_to?(:to_str)
277         discovery_document = discovery_document.to_str
278       else
279         raise TypeError,
280           "Expected String or StringIO, got #{discovery_document.class}."
281       end
282       @discovery_documents["#{api}:#{version}"] =
283         JSON.parse(discovery_document)
284     end
285
286     ##
287     # Returns the parsed directory document.
288     #
289     # @return [Hash] The parsed JSON from the directory document.
290     def directory_document
291       return @directory_document ||= (begin
292         request_uri = self.directory_uri
293         request = ['GET', request_uri, [], []]
294         response = self.transmit_request(request)
295         status, headers, body = response
296         if status == 200 # TODO(bobaman) Better status code handling?
297           merged_body = StringIO.new
298           body.each do |chunk|
299             merged_body.write(chunk)
300           end
301           merged_body.rewind
302           JSON.parse(merged_body.string)
303         else
304           raise TransmissionError,
305             "Could not retrieve discovery document at: #{request_uri}"
306         end
307       end)
308     end
309
310     ##
311     # Returns the parsed discovery document.
312     #
313     # @param [String, Symbol] api The service name.
314     # @param [String] version The desired version of the service.
315     # @return [Hash] The parsed JSON from the discovery document.
316     def discovery_document(api, version=nil)
317       api = api.to_s
318       version = version || 'v1'
319       return @discovery_documents["#{api}:#{version}"] ||= (begin
320         request_uri = self.discovery_uri(api, version)
321         request = ['GET', request_uri, [], []]
322         response = self.transmit_request(request)
323         status, headers, body = response
324         if status == 200 # TODO(bobaman) Better status code handling?
325           merged_body = StringIO.new
326           body.each do |chunk|
327             merged_body.write(chunk)
328           end
329           merged_body.rewind
330           JSON.parse(merged_body.string)
331         else
332           raise TransmissionError,
333             "Could not retrieve discovery document at: #{request_uri}"
334         end
335       end)
336     end
337
338     ##
339     # Returns all APIs published in the directory document.
340     #
341     # @return [Array] The list of available APIs.
342     def discovered_apis
343       @directory_apis ||= (begin
344         document_base = self.directory_uri
345         if self.directory_document && self.directory_document['items']
346           self.directory_document['items'].map do |discovery_document|
347             ::Google::APIClient::API.new(
348               document_base,
349               discovery_document
350             )
351           end
352         else
353           []
354         end
355       end)
356     end
357
358     ##
359     # Returns the service object for a given service name and service version.
360     #
361     # @param [String, Symbol] api The service name.
362     # @param [String] version The desired version of the service.
363     #
364     # @return [Google::APIClient::API] The service object.
365     def discovered_api(api, version=nil)
366       if !api.kind_of?(String) && !api.kind_of?(Symbol)
367         raise TypeError,
368           "Expected String or Symbol, got #{api.class}."
369       end
370       api = api.to_s
371       version = version || 'v1'
372       return @discovered_apis["#{api}:#{version}"] ||= begin
373         document_base = self.discovery_uri(api, version)
374         discovery_document = self.discovery_document(api, version)
375         if document_base && discovery_document
376           ::Google::APIClient::API.new(
377             document_base,
378             discovery_document
379           )
380         else
381           nil
382         end
383       end
384     end
385
386     ##
387     # Returns the method object for a given RPC name and service version.
388     #
389     # @param [String, Symbol] rpc_name The RPC name of the desired method.
390     # @param [String] version The desired version of the service.
391     #
392     # @return [Google::APIClient::Method] The method object.
393     def discovered_method(rpc_name, api, version=nil)
394       if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
395         raise TypeError,
396           "Expected String or Symbol, got #{rpc_name.class}."
397       end
398       rpc_name = rpc_name.to_s
399       api = api.to_s
400       version = version || 'v1'
401       service = self.discovered_api(api, version)
402       if service.to_h[rpc_name]
403         return service.to_h[rpc_name]
404       else
405         return nil
406       end
407     end
408
409     ##
410     # Returns the service object with the highest version number.
411     #
412     # @note <em>Warning</em>: This method should be used with great care.
413     # As APIs are updated, minor differences between versions may cause
414     # incompatibilities. Requesting a specific version will avoid this issue.
415     #
416     # @param [String, Symbol] api The name of the service.
417     #
418     # @return [Google::APIClient::API] The service object.
419     def preferred_version(api)
420       if !api.kind_of?(String) && !api.kind_of?(Symbol)
421         raise TypeError,
422           "Expected String or Symbol, got #{api.class}."
423       end
424       api = api.to_s
425       # TODO(bobaman): Update to use directory API.
426       return self.discovered_apis.detect do |a|
427         a.name == api && a.preferred == true
428       end
429     end
430
431     ##
432     # Generates a request.
433     #
434     # @param [Google::APIClient::Method, String] api_method
435     #   The method object or the RPC name of the method being executed.
436     # @param [Hash, Array] parameters
437     #   The parameters to send to the method.
438     # @param [String] body The body of the request.
439     # @param [Hash, Array] headers The HTTP headers for the request.
440     # @param [Hash] options
441     #   The configuration parameters for the request.
442     #   - <code>:version</code> — 
443     #     The service version.  Only used if <code>api_method</code> is a
444     #     <code>String</code>.  Defaults to <code>'v1'</code>.
445     #   - <code>:parser</code> — 
446     #     The parser for the response.
447     #   - <code>:authorization</code> — 
448     #     The authorization mechanism for the response.  Used only if
449     #     <code>:authenticated</code> is <code>true</code>.
450     #   - <code>:authenticated</code> — 
451     #     <code>true</code> if the request must be signed or otherwise
452     #     authenticated, <code>false</code>
453     #     otherwise.  Defaults to <code>true</code> if an authorization
454     #     mechanism has been set, <code>false</code> otherwise.
455     #
456     # @return [Array] The generated request.
457     #
458     # @example
459     #   request = client.generate_request(
460     #     'chili.activities.list',
461     #     {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
462     #   )
463     #   method, uri, headers, body = request
464     def generate_request(
465         api_method, parameters={}, body='', headers=[], options={})
466       options={
467         :parser => self.parser,
468         :version => 'v1',
469         :authorization => self.authorization
470       }.merge(options)
471       # The default value for the :authenticated option depends on whether an
472       # authorization mechanism has been set.
473       if options[:authorization]
474         options = {:authenticated => true}.merge(options)
475       else
476         options = {:authenticated => false}.merge(options)
477       end
478       if api_method.kind_of?(String) || api_method.kind_of?(Symbol)
479         api_method = api_method.to_s
480         # This method of guessing the API is unreliable. This will fail for
481         # APIs where the first segment of the RPC name does not match the
482         # service name. However, this is a fallback mechanism anyway.
483         # Developers should be passing in a reference to the method, rather
484         # than passing in a string or symbol. This should raise an error
485         # in the case of a mismatch.
486         api = api_method[/^([^.]+)\./, 1]
487         api_method = self.discovered_method(
488           api_method, api, options[:version]
489         )
490       elsif !api_method.kind_of?(::Google::APIClient::Method)
491         raise TypeError,
492           "Expected String, Symbol, or Google::APIClient::Method, " +
493           "got #{api_method.class}."
494       end
495       unless api_method
496         raise ArgumentError, "API method could not be found."
497       end
498       request = api_method.generate_request(parameters, body, headers)
499       if options[:authenticated]
500         request = self.generate_authenticated_request(:request => request)
501       end
502       return request
503     end
504
505     ##
506     # Generates a request and transmits it.
507     #
508     # @param [Google::APIClient::Method, String] api_method
509     #   The method object or the RPC name of the method being executed.
510     # @param [Hash, Array] parameters
511     #   The parameters to send to the method.
512     # @param [String] body The body of the request.
513     # @param [Hash, Array] headers The HTTP headers for the request.
514     # @param [Hash] options
515     #   The configuration parameters for the request.
516     #   - <code>:version</code> — 
517     #     The service version.  Only used if <code>api_method</code> is a
518     #     <code>String</code>.  Defaults to <code>'v1'</code>.
519     #   - <code>:adapter</code> — 
520     #     The HTTP adapter.
521     #   - <code>:parser</code> — 
522     #     The parser for the response.
523     #   - <code>:authorization</code> — 
524     #     The authorization mechanism for the response.  Used only if
525     #     <code>:authenticated</code> is <code>true</code>.
526     #   - <code>:authenticated</code> — 
527     #     <code>true</code> if the request must be signed or otherwise
528     #     authenticated, <code>false</code>
529     #     otherwise.  Defaults to <code>true</code>.
530     #
531     # @return [Array] The response from the API.
532     #
533     # @example
534     #   response = client.execute(
535     #     'chili.activities.list',
536     #     {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
537     #   )
538     #   status, headers, body = response
539     def execute(api_method, parameters={}, body='', headers=[], options={})
540       request = self.generate_request(
541         api_method, parameters, body, headers, options
542       )
543       return self.transmit_request(
544         request,
545         options[:adapter] || self.http_adapter
546       )
547     end
548
549     ##
550     # Transmits the request using the current HTTP adapter.
551     #
552     # @param [Array] request The request to transmit.
553     # @param [#transmit] adapter The HTTP adapter.
554     #
555     # @return [Array] The response from the server.
556     def transmit_request(request, adapter=self.http_adapter)
557       if self.user_agent != nil
558         # If there's no User-Agent header, set one.
559         method, uri, headers, body = request
560         unless headers.kind_of?(Enumerable)
561           # We need to use some Enumerable methods, relying on the presence of
562           # the #each method.
563           class <<headers
564             include Enumerable
565           end
566         end
567         if self.user_agent.kind_of?(String)
568           unless headers.any? { |k, v| k.downcase == 'User-Agent'.downcase }
569             headers = headers.to_a.insert(0, ['User-Agent', self.user_agent])
570           end
571         elsif self.user_agent != nil
572           raise TypeError,
573             "Expected User-Agent to be String, got #{self.user_agent.class}"
574         end
575       end
576       adapter.transmit([method, uri, headers, body])
577     end
578
579     ##
580     # Signs a request using the current authorization mechanism.
581     #
582     # @param [Hash] options The options to pass through.
583     #
584     # @return [Array] The signed or otherwise authenticated request.
585     def generate_authenticated_request(options={})
586       return authorization.generate_authenticated_request(options)
587     end
588   end
589 end
590
591 require 'google/api_client/version'