remotable.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # frozen_string_literal: true
  2. module Remotable
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. def remotable_attachment(attachment_name, limit, suppress_errors: true, download_on_assign: true, attribute_name: nil)
  6. attribute_name ||= :"#{attachment_name}_remote_url"
  7. define_method("download_#{attachment_name}!") do |url = nil|
  8. url ||= self[attribute_name]
  9. return if url.blank?
  10. begin
  11. parsed_url = Addressable::URI.parse(url).normalize
  12. rescue Addressable::URI::InvalidURIError
  13. return
  14. end
  15. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.blank?
  16. begin
  17. Request.new(:get, url).perform do |response|
  18. raise Mastodon::UnexpectedResponseError, response unless (200...300).cover?(response.code)
  19. public_send("#{attachment_name}=", ResponseWithLimit.new(response, limit))
  20. end
  21. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError => e
  22. Rails.logger.debug { "Error fetching remote #{attachment_name}: #{e}" }
  23. public_send("#{attachment_name}=", nil) if public_send("#{attachment_name}_file_name").present?
  24. raise e unless suppress_errors
  25. rescue Paperclip::Errors::NotIdentifiedByImageMagickError, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError, Paperclip::Error, Mastodon::DimensionsValidationError, Mastodon::StreamValidationError => e
  26. Rails.logger.debug { "Error fetching remote #{attachment_name}: #{e}" }
  27. public_send("#{attachment_name}=", nil) if public_send("#{attachment_name}_file_name").present?
  28. end
  29. nil
  30. end
  31. define_method("#{attribute_name}=") do |url|
  32. return if self[attribute_name] == url && public_send("#{attachment_name}_file_name").present?
  33. self[attribute_name] = url if has_attribute?(attribute_name)
  34. public_send("download_#{attachment_name}!", url) if download_on_assign
  35. end
  36. alias_method("reset_#{attachment_name}!", "download_#{attachment_name}!")
  37. end
  38. end
  39. end