Class: HandleChunkUpload

Inherits:
Object
  • Object
show all
Defined in:
app/services/handle_chunk_upload.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(chunk, params = {}) ⇒ HandleChunkUpload

Returns a new instance of HandleChunkUpload.



4
5
6
7
# File 'app/services/handle_chunk_upload.rb', line 4

def initialize(chunk, params = {})
  @chunk = chunk
  @params = params
end

Class Method Details

.check_chunk(chunk, params) ⇒ Object



9
10
11
# File 'app/services/handle_chunk_upload.rb', line 9

def self.check_chunk(chunk, params)
  HandleChunkUpload.new(chunk, params).check_chunk
end

.merge_chunks(chunk, params) ⇒ Object



17
18
19
# File 'app/services/handle_chunk_upload.rb', line 17

def self.merge_chunks(chunk, params)
  HandleChunkUpload.new(chunk, params).merge_chunks
end

.upload_chunk(chunk, params) ⇒ Object



13
14
15
# File 'app/services/handle_chunk_upload.rb', line 13

def self.upload_chunk(chunk, params)
  HandleChunkUpload.new(chunk, params).upload_chunk
end

Instance Method Details

#check_chunkObject



21
22
23
24
25
26
27
# File 'app/services/handle_chunk_upload.rb', line 21

def check_chunk
  # check whether the chunk has already been uploaded
  has_chunk_been_uploaded =
    File.exist?(@chunk) && File.size(@chunk) == @params[:current_chunk_size]
  # 200 = exists, 404 = not uploaded yet
  status = has_chunk_been_uploaded ? 200 : 404
end

#merge_chunksObject



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
69
70
# File 'app/services/handle_chunk_upload.rb', line 38

def merge_chunks
  upload_path = @params[:upload_path]
  tmp_upload_path = @params[:tmp_upload_path]
  identifier = @params[:identifier]
  filename = @params[:filename]
  tmp_directory = @params[:tmp_directory]

  # delete destination files
  begin
    File.delete(upload_path)
    File.delete(tmp_upload_path)
  rescue Errno::ENOENT
  end

  # merge all the chunks
  File.open(tmp_upload_path, "a") do |file|
    (1..@chunk).each do |chunk_number|
      # path to chunk
      chunk_path = BackupRestore::LocalBackupStore.chunk_path(identifier, filename, chunk_number)
      # add chunk to file
      file << File.open(chunk_path).read
    end
  end

  # rename tmp file to final file name
  FileUtils.mv(tmp_upload_path, upload_path, force: true)

  # remove tmp directory
  begin
    FileUtils.rm_rf(tmp_directory)
  rescue Errno::ENOENT
  end
end

#upload_chunkObject



29
30
31
32
33
34
35
36
# File 'app/services/handle_chunk_upload.rb', line 29

def upload_chunk
  # path to chunk file
  dir = File.dirname(@chunk)
  # ensure directory exists
  FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
  # save chunk to the directory
  File.open(@chunk, "wb") { |f| f.write(@params[:file].tempfile.read) }
end