gitlab-org--gitlab-foss/app/uploaders/file_mover.rb

83 lines
1.9 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2017-05-03 11:26:49 -04:00
class FileMover
attr_reader :secret, :file_name, :from_model, :to_model, :update_field
2017-05-03 11:26:49 -04:00
def initialize(file_path, update_field = :description, from_model:, to_model:)
2017-05-03 11:26:49 -04:00
@secret = File.split(File.dirname(file_path)).last
@file_name = File.basename(file_path)
@from_model = from_model
@to_model = to_model
@update_field = update_field
2017-05-03 11:26:49 -04:00
end
def execute
return unless valid?
2017-05-03 11:26:49 -04:00
move
if update_markdown
update_upload_model
uploader.schedule_background_upload
end
2017-05-03 11:26:49 -04:00
end
private
def valid?
Pathname.new(temp_file_path).realpath.to_path.start_with?(
(Pathname(temp_file_uploader.root) + temp_file_uploader.base_dir).to_path
)
end
2017-05-03 11:26:49 -04:00
def move
FileUtils.mkdir_p(File.dirname(file_path))
2017-05-03 11:26:49 -04:00
FileUtils.move(temp_file_path, file_path)
end
def update_markdown
updated_text = to_model.read_attribute(update_field)
.gsub(temp_file_uploader.markdown_link, uploader.markdown_link)
to_model.update_attribute(update_field, updated_text)
rescue
revert
false
2017-05-03 11:26:49 -04:00
end
def update_upload_model
return unless upload = temp_file_uploader.upload
upload.update!(model_id: to_model.id, model_type: to_model.type)
end
2017-05-03 11:26:49 -04:00
def temp_file_path
return @temp_file_path if @temp_file_path
2017-05-03 11:26:49 -04:00
temp_file_uploader.retrieve_from_store!(file_name)
@temp_file_path = temp_file_uploader.file.path
2017-05-03 11:26:49 -04:00
end
def file_path
return @file_path if @file_path
uploader.retrieve_from_store!(file_name)
@file_path = uploader.file.path
end
def uploader
@uploader ||= PersonalFileUploader.new(to_model, secret: secret)
2017-05-03 11:26:49 -04:00
end
def temp_file_uploader
@temp_file_uploader ||= PersonalFileUploader.new(from_model, secret: secret)
2017-05-03 11:26:49 -04:00
end
def revert
Rails.logger.warn("Markdown not updated, file move reverted for #{to_model}")
FileUtils.move(file_path, temp_file_path)
end
2017-05-03 11:26:49 -04:00
end