debian-mirror-gitlab/app/uploaders/file_mover.rb

76 lines
1.7 KiB
Ruby
Raw Normal View History

2018-11-08 19:23:39 +05:30
# frozen_string_literal: true
2017-09-10 17:25:29 +05:30
class FileMover
attr_reader :secret, :file_name, :model, :update_field
def initialize(file_path, model, update_field = :description)
@secret = File.split(File.dirname(file_path)).last
@file_name = File.basename(file_path)
@model = model
@update_field = update_field
end
def execute
2019-03-13 22:55:13 +05:30
return unless valid?
2017-09-10 17:25:29 +05:30
move
2018-05-09 12:01:36 +05:30
if update_markdown
uploader.record_upload
uploader.schedule_background_upload
end
2017-09-10 17:25:29 +05:30
end
private
2019-03-13 22:55:13 +05:30
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-09-10 17:25:29 +05:30
def move
FileUtils.mkdir_p(File.dirname(file_path))
FileUtils.move(temp_file_path, file_path)
end
def update_markdown
2018-03-17 18:26:18 +05:30
updated_text = model.read_attribute(update_field)
.gsub(temp_file_uploader.markdown_link, uploader.markdown_link)
2017-09-10 17:25:29 +05:30
model.update_attribute(update_field, updated_text)
rescue
revert
false
end
def temp_file_path
return @temp_file_path if @temp_file_path
temp_file_uploader.retrieve_from_store!(file_name)
@temp_file_path = temp_file_uploader.file.path
end
def file_path
return @file_path if @file_path
uploader.retrieve_from_store!(file_name)
@file_path = uploader.file.path
end
def uploader
2018-03-17 18:26:18 +05:30
@uploader ||= PersonalFileUploader.new(model, secret: secret)
2017-09-10 17:25:29 +05:30
end
def temp_file_uploader
2018-03-17 18:26:18 +05:30
@temp_file_uploader ||= PersonalFileUploader.new(nil, secret: secret)
2017-09-10 17:25:29 +05:30
end
def revert
Rails.logger.warn("Markdown not updated, file move reverted for #{model}")
FileUtils.move(file_path, temp_file_path)
end
end