This repository has been archived by the owner on Jul 13, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
content_type_detector.rb
74 lines (63 loc) · 1.98 KB
/
content_type_detector.rb
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
module Paperclip
class ContentTypeDetector
# The content-type detection strategy is as follows:
#
# 1. Blank/Empty files: If there's no filepath or the file is empty,
# provide a sensible default (application/octet-stream or inode/x-empty)
#
# 2. Calculated match: Return the first result that is found by both the
# `file` command and MIME::Types.
#
# 3. Standard types: Return the first standard (without an x- prefix) entry
# in MIME::Types
#
# 4. Experimental types: If there were no standard types in MIME::Types
# list, try to return the first experimental one
#
# 5. Raw `file` command: Just use the output of the `file` command raw, or
# a sensible default. This is cached from Step 2.
EMPTY_TYPE = "inode/x-empty"
SENSIBLE_DEFAULT = "application/octet-stream"
def initialize(filepath)
@filepath = filepath
end
# Returns a String describing the file's content type
def detect
if blank_name?
SENSIBLE_DEFAULT
elsif empty_file?
EMPTY_TYPE
elsif calculated_type_matches.any?
calculated_type_matches.first
else
type_from_file_contents || SENSIBLE_DEFAULT
end.to_s
end
private
def blank_name?
@filepath.nil? || @filepath.empty?
end
def empty_file?
File.exist?(@filepath) && File.size(@filepath) == 0
end
alias :empty? :empty_file?
def calculated_type_matches
possible_types.select do |content_type|
content_type == type_from_file_contents
end
end
def possible_types
MIME::Types.type_for(@filepath).collect(&:content_type)
end
def type_from_file_contents
type_from_file_command
rescue Errno::ENOENT => e
Paperclip.log("Error while determining content type: #{e}")
SENSIBLE_DEFAULT
end
def type_from_file_command
@type_from_file_command ||=
FileCommandContentTypeDetector.new(@filepath).detect
end
end
end