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

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