class B2::APIConnection
Attributes
download_url[R]
key_id[R]
key_secret[R]
Public Class Methods
new(key_id, secret)
click to toggle source
# File lib/b2/api_connection.rb, line 6 def initialize(key_id, secret) @key_id = key_id @key_secret = secret end
Public Instance Methods
account_id()
click to toggle source
# File lib/b2/api_connection.rb, line 39 def account_id return @account_id if !@account_id.nil? connect! @account_id end
active?()
click to toggle source
# File lib/b2/api_connection.rb, line 65 def active? !@connection.nil? && @connection.active? end
connect!()
click to toggle source
# File lib/b2/api_connection.rb, line 11 def connect! conn = Net::HTTP.new('api.backblazeb2.com', 443) conn.use_ssl = true req = Net::HTTP::Get.new('/b2api/v2/b2_authorize_account') req.basic_auth(@key_id, @key_secret) key_expiration = Time.now.to_i + 86_400 #24hr expiry resp = conn.start { |http| http.request(req) } if resp.is_a?(Net::HTTPSuccess) resp = JSON.parse(resp.body) else raise "Error connecting to B2 API" end uri = URI.parse(resp['apiUrl']) @connection = Net::HTTP.new(uri.host, uri.port) @connection.use_ssl = uri.scheme == 'https' @connection.start @auth_token_expires_at = key_expiration @account_id = resp['accountId'] @minimum_part_size = resp['absoluteMinimumPartSize'] @recommended_part_size = resp['recommendedPartSize'] @auth_token = resp['authorizationToken'] @download_url = resp['downloadUrl'] end
connection()
click to toggle source
# File lib/b2/api_connection.rb, line 69 def connection reconnect! if !active? @connection end
disconnect!()
click to toggle source
# File lib/b2/api_connection.rb, line 46 def disconnect! if @connection @connection.finish if @connection.active? @connection = nil end end
reconnect!()
click to toggle source
# File lib/b2/api_connection.rb, line 53 def reconnect! disconnect! connect! end
send_request(request, body=nil) { |response| ... }
click to toggle source
# File lib/b2/api_connection.rb, line 74 def send_request(request, body=nil, &block) retries = 0 request['Authorization'] = authorization_token request.body = (body.is_a?(String) ? body : JSON.generate(body)) if body return_value = nil close_connection = false begin connection.request(request) do |response| close_connection = response['Connection'] == 'close' case response when Net::HTTPSuccess if block_given? return_value = yield(response) else return_value = JSON.parse(response.body) end else body = JSON.parse(response.body) case body['code'] when 'not_found' raise B2::NotFound(body['message']) when 'expired_auth_token' raise B2::ExpiredAuthToken(body['message']) else raise "Error connecting to B2 API #{response.body}" end end end # Unexpected EOF (end of file) errors can occur when streaming from a # remote because of Backblaze quota restrictions. rescue B2::ExpiredAuthToken, EOFError reconnect! retries =+ 1 retry if retries < 2 end disconnect! if close_connection return_value end