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.

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