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.

69 lines
2.4 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. included do
  7. before_post_process :set_file_extensions
  8. before_post_process :check_image_dimensions
  9. before_post_process :set_file_content_type
  10. end
  11. private
  12. def set_file_content_type
  13. self.class.attachment_definitions.each_key do |attachment_name|
  14. attachment = send(attachment_name)
  15. next if attachment.blank? || attachment.queued_for_write[:original].blank?
  16. attachment.instance_write :content_type, calculated_content_type(attachment)
  17. end
  18. end
  19. def set_file_extensions
  20. self.class.attachment_definitions.each_key do |attachment_name|
  21. attachment = send(attachment_name)
  22. next if attachment.blank?
  23. attachment.instance_write :file_name, [Paperclip::Interpolations.basename(attachment, :original), appropriate_extension(attachment)].delete_if(&:blank?).join('.')
  24. end
  25. end
  26. def check_image_dimensions
  27. self.class.attachment_definitions.each_key do |attachment_name|
  28. attachment = send(attachment_name)
  29. next if attachment.blank? || !/image.*/.match?(attachment.content_type) || attachment.queued_for_write[:original].blank?
  30. width, height = FastImage.size(attachment.queued_for_write[:original].path)
  31. raise Mastodon::DimensionsValidationError, "#{width}x#{height} images are not supported" if width.present? && height.present? && (width * height >= MAX_MATRIX_LIMIT)
  32. end
  33. end
  34. def appropriate_extension(attachment)
  35. mime_type = MIME::Types[attachment.content_type]
  36. extensions_for_mime_type = mime_type.empty? ? [] : mime_type.first.extensions
  37. original_extension = Paperclip::Interpolations.extension(attachment, :original)
  38. proper_extension = extensions_for_mime_type.first.to_s
  39. extension = extensions_for_mime_type.include?(original_extension) ? original_extension : proper_extension
  40. extension = 'jpeg' if extension == 'jpe'
  41. extension
  42. end
  43. def calculated_content_type(attachment)
  44. content_type = Paperclip.run('file', '-b --mime :file', file: attachment.queued_for_write[:original].path).split(/[:;\s]+/).first.chomp
  45. content_type = 'video/mp4' if content_type == 'video/x-m4v'
  46. content_type
  47. rescue Terrapin::CommandLineError
  48. ''
  49. end
  50. end