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.

65 lines
1.6 KiB

  1. # frozen_string_literal: true
  2. class MediaAttachment < ApplicationRecord
  3. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  4. VIDEO_MIME_TYPES = ['video/webm', 'video/mp4'].freeze
  5. belongs_to :account, inverse_of: :media_attachments
  6. belongs_to :status, inverse_of: :media_attachments
  7. has_attached_file :file,
  8. styles: -> (f) { file_styles f },
  9. processors: -> (f) { f.video? ? [:transcoder] : [:thumbnail] },
  10. convert_options: { all: '-strip' }
  11. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES
  12. validates_attachment_size :file, less_than: 4.megabytes
  13. validates :account, presence: true
  14. def local?
  15. remote_url.blank?
  16. end
  17. def file_remote_url=(url)
  18. self.file = URI.parse(url)
  19. rescue OpenURI::HTTPError => e
  20. Rails.logger.debug "Error fetching remote attachment: #{e}"
  21. end
  22. def image?
  23. IMAGE_MIME_TYPES.include? file_content_type
  24. end
  25. def video?
  26. VIDEO_MIME_TYPES.include? file_content_type
  27. end
  28. def type
  29. image? ? 'image' : 'video'
  30. end
  31. class << self
  32. private
  33. def file_styles(f)
  34. if f.instance.image?
  35. {
  36. original: '100%',
  37. small: '510x680>',
  38. }
  39. else
  40. {
  41. small: {
  42. convert_options: {
  43. output: {
  44. vf: 'scale=\'min(510\, iw):min(680\, ih)\':force_original_aspect_ratio=decrease',
  45. },
  46. },
  47. format: 'png',
  48. time: 1,
  49. },
  50. }
  51. end
  52. end
  53. end
  54. end