| 1 |
require 'uri' |
| 2 |
require 'httpclient' |
| 3 |
|
| 4 |
class DAV |
| 5 |
attr_reader :headers |
| 6 |
|
| 7 |
def initialize(uri = nil) |
| 8 |
@uri = nil |
| 9 |
@headers = {} |
| 10 |
open(uri) if uri |
| 11 |
proxy = ENV['HTTP_PROXY'] || ENV['http_proxy'] || nil |
| 12 |
@client = HTTPClient.new(proxy) |
| 13 |
end |
| 14 |
|
| 15 |
def open(uri) |
| 16 |
@uri = if uri.is_a?(URI) |
| 17 |
uri |
| 18 |
else |
| 19 |
URI.parse(uri) |
| 20 |
end |
| 21 |
end |
| 22 |
|
| 23 |
def set_basic_auth(user_id, passwd) |
| 24 |
@client.set_basic_auth(@uri, user_id, passwd) |
| 25 |
end |
| 26 |
|
| 27 |
# TODO: propget/propset support |
| 28 |
|
| 29 |
def propfind(target) |
| 30 |
target_uri = @uri + target |
| 31 |
res = @client.propfind(target_uri) |
| 32 |
res.body.content |
| 33 |
end |
| 34 |
|
| 35 |
def get(target, local = nil) |
| 36 |
local ||= target |
| 37 |
target_uri = @uri + target |
| 38 |
if FileTest.exist?(local) |
| 39 |
raise RuntimeError.new("File #{ local } exists.") |
| 40 |
end |
| 41 |
f = File.open(local, "wb") |
| 42 |
res = @client.get(target_uri, nil, @headers) do |data| |
| 43 |
f << data |
| 44 |
end |
| 45 |
f.close |
| 46 |
STDOUT.puts("#{ res.header['content-length'][0] } bytes saved to file #{ target }.") |
| 47 |
end |
| 48 |
|
| 49 |
def debug_dev=(dev) |
| 50 |
@client.debug_dev = dev |
| 51 |
end |
| 52 |
|
| 53 |
def get_content(target) |
| 54 |
target_uri = @uri + target |
| 55 |
@client.get_content(target_uri, nil, @headers) |
| 56 |
end |
| 57 |
|
| 58 |
def put_content(target, content) |
| 59 |
target_uri = @uri + target |
| 60 |
res = @client.put(target_uri, content, @headers) |
| 61 |
if res.status < 200 or res.status >= 300 |
| 62 |
raise "HTTP PUT failed: #{res.inspect}" |
| 63 |
end |
| 64 |
end |
| 65 |
|
| 66 |
class Mock |
| 67 |
attr_reader :headers |
| 68 |
|
| 69 |
def initialize(uri = nil) |
| 70 |
@uri = nil |
| 71 |
@headers = {} |
| 72 |
open(uri) if uri |
| 73 |
|
| 74 |
@cache = {} |
| 75 |
end |
| 76 |
|
| 77 |
def open(uri) |
| 78 |
@uri = uri.is_a?(URI) ? uri : URI.parse(uri) |
| 79 |
end |
| 80 |
|
| 81 |
def set_basic_auth(user_id, passwd) |
| 82 |
# ignore |
| 83 |
end |
| 84 |
|
| 85 |
def propfind(target) |
| 86 |
# not found |
| 87 |
nil |
| 88 |
end |
| 89 |
|
| 90 |
def get(target, local = nil) |
| 91 |
# ignore |
| 92 |
end |
| 93 |
|
| 94 |
def get_content(target) |
| 95 |
@cache[target] |
| 96 |
end |
| 97 |
|
| 98 |
def put_content(target, content) |
| 99 |
@cache[target] = content |
| 100 |
nil |
| 101 |
end |
| 102 |
end |
| 103 |
end |