gitlab-org--gitlab-foss/app/models/upload.rb

92 lines
1.8 KiB
Ruby
Raw Normal View History

class Upload < ActiveRecord::Base
# Upper limit for foreground checksum processing
CHECKSUM_THRESHOLD = 100.megabytes
belongs_to :model, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
validates :size, presence: true
validates :path, presence: true
validates :model, presence: true
validates :uploader, presence: true
2018-01-29 12:57:34 -05:00
before_save :calculate_checksum!, if: :foreground_checksummable?
after_commit :schedule_checksum, if: :checksummable?
# as the FileUploader is not mounted, the default CarrierWave ActiveRecord
# hooks are not executed and the file will not be deleted
2018-01-31 10:59:35 -05:00
after_destroy :delete_file!, if: -> { uploader_class <= FileUploader }
2018-01-29 12:57:34 -05:00
def self.hexdigest(path)
Digest::SHA256.file(path).hexdigest
end
def absolute_path
return path unless relative_path?
uploader_class.absolute_path(self)
end
2018-01-29 12:57:34 -05:00
def calculate_checksum!
self.checksum = nil
return unless checksummable?
2018-01-29 12:57:34 -05:00
self.checksum = self.class.hexdigest(absolute_path)
end
def build_uploader
2018-01-30 14:38:10 -05:00
uploader_class.new(model, mount_point, **uploader_context).tap do |uploader|
2018-01-29 12:57:34 -05:00
uploader.upload = self
uploader.retrieve_from_store!(identifier)
end
end
def exist?
File.exist?(absolute_path)
end
def uploader_context
{
identifier: identifier,
secret: secret
}.compact
end
private
def delete_file!
build_uploader.remove!
end
2018-01-29 12:57:34 -05:00
def checksummable?
checksum.nil? && local? && exist?
end
def local?
2018-01-30 08:15:34 -05:00
true
2018-01-29 12:57:34 -05:00
end
def foreground_checksummable?
checksummable? && size <= CHECKSUM_THRESHOLD
end
def schedule_checksum
UploadChecksumWorker.perform_async(id)
end
def relative_path?
!path.start_with?('/')
end
def uploader_class
Object.const_get(uploader)
end
2018-01-29 12:57:34 -05:00
def identifier
File.basename(path)
end
def mount_point
super&.to_sym
end
end