class Fontist::Utils::Downloader

Attributes

file[R]
file_size[R]
sha[R]

Public Class Methods

download(*args) click to toggle source
# File lib/fontist/utils/downloader.rb, line 7
def download(*args)
  new(*args).download
end
new(file, file_size: nil, sha: nil, progress_bar: nil) click to toggle source
# File lib/fontist/utils/downloader.rb, line 13
def initialize(file, file_size: nil, sha: nil, progress_bar: nil)
  # TODO: If the first mirror fails, try the second one
  @file = file
  @sha = [sha].flatten.compact
  @file_size = file_size.to_i if file_size
  @progress_bar = set_progress_bar(progress_bar)
  @cache = Cache.new
end

Public Instance Methods

download() click to toggle source
# File lib/fontist/utils/downloader.rb, line 22
def download
  file = @cache.fetch(url) do
    download_file
  end

  raise_if_tampered(file)

  file
end

Private Instance Methods

byte_to_megabyte() click to toggle source
# File lib/fontist/utils/downloader.rb, line 49
def byte_to_megabyte
  @byte_to_megabyte ||= 1024 * 1024
end
download_file() click to toggle source
# File lib/fontist/utils/downloader.rb, line 65
def download_file
  file = Down.download(
    url,
    open_timeout: 10,
    read_timeout: 10,
    max_redirects: 10,
    headers: headers,
    content_length_proc: ->(content_length) {
      @progress_bar.total = content_length if content_length
    },
    progress_proc: -> (progress) {
      @progress_bar.increment(progress)
    }
  )

  @progress_bar.finish

  file
rescue Down::NotFound
  raise(Fontist::Errors::InvalidResourceError.new("Invalid URL: #{@file}"))
end
download_path() click to toggle source
# File lib/fontist/utils/downloader.rb, line 53
def download_path
  options[:download_path] || Fontist.root_path.join("tmp")
end
headers() click to toggle source
# File lib/fontist/utils/downloader.rb, line 91
def headers
  @file.respond_to?(:headers) &&
    @file.headers &&
    @file.headers.to_h.map { |k, v| [k.to_s, v] }.to_h || # rubocop:disable Style/HashTransformKeys, Metrics/LineLength
    {}
end
raise_if_tampered(file) click to toggle source
# File lib/fontist/utils/downloader.rb, line 36
def raise_if_tampered(file)
  file_checksum = Digest::SHA256.file(file).to_s
  if !sha.empty? && !sha.include?(file_checksum)
    raise(
      Fontist::Errors::TamperedFileError.new(
        "The downloaded file from #{@file} doesn't " \
        "match with the expected sha256 checksum (#{file_checksum})!\n" \
        "Beginning of content: #{File.read(file, 3000)}",
      ),
    )
  end
end
set_progress_bar(progress_bar) click to toggle source
# File lib/fontist/utils/downloader.rb, line 57
def set_progress_bar(progress_bar)
  if progress_bar
    ProgressBar.new(@file_size)
  else
    NullProgressBar.new(@file_size)
  end
end
url() click to toggle source
# File lib/fontist/utils/downloader.rb, line 87
def url
  @file.respond_to?(:url) ? @file.url : @file
end