Skip to content
Snippets Groups Projects
Commit 40879470 authored by Mateus Rambo Strey's avatar Mateus Rambo Strey
Browse files

add chunks controller and service

parent 26491acb
No related branches found
No related tags found
No related merge requests found
class LearningObjects::ChunksController < ApplicationController
before_action :chunk_service
# GET /learning_objects/:learning_object_id/chunk
def show
if @chunk.exist?
post_file
render nothing: true, status: :ok
else
render nothing: true, status: :not_found # chunk doesnt exists and needs to be uploaded
end
end
# POST /learning_objects/:learning_object_id/chunk
def create
@chunk.save
post_file
render nothing: true, status: :ok
end
private
def chunk_service
@chunk = ChunksService.new(chunks_params)
return render(nothing: true, status: :unsupported_media_type) if @chunk.nil?
end
# Never trust parameters from the scary internet, only allow the white list through.
def chunks_params
params.permit(:file, :learning_object_id, :resumableIdentifier, :resumableFilename, :resumableChunkNumber, :resumableTotalChunks, :resumableChunkSize)
end
def post_file
return false unless @chunk.last?
publisher = LearningObjectPublisher.new(DspaceService.create_client)
publisher.post @chunk.learning_object, @chunk.resumable_filename
end
end
class ChunksService
attr_reader :learning_object, :resumable_filename
def initialize(params)
@learning_object = LearningObject.find params[:learning_object_id]
return nil if @learning_object.blank?
@dir = "/tmp/#{chunks_params[:resumableIdentifier]}"
@resumable_filename = "#{@dir}/#{params[:resumableFilename]}"
@resumable_file_extension = File.extname(@resumable_filename)[1..-1]
return nil unless valid_mime_type?
@total_chunks = params[:resumableTotalChunks].to_i
@chunk_number = params[:resumableChunkNumber].to_i
@chunk_size = params[:resumableChunkSize].to_i
@chunk_tmpfile = params[:file].tempfile
@chunk = resumable_chunk @chunk_number
end
def exist?
File.exist? @chunk
end
def save
# Create chunks directory when not present on system
FileUtils.mkdir(@dir, mode: 0700) unless File.directory?(@dir)
# Move the uploaded chunk to the directory
FileUtils.mv @chunk_tmpfile, @chunk
concatenate_chunks if last?
end
def last?
@chunk_number == @total_chunks
end
private
def valid_mime_type?
mime_types = @learning_object.object_type.mime_types.map(&:extension)
return true if mime_types.empty?
mime_types.include? @resumable_file_extension
end
def resumable_chunk(part)
"#{@resumable_filename}.part#{part}"
end
def concatenate_chunks
File.open(@resumable_filename, 'a') do |target|
[1..@chunk_number].each do |i|
chunk = File.open(resumable_chunk(i), 'r').read
chunk.each_line { |line| target << line }
FileUtils.rm resumable_chunk(i), force: true
end
logger.info "File saved to #{@resumable_filename}"
end
end
end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment