Sha256: e96c553593c686a208ac97459c3e784c2a6b4929f21c6ef20415d88ea91c2f8f

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 KB

Contents

require 'rmega/loggable'
require 'rmega/utils'
require 'rmega/pool'
require 'rmega/progress'

module Rmega
  class Uploader
    include Loggable

    attr_reader :pool, :base_url, :filesize, :local_path, :last_result

    def initialize(params)
      @pool = Pool.new(params[:threads])
      @filesize = params[:filesize]
      @base_url = params[:base_url]
      @local_path = params[:local_path]
      @last_result = nil
    end

    def upload_chunk(start, buffer)
      size = buffer.length
      stop = start + size - 1
      url = "#{base_url}/#{start}-#{stop}"

      HTTPClient.new.post(url, buffer).body
    end

    def read_chunk(start, size)
      @local_file.seek(start)
      @local_file.read(size)
    end

    def chunks
      Utils.chunks(filesize)
    end

    def upload(&block)
      @local_file = ::File.open(local_path, 'rb')

      progress = Progress.new(filesize: filesize, verb: 'upload')

      chunks.each do |start, size|

        pool.defer do
          clean_buffer = pool.syncronize { read_chunk(start, size) }
          encrypted_buffer = yield(start, clean_buffer)
          @last_result = upload_chunk(start, encrypted_buffer)
          progress.increment(buffer.size)
        end
      end

      pool.wait_done
      pool.shutdown
    ensure
      @local_file.close
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rmega-0.1.0 lib/rmega/uploader.rb