File: dav.rb

package info (click to toggle)
ruby-httpclient 2.8.3-3%2Bdeb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,672 kB
  • sloc: ruby: 9,462; makefile: 8; sh: 2
file content (103 lines) | stat: -rw-r--r-- 1,967 bytes parent folder | download | duplicates (7)
1
2
3
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
require 'uri'
require 'httpclient'

class DAV
  attr_reader :headers

  def initialize(uri = nil)
    @uri = nil
    @headers = {}
    open(uri) if uri
    proxy = ENV['HTTP_PROXY'] || ENV['http_proxy'] || nil
    @client = HTTPClient.new(proxy)
  end

  def open(uri)
    @uri = if uri.is_a?(URI)
	uri
      else
	URI.parse(uri)
      end
  end

  def set_basic_auth(user_id, passwd)
    @client.set_basic_auth(@uri, user_id, passwd)
  end

  # TODO: propget/propset support

  def propfind(target)
    target_uri = @uri + target
    res = @client.propfind(target_uri)
    res.body.content
  end

  def get(target, local = nil)
    local ||= target
    target_uri = @uri + target
    if FileTest.exist?(local)
      raise RuntimeError.new("File #{ local } exists.")
    end
    f = File.open(local, "wb")
    res = @client.get(target_uri, nil, @headers) do |data|
      f << data
    end
    f.close
    STDOUT.puts("#{ res.header['content-length'][0] } bytes saved to file #{ target }.")
  end

  def debug_dev=(dev)
    @client.debug_dev = dev
  end

  def get_content(target)
    target_uri = @uri + target
    @client.get_content(target_uri, nil, @headers)
  end

  def put_content(target, content)
    target_uri = @uri + target
    res = @client.put(target_uri, content, @headers)
    if res.status < 200 or res.status >= 300
      raise "HTTP PUT failed: #{res.inspect}"
    end
  end

  class Mock
    attr_reader :headers

    def initialize(uri = nil)
      @uri = nil
      @headers = {}
      open(uri) if uri

      @cache = {}
    end

    def open(uri)
      @uri = uri.is_a?(URI) ?  uri : URI.parse(uri)
    end

    def set_basic_auth(user_id, passwd)
      # ignore
    end

    def propfind(target)
      # not found
      nil
    end

    def get(target, local = nil)
      # ignore
    end

    def get_content(target)
      @cache[target]
    end

    def put_content(target, content)
      @cache[target] = content
      nil
    end
  end
end