You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.7 KiB

  1. # frozen_string_literal: true
  2. module Remotable
  3. extend ActiveSupport::Concern
  4. included do
  5. attachment_definitions.each_key do |attachment_name|
  6. attribute_name = "#{attachment_name}_remote_url".to_sym
  7. method_name = "#{attribute_name}=".to_sym
  8. alt_method_name = "reset_#{attachment_name}!".to_sym
  9. define_method method_name do |url|
  10. return if url.blank?
  11. begin
  12. parsed_url = Addressable::URI.parse(url).normalize
  13. rescue Addressable::URI::InvalidURIError
  14. return
  15. end
  16. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[attribute_name] == url
  17. begin
  18. response = Request.new(:get, url).perform
  19. return if response.code != 200
  20. matches = response.headers['content-disposition']&.match(/filename="([^"]*)"/)
  21. filename = matches.nil? ? parsed_url.path.split('/').last : matches[1]
  22. basename = SecureRandom.hex(8)
  23. extname = File.extname(filename)
  24. send("#{attachment_name}=", StringIO.new(response.to_s))
  25. send("#{attachment_name}_file_name=", basename + extname)
  26. self[attribute_name] = url if has_attribute?(attribute_name)
  27. rescue HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError, Paperclip::Errors::NotIdentifiedByImageMagickError, Addressable::URI::InvalidURIError => e
  28. Rails.logger.debug "Error fetching remote #{attachment_name}: #{e}"
  29. nil
  30. end
  31. end
  32. define_method alt_method_name do
  33. url = self[attribute_name]
  34. return if url.blank?
  35. self[attribute_name] = ''
  36. send(method_name, url)
  37. end
  38. end
  39. end
  40. end