1 # Copyright 2010 Google Inc.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 require 'faraday/utils'
17 require 'faraday/request/multipart'
19 require 'compat/multi_json'
20 require 'addressable/uri'
22 require 'google/api_client/discovery'
23 require 'google/api_client/logging'
29 # Represents an API request.
31 include Google::APIClient::Logging
33 MULTIPART_BOUNDARY = "-----------RubyApiMultipartPost".freeze
35 # @return [Hash] Request parameters
36 attr_reader :parameters
37 # @return [Hash] Additional HTTP headers
39 # @return [Google::APIClient::Method] API method to invoke
40 attr_reader :api_method
41 # @return [Google::APIClient::UploadIO] File to upload
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
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
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]
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]
88 self.initialize_media_upload(options)
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])
98 unless self.api_method
99 self.http_method = options[:http_method] || 'GET'
100 self.uri = options[:uri]
104 # @!attribute [r] upload_type
105 # @return [String] protocol used for upload
107 return self.parameters['uploadType'] || self.parameters['upload_type']
110 # @!attribute http_method
111 # @return [Symbol] HTTP method if invoking a URI
113 return @http_method ||= self.api_method.http_method.to_s.downcase.to_sym
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
123 "Expected String or Symbol, got #{new_http_method.class}."
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
132 "Expected Google::APIClient::Method, got #{new_api_method.class}."
137 # @return [Addressable::URI] URI to send request
139 return @uri ||= self.api_method.generate_uri(self.parameters)
143 @uri = Addressable::URI.parse(new_uri)
144 @parameters.update(@uri.query_values) unless @uri.query_values.nil?
148 # Transmits the request with the given connection
152 # @param [Faraday::Connection] connection
153 # the connection to transmit with
155 # @return [Google::APIClient::Result]
156 # result of API request
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)
163 logger.debug { "#{self.class} Result: #{result.status} #{result.headers}" }
165 # Resumamble slightly different than other upload protocols in that it requires at least
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)
177 # Convert to an HTTP request. Returns components in order of method, URI,
178 # request headers, and body
182 # @return [Array<(Symbol, Addressable::URI, Hash, [#read,#to_str])>]
186 self.api_method.generate_request(self.parameters, self.body, self.headers)
188 unless self.parameters.empty?
189 self.uri.query = Addressable::URI.form_encode(self.parameters)
191 [self.http_method, self.uri.to_s, self.headers, self.body]
197 # Hashified verison of the API request
203 options[:api_method] = self.api_method
204 options[:parameters] = self.parameters
206 options[:http_method] = self.http_method
207 options[:uri] = self.uri
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
219 # Prepares the request for execution, building a hash of parts
220 # suitable for sending to Faraday::Connection.
224 # @param [Faraday::Connection] connection
225 # Connection for building the request
229 def to_env(connection)
230 method, uri, headers, body = self.to_http_request
231 http_request = connection.build_request(method) do |req|
233 req.headers.update(headers)
237 if self.authorization.respond_to?(:generate_authenticated_request)
238 http_request = self.authorization.generate_authenticated_request(
239 :request => http_request,
240 :connection => connection
244 request_env = http_request.to_env(connection)
248 # Convert HTTP response to an API Result
252 # @param [Faraday::Response] response
255 # @return [Google::APIClient::Result]
256 # Processed API response
257 def process_http_response(response)
258 Result.new(self, response)
264 # Adjust headers & body for media uploads
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
282 if options[:body] || options[:body_object]
283 raise ArgumentError, "Can not specify body & body object for simple uploads"
285 self.headers['Content-Type'] ||= self.media.content_type
286 self.body = self.media
288 unless options[:body_object]
289 raise ArgumentError, "Multipart requested but no body object"
291 metadata = StringIO.new(serialize_body(options[:body_object]))
292 build_multipart([Faraday::UploadIO.new(metadata, 'application/json', 'file.json'), self.media])
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])
307 # Assemble a multipart message from a set of parts
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])
328 # Serialize body object to JSON
332 # @param [#to_json,#to_hash] body
333 # object to serialize
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.'