remotable.rb 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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".to_sym
  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. raise e unless suppress_errors
  24. rescue Paperclip::Errors::NotIdentifiedByImageMagickError, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError, Paperclip::Error, Mastodon::DimensionsValidationError, Mastodon::StreamValidationError => e
  25. Rails.logger.debug "Error fetching remote #{attachment_name}: #{e}"
  26. end
  27. nil
  28. end
  29. define_method("#{attribute_name}=") do |url|
  30. return if self[attribute_name] == url && public_send("#{attachment_name}_file_name").present?
  31. self[attribute_name] = url if has_attribute?(attribute_name)
  32. public_send("download_#{attachment_name}!", url) if download_on_assign
  33. end
  34. alias_method("reset_#{attachment_name}!", "download_#{attachment_name}!")
  35. end
  36. end
  37. end