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

239 lines
5.9 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: media_attachments
  5. #
  6. # id :bigint(8) not null, primary key
  7. # status_id :bigint(8)
  8. # file_file_name :string
  9. # file_content_type :string
  10. # file_file_size :integer
  11. # file_updated_at :datetime
  12. # remote_url :string default(""), not null
  13. # created_at :datetime not null
  14. # updated_at :datetime not null
  15. # shortcode :string
  16. # type :integer default("image"), not null
  17. # file_meta :json
  18. # account_id :bigint(8)
  19. # description :text
  20. #
  21. class MediaAttachment < ApplicationRecord
  22. self.inheritance_column = nil
  23. enum type: [:image, :gifv, :video, :unknown]
  24. IMAGE_FILE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif'].freeze
  25. VIDEO_FILE_EXTENSIONS = ['.webm', '.mp4', '.m4v', '.mov'].freeze
  26. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  27. VIDEO_MIME_TYPES = ['video/webm', 'video/mp4', 'video/quicktime'].freeze
  28. VIDEO_CONVERTIBLE_MIME_TYPES = ['video/webm', 'video/quicktime'].freeze
  29. IMAGE_STYLES = {
  30. original: {
  31. pixels: 1_638_400, # 1280x1280px
  32. file_geometry_parser: FastGeometryParser,
  33. },
  34. small: {
  35. pixels: 160_000, # 400x400px
  36. file_geometry_parser: FastGeometryParser,
  37. },
  38. }.freeze
  39. VIDEO_STYLES = {
  40. small: {
  41. convert_options: {
  42. output: {
  43. vf: 'scale=\'min(400\, iw):min(400\, ih)\':force_original_aspect_ratio=decrease',
  44. },
  45. },
  46. format: 'png',
  47. time: 0,
  48. },
  49. }.freeze
  50. VIDEO_FORMAT = {
  51. format: 'mp4',
  52. convert_options: {
  53. output: {
  54. 'movflags' => 'faststart',
  55. 'pix_fmt' => 'yuv420p',
  56. 'vf' => 'scale=\'trunc(iw/2)*2:trunc(ih/2)*2\'',
  57. 'vsync' => 'cfr',
  58. 'c:v' => 'h264',
  59. 'b:v' => '500K',
  60. 'maxrate' => '1300K',
  61. 'bufsize' => '1300K',
  62. 'crf' => 18,
  63. },
  64. },
  65. }.freeze
  66. IMAGE_LIMIT = 8.megabytes
  67. VIDEO_LIMIT = 40.megabytes
  68. belongs_to :account, inverse_of: :media_attachments, optional: true
  69. belongs_to :status, inverse_of: :media_attachments, optional: true
  70. has_attached_file :file,
  71. styles: ->(f) { file_styles f },
  72. processors: ->(f) { file_processors f },
  73. convert_options: { all: '-quality 90 -strip' }
  74. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES
  75. validates_attachment_size :file, less_than: IMAGE_LIMIT, unless: :video?
  76. validates_attachment_size :file, less_than: VIDEO_LIMIT, if: :video?
  77. remotable_attachment :file, VIDEO_LIMIT
  78. include Attachmentable
  79. validates :account, presence: true
  80. validates :description, length: { maximum: 420 }, if: :local?
  81. scope :attached, -> { where.not(status_id: nil) }
  82. scope :unattached, -> { where(status_id: nil) }
  83. scope :local, -> { where(remote_url: '') }
  84. scope :remote, -> { where.not(remote_url: '') }
  85. default_scope { order(id: :asc) }
  86. def local?
  87. remote_url.blank?
  88. end
  89. def needs_redownload?
  90. file.blank? && remote_url.present?
  91. end
  92. def to_param
  93. shortcode
  94. end
  95. def focus=(point)
  96. return if point.blank?
  97. x, y = (point.is_a?(Enumerable) ? point : point.split(',')).map(&:to_f)
  98. meta = file.instance_read(:meta) || {}
  99. meta['focus'] = { 'x' => x, 'y' => y }
  100. file.instance_write(:meta, meta)
  101. end
  102. def focus
  103. x = file.meta['focus']['x']
  104. y = file.meta['focus']['y']
  105. "#{x},#{y}"
  106. end
  107. after_commit :reset_parent_cache, on: :update
  108. before_create :prepare_description, unless: :local?
  109. before_create :set_shortcode
  110. before_post_process :set_type_and_extension
  111. before_save :set_meta
  112. class << self
  113. private
  114. def file_styles(f)
  115. if f.instance.file_content_type == 'image/gif'
  116. {
  117. small: IMAGE_STYLES[:small],
  118. original: VIDEO_FORMAT,
  119. }
  120. elsif IMAGE_MIME_TYPES.include? f.instance.file_content_type
  121. IMAGE_STYLES
  122. elsif VIDEO_CONVERTIBLE_MIME_TYPES.include?(f.instance.file_content_type)
  123. {
  124. small: VIDEO_STYLES[:small],
  125. original: VIDEO_FORMAT,
  126. }
  127. else
  128. VIDEO_STYLES
  129. end
  130. end
  131. def file_processors(f)
  132. if f.file_content_type == 'image/gif'
  133. [:gif_transcoder]
  134. elsif VIDEO_MIME_TYPES.include? f.file_content_type
  135. [:video_transcoder]
  136. else
  137. [:lazy_thumbnail]
  138. end
  139. end
  140. end
  141. private
  142. def set_shortcode
  143. self.type = :unknown if file.blank? && !type_changed?
  144. return unless local?
  145. loop do
  146. self.shortcode = SecureRandom.urlsafe_base64(14)
  147. break if MediaAttachment.find_by(shortcode: shortcode).nil?
  148. end
  149. end
  150. def prepare_description
  151. self.description = description.strip[0...420] unless description.nil?
  152. end
  153. def set_type_and_extension
  154. self.type = VIDEO_MIME_TYPES.include?(file_content_type) ? :video : :image
  155. end
  156. def set_meta
  157. meta = populate_meta
  158. return if meta == {}
  159. file.instance_write :meta, meta
  160. end
  161. def populate_meta
  162. meta = file.instance_read(:meta) || {}
  163. file.queued_for_write.each do |style, file|
  164. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  165. end
  166. meta
  167. end
  168. def image_geometry(file)
  169. width, height = FastImage.size(file.path)
  170. return {} if width.nil?
  171. {
  172. width: width,
  173. height: height,
  174. size: "#{width}x#{height}",
  175. aspect: width.to_f / height.to_f,
  176. }
  177. end
  178. def video_metadata(file)
  179. movie = FFMPEG::Movie.new(file.path)
  180. return {} unless movie.valid?
  181. {
  182. width: movie.width,
  183. height: movie.height,
  184. frame_rate: movie.frame_rate,
  185. duration: movie.duration,
  186. bitrate: movie.bitrate,
  187. }
  188. end
  189. def reset_parent_cache
  190. return if status_id.nil?
  191. Rails.cache.delete("statuses/#{status_id}")
  192. end
  193. end