4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
# File 'lib/filefm/downloaders/cloudfiles.rb', line 4
def self.download(link, opts = {})
require 'fog'
require 'fog/rackspace/storage'
uri = URI.parse(link)
container = uri.host
object = link.gsub(/^.*#{container}\//, "")
auth_url = "https://auth.api.rackspacecloud.com/v1.0"
if (not opts[:username] or not opts[:password])
raise "Invalid Credentials"
end
secure = true
scheme = secure ? "https" : "http"
username = opts[:username]
password = opts[:password]
conn = Fog::Storage.new({
:provider => 'Rackspace',
:rackspace_username => username,
:rackspace_api_key => password
})
out = RestClient.get auth_url, 'X-Auth-User' => username, 'X-Auth-Key' => password
storage_url = out.[:x_storage_url]
auth_token = out.[:x_auth_token]
raise "Error authenticating" unless out.code == 204
o = {
:location => nil,
:size => nil,
:filename => nil
}.merge(opts)
@location = o[:location] ||= ""
@filename = o[:filename]
progress = 0
= {
"User-Agent" => "FileFM #{VERSION}",
"X-Auth-Token" => auth_token
}
c = conn.directories.get container
raise "Container not found" if c.nil?
o = c.files.get object
@size = o.content_length
uri = URI.parse storage_url
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == "https"
http.open_timeout = 3 http.read_timeout = 3 path = uri.path + "/#{container}/#{object}"
request = Net::HTTP::Get.new(path)
request.
puts "unknown file size for #{@filename} but downloading..." if @size.nil?
dest_file = opts[:destination] || File.basename(object)
response = http.request(request) do |response|
if opts[:progressbar]
bar = ProgressBar.new("Progress", @size.to_i) unless @size.nil?
bar.format_arguments=[:title, :percentage, :bar, :stat_for_file_transfer] unless @size.nil?
end
File.open(dest_file, "wb") do |file|
response.read_body do |segment|
if opts[:progressbar]
progress += segment.length
bar.set(progress) unless @size.nil?
end
file.write(segment)
end
end
end
FileUtils.rm dest_file unless response.is_a? Net::HTTPOK
raise "Error downlading file: #{response.class.to_s}" unless response.is_a? Net::HTTPOK
end
|