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.

84 lines
2.6 KiB

  1. # frozen_string_literal: true
  2. module Remotable
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. def remotable_attachment(attachment_name, limit)
  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. Request.new(:get, url).perform do |response|
  19. next if response.code != 200
  20. content_type = parse_content_type(response.headers['content-type'])
  21. extname = detect_extname_from_content_type(content_type)
  22. if extname.nil?
  23. matches = response.headers['content-disposition']&.match(/filename="([^"]*)"/)
  24. filename = matches.nil? ? parsed_url.path.split('/').last : matches[1]
  25. extname = filename.nil? ? '' : File.extname(filename)
  26. end
  27. basename = SecureRandom.hex(8)
  28. send("#{attachment_name}=", StringIO.new(response.body_with_limit(limit)))
  29. send("#{attachment_name}_file_name=", basename + extname)
  30. self[attribute_name] = url if has_attribute?(attribute_name)
  31. end
  32. rescue HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError, Paperclip::Errors::NotIdentifiedByImageMagickError, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError => e
  33. Rails.logger.debug "Error fetching remote #{attachment_name}: #{e}"
  34. nil
  35. rescue Paperclip::Error, Mastodon::DimensionsValidationError => e
  36. Rails.logger.debug "Error processing remote #{attachment_name}: #{e}"
  37. nil
  38. end
  39. end
  40. define_method alt_method_name do
  41. url = self[attribute_name]
  42. return if url.blank?
  43. self[attribute_name] = ''
  44. send(method_name, url)
  45. end
  46. end
  47. end
  48. private
  49. def detect_extname_from_content_type(content_type)
  50. return if content_type.nil?
  51. type = MIME::Types[content_type].first
  52. return if type.nil?
  53. extname = type.extensions.first
  54. return if extname.nil?
  55. ".#{extname}"
  56. end
  57. def parse_content_type(content_type)
  58. return if content_type.nil?
  59. content_type.split(/\s*;\s*/).first
  60. end
  61. end