Method: B2::Connection#download

Defined in:
lib/b2/connection.rb

#download(bucket, key, to = nil) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/b2/connection.rb', line 93

def download(bucket, key, to=nil)
  opened_file = (to && to.is_a?(String))
  to = ::File.open(to, 'wb') if to.is_a?(String)
  digestor = Digest::SHA1.new
  data = ""

  uri = URI.parse(download_url)
  conn = Net::HTTP.new(uri.host, uri.port)
  conn.use_ssl = uri.scheme == 'https'

  req = Net::HTTP::Get.new("/file/#{bucket}/#{key}")
  req['Authorization'] = authorization_token
  conn.start do |http|
      http.request(req) do |response|
        case response
        when Net::HTTPSuccess
          response.read_body do |chunk|
            digestor << chunk
            if to
              to << chunk
            elsif block_given?
              yield(chunk)
            else
              data << chunk
            end
          end
  
          if response['X-Bz-Content-Sha1'] != 'none' && digestor.hexdigest != response['X-Bz-Content-Sha1']
            rase B2::FileIntegrityError.new("SHA1 Mismatch, expected: \"#{response['X-Bz-Content-Sha1']}\", actual: \"#{digestor.hexdigest}\"")
          end
        when Net::HTTPNotFound
          raise B2::NotFound.new(JSON.parse(response.body)['message'])
        else
          begin
            body = JSON.parse(response.body)
          if body['code'] == 'not_found'
              raise B2::NotFound(body['message'])
            else
              raise "#{body['code']} (#{body['message']})"
            end
          rescue
            raise response.body
          end
        end
      end
  end
  
  if opened_file
    to.close
  elsif to
    to.flush
  end
  !block_given? && to.nil? ? data : nil
end