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.

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