Sha256: 2d486fceff687f62b2e3360de3421e138e9e9acb3c9498ef4f62c13e5543a5e1

Contents?: true

Size: 1.45 KB

Versions: 4

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

require "marcel"

class ResourceUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  before :cache, :check_image_content_type!

  def content_type_allowlist
    [%r{image/}, %r{audio/}, %r{video/}, "text/plain"]
  end

  def store_dir
    "files/#{model.class.to_s.underscore}/#{model.id}"
  end

  version :thumb, if: :image? do
    process dynamic_resize_to_fit: :thumb
  end

  version :medium, if: :image? do
    process dynamic_resize_to_fit: :medium
  end

  version :avatar, if: :image? do
    process dynamic_resize_to_fit: :avatar
  end

  def dynamic_resize_to_fit(size)
    resize_setting = model.blog.send("image_#{size}_size").to_i

    resize_to_fit(resize_setting, resize_setting)
  end

  def image?(new_file)
    content_type = new_file.content_type
    content_type&.include?("image")
  end

  def check_image_content_type!(new_file)
    if image?(new_file)
      magic_type = mime_magic_content_type(new_file)
      if magic_type != new_file.content_type
        raise CarrierWave::IntegrityError, "has MIME type mismatch"
      end
    end
  end

  private

  # NOTE: This method was adapted from MagicMimeBlacklist#extract_content_type
  # from CarrierWave 1.0.0 and SanitizedFile#mime_magic_content_type from CarrierWave 0.11.2
  def mime_magic_content_type(new_file)
    content_type = nil

    File.open(new_file.path) do |fd|
      content_type = Marcel::MimeType.for(fd)
    end

    content_type
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
publify_core-9.2.8 app/uploaders/resource_uploader.rb
publify_core-9.2.7 app/uploaders/resource_uploader.rb
publify_core-9.2.6 app/uploaders/resource_uploader.rb
publify_core-9.2.5 app/uploaders/resource_uploader.rb