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.

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