class Qiniu2Upyun::Upyun

Constants

HOST
NAME

Attributes

config[R]

Public Class Methods

new(config) click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 8
def initialize(config)
  @config = config
end

Public Instance Methods

exist?(key) click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 16
def exist?(key)
  info(key)
rescue ResponseError
  false
end
info(key) click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 28
def info(key)
  uri = URI(URI.encode("#{HOST}/#{config.bucket}/#{key}"))

  response = send_request(uri, 'HEAD')

  response.is_a?(Net::HTTPOK) or raise ResponseError.new(response)
end
name() click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 12
def name
  NAME
end
upload(key, data) click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 22
def upload(key, data)
  uri = URI(URI.encode("#{HOST}/#{config.bucket}/#{key}"))

  send_request(uri, 'PUT', data)
end

Private Instance Methods

get_request(method, uri) click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 56
def get_request(method, uri)
  Net::HTTP.const_get(method[0].concat(method[1..-1].downcase)).new(uri)
end
get_sign(method, current, uri, content_length) click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 78
def get_sign(method, current, uri, content_length)
  digested_password = Digest::MD5.hexdigest(config.password)

  signing_str = "#{method}&#{uri.path}&#{current}&#{content_length}&#{digested_password}"

  sign = Digest::MD5.hexdigest(signing_str)

  "UpYun #{config.username}:#{sign}"
end
send_request(uri, method, data=nil, headers={}) click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 38
def send_request(uri, method, data=nil, headers={})
  Net::HTTP.start(uri.host) do |http|
    request = get_request(method, uri)

    set_headers(request, uri, method, data, headers)

    if data.nil?
      http.request(request)
    else
      bar = Utils.get_bar(data.length, 'Upload')

      request.body_stream = Data.new(data, bar)

      http.request(request)
    end
  end
end
set_headers(request, uri, method, data, headers) click to toggle source
# File lib/qiniu2upyun/upyun.rb, line 60
def set_headers(request, uri, method, data, headers)
  current = Time.now.utc.httpdate

  content_length = data ? data.length : 0

  sign = get_sign(method, current, uri, content_length)

  default_headers = {
    'Authorization'  => sign,
    'Date'           => current,
    'Content-Length' => content_length
  }

  headers = default_headers.merge(headers)

  headers.each { |key, value| request[key] = value }
end