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.

258 lines
6.7 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: media_attachments
  5. #
  6. # id :integer not null, primary key
  7. # status_id :integer
  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 :integer
  19. # description :text
  20. #
  21. require 'mime/types'
  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'].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'].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. geometry: '1280x1280>',
  34. file_geometry_parser: FastGeometryParser,
  35. },
  36. small: {
  37. geometry: '400x400>',
  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. LIMIT = 8.megabytes
  68. belongs_to :account, inverse_of: :media_attachments, optional: true
  69. belongs_to :status, inverse_of: :media_attachments, optional: true
  70. has_attached_file :file,
  71. styles: ->(f) { file_styles f },
  72. processors: ->(f) { file_processors f },
  73. convert_options: { all: '-quality 90 -strip' }
  74. include Remotable
  75. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  76. validates_attachment_size :file, less_than: LIMIT
  77. remotable_attachment :file, LIMIT
  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. 'b:v' => '1300K',
  125. 'maxrate' => '500K',
  126. 'bufsize' => '1300K',
  127. 'crf' => 18,
  128. },
  129. },
  130. },
  131. }
  132. elsif IMAGE_MIME_TYPES.include? f.instance.file_content_type
  133. IMAGE_STYLES
  134. elsif AUDIO_MIME_TYPES.include? f.instance.file_content_type
  135. AUDIO_STYLES
  136. else
  137. VIDEO_STYLES
  138. end
  139. end
  140. def file_processors(f)
  141. if f.file_content_type == 'image/gif'
  142. [:gif_transcoder]
  143. elsif VIDEO_MIME_TYPES.include? f.file_content_type
  144. [:video_transcoder]
  145. elsif AUDIO_MIME_TYPES.include? f.file_content_type
  146. [:audio_transcoder]
  147. else
  148. [:thumbnail]
  149. end
  150. end
  151. end
  152. private
  153. def set_shortcode
  154. self.type = :unknown if file.blank? && !type_changed?
  155. return unless local?
  156. loop do
  157. self.shortcode = SecureRandom.urlsafe_base64(14)
  158. break if MediaAttachment.find_by(shortcode: shortcode).nil?
  159. end
  160. end
  161. def prepare_description
  162. self.description = description.strip[0...420] unless description.nil?
  163. end
  164. def set_type_and_extension
  165. self.type = VIDEO_MIME_TYPES.include?(file_content_type) ? :video : AUDIO_MIME_TYPES.include?(file_content_type) ? :audio : :image
  166. extension = AUDIO_MIME_TYPES.include?(file_content_type) ? '.mp4' : appropriate_extension
  167. basename = Paperclip::Interpolations.basename(file, :original)
  168. file.instance_write :file_name, [basename, extension].delete_if(&:blank?).join('.')
  169. end
  170. def set_meta
  171. meta = populate_meta
  172. return if meta == {}
  173. file.instance_write :meta, meta
  174. end
  175. def populate_meta
  176. meta = file.instance_read(:meta) || {}
  177. file.queued_for_write.each do |style, file|
  178. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  179. end
  180. meta
  181. end
  182. def image_geometry(file)
  183. width, height = FastImage.size(file.path)
  184. return {} if width.nil?
  185. {
  186. width: width,
  187. height: height,
  188. size: "#{width}x#{height}",
  189. aspect: width.to_f / height.to_f,
  190. }
  191. end
  192. def video_metadata(file)
  193. movie = FFMPEG::Movie.new(file.path)
  194. return {} unless movie.valid?
  195. {
  196. width: movie.width,
  197. height: movie.height,
  198. frame_rate: movie.frame_rate,
  199. duration: movie.duration,
  200. bitrate: movie.bitrate,
  201. }
  202. end
  203. def appropriate_extension
  204. mime_type = MIME::Types[file.content_type]
  205. extensions_for_mime_type = mime_type.empty? ? [] : mime_type.first.extensions
  206. original_extension = Paperclip::Interpolations.extension(file, :original)
  207. extensions_for_mime_type.include?(original_extension) ? original_extension : extensions_for_mime_type.first
  208. end
  209. end