闭社主体 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.

109 lines
2.7 KiB

  1. # frozen_string_literal: true
  2. class MediaAttachment < ApplicationRecord
  3. self.inheritance_column = nil
  4. enum type: [:image, :gifv, :video]
  5. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  6. VIDEO_MIME_TYPES = ['video/webm', 'video/mp4'].freeze
  7. IMAGE_STYLES = { original: '1280x1280>', small: '400x400>' }.freeze
  8. VIDEO_STYLES = {
  9. small: {
  10. convert_options: {
  11. output: {
  12. vf: 'scale=\'min(400\, iw):min(400\, ih)\':force_original_aspect_ratio=decrease',
  13. },
  14. },
  15. format: 'png',
  16. time: 0,
  17. },
  18. }.freeze
  19. belongs_to :account, inverse_of: :media_attachments
  20. belongs_to :status, inverse_of: :media_attachments
  21. has_attached_file :file,
  22. styles: ->(f) { file_styles f },
  23. processors: ->(f) { file_processors f },
  24. convert_options: { all: '-quality 90 -strip' }
  25. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES
  26. validates_attachment_size :file, less_than: 8.megabytes
  27. validates :account, presence: true
  28. scope :attached, -> { where.not(status_id: nil) }
  29. scope :local, -> { where(remote_url: '') }
  30. default_scope { order('id asc') }
  31. def local?
  32. remote_url.blank?
  33. end
  34. def file_remote_url=(url)
  35. self.file = URI.parse(url)
  36. end
  37. def to_param
  38. shortcode
  39. end
  40. before_create :set_shortcode
  41. before_post_process :set_type
  42. class << self
  43. private
  44. def file_styles(f)
  45. if f.instance.file_content_type == 'image/gif'
  46. {
  47. small: IMAGE_STYLES[:small],
  48. original: {
  49. format: 'mp4',
  50. convert_options: {
  51. output: {
  52. 'movflags' => 'faststart',
  53. 'pix_fmt' => 'yuv420p',
  54. 'vf' => 'scale=\'trunc(iw/2)*2:trunc(ih/2)*2\'',
  55. 'vsync' => 'cfr',
  56. 'b:v' => '1300K',
  57. 'maxrate' => '500K',
  58. 'crf' => 6,
  59. },
  60. },
  61. },
  62. }
  63. elsif IMAGE_MIME_TYPES.include? f.instance.file_content_type
  64. IMAGE_STYLES
  65. else
  66. VIDEO_STYLES
  67. end
  68. end
  69. def file_processors(f)
  70. if f.file_content_type == 'image/gif'
  71. [:gif_transcoder]
  72. elsif VIDEO_MIME_TYPES.include? f.file_content_type
  73. [:video_transcoder]
  74. else
  75. [:thumbnail]
  76. end
  77. end
  78. end
  79. private
  80. def set_shortcode
  81. return unless local?
  82. loop do
  83. self.shortcode = SecureRandom.urlsafe_base64(14)
  84. break if MediaAttachment.find_by(shortcode: shortcode).nil?
  85. end
  86. end
  87. def set_type
  88. self.type = VIDEO_MIME_TYPES.include?(file_content_type) ? :video : :image
  89. end
  90. end