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