Class: Softcover::Uploader

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/softcover/uploader.rb

Constant Summary

Constants included from Utils

Softcover::Utils::UNITS

Instance Method Summary collapse

Methods included from Utils

#add_highlight_class!, #as_size, #current_book, #digest, #executable, #execute, #in_book_directory?, #logged_in?, #mkdir, #path, #reset_current_book!, #rm, #silence, #source, #tmpify, #write_pygments_file

Constructor Details

#initialize(res) ⇒ Uploader

Takes response from S3 upload signature generation API endpoint.



6
7
8
9
10
# File 'lib/softcover/uploader.rb', line 6

def initialize(res)
  @params = res['upload_params']
  @bucket = res['bucket']
  @access_key = res['access_key']
end

Instance Method Details

#after_each(&blk) ⇒ Object



12
13
14
# File 'lib/softcover/uploader.rb', line 12

def after_each(&blk)
  @after_each_blk = blk
end

#file_countObject



76
77
78
# File 'lib/softcover/uploader.rb', line 76

def file_count
  @params.size
end

#total_sizeObject



70
71
72
73
74
# File 'lib/softcover/uploader.rb', line 70

def total_size
  @params.inject(0) do |sum, p|
    sum += File.size?(p['path']) || 0
  end
end

#upload!(options = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/softcover/uploader.rb', line 16

def upload!(options={})
  unless @params.empty?
    bar = ProgressBar.create title: "Starting Upload...",
      format: "%t |%B| %P%% %e", total: total_size, smoothing: 0.75,
      output: Softcover::Output.stream

    upload_host = "http://#{@bucket}.s3.amazonaws.com"

    @params.each do |params|
      path = params['path']

      size = File.size? path

      c = Curl::Easy.new "http://#{@bucket}.s3.amazonaws.com"

      c.multipart_form_post = true

      last_chunk = 0
      c.on_progress do |_, _, ul_total, ul_now|
        uploaded = ul_now > size ? size : ul_now

        bar.title = "#{path} (#{as_size uploaded} / #{as_size size})"
        bar.progress += ul_now - last_chunk rescue nil
        last_chunk = ul_now
        true
      end

      c.http_post(
        Curl::PostField.content('key', params['key']),
        Curl::PostField.content('acl', params['acl']),
        Curl::PostField.content('Signature', params['signature']),
        Curl::PostField.content('Policy', params['policy']),
        Curl::PostField.content('Content-Type', params['content_type']),
        Curl::PostField.content('AWSAccessKeyId', @access_key),
        Curl::PostField.file('file', path)
      )

      if c.body_str =~ /Error/
        puts c.body_str
        break
      end

      if @after_each_blk
        @after_each_blk.call params
      end
    end

    bar.finish
  else
    puts "Nothing to upload." unless options[:silent]
  end

end