about summary refs log tree commit diff
path: root/lib/paperclip/response_with_limit_adapter.rb
blob: deb89717a405919e05f7358d14ad9b3cd7b82375 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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.presence || filename_from_path.presence || 'data'
      @tempfile = copy_to_tempfile(@target)
      @content_type = ContentTypeDetector.new(@tempfile.path).detect
      @size = File.size(@tempfile)
    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