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.

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