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.

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