Class: Datasets::Downloader

Inherits:
Object
  • Object
show all
Defined in:
lib/datasets/downloader.rb

Defined Under Namespace

Classes: ProgressReporter, TooManyRedirects

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ Downloader

Returns a new instance of Downloader.



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/datasets/downloader.rb', line 13

def initialize(url)
  if url.is_a?(URI::Generic)
    url = url.dup
  else
    url = URI.parse(url)
  end
  @url = url
  unless @url.is_a?(URI::HTTP)
    raise ArgumentError, "download URL must be HTTP or HTTPS: <#{@url}>"
  end
end

Instance Method Details

#download(output_path, &block) ⇒ Object



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
# File 'lib/datasets/downloader.rb', line 25

def download(output_path, &block)
  if output_path.exist?
    yield_chunks(output_path, &block) if block_given?
    return
  end

  partial_output_path = Pathname.new("#{output_path}.partial")
  synchronize(output_path, partial_output_path) do
    output_path.parent.mkpath

    n_retries = 0
    n_max_retries = 5
    begin
      headers = {
        "Accept-Encoding" => "identity",
        "User-Agent" => "Red Datasets/#{VERSION}",
      }
      start = nil
      if partial_output_path.exist?
        start = partial_output_path.size
        headers["Range"] = "bytes=#{start}-"
      end

      start_http(@url, headers) do |response|
        if response.is_a?(Net::HTTPPartialContent)
          mode = "ab"
        else
          start = nil
          mode = "wb"
        end

        base_name = @url.path.split("/").last
        size_current = 0
        size_max = response.content_length
        if start
          size_current += start
          size_max += start
          if block_given? and n_retries.zero?
            yield_chunks(partial_output_path, &block)
          end
        end
        progress_reporter = ProgressReporter.new(base_name, size_max)
        partial_output_path.open(mode) do |output|
          response.read_body do |chunk|
            size_current += chunk.bytesize
            progress_reporter.report(size_current)
            output.write(chunk)
            yield(chunk) if block_given?
          end
        end
      end
      FileUtils.mv(partial_output_path, output_path)
    rescue Net::ReadTimeout => error
      n_retries += 1
      retry if n_retries < n_max_retries
      raise
    rescue TooManyRedirects => error
      last_url = error.message[/\Atoo many redirections: (.+)\z/, 1]
      raise TooManyRedirects, "too many redirections: #{@url} .. #{last_url}"
    end
  end
end