Class: Rmega::Uploader

Inherits:
Object
  • Object
show all
Includes:
Loggable
Defined in:
lib/rmega/uploader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Loggable

included, #logger

Constructor Details

#initialize(params) ⇒ Uploader

Returns a new instance of Uploader.



12
13
14
15
16
17
18
# File 'lib/rmega/uploader.rb', line 12

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

Instance Attribute Details

#base_urlObject (readonly)

Returns the value of attribute base_url.



10
11
12
# File 'lib/rmega/uploader.rb', line 10

def base_url
  @base_url
end

#filesizeObject (readonly)

Returns the value of attribute filesize.



10
11
12
# File 'lib/rmega/uploader.rb', line 10

def filesize
  @filesize
end

#last_resultObject (readonly)

Returns the value of attribute last_result.



10
11
12
# File 'lib/rmega/uploader.rb', line 10

def last_result
  @last_result
end

#local_pathObject (readonly)

Returns the value of attribute local_path.



10
11
12
# File 'lib/rmega/uploader.rb', line 10

def local_path
  @local_path
end

#poolObject (readonly)

Returns the value of attribute pool.



10
11
12
# File 'lib/rmega/uploader.rb', line 10

def pool
  @pool
end

Instance Method Details

#chunksObject



33
34
35
# File 'lib/rmega/uploader.rb', line 33

def chunks
  Utils.chunks(filesize)
end

#read_chunk(start, size) ⇒ Object



28
29
30
31
# File 'lib/rmega/uploader.rb', line 28

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

#upload(&block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rmega/uploader.rb', line 37

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

  progress = Progress.new(total: filesize, caption: 'Upload')

  chunks.each do |start, size|

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

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

#upload_chunk(start, buffer) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/rmega/uploader.rb', line 20

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

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