about summary refs log tree commit diff
path: root/lib/paperclip/media_type_spoof_detector_extensions.rb
blob: 9c05573564f16ef0148fc7f325f4e96f63e5fc92 (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
# frozen_string_literal: true

module Paperclip
  module MediaTypeSpoofDetectorExtensions
    def calculated_content_type
      @calculated_content_type ||= type_from_mime_magic || type_from_file_command
    end

    def type_from_mime_magic
      @type_from_mime_magic ||= begin
        begin
          File.open(@file.path) do |file|
            MimeMagic.by_magic(file)&.type
          end
        rescue Errno::ENOENT
          ''
        end
      end
    end

    def type_from_file_command
      @type_from_file_command ||= FileCommandContentTypeDetector.new(@file.path).detect
    end
  end
end

Paperclip::MediaTypeSpoofDetector.prepend(Paperclip::MediaTypeSpoofDetectorExtensions)