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/request/multipart'
18 require 'compat/multi_json'
19 require 'addressable/uri'
21 require 'google/api_client/discovery'
22 require 'google/api_client/logging'
28 # Represents an API request.
30 include Google::APIClient::Logging
32 MULTIPART_BOUNDARY = "-----------RubyApiMultipartPost".freeze
34 # @return [Hash] Request parameters
35 attr_reader :parameters
36 # @return [Hash] Additional HTTP headers
38 # @return [Google::APIClient::Method] API method to invoke
39 attr_reader :api_method
40 # @return [Google::APIClient::UploadIO] File to upload
42 # @return [#generated_authenticated_request] User credentials
43 attr_accessor :authorization
44 # @return [TrueClass,FalseClass] True if request should include credentials
45 attr_accessor :authenticated
46 # @return [#read, #to_str] Request body
52 # @param [Hash] options
53 # @option options [Hash, Array] :parameters
54 # Request parameters for the API method.
55 # @option options [Google::APIClient::Method] :api_method
56 # API method to invoke. Either :api_method or :uri must be specified
57 # @option options [TrueClass, FalseClass] :authenticated
58 # True if request should include credentials. Implicitly true if
59 # unspecified and :authorization present
60 # @option options [#generate_signed_request] :authorization
62 # @option options [Google::APIClient::UploadIO] :media
63 # File to upload, if media upload request
64 # @option options [#to_json, #to_hash] :body_object
65 # Main body of the API request. Typically hash or object that can
66 # be serialized to JSON
67 # @option options [#read, #to_str] :body
68 # Raw body to send in POST/PUT requests
69 # @option options [String, Addressable::URI] :uri
70 # URI to request. Either :api_method or :uri must be specified
71 # @option options [String, Symbol] :http_method
72 # HTTP method when requesting a URI
73 def initialize(options={})
74 @parameters = Faraday::Utils::ParamsHash.new
75 @headers = Faraday::Utils::Headers.new
77 self.parameters.merge!(options[:parameters]) unless options[:parameters].nil?
78 self.headers.merge!(options[:headers]) unless options[:headers].nil?
79 self.api_method = options[:api_method]
80 self.authenticated = options[:authenticated]
81 self.authorization = options[:authorization]
83 # These parameters are handled differently because they're not
84 # parameters to the API method, but rather to the API system.
85 self.parameters['key'] ||= options[:key] if options[:key]
86 self.parameters['userIp'] ||= options[:user_ip] if options[:user_ip]
89 self.initialize_media_upload(options)
91 self.body = options[:body]
92 elsif options[:body_object]
93 self.headers['Content-Type'] ||= 'application/json'
94 self.body = serialize_body(options[:body_object])
99 unless self.api_method
100 self.http_method = options[:http_method] || 'GET'
101 self.uri = options[:uri]
105 # @!attribute [r] upload_type
106 # @return [String] protocol used for upload
108 return self.parameters['uploadType'] || self.parameters['upload_type']
111 # @!attribute http_method
112 # @return [Symbol] HTTP method if invoking a URI
114 return @http_method ||= self.api_method.http_method.to_s.downcase.to_sym
117 def http_method=(new_http_method)
118 if new_http_method.kind_of?(Symbol)
119 @http_method = new_http_method.to_s.downcase.to_sym
120 elsif new_http_method.respond_to?(:to_str)
121 @http_method = new_http_method.to_s.downcase.to_sym
124 "Expected String or Symbol, got #{new_http_method.class}."
128 def api_method=(new_api_method)
129 if new_api_method.nil? || new_api_method.kind_of?(Google::APIClient::Method)
130 @api_method = new_api_method
133 "Expected Google::APIClient::Method, got #{new_api_method.class}."
138 # @return [Addressable::URI] URI to send request
140 return @uri ||= self.api_method.generate_uri(self.parameters)
144 @uri = Addressable::URI.parse(new_uri)
145 @parameters.update(@uri.query_values) unless @uri.query_values.nil?
149 # Transmits the request with the given connection
153 # @param [Faraday::Connection] connection
154 # the connection to transmit with
155 # @param [TrueValue,FalseValue] is_retry
156 # True if request has been previous sent
158 # @return [Google::APIClient::Result]
159 # result of API request
160 def send(connection, is_retry = false)
161 self.body.rewind if is_retry && self.body.respond_to?(:rewind)
162 env = self.to_env(connection)
163 logger.debug { "#{self.class} Sending API request #{env[:method]} #{env[:url].to_s} #{env[:request_headers]}" }
164 http_response = connection.app.call(env)
165 result = self.process_http_response(http_response)
167 logger.debug { "#{self.class} Result: #{result.status} #{result.headers}" }
169 # Resumamble slightly different than other upload protocols in that it requires at least
171 if result.status == 200 && self.upload_type == 'resumable'
172 upload = result.resumable_upload
173 unless upload.complete?
174 logger.debug { "#{self.class} Sending upload body" }
175 result = upload.send(connection)
181 # Convert to an HTTP request. Returns components in order of method, URI,
182 # request headers, and body
186 # @return [Array<(Symbol, Addressable::URI, Hash, [#read,#to_str])>]
190 self.api_method.generate_request(self.parameters, self.body, self.headers)
192 unless self.parameters.empty?
193 self.uri.query = Addressable::URI.form_encode(self.parameters)
195 [self.http_method, self.uri.to_s, self.headers, self.body]
201 # Hashified verison of the API request
207 options[:api_method] = self.api_method
208 options[:parameters] = self.parameters
210 options[:http_method] = self.http_method
211 options[:uri] = self.uri
213 options[:headers] = self.headers
214 options[:body] = self.body
215 options[:media] = self.media
216 unless self.authorization.nil?
217 options[:authorization] = self.authorization
223 # Prepares the request for execution, building a hash of parts
224 # suitable for sending to Faraday::Connection.
228 # @param [Faraday::Connection] connection
229 # Connection for building the request
233 def to_env(connection)
234 method, uri, headers, body = self.to_http_request
235 http_request = connection.build_request(method) do |req|
237 req.headers.update(headers)
241 if self.authorization.respond_to?(:generate_authenticated_request)
242 http_request = self.authorization.generate_authenticated_request(
243 :request => http_request,
244 :connection => connection
248 request_env = http_request.to_env(connection)
252 # Convert HTTP response to an API Result
256 # @param [Faraday::Response] response
259 # @return [Google::APIClient::Result]
260 # Processed API response
261 def process_http_response(response)
262 Result.new(self, response)
268 # Adjust headers & body for media uploads
272 # @param [Hash] options
273 # @option options [Hash, Array] :parameters
274 # Request parameters for the API method.
275 # @option options [Google::APIClient::UploadIO] :media
276 # File to upload, if media upload request
277 # @option options [#to_json, #to_hash] :body_object
278 # Main body of the API request. Typically hash or object that can
279 # be serialized to JSON
280 # @option options [#read, #to_str] :body
281 # Raw body to send in POST/PUT requests
282 def initialize_media_upload(options)
283 self.media = options[:media]
284 case self.upload_type
286 if options[:body] || options[:body_object]
287 raise ArgumentError, "Can not specify body & body object for simple uploads"
289 self.headers['Content-Type'] ||= self.media.content_type
290 self.body = self.media
292 unless options[:body_object]
293 raise ArgumentError, "Multipart requested but no body object"
295 metadata = StringIO.new(serialize_body(options[:body_object]))
296 build_multipart([Faraday::UploadIO.new(metadata, 'application/json', 'file.json'), self.media])
298 file_length = self.media.length
299 self.headers['X-Upload-Content-Type'] = self.media.content_type
300 self.headers['X-Upload-Content-Length'] = file_length.to_s
301 if options[:body_object]
302 self.headers['Content-Type'] ||= 'application/json'
303 self.body = serialize_body(options[:body_object])
311 # Assemble a multipart message from a set of parts
315 # @param [Array<[#read,#to_str]>] parts
316 # Array of parts to encode.
317 # @param [String] mime_type
318 # MIME type of the message
319 # @param [String] boundary
320 # Boundary for separating each part of the message
321 def build_multipart(parts, mime_type = 'multipart/related', boundary = MULTIPART_BOUNDARY)
322 env = Faraday::Env.new
323 env.request = Faraday::RequestOptions.new
324 env.request.boundary = boundary
325 env.request_headers = {'Content-Type' => "#{mime_type};boundary=#{boundary}"}
326 multipart = Faraday::Request::Multipart.new
327 self.body = multipart.create_multipart(env, parts.map {|part| [nil, part]})
328 self.headers.update(env[:request_headers])
332 # Serialize body object to JSON
336 # @param [#to_json,#to_hash] body
337 # object to serialize
341 def serialize_body(body)
342 return body.to_json if body.respond_to?(:to_json)
343 return MultiJson.dump(body.to_hash) if body.respond_to?(:to_hash)
344 raise TypeError, 'Could not convert body object to JSON.' +
345 'Must respond to :to_json or :to_hash.'