module MDowloader

Constants

VERSION

Public Instance Methods

check_wget() click to toggle source
# File lib/MDowloader.rb, line 57
def check_wget
  raise Exception.new('Wget not found. Please install it.') if `which wget`.empty?
end
download(url, path, options = {}, &block) click to toggle source
# File lib/MDowloader.rb, line 5
def download(url, path, options = {}, &block)
  check_wget

  resume_cmd = options[:resume] ? '-c' : ''

  if options[:retry] == 0
    retry_cmd = ''

  elsif options[:retry] == :any
    retry_cmd = '-t 0'

  elsif options[:retry].is_a? Numeric
    retry_cmd = "-t #{options[:retry]}"

  else
    raise Exception.new('Unknown retry option')

  end

  begin
    IO.popen("wget #{resume_cmd} #{retry_cmd} -O #{path} #{url} 2>&1", "r") do |pipe|
      pipe.each do |line|
        result = Hash.new
        match_pre = line.match(/ (\d{1,})% /)
        unless match_pre.nil?
          result[:percent] = match_pre[1]

          match_s = line.match(/(\d{1,})s/)
          unless match_s.nil?
            result[:sec] = match_s[1]
            match_m = line.match(/ (\d{1,})m/)
            unless match_m.nil?
              result[:min] = match_m[1]
            end
          end

        else
          if line.include?('saved')
            return true, nil
          end
        end

        block.call result
      end
    end

  rescue => err
    return false, err
  end

end