闭社主体 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.

41 lines
1.2 KiB

  1. # frozen_string_literal: true
  2. module AccountAvatar
  3. extend ActiveSupport::Concern
  4. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  5. class_methods do
  6. def avatar_styles(file)
  7. styles = { original: '120x120#' }
  8. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  9. styles
  10. end
  11. private :avatar_styles
  12. end
  13. included do
  14. # Avatar upload
  15. has_attached_file :avatar, styles: ->(f) { avatar_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  16. validates_attachment_content_type :avatar, content_type: IMAGE_MIME_TYPES
  17. validates_attachment_size :avatar, less_than: 2.megabytes
  18. def avatar_original_url
  19. avatar.url(:original)
  20. end
  21. def avatar_static_url
  22. avatar_content_type == 'image/gif' ? avatar.url(:static) : avatar_original_url
  23. end
  24. def avatar_remote_url=(url)
  25. parsed_url = Addressable::URI.parse(url).normalize
  26. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:avatar_remote_url] == url
  27. self.avatar = URI.parse(parsed_url.to_s)
  28. self[:avatar_remote_url] = url
  29. rescue OpenURI::HTTPError => e
  30. Rails.logger.debug "Error fetching remote avatar: #{e}"
  31. end
  32. end
  33. end