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.
14 require 'google/api_client/reference'
19 # Uploadable media support. Holds an IO stream & content type.
21 # @see Faraday::UploadIO
23 # media = Google::APIClient::UploadIO.new('mymovie.m4v', 'video/mp4')
24 class UploadIO < Faraday::UploadIO
26 # @return [Fixnum] Size of chunks to upload. Default is nil, meaning upload the entire file in a single request
27 attr_accessor :chunk_size
30 # Get the length of the stream
33 # Length of stream, in bytes
35 io.respond_to?(:length) ? io.length : File.size(local_path)
40 # Wraps an input stream and limits data to a given range
43 # chunk = Google::APIClient::RangedIO.new(io, 0, 1000)
46 # Bind an input stream to a specific range.
50 # @param [Fixnum] offset
51 # Starting offset of the range
52 # @param [Fixnum] length
54 def initialize(io, offset, length)
63 def read(amount = nil, buf = nil)
72 size = [@length - @pos, amount].min
77 result = @io.read(size)
78 result.force_encoding("BINARY") if result.respond_to?(:force_encoding)
79 buffer << result if result
106 @io.pos = @offset + pos
111 # Resumable uploader.
113 class ResumableUpload < Request
114 # @return [Fixnum] Max bytes to send in a single request
115 attr_accessor :chunk_size
118 # Creates a new uploader.
120 # @param [Hash] options
122 def initialize(options={})
124 self.uri = options[:uri]
125 self.http_method = :put
126 @offset = options[:offset] || 0
132 # Sends all remaining chunks to the server
134 # @deprecated Pass the instance to {Google::APIClient#execute} instead
136 # @param [Google::APIClient] api_client
137 # API Client instance to use for sending
138 def send_all(api_client)
141 result = send_chunk(api_client)
142 break unless result.status == 308
149 # Sends the next chunk to the server
151 # @deprecated Pass the instance to {Google::APIClient#execute} instead
153 # @param [Google::APIClient] api_client
154 # API Client instance to use for sending
155 def send_chunk(api_client)
156 return api_client.execute(self)
160 # Check if upload is complete
162 # @return [TrueClass, FalseClass]
163 # Whether or not the upload complete successfully
169 # Check if the upload URL expired (upload not completed in alotted time.)
170 # Expired uploads must be restarted from the beginning
172 # @return [TrueClass, FalseClass]
173 # Whether or not the upload has expired and can not be resumed
179 # Check if upload is resumable. That is, neither complete nor expired
181 # @return [TrueClass, FalseClass] True if upload can be resumed
183 return !(self.complete? or self.expired?)
187 # Convert to an HTTP request. Returns components in order of method, URI,
188 # request headers, and body
192 # @return [Array<(Symbol, Addressable::URI, Hash, [#read,#to_str])>]
195 raise Google::APIClient::ClientError, "Upload already complete"
197 self.headers.update({
198 'Content-Length' => "0",
199 'Content-Range' => "bytes */#{media.length}" })
201 start_offset = @offset
202 remaining = self.media.length - start_offset
203 chunk_size = self.media.chunk_size || self.chunk_size || self.media.length
204 content_length = [remaining, chunk_size].min
205 chunk = RangedIO.new(self.media.io, start_offset, content_length)
206 end_offset = start_offset + content_length - 1
207 self.headers.update({
208 'Content-Length' => "#{content_length}",
209 'Content-Type' => self.media.content_type,
210 'Content-Range' => "bytes #{start_offset}-#{end_offset}/#{media.length}" })
217 # Check the result from the server, updating the offset and/or location
222 # @param [Faraday::Response] response
225 # @return [Google::APIClient::Result]
226 # Processed API response
227 def process_http_response(response)
232 range = response.headers['range']
234 @offset = range.scan(/\d+/).collect{|x| Integer(x)}.last + 1
236 if response.headers['location']
237 self.uri = response.headers['location']
242 # Invalidate the offset to mark it needs to be queried on the
246 return Google::APIClient::Result.new(self, response)
250 # Hashified verison of the API request
254 super.merge(:offset => @offset)