Class: Datasets::Downloader
- Inherits:
-
Object
- Object
- Datasets::Downloader
- Defined in:
- lib/datasets/downloader.rb
Defined Under Namespace
Classes: ProgressReporter, TooManyRedirects
Instance Method Summary collapse
- #download(output_path, &block) ⇒ Object
-
#initialize(url, *fallback_urls, http_method: nil, http_parameters: nil) ⇒ Downloader
constructor
A new instance of Downloader.
Constructor Details
#initialize(url, *fallback_urls, http_method: nil, http_parameters: nil) ⇒ Downloader
Returns a new instance of Downloader.
15 16 17 18 19 20 |
# File 'lib/datasets/downloader.rb', line 15 def initialize(url, *fallback_urls, http_method: nil, http_parameters: nil) @url = normalize_url(url) @fallback_urls = fallback_urls.collect { |fallback_url| normalize_url(fallback_url) } @http_method = http_method @http_parameters = http_parameters end |
Instance Method Details
#download(output_path, &block) ⇒ Object
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 |
# File 'lib/datasets/downloader.rb', line 22 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, @fallback_urls, 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.[/\Atoo many redirections: (.+)\z/, 1] raise TooManyRedirects, "too many redirections: #{@url} .. #{last_url}" end end end |