Class: Tus::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/tus/client.rb,
lib/tus/client/version.rb

Constant Summary collapse

CHUNK_SIZE =

100 MiB is ok for now…

100 * 1024 * 1024
TUS_VERSION =
'1.0.0'
NUM_RETRIES =
5
VERSION =
'0.0.3'

Instance Method Summary collapse

Constructor Details

#initialize(server_url) ⇒ Client

Returns a new instance of Client.



15
16
17
18
19
20
21
22
# File 'lib/tus/client.rb', line 15

def initialize(server_url)
  @server_uri = URI.parse(server_url)

  # better to open the connection now
  @http = Net::HTTP.start(@server_uri.host, @server_uri.port)
  # we cache this value for further use
  @capabilities = capabilities
end

Instance Method Details

#upload(file_path) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/tus/client.rb', line 24

def upload(file_path)
  raise 'No such file!' unless File.file?(file_path)

  file_name = File.basename(file_path)
  file_size = File.size(file_path)
  io = File.open(file_path, 'rb')

  upload_by_io(file_name: file_name, file_size: file_size, io: io)
end

#upload_by_io(file_name:, file_size:, io:) ⇒ Object



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
# File 'lib/tus/client.rb', line 34

def upload_by_io(file_name:, file_size:, io:)
  raise 'Cannot upload a stream of unknown size!' unless file_size

  uri = create_remote(file_name, file_size)
  # we use only parameters that are known to the server
  offset, length = upload_parameters(uri)

  chunks = Enumerator.new do |yielder|
    loop do
      chunk = io.read(CHUNK_SIZE)

      break unless chunk

      yielder << chunk
    end
  end

  begin
    offset = chunks.lazy.inject(offset) do |current_offset, chunk|
      upload_chunk(uri, current_offset, chunk)
    end
  rescue StandardError
    raise 'Broken upload! Cannot send a chunk!'
  end

  raise 'Broken upload!' unless offset == length

  io.close
end