Sha256: 607f04da855b17c46359f0c587a7abd2cc57d1cff4f5e6a234b59e0de8e86980

Contents?: true

Size: 1.54 KB

Versions: 7

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

require "digest"
require "fileutils"

require "down/http"

module Miteru
  class Downloader < Service
    prepend MemoWise

    # @return [String]
    attr_reader :base_dir

    # @return [Miteru::Kit]
    attr_reader :kit

    #
    # <Description>
    #
    # @param [Miteru::Kit] kit
    # @param [String] base_dir
    #
    def initialize(kit, base_dir: Miteru.config.download_to)
      super()
      @kit = kit
      @base_dir = base_dir
    end

    #
    # @return [String]
    #
    def call
      destination = kit.filepath_to_download

      # downloader.download(kit.url, destination:, max_size:)
      downloader.download(kit.url, destination:, max_size:)

      unless Record.unique_sha256?(sha256(destination))
        FileUtils.rm destination
        raise UniquenessError, "Kit:#{sha256(destination)} is registered already."
      end

      # Record a kit in DB
      Record.create_by_kit_and_hash(kit, sha256: sha256(destination))
      Miteru.logger.info "Download #{kit.url} as #{destination}"

      destination
    end

    private

    def timeout
      Miteru.config.download_timeout
    end

    def downloader
      Down::Http.new(ssl_context:) { |client| client.timeout(timeout) }
    end

    def ssl_context
      OpenSSL::SSL::SSLContext.new.tap do |ctx|
        ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
    end

    def max_size
      Miteru.config.file_max_size
    end

    def sha256(path)
      digest = Digest::SHA256.file(path)
      digest.hexdigest
    end
    memo_wise :sha256
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
miteru-2.2.0 lib/miteru/downloader.rb
miteru-2.1.1 lib/miteru/downloader.rb
miteru-2.1.0 lib/miteru/downloader.rb
miteru-2.0.3 lib/miteru/downloader.rb
miteru-2.0.2 lib/miteru/downloader.rb
miteru-2.0.1 lib/miteru/downloader.rb
miteru-2.0.0 lib/miteru/downloader.rb