forked from cybrespace/mastodon
Detect extname from Content-Type (#7733)
This commit is contained in:
parent
1637d24af4
commit
dc73241bd9
|
@ -24,14 +24,16 @@ module Remotable
|
||||||
Request.new(:get, url).perform do |response|
|
Request.new(:get, url).perform do |response|
|
||||||
next if response.code != 200
|
next if response.code != 200
|
||||||
|
|
||||||
matches = response.headers['content-disposition']&.match(/filename="([^"]*)"/)
|
content_type = parse_content_type(response.headers['content-type'])
|
||||||
filename = matches.nil? ? parsed_url.path.split('/').last : matches[1]
|
extname = detect_extname_from_content_type(content_type)
|
||||||
|
|
||||||
|
if extname.nil?
|
||||||
|
matches = response.headers['content-disposition']&.match(/filename="([^"]*)"/)
|
||||||
|
filename = matches.nil? ? parsed_url.path.split('/').last : matches[1]
|
||||||
|
extname = filename.nil? ? '' : File.extname(filename)
|
||||||
|
end
|
||||||
|
|
||||||
basename = SecureRandom.hex(8)
|
basename = SecureRandom.hex(8)
|
||||||
extname = if filename.nil?
|
|
||||||
''
|
|
||||||
else
|
|
||||||
File.extname(filename)
|
|
||||||
end
|
|
||||||
|
|
||||||
send("#{attachment_name}=", StringIO.new(response.body_with_limit(limit)))
|
send("#{attachment_name}=", StringIO.new(response.body_with_limit(limit)))
|
||||||
send("#{attachment_name}_file_name=", basename + extname)
|
send("#{attachment_name}_file_name=", basename + extname)
|
||||||
|
@ -57,4 +59,22 @@ module Remotable
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def detect_extname_from_content_type(content_type)
|
||||||
|
return if content_type.nil?
|
||||||
|
|
||||||
|
type = MIME::Types[content_type].first
|
||||||
|
|
||||||
|
return if type.nil?
|
||||||
|
|
||||||
|
type.extensions.first
|
||||||
|
end
|
||||||
|
|
||||||
|
def parse_content_type(content_type)
|
||||||
|
return if content_type.nil?
|
||||||
|
|
||||||
|
content_type.split(/\s*;\s*/).first
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in New Issue