闭社主体 forked from https://github.com/tootsuite/mastodon
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.

36 lines
1.2 KiB

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