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

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