Restrict ActiveStorage previews format to only PNG or JPEG [SCI-10969] (#7810)

This commit is contained in:
Alex Kriuchykhin 2024-09-02 13:44:57 +02:00 committed by GitHub
parent c0d386f0c1
commit c8af20a822
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 20 additions and 6 deletions

View file

@ -0,0 +1,11 @@
# frozen_string_literal: true
module ActiveStorageHelper
def image_preview_format(blob)
if ['image/jpeg', 'image/jpg'].include?(blob&.content_type)
:jpeg
else
:png
end
end
end

View file

@ -2,6 +2,8 @@
# Provides asynchronous generation of image previews for ActiveStorage::Blob records.
class ActiveStorage::PreviewJob < ActiveStorage::BaseJob
include ActiveStorageHelper
queue_as :assets
discard_on StandardError do |job, error|
@ -18,11 +20,11 @@ class ActiveStorage::PreviewJob < ActiveStorage::BaseJob
def perform(blob_id)
blob = ActiveStorage::Blob.find(blob_id)
preview = blob.representation(resize_to_limit: Constants::MEDIUM_PIC_FORMAT).processed
preview = blob.representation(resize_to_limit: Constants::MEDIUM_PIC_FORMAT, format: image_preview_format(blob)).processed
Rails.logger.info "Preview for the Blod with id: #{blob.id} - successfully generated.\n" \
"Transformations applied: #{preview.variation.transformations}"
preview = blob.representation(resize_to_limit: Constants::LARGE_PIC_FORMAT).processed
preview = blob.representation(resize_to_limit: Constants::LARGE_PIC_FORMAT, format: image_preview_format(blob)).processed
Rails.logger.info "Preview for the Blod with id: #{blob.id} - successfully generated.\n" \
"Transformations applied: #{preview.variation.transformations}"

View file

@ -7,6 +7,7 @@ class Asset < ApplicationRecord
include WopiUtil
include ActiveStorageFileUtil
include ActiveStorageConcerns
include ActiveStorageHelper
require 'tempfile'
# Lock duration set to 30 minutes
@ -105,11 +106,11 @@ class Asset < ApplicationRecord
end
def medium_preview
preview_attachment.representation(resize_to_limit: Constants::MEDIUM_PIC_FORMAT)
preview_attachment.representation(resize_to_limit: Constants::MEDIUM_PIC_FORMAT, format: image_preview_format(blob))
end
def large_preview
preview_attachment.representation(resize_to_limit: Constants::LARGE_PIC_FORMAT)
preview_attachment.representation(resize_to_limit: Constants::LARGE_PIC_FORMAT, format: image_preview_format(blob))
end
def file_name

View file

@ -11,9 +11,9 @@ module Reports
def self.image_prepare(asset)
if asset.class == Asset
if asset.inline?
asset.preview_attachment.representation(resize_to_limit: Constants::MEDIUM_PIC_FORMAT, format: :png)
asset.medium_preview
else
asset.preview_attachment.representation(resize_to_limit: Constants::LARGE_PIC_FORMAT, format: :png)
asset.large_preview
end
elsif asset.class == TinyMceAsset
asset.image.representation(format: :png)