diff options
author | Starfall <us@starfall.systems> | 2020-07-01 16:04:26 -0500 |
---|---|---|
committer | Starfall <us@starfall.systems> | 2020-07-01 16:04:26 -0500 |
commit | 9b8ab85007cc9b527ba8c59a3624731cd8e46ffe (patch) | |
tree | 28cf79b4c73ec6d328136ea04a63321862096e5a /lib/paperclip/response_with_limit_adapter.rb | |
parent | 6ec1f4c99e51a13ca56d639b85168dfb874daf75 (diff) | |
parent | 665eb1affe7ba765af476e6f00096aad3af70735 (diff) |
Merge branch 'glitch' into main
Diffstat (limited to 'lib/paperclip/response_with_limit_adapter.rb')
-rw-r--r-- | lib/paperclip/response_with_limit_adapter.rb | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/paperclip/response_with_limit_adapter.rb b/lib/paperclip/response_with_limit_adapter.rb new file mode 100644 index 000000000..7d897b8d6 --- /dev/null +++ b/lib/paperclip/response_with_limit_adapter.rb @@ -0,0 +1,55 @@ +# 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 + @original_filename = filename_from_content_disposition || filename_from_path || 'data' + @size = @target.response.content_length + @tempfile = copy_to_tempfile(@target) + @content_type = @target.response.mime_type || ContentTypeDetector.new(@tempfile.path).detect + end + + def copy_to_tempfile(source) + bytes_read = 0 + + source.response.body.each do |chunk| + bytes_read += chunk.bytesize + + destination.write(chunk) + chunk.clear + + raise Mastodon::LengthValidationError if bytes_read > source.limit + end + + destination.rewind + destination + rescue Mastodon::LengthValidationError + destination.close(true) + raise + ensure + source.response.connection.close + end + + 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 |