2020-06-30 23:58:02 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Paperclip
|
|
|
|
class ResponseWithLimitAdapter < AbstractAdapter
|
|
|
|
def self.register
|
|
|
|
Paperclip.io_adapters.register self do |target|
|
|
|
|
target.is_a?(ResponseWithLimit)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def initialize(target, options = {})
|
|
|
|
super
|
|
|
|
cache_current_values
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def cache_current_values
|
2024-08-06 10:23:48 +02:00
|
|
|
@target.response.require_limit_not_exceeded!(@target.limit)
|
|
|
|
|
2024-01-19 19:52:59 +01:00
|
|
|
@original_filename = truncated_filename
|
2020-06-30 23:58:02 +02:00
|
|
|
@tempfile = copy_to_tempfile(@target)
|
2020-08-02 11:21:10 +02:00
|
|
|
@content_type = ContentTypeDetector.new(@tempfile.path).detect
|
2021-11-16 21:36:28 +01:00
|
|
|
@size = File.size(@tempfile)
|
2020-06-30 23:58:02 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def copy_to_tempfile(source)
|
|
|
|
bytes_read = 0
|
|
|
|
|
|
|
|
source.response.body.each do |chunk|
|
|
|
|
bytes_read += chunk.bytesize
|
2024-08-06 10:23:48 +02:00
|
|
|
raise Mastodon::LengthValidationError, "Body size exceeds limit of #{source.limit}" if bytes_read > source.limit
|
2020-06-30 23:58:02 +02:00
|
|
|
|
|
|
|
destination.write(chunk)
|
|
|
|
chunk.clear
|
|
|
|
end
|
|
|
|
|
|
|
|
destination.rewind
|
|
|
|
destination
|
2024-08-06 10:23:48 +02:00
|
|
|
rescue
|
2020-06-30 23:58:02 +02:00
|
|
|
destination.close(true)
|
|
|
|
raise
|
|
|
|
ensure
|
|
|
|
source.response.connection.close
|
|
|
|
end
|
|
|
|
|
2024-01-19 19:52:59 +01:00
|
|
|
def truncated_filename
|
|
|
|
filename = filename_from_content_disposition.presence || filename_from_path.presence || 'data'
|
|
|
|
extension = File.extname(filename)
|
|
|
|
basename = File.basename(filename, extension)
|
|
|
|
[basename[...20], extension[..4]].compact_blank.join
|
|
|
|
end
|
|
|
|
|
2020-06-30 23:58:02 +02:00
|
|
|
def filename_from_content_disposition
|
|
|
|
disposition = @target.response.headers['content-disposition']
|
|
|
|
disposition&.match(/filename="([^"]*)"/)&.captures&.first
|
|
|
|
end
|
|
|
|
|
|
|
|
def filename_from_path
|
|
|
|
@target.response.uri.path.split('/').last
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|