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.

97 lines
2.8 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: preview_cards
  5. #
  6. # id :bigint(8) not null, primary key
  7. # url :string default(""), not null
  8. # title :string default(""), not null
  9. # description :string default(""), not null
  10. # image_file_name :string
  11. # image_content_type :string
  12. # image_file_size :integer
  13. # image_updated_at :datetime
  14. # type :integer default("link"), not null
  15. # html :text default(""), not null
  16. # author_name :string default(""), not null
  17. # author_url :string default(""), not null
  18. # provider_name :string default(""), not null
  19. # provider_url :string default(""), not null
  20. # width :integer default(0), not null
  21. # height :integer default(0), not null
  22. # created_at :datetime not null
  23. # updated_at :datetime not null
  24. # embed_url :string default(""), not null
  25. # image_storage_schema_version :integer
  26. #
  27. class PreviewCard < ApplicationRecord
  28. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  29. LIMIT = 1.megabytes
  30. self.inheritance_column = false
  31. enum type: [:link, :photo, :video, :rich]
  32. has_and_belongs_to_many :statuses
  33. has_attached_file :image, styles: ->(f) { image_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  34. include Attachmentable
  35. validates :url, presence: true, uniqueness: true
  36. validates_attachment_content_type :image, content_type: IMAGE_MIME_TYPES
  37. validates_attachment_size :image, less_than: LIMIT
  38. remotable_attachment :image, LIMIT
  39. scope :cached, -> { where.not(image_file_name: [nil, '']) }
  40. before_save :extract_dimensions, if: :link?
  41. def local?
  42. false
  43. end
  44. def missing_image?
  45. width.present? && height.present? && image_file_name.blank?
  46. end
  47. def save_with_optional_image!
  48. save!
  49. rescue ActiveRecord::RecordInvalid
  50. self.image = nil
  51. save!
  52. end
  53. class << self
  54. private
  55. def image_styles(f)
  56. styles = {
  57. original: {
  58. geometry: '400x400>',
  59. file_geometry_parser: FastGeometryParser,
  60. convert_options: '-coalesce -strip',
  61. },
  62. }
  63. styles[:original][:format] = 'jpg' if f.instance.image_content_type == 'image/gif'
  64. styles
  65. end
  66. end
  67. private
  68. def extract_dimensions
  69. file = image.queued_for_write[:original]
  70. return if file.nil?
  71. width, height = FastImage.size(file.path)
  72. return nil if width.nil?
  73. self.width = width
  74. self.height = height
  75. end
  76. end