2017-05-01 17:20:57 +03:00
# frozen_string_literal: true
2018-04-23 10:16:38 +03:00
require 'mime/types'
2017-05-01 17:20:57 +03:00
module Attachmentable
extend ActiveSupport :: Concern
2018-04-23 10:16:38 +03:00
MAX_MATRIX_LIMIT = 16_777_216 # 4096x4096px or approx. 16MB
2017-05-01 17:20:57 +03:00
included do
before_post_process :set_file_extensions
2018-04-23 10:16:38 +03:00
before_post_process :check_image_dimensions
2017-05-01 17:20:57 +03:00
end
private
def set_file_extensions
self . class . attachment_definitions . each_key do | attachment_name |
attachment = send ( attachment_name )
2018-04-23 10:16:38 +03:00
2017-05-01 17:20:57 +03:00
next if attachment . blank?
2018-04-23 10:16:38 +03:00
attachment . instance_write :file_name , [ Paperclip :: Interpolations . basename ( attachment , :original ) , appropriate_extension ( attachment ) ] . delete_if ( & :blank? ) . join ( '.' )
end
end
def check_image_dimensions
self . class . attachment_definitions . each_key do | attachment_name |
attachment = send ( attachment_name )
next if attachment . blank? || ! attachment . content_type . match? ( / image.* / ) || attachment . queued_for_write [ :original ] . blank?
width , height = FastImage . size ( attachment . queued_for_write [ :original ] . path )
raise Mastodon :: DimensionsValidationError , " #{ width } x #{ height } images are not supported " if width . present? && height . present? && ( width * height > = MAX_MATRIX_LIMIT )
2017-05-01 17:20:57 +03:00
end
end
2018-04-23 10:16:38 +03:00
def appropriate_extension ( attachment )
mime_type = MIME :: Types [ attachment . content_type ]
extensions_for_mime_type = mime_type . empty? ? [ ] : mime_type . first . extensions
original_extension = Paperclip :: Interpolations . extension ( attachment , :original )
extensions_for_mime_type . include? ( original_extension ) ? original_extension : extensions_for_mime_type . first
end
2017-05-01 17:20:57 +03:00
end