2017-05-18 06:43:10 -07:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Remotable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
|
|
|
attachment_definitions.each_key do |attachment_name|
|
2017-07-11 08:25:49 -07:00
|
|
|
attribute_name = "#{attachment_name}_remote_url".to_sym
|
|
|
|
method_name = "#{attribute_name}=".to_sym
|
|
|
|
alt_method_name = "reset_#{attachment_name}!".to_sym
|
2017-05-18 06:43:10 -07:00
|
|
|
|
|
|
|
define_method method_name do |url|
|
2017-08-08 12:52:15 -07:00
|
|
|
return if url.blank?
|
|
|
|
|
2017-07-03 02:03:34 -07:00
|
|
|
begin
|
|
|
|
parsed_url = Addressable::URI.parse(url).normalize
|
|
|
|
rescue Addressable::URI::InvalidURIError
|
|
|
|
return
|
|
|
|
end
|
2017-05-18 06:43:10 -07:00
|
|
|
|
|
|
|
return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[attribute_name] == url
|
|
|
|
|
|
|
|
begin
|
2017-07-14 11:41:49 -07:00
|
|
|
response = Request.new(:get, url).perform
|
2017-05-18 06:43:10 -07:00
|
|
|
|
|
|
|
return if response.code != 200
|
|
|
|
|
|
|
|
matches = response.headers['content-disposition']&.match(/filename="([^"]*)"/)
|
|
|
|
filename = matches.nil? ? parsed_url.path.split('/').last : matches[1]
|
2017-09-14 07:41:59 -07:00
|
|
|
basename = SecureRandom.hex(8)
|
2018-03-07 17:25:10 -08:00
|
|
|
extname = if filename.nil?
|
|
|
|
''
|
|
|
|
else
|
|
|
|
File.extname(filename)
|
|
|
|
end
|
2017-05-18 06:43:10 -07:00
|
|
|
|
|
|
|
send("#{attachment_name}=", StringIO.new(response.to_s))
|
2017-09-14 07:41:59 -07:00
|
|
|
send("#{attachment_name}_file_name=", basename + extname)
|
2017-05-18 06:43:10 -07:00
|
|
|
|
|
|
|
self[attribute_name] = url if has_attribute?(attribute_name)
|
2017-07-03 02:03:34 -07:00
|
|
|
rescue HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError, Paperclip::Errors::NotIdentifiedByImageMagickError, Addressable::URI::InvalidURIError => e
|
2017-05-18 06:43:10 -07:00
|
|
|
Rails.logger.debug "Error fetching remote #{attachment_name}: #{e}"
|
2017-06-30 04:38:36 -07:00
|
|
|
nil
|
2017-05-18 06:43:10 -07:00
|
|
|
end
|
|
|
|
end
|
2017-07-11 08:25:49 -07:00
|
|
|
|
|
|
|
define_method alt_method_name do
|
|
|
|
url = self[attribute_name]
|
|
|
|
|
|
|
|
return if url.blank?
|
|
|
|
|
|
|
|
self[attribute_name] = ''
|
|
|
|
send(method_name, url)
|
|
|
|
end
|
2017-05-18 06:43:10 -07:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|