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.

71 lines
2.5 KiB

  1. # frozen_string_literal: true
  2. require 'mime/types/columnar'
  3. module Attachmentable
  4. extend ActiveSupport::Concern
  5. MAX_MATRIX_LIMIT = 16_777_216 # 4096x4096px or approx. 16MB
  6. GIF_MATRIX_LIMIT = 921_600 # 1280x720px
  7. included do
  8. before_post_process :set_file_extensions
  9. before_post_process :check_image_dimensions
  10. before_post_process :set_file_content_type
  11. end
  12. private
  13. def set_file_content_type
  14. self.class.attachment_definitions.each_key do |attachment_name|
  15. attachment = send(attachment_name)
  16. next if attachment.blank? || attachment.queued_for_write[:original].blank?
  17. attachment.instance_write :content_type, calculated_content_type(attachment)
  18. end
  19. end
  20. def set_file_extensions
  21. self.class.attachment_definitions.each_key do |attachment_name|
  22. attachment = send(attachment_name)
  23. next if attachment.blank?
  24. attachment.instance_write :file_name, [Paperclip::Interpolations.basename(attachment, :original), appropriate_extension(attachment)].delete_if(&:blank?).join('.')
  25. end
  26. end
  27. def check_image_dimensions
  28. self.class.attachment_definitions.each_key do |attachment_name|
  29. attachment = send(attachment_name)
  30. next if attachment.blank? || !/image.*/.match?(attachment.content_type) || attachment.queued_for_write[:original].blank?
  31. width, height = FastImage.size(attachment.queued_for_write[:original].path)
  32. matrix_limit = attachment.content_type == 'image/gif' ? GIF_MATRIX_LIMIT : MAX_MATRIX_LIMIT
  33. raise Mastodon::DimensionsValidationError, "#{width}x#{height} images are not supported" if width.present? && height.present? && (width * height > matrix_limit)
  34. end
  35. end
  36. def appropriate_extension(attachment)
  37. mime_type = MIME::Types[attachment.content_type]
  38. extensions_for_mime_type = mime_type.empty? ? [] : mime_type.first.extensions
  39. original_extension = Paperclip::Interpolations.extension(attachment, :original)
  40. proper_extension = extensions_for_mime_type.first.to_s
  41. extension = extensions_for_mime_type.include?(original_extension) ? original_extension : proper_extension
  42. extension = 'jpeg' if extension == 'jpe'
  43. extension
  44. end
  45. def calculated_content_type(attachment)
  46. content_type = Paperclip.run('file', '-b --mime :file', file: attachment.queued_for_write[:original].path).split(/[:;\s]+/).first.chomp
  47. content_type = 'video/mp4' if content_type == 'video/x-m4v'
  48. content_type
  49. rescue Terrapin::CommandLineError
  50. ''
  51. end
  52. end