mastodon/app/models/site_upload.rb
Eugen Rochko a7171af0a3
Fix avatar and header issues by using custom geometry detector (#6515)
* Fix avatar and header issues by using custom geometry detector

Revert a part of #6508. The file passed to dynamic styles method
was not actually a file, but an instance of Paperclip::Attachment,
which broke all styles by always returning {} from the method.

One problem with GIF avatars was that Paperclip::GeometryDetector
reported wrong dimensions for them, e.g. 120x120 GIF avatar would
for some reason be detected as 120x53. By writing our own geometry
parser, we can use FastImage, which also happens to be faster than
ImageMagick, to detect image dimensions, which are also correct.

Unfortunately, this PR does not implement skipping a `convert`
entirely if the dimensions are already correct, as I found no easy
way to write that behaviour into Paperclip without rewriting the
Paperclip::Thumbnail class.

* Only invoke convert if dimension or format needs to be changed
2018-02-21 03:40:12 +01:00

44 lines
1,015 B
Ruby

# frozen_string_literal: true
# == Schema Information
#
# Table name: site_uploads
#
# id :integer not null, primary key
# var :string default(""), not null
# file_file_name :string
# file_content_type :string
# file_file_size :integer
# file_updated_at :datetime
# meta :json
# created_at :datetime not null
# updated_at :datetime not null
#
class SiteUpload < ApplicationRecord
has_attached_file :file
validates_attachment_content_type :file, content_type: /\Aimage\/.*\z/
validates :var, presence: true, uniqueness: true
before_save :set_meta
after_commit :clear_cache
def cache_key
"site_uploads/#{var}"
end
private
def set_meta
tempfile = file.queued_for_write[:original]
return if tempfile.nil?
width, height = FastImage.size(tempfile.path)
self.meta = { width: width, height: height }
end
def clear_cache
Rails.cache.delete(cache_key)
end
end