闭社主体 forked from https://github.com/tootsuite/mastodon
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.

66 lines
2.0 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: preview_cards
  5. #
  6. # id :integer 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. #
  25. class PreviewCard < ApplicationRecord
  26. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  27. self.inheritance_column = false
  28. enum type: [:link, :photo, :video, :rich]
  29. has_and_belongs_to_many :statuses
  30. has_attached_file :image, styles: { original: '280x280>' }, convert_options: { all: '-quality 80 -strip' }
  31. include Attachmentable
  32. include Remotable
  33. validates :url, presence: true, uniqueness: true
  34. validates_attachment_content_type :image, content_type: IMAGE_MIME_TYPES
  35. validates_attachment_size :image, less_than: 1.megabytes
  36. before_save :extract_dimensions, if: :link?
  37. def save_with_optional_image!
  38. save!
  39. rescue ActiveRecord::RecordInvalid
  40. self.image = nil
  41. save!
  42. end
  43. private
  44. def extract_dimensions
  45. file = image.queued_for_write[:original]
  46. return if file.nil?
  47. geo = Paperclip::Geometry.from_file(file)
  48. self.width = geo.width.to_i
  49. self.height = geo.height.to_i
  50. rescue Paperclip::Errors::NotIdentifiedByImageMagickError
  51. nil
  52. end
  53. end