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'
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 = Hash[options[:parameters] || {}]
75 @headers = Faraday::Utils::Headers.new
76 self.headers.merge!(options[:headers]) unless options[:headers].nil?
77 self.api_method = options[:api_method]
78 self.authenticated = options[:authenticated]
79 self.authorization = options[:authorization]
81 # These parameters are handled differently because they're not
82 # parameters to the API method, but rather to the API system.
83 self.parameters['key'] ||= options[:key] if options[:key]
84 self.parameters['userIp'] ||= options[:user_ip] if options[:user_ip]
87 self.initialize_media_upload(options)
89 self.body = options[:body]
90 elsif options[:body_object]
91 self.headers['Content-Type'] ||= 'application/json'
92 self.body = serialize_body(options[:body_object])
97 unless self.api_method
98 self.http_method = options[:http_method] || 'GET'
99 self.uri = options[:uri]
103 # @!attribute [r] upload_type
104 # @return [String] protocol used for upload
106 return self.parameters['uploadType'] || self.parameters['upload_type']
109 # @!attribute http_method
110 # @return [Symbol] HTTP method if invoking a URI
112 return @http_method ||= self.api_method.http_method.to_s.downcase.to_sym
115 def http_method=(new_http_method)
116 if new_http_method.kind_of?(Symbol)
117 @http_method = new_http_method.to_s.downcase.to_sym
118 elsif new_http_method.respond_to?(:to_str)
119 @http_method = new_http_method.to_s.downcase.to_sym
122 "Expected String or Symbol, got #{new_http_method.class}."
126 def api_method=(new_api_method)
127 if new_api_method.nil? || new_api_method.kind_of?(Google::APIClient::Method)
128 @api_method = new_api_method
131 "Expected Google::APIClient::Method, got #{new_api_method.class}."
136 # @return [Addressable::URI] URI to send request
138 return @uri ||= self.api_method.generate_uri(self.parameters)
142 @uri = Addressable::URI.parse(new_uri)
143 @parameters.update(@uri.query_values) unless @uri.query_values.nil?
147 # Transmits the request with the given connection
151 # @param [Faraday::Connection] connection
152 # the connection to transmit with
154 # @return [Google::APIClient::Result]
155 # result of API request
157 env = self.to_env(connection)
158 logger.debug { "#{self.class} Sending API request #{env[:method]} #{env[:url].to_s} #{env[:request_headers]}" }
159 http_response = connection.app.call(env)
160 result = self.process_http_response(http_response)
162 logger.debug { "#{self.class} Result: #{result.status} #{result.headers}" }
164 # Resumamble slightly different than other upload protocols in that it requires at least
166 if self.upload_type == 'resumable'
167 upload = result.resumable_upload
168 unless upload.complete?
169 logger.debug { "#{self.class} Sending upload body" }
170 result = upload.send(connection)
176 # Convert to an HTTP request. Returns components in order of method, URI,
177 # request headers, and body
181 # @return [Array<(Symbol, Addressable::URI, Hash, [#read,#to_str])>]
185 unless self.parameters.empty?
186 self.uri.query = Addressable::URI.form_encode(self.parameters)
188 [self.http_method, self.uri.to_s, self.headers, self.body]
190 self.api_method.generate_request(self.parameters, self.body, self.headers)
195 # Hashified verison of the API request
201 options[:api_method] = self.api_method
202 options[:parameters] = self.parameters
204 options[:http_method] = self.http_method
205 options[:uri] = self.uri
207 options[:headers] = self.headers
208 options[:body] = self.body
209 options[:media] = self.media
210 unless self.authorization.nil?
211 options[:authorization] = self.authorization
217 # Prepares the request for execution, building a hash of parts
218 # suitable for sending to Faraday::Connection.
222 # @param [Faraday::Connection] connection
223 # Connection for building the request
227 def to_env(connection)
228 method, uri, headers, body = self.to_http_request
229 http_request = connection.build_request(method) do |req|
231 req.headers.update(headers)
235 if self.authorization.respond_to?(:generate_authenticated_request)
236 http_request = self.authorization.generate_authenticated_request(
237 :request => http_request,
238 :connection => connection
242 request_env = http_request.to_env(connection)
246 # Convert HTTP response to an API Result
250 # @param [Faraday::Response] response
253 # @return [Google::APIClient::Result]
254 # Processed API response
255 def process_http_response(response)
256 Result.new(self, response)
262 # Adjust headers & body for media uploads
266 # @param [Hash] options
267 # @option options [Hash, Array] :parameters
268 # Request parameters for the API method.
269 # @option options [Google::APIClient::UploadIO] :media
270 # File to upload, if media upload request
271 # @option options [#to_json, #to_hash] :body_object
272 # Main body of the API request. Typically hash or object that can
273 # be serialized to JSON
274 # @option options [#read, #to_str] :body
275 # Raw body to send in POST/PUT requests
276 def initialize_media_upload(options)
277 self.media = options[:media]
278 case self.upload_type
280 if options[:body] || options[:body_object]
281 raise ArgumentError, "Can not specify body & body object for simple uploads"
283 self.headers['Content-Type'] ||= self.media.content_type
284 self.body = self.media
286 unless options[:body_object]
287 raise ArgumentError, "Multipart requested but no body object"
289 metadata = StringIO.new(serialize_body(options[:body_object]))
290 build_multipart([Faraday::UploadIO.new(metadata, 'application/json', 'file.json'), self.media])
292 file_length = self.media.length
293 self.headers['X-Upload-Content-Type'] = self.media.content_type
294 self.headers['X-Upload-Content-Length'] = file_length.to_s
295 if options[:body_object]
296 self.headers['Content-Type'] ||= 'application/json'
297 self.body = serialize_body(options[:body_object])
305 # Assemble a multipart message from a set of parts
309 # @param [Array<[#read,#to_str]>] parts
310 # Array of parts to encode.
311 # @param [String] mime_type
312 # MIME type of the message
313 # @param [String] boundary
314 # Boundary for separating each part of the message
315 def build_multipart(parts, mime_type = 'multipart/related', boundary = MULTIPART_BOUNDARY)
317 :request_headers => {'Content-Type' => "#{mime_type};boundary=#{boundary}"},
318 :request => { :boundary => boundary }
320 multipart = Faraday::Request::Multipart.new
321 self.body = multipart.create_multipart(env, parts.map {|part| [nil, part]})
322 self.headers.update(env[:request_headers])
326 # Serialize body object to JSON
330 # @param [#to_json,#to_hash] body
331 # object to serialize
335 def serialize_body(body)
336 return body.to_json if body.respond_to?(:to_json)
337 return MultiJson.dump(body.to_hash) if body.respond_to?(:to_hash)
338 raise TypeError, 'Could not convert body object to JSON.' +
339 'Must respond to :to_json or :to_hash.'