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.

291 lines
7.6 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 .webp).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).freeze
  29. IMAGE_MIME_TYPES = %w(image/jpeg image/png image/gif image/webp).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/3gpp).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
  107. include Attachmentable
  108. validates :account, presence: true
  109. validates :description, length: { maximum: 420 }, 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. default_scope { order(id: :asc) }
  115. def local?
  116. remote_url.blank?
  117. end
  118. def needs_redownload?
  119. file.blank? && remote_url.present?
  120. end
  121. def larger_media_format?
  122. video? || gifv? || audio?
  123. end
  124. def audio_or_video?
  125. audio? || video?
  126. end
  127. def to_param
  128. shortcode
  129. end
  130. def focus=(point)
  131. return if point.blank?
  132. x, y = (point.is_a?(Enumerable) ? point : point.split(',')).map(&:to_f)
  133. meta = file.instance_read(:meta) || {}
  134. meta['focus'] = { 'x' => x, 'y' => y }
  135. file.instance_write(:meta, meta)
  136. end
  137. def focus
  138. x = file.meta['focus']['x']
  139. y = file.meta['focus']['y']
  140. "#{x},#{y}"
  141. end
  142. after_commit :reset_parent_cache, on: :update
  143. before_create :prepare_description, unless: :local?
  144. before_create :set_shortcode
  145. before_post_process :set_type_and_extension
  146. before_save :set_meta
  147. class << self
  148. def supported_mime_types
  149. IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  150. end
  151. def supported_file_extensions
  152. IMAGE_FILE_EXTENSIONS + VIDEO_FILE_EXTENSIONS + AUDIO_FILE_EXTENSIONS
  153. end
  154. private
  155. def file_styles(f)
  156. if f.instance.file_content_type == 'image/gif' || VIDEO_CONVERTIBLE_MIME_TYPES.include?(f.instance.file_content_type)
  157. VIDEO_CONVERTED_STYLES
  158. elsif IMAGE_MIME_TYPES.include?(f.instance.file_content_type)
  159. IMAGE_STYLES
  160. elsif VIDEO_MIME_TYPES.include?(f.instance.file_content_type)
  161. VIDEO_STYLES
  162. else
  163. AUDIO_STYLES
  164. end
  165. end
  166. def file_processors(f)
  167. if f.file_content_type == 'image/gif'
  168. [:gif_transcoder, :blurhash_transcoder]
  169. elsif VIDEO_MIME_TYPES.include?(f.file_content_type)
  170. [:video_transcoder, :blurhash_transcoder, :type_corrector]
  171. elsif AUDIO_MIME_TYPES.include?(f.file_content_type)
  172. [:transcoder, :type_corrector]
  173. else
  174. [:lazy_thumbnail, :blurhash_transcoder, :type_corrector]
  175. end
  176. end
  177. end
  178. private
  179. def set_shortcode
  180. self.type = :unknown if file.blank? && !type_changed?
  181. return unless local?
  182. loop do
  183. self.shortcode = SecureRandom.urlsafe_base64(14)
  184. break if MediaAttachment.find_by(shortcode: shortcode).nil?
  185. end
  186. end
  187. def prepare_description
  188. self.description = description.strip[0...420] unless description.nil?
  189. end
  190. def set_type_and_extension
  191. self.type = begin
  192. if VIDEO_MIME_TYPES.include?(file_content_type)
  193. :video
  194. elsif AUDIO_MIME_TYPES.include?(file_content_type)
  195. :audio
  196. else
  197. :image
  198. end
  199. end
  200. end
  201. def set_meta
  202. meta = populate_meta
  203. return if meta == {}
  204. file.instance_write :meta, meta
  205. end
  206. def populate_meta
  207. meta = file.instance_read(:meta) || {}
  208. file.queued_for_write.each do |style, file|
  209. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  210. end
  211. meta
  212. end
  213. def image_geometry(file)
  214. width, height = FastImage.size(file.path)
  215. return {} if width.nil?
  216. {
  217. width: width,
  218. height: height,
  219. size: "#{width}x#{height}",
  220. aspect: width.to_f / height.to_f,
  221. }
  222. end
  223. def video_metadata(file)
  224. movie = FFMPEG::Movie.new(file.path)
  225. return {} unless movie.valid?
  226. {
  227. width: movie.width,
  228. height: movie.height,
  229. frame_rate: movie.frame_rate,
  230. duration: movie.duration,
  231. bitrate: movie.bitrate,
  232. }.compact
  233. end
  234. def reset_parent_cache
  235. return if status_id.nil?
  236. Rails.cache.delete("statuses/#{status_id}")
  237. end
  238. end