Merge branch 'master' of https://github.com/google/google-api-ruby-client
[arvados.git] / lib / google / api_client / request.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 require 'faraday'
16 require 'faraday/utils'
17 require 'faraday/request/multipart'
18 require 'multi_json'
19 require 'compat/multi_json'
20 require 'addressable/uri'
21 require 'stringio'
22 require 'google/api_client/discovery'
23 require 'google/api_client/logging'
24
25 module Google
26   class APIClient
27
28     ##
29     # Represents an API request.
30     class Request
31       include Google::APIClient::Logging
32       
33       MULTIPART_BOUNDARY = "-----------RubyApiMultipartPost".freeze
34
35       # @return [Hash] Request parameters
36       attr_reader :parameters
37       # @return [Hash] Additional HTTP headers
38       attr_reader :headers
39       # @return [Google::APIClient::Method] API method to invoke
40       attr_reader :api_method
41       # @return [Google::APIClient::UploadIO] File to upload
42       attr_accessor :media
43       # @return [#generated_authenticated_request] User credentials
44       attr_accessor :authorization
45       # @return [TrueClass,FalseClass] True if request should include credentials
46       attr_accessor :authenticated
47       # @return [#read, #to_str] Request body
48       attr_accessor :body
49
50       ##
51       # Build a request
52       #
53       # @param [Hash] options
54       # @option options [Hash, Array] :parameters
55       #   Request parameters for the API method.
56       # @option options [Google::APIClient::Method] :api_method
57       #   API method to invoke. Either :api_method or :uri must be specified
58       # @option options [TrueClass, FalseClass] :authenticated
59       #   True if request should include credentials. Implicitly true if
60       #   unspecified and :authorization present
61       # @option options [#generate_signed_request] :authorization
62       #   OAuth credentials
63       # @option options [Google::APIClient::UploadIO] :media
64       #   File to upload, if media upload request
65       # @option options [#to_json, #to_hash] :body_object
66       #   Main body of the API request. Typically hash or object that can
67       #   be serialized to JSON
68       # @option options [#read, #to_str] :body
69       #   Raw body to send in POST/PUT requests
70       # @option options [String, Addressable::URI] :uri
71       #   URI to request. Either :api_method or :uri must be specified
72       # @option options [String, Symbol] :http_method
73       #   HTTP method when requesting a URI
74       def initialize(options={})
75         @parameters = Faraday::Utils::ParamsHash[options[:parameters] || {}]
76         @headers = Faraday::Utils::Headers.new
77         self.headers.merge!(options[:headers]) unless options[:headers].nil?
78         self.api_method = options[:api_method]
79         self.authenticated = options[:authenticated]
80         self.authorization = options[:authorization]
81
82         # These parameters are handled differently because they're not
83         # parameters to the API method, but rather to the API system.
84         self.parameters['key'] ||= options[:key] if options[:key]
85         self.parameters['userIp'] ||= options[:user_ip] if options[:user_ip]
86
87         if options[:media]
88           self.initialize_media_upload(options)
89         elsif options[:body]
90           self.body = options[:body]
91         elsif options[:body_object]
92           self.headers['Content-Type'] ||= 'application/json'
93           self.body = serialize_body(options[:body_object])
94         else
95           self.body = ''
96         end
97
98         unless self.api_method
99           self.http_method = options[:http_method] || 'GET'
100           self.uri = options[:uri]
101         end
102       end
103
104       # @!attribute [r] upload_type
105       # @return [String] protocol used for upload
106       def upload_type
107         return self.parameters['uploadType'] || self.parameters['upload_type']
108       end
109
110       # @!attribute http_method
111       # @return [Symbol] HTTP method if invoking a URI
112       def http_method
113         return @http_method ||= self.api_method.http_method.to_s.downcase.to_sym
114       end
115
116       def http_method=(new_http_method)
117         if new_http_method.kind_of?(Symbol)
118           @http_method = new_http_method.to_s.downcase.to_sym
119         elsif new_http_method.respond_to?(:to_str)
120           @http_method = new_http_method.to_s.downcase.to_sym
121         else
122           raise TypeError,
123             "Expected String or Symbol, got #{new_http_method.class}."
124         end
125       end
126
127       def api_method=(new_api_method)
128         if new_api_method.nil? || new_api_method.kind_of?(Google::APIClient::Method)
129           @api_method = new_api_method
130         else
131           raise TypeError,
132             "Expected Google::APIClient::Method, got #{new_api_method.class}."
133         end
134       end
135
136       # @!attribute uri
137       # @return [Addressable::URI] URI to send request
138       def uri
139         return @uri ||= self.api_method.generate_uri(self.parameters)
140       end
141
142       def uri=(new_uri)
143         @uri = Addressable::URI.parse(new_uri)
144         @parameters.update(@uri.query_values) unless @uri.query_values.nil?
145       end
146
147
148       # Transmits the request with the given connection
149       #
150       # @api private
151       #
152       # @param [Faraday::Connection] connection
153       #   the connection to transmit with
154       #
155       # @return [Google::APIClient::Result]
156       #   result of API request
157       def send(connection)
158         env = self.to_env(connection)
159         logger.debug  { "#{self.class} Sending API request #{env[:method]} #{env[:url].to_s} #{env[:request_headers]}" }
160         http_response = connection.app.call(env)
161         result = self.process_http_response(http_response)
162
163         logger.debug { "#{self.class} Result: #{result.status} #{result.headers}" }
164
165         # Resumamble slightly different than other upload protocols in that it requires at least
166         # 2 requests.
167         if result.status == 200 && self.upload_type == 'resumable'
168           upload = result.resumable_upload
169           unless upload.complete?
170             logger.debug { "#{self.class} Sending upload body" }
171             result = upload.send(connection)
172           end
173         end
174         return result
175       end
176
177       # Convert to an HTTP request. Returns components in order of method, URI,
178       # request headers, and body
179       #
180       # @api private
181       #
182       # @return [Array<(Symbol, Addressable::URI, Hash, [#read,#to_str])>]
183       def to_http_request
184         request = (
185           if self.api_method
186             self.api_method.generate_request(self.parameters, self.body, self.headers)
187           elsif self.uri
188             unless self.parameters.empty?
189               self.uri.query = Addressable::URI.form_encode(self.parameters)
190             end
191             [self.http_method, self.uri.to_s, self.headers, self.body]
192           end)
193         return request
194       end
195
196       ##
197       # Hashified verison of the API request
198       #
199       # @return [Hash]
200       def to_hash
201         options = {}
202         if self.api_method
203           options[:api_method] = self.api_method
204           options[:parameters] = self.parameters
205         else
206           options[:http_method] = self.http_method
207           options[:uri] = self.uri
208         end
209         options[:headers] = self.headers
210         options[:body] = self.body
211         options[:media] = self.media
212         unless self.authorization.nil?
213           options[:authorization] = self.authorization
214         end
215         return options
216       end
217
218       ##
219       # Prepares the request for execution, building a hash of parts
220       # suitable for sending to Faraday::Connection.
221       #
222       # @api private
223       #
224       # @param [Faraday::Connection] connection
225       #   Connection for building the request
226       #
227       # @return [Hash]
228       #   Encoded request
229       def to_env(connection)
230         method, uri, headers, body = self.to_http_request
231         http_request = connection.build_request(method) do |req|
232           req.url(uri.to_s)
233           req.headers.update(headers)
234           req.body = body
235         end
236
237         if self.authorization.respond_to?(:generate_authenticated_request)
238           http_request = self.authorization.generate_authenticated_request(
239             :request => http_request,
240             :connection => connection
241           )
242         end
243
244         request_env = http_request.to_env(connection)
245       end
246
247       ##
248       # Convert HTTP response to an API Result
249       #
250       # @api private
251       #
252       # @param [Faraday::Response] response
253       #   HTTP response
254       #
255       # @return [Google::APIClient::Result]
256       #   Processed API response
257       def process_http_response(response)
258         Result.new(self, response)
259       end
260
261       protected
262
263       ##
264       # Adjust headers & body for media uploads
265       #
266       # @api private
267       #
268       # @param [Hash] options
269       # @option options [Hash, Array] :parameters
270       #   Request parameters for the API method.
271       # @option options [Google::APIClient::UploadIO] :media
272       #   File to upload, if media upload request
273       # @option options [#to_json, #to_hash] :body_object
274       #   Main body of the API request. Typically hash or object that can
275       #   be serialized to JSON
276       # @option options [#read, #to_str] :body
277       #   Raw body to send in POST/PUT requests
278       def initialize_media_upload(options)
279         self.media = options[:media]
280         case self.upload_type
281         when "media"
282           if options[:body] || options[:body_object]
283             raise ArgumentError, "Can not specify body & body object for simple uploads"
284           end
285           self.headers['Content-Type'] ||= self.media.content_type
286           self.body = self.media
287         when "multipart"
288           unless options[:body_object]
289             raise ArgumentError, "Multipart requested but no body object"
290           end
291           metadata = StringIO.new(serialize_body(options[:body_object]))
292           build_multipart([Faraday::UploadIO.new(metadata, 'application/json', 'file.json'), self.media])
293         when "resumable"
294           file_length = self.media.length
295           self.headers['X-Upload-Content-Type'] = self.media.content_type
296           self.headers['X-Upload-Content-Length'] = file_length.to_s
297           if options[:body_object]
298             self.headers['Content-Type'] ||= 'application/json'
299             self.body = serialize_body(options[:body_object])
300           else
301             self.body = ''
302           end
303         end
304       end
305
306       ##
307       # Assemble a multipart message from a set of parts
308       #
309       # @api private
310       #
311       # @param [Array<[#read,#to_str]>] parts
312       #   Array of parts to encode.
313       # @param [String] mime_type
314       #   MIME type of the message
315       # @param [String] boundary
316       #   Boundary for separating each part of the message
317       def build_multipart(parts, mime_type = 'multipart/related', boundary = MULTIPART_BOUNDARY)
318         env = Faraday::Env.new
319         env.request = Faraday::RequestOptions.new
320         env.request.boundary = boundary
321         env.request_headers = {'Content-Type' => "#{mime_type};boundary=#{boundary}"}
322         multipart = Faraday::Request::Multipart.new
323         self.body = multipart.create_multipart(env, parts.map {|part| [nil, part]})
324         self.headers.update(env[:request_headers])
325       end
326
327       ##
328       # Serialize body object to JSON
329       #
330       # @api private
331       #
332       # @param [#to_json,#to_hash] body
333       #   object to serialize
334       #
335       # @return [String]
336       #   JSON
337       def serialize_body(body)
338         return body.to_json if body.respond_to?(:to_json)
339         return MultiJson.dump(body.to_hash) if body.respond_to?(:to_hash)
340         raise TypeError, 'Could not convert body object to JSON.' +
341                          'Must respond to :to_json or :to_hash.'
342       end
343
344     end
345   end
346 end