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.

47 lines
1.5 KiB

  1. # frozen_string_literal: true
  2. require 'mime/types'
  3. module Attachmentable
  4. extend ActiveSupport::Concern
  5. MAX_MATRIX_LIMIT = 16_777_216 # 4096x4096px or approx. 16MB
  6. included do
  7. before_post_process :set_file_extensions
  8. before_post_process :check_image_dimensions
  9. end
  10. private
  11. def set_file_extensions
  12. self.class.attachment_definitions.each_key do |attachment_name|
  13. attachment = send(attachment_name)
  14. next if attachment.blank?
  15. attachment.instance_write :file_name, [Paperclip::Interpolations.basename(attachment, :original), appropriate_extension(attachment)].delete_if(&:blank?).join('.')
  16. end
  17. end
  18. def check_image_dimensions
  19. self.class.attachment_definitions.each_key do |attachment_name|
  20. attachment = send(attachment_name)
  21. next if attachment.blank? || !attachment.content_type.match?(/image.*/) || attachment.queued_for_write[:original].blank?
  22. width, height = FastImage.size(attachment.queued_for_write[:original].path)
  23. raise Mastodon::DimensionsValidationError, "#{width}x#{height} images are not supported" if width.present? && height.present? && (width * height >= MAX_MATRIX_LIMIT)
  24. end
  25. end
  26. def appropriate_extension(attachment)
  27. mime_type = MIME::Types[attachment.content_type]
  28. extensions_for_mime_type = mime_type.empty? ? [] : mime_type.first.extensions
  29. original_extension = Paperclip::Interpolations.extension(attachment, :original)
  30. extensions_for_mime_type.include?(original_extension) ? original_extension : extensions_for_mime_type.first
  31. end
  32. end