module Eaternet::Util

Public Class Methods

download(source:, dest:) click to toggle source

Download a file from the network.

@param [String] source the URL to retrieve @param [String] dest pathname in which to save the file @return [File] the file

# File lib/eaternet/util.rb, line 37
def self.download(source:, dest:)
  File.open(dest, 'wb') do |file|
    file << HTTParty.get(source, verify: false).body
  end
end
download_and_cache(source:, dest:) click to toggle source

Download a file from the network, using a 12-hour cache.

@param [String] source the URL to retrieve @param [String] dest pathname in which to save the file @return [File] the file

# File lib/eaternet/util.rb, line 25
def self.download_and_cache(source:, dest:)
  cache_path = generate_cache_path(source)
  download(source: source, dest: cache_path) if expired? cache_path
  FileUtils.cp cache_path, dest
  File.open dest
end
download_and_extract_zipfile(url) click to toggle source

Download a zip file and extract it into a temp directory.

@return [String] the directory path

# File lib/eaternet/util.rb, line 12
def self.download_and_extract_zipfile(url)
  dir = Dir.mktmpdir
  zip_path = File.join(dir, 'zip-file.zip')
  download_and_cache(source: url, dest: zip_path)
  extract_zipfile(path: zip_path, dest_dir: dir)
  dir
end
expired?(cache_path) click to toggle source
# File lib/eaternet/util.rb, line 65
def self.expired?(cache_path)
  !File.exist?(cache_path) || file_age_in_days(cache_path) > 0.5
end
extract_zipfile(path:, dest_dir:) click to toggle source

Extract a Zip archive.

@param [String] path the Zip file's location @param [String] dest_dir directory in which to perform the

extraction

@return nil

# File lib/eaternet/util.rb, line 49
def self.extract_zipfile(path:, dest_dir:)
  open(path) do |zip_file|
    Zip::File.open(zip_file, 'rb') do |zip_data|
      zip_data.each do |entry|
        dest_path = File.join(dest_dir, entry.name)
        entry.extract(dest_path)
      end
    end
  end
end
file_age_in_days(path) click to toggle source

@return [Float]

# File lib/eaternet/util.rb, line 61
def self.file_age_in_days(path)
  (Time.now - File.mtime(path)).to_i / 86_400.0
end
generate_cache_path(url) click to toggle source
# File lib/eaternet/util.rb, line 69
def self.generate_cache_path(url)
  cache_dir = prepare_cache_dir
  cache_key = 'cache-key-' + Base64.strict_encode64(url)
  File.join(cache_dir, cache_key)
end
prepare_cache_dir() click to toggle source
# File lib/eaternet/util.rb, line 75
def self.prepare_cache_dir
  cache_dir = '/tmp/eaternet'
  `mkdir -p #{cache_dir}`
  cache_dir
end