The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

329 lines
8.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. # scheduled_status_id :bigint(8)
  21. # blurhash :string
  22. #
  23. class MediaAttachment < ApplicationRecord
  24. self.inheritance_column = nil
  25. enum type: [:image, :gifv, :video, :unknown, :audio]
  26. MAX_DESCRIPTION_LENGTH = 1_500
  27. IMAGE_FILE_EXTENSIONS = %w(.jpg .jpeg .png .gif).freeze
  28. VIDEO_FILE_EXTENSIONS = %w(.webm .mp4 .m4v .mov).freeze
  29. AUDIO_FILE_EXTENSIONS = %w(.ogg .oga .mp3 .wav .flac .opus .aac .m4a .3gp .wma).freeze
  30. IMAGE_MIME_TYPES = %w(image/jpeg image/png image/gif).freeze
  31. VIDEO_MIME_TYPES = %w(video/webm video/mp4 video/quicktime video/ogg).freeze
  32. VIDEO_CONVERTIBLE_MIME_TYPES = %w(video/webm video/quicktime).freeze
  33. AUDIO_MIME_TYPES = %w(audio/wave audio/wav audio/x-wav audio/x-pn-wave audio/ogg audio/mpeg audio/mp3 audio/webm audio/flac audio/aac audio/m4a audio/x-m4a audio/mp4 audio/3gpp video/x-ms-asf).freeze
  34. BLURHASH_OPTIONS = {
  35. x_comp: 4,
  36. y_comp: 4,
  37. }.freeze
  38. IMAGE_STYLES = {
  39. original: {
  40. pixels: 1_638_400, # 1280x1280px
  41. file_geometry_parser: FastGeometryParser,
  42. },
  43. small: {
  44. pixels: 160_000, # 400x400px
  45. file_geometry_parser: FastGeometryParser,
  46. blurhash: BLURHASH_OPTIONS,
  47. },
  48. }.freeze
  49. VIDEO_STYLES = {
  50. small: {
  51. convert_options: {
  52. output: {
  53. 'loglevel' => 'fatal',
  54. vf: 'scale=\'min(400\, iw):min(400\, ih)\':force_original_aspect_ratio=decrease',
  55. },
  56. },
  57. format: 'png',
  58. time: 0,
  59. file_geometry_parser: FastGeometryParser,
  60. blurhash: BLURHASH_OPTIONS,
  61. },
  62. original: {
  63. keep_same_format: true,
  64. convert_options: {
  65. output: {
  66. 'loglevel' => 'fatal',
  67. 'map_metadata' => '-1',
  68. 'c:v' => 'copy',
  69. 'c:a' => 'copy',
  70. },
  71. },
  72. },
  73. }.freeze
  74. AUDIO_STYLES = {
  75. original: {
  76. format: 'mp3',
  77. content_type: 'audio/mpeg',
  78. convert_options: {
  79. output: {
  80. 'loglevel' => 'fatal',
  81. 'map_metadata' => '-1',
  82. 'q:a' => 2,
  83. },
  84. },
  85. },
  86. }.freeze
  87. VIDEO_FORMAT = {
  88. format: 'mp4',
  89. content_type: 'video/mp4',
  90. convert_options: {
  91. output: {
  92. 'loglevel' => 'fatal',
  93. 'movflags' => 'faststart',
  94. 'pix_fmt' => 'yuv420p',
  95. 'vf' => 'scale=\'trunc(iw/2)*2:trunc(ih/2)*2\'',
  96. 'vsync' => 'cfr',
  97. 'c:v' => 'h264',
  98. 'maxrate' => '1300K',
  99. 'bufsize' => '1300K',
  100. 'frames:v' => 60 * 60 * 3,
  101. 'crf' => 18,
  102. 'map_metadata' => '-1',
  103. },
  104. },
  105. }.freeze
  106. VIDEO_CONVERTED_STYLES = {
  107. small: VIDEO_STYLES[:small],
  108. original: VIDEO_FORMAT,
  109. }.freeze
  110. IMAGE_LIMIT = 10.megabytes
  111. VIDEO_LIMIT = 40.megabytes
  112. belongs_to :account, inverse_of: :media_attachments, optional: true
  113. belongs_to :status, inverse_of: :media_attachments, optional: true
  114. belongs_to :scheduled_status, inverse_of: :media_attachments, optional: true
  115. has_attached_file :file,
  116. styles: ->(f) { file_styles f },
  117. processors: ->(f) { file_processors f },
  118. convert_options: { all: '-quality 90 -strip +set modify-date +set create-date' }
  119. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  120. validates_attachment_size :file, less_than: IMAGE_LIMIT, unless: :larger_media_format?
  121. validates_attachment_size :file, less_than: VIDEO_LIMIT, if: :larger_media_format?
  122. remotable_attachment :file, VIDEO_LIMIT, suppress_errors: false
  123. include Attachmentable
  124. validates :account, presence: true
  125. validates :description, length: { maximum: MAX_DESCRIPTION_LENGTH }, if: :local?
  126. scope :attached, -> { where.not(status_id: nil).or(where.not(scheduled_status_id: nil)) }
  127. scope :unattached, -> { where(status_id: nil, scheduled_status_id: nil) }
  128. scope :local, -> { where(remote_url: '') }
  129. scope :remote, -> { where.not(remote_url: '') }
  130. scope :cached, -> { remote.where.not(file_file_name: nil) }
  131. default_scope { order(id: :asc) }
  132. def local?
  133. remote_url.blank?
  134. end
  135. def needs_redownload?
  136. file.blank? && remote_url.present?
  137. end
  138. def larger_media_format?
  139. video? || gifv? || audio?
  140. end
  141. def audio_or_video?
  142. audio? || video?
  143. end
  144. def variant?(other_file_name)
  145. return true if file_file_name == other_file_name
  146. formats = file.styles.values.map(&:format).compact
  147. return false if formats.empty?
  148. extension = File.extname(other_file_name)
  149. formats.include?(extension.delete('.')) && File.basename(other_file_name, extension) == File.basename(file_file_name, File.extname(file_file_name))
  150. end
  151. def to_param
  152. shortcode
  153. end
  154. def focus=(point)
  155. return if point.blank?
  156. x, y = (point.is_a?(Enumerable) ? point : point.split(',')).map(&:to_f)
  157. meta = file.instance_read(:meta) || {}
  158. meta['focus'] = { 'x' => x, 'y' => y }
  159. file.instance_write(:meta, meta)
  160. end
  161. def focus
  162. x = file.meta['focus']['x']
  163. y = file.meta['focus']['y']
  164. "#{x},#{y}"
  165. end
  166. after_commit :reset_parent_cache, on: :update
  167. before_create :prepare_description, unless: :local?
  168. before_create :set_shortcode
  169. before_post_process :set_type_and_extension
  170. before_save :set_meta
  171. class << self
  172. def supported_mime_types
  173. IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  174. end
  175. def supported_file_extensions
  176. IMAGE_FILE_EXTENSIONS + VIDEO_FILE_EXTENSIONS + AUDIO_FILE_EXTENSIONS
  177. end
  178. private
  179. def file_styles(f)
  180. if f.instance.file_content_type == 'image/gif' || VIDEO_CONVERTIBLE_MIME_TYPES.include?(f.instance.file_content_type)
  181. VIDEO_CONVERTED_STYLES
  182. elsif IMAGE_MIME_TYPES.include?(f.instance.file_content_type)
  183. IMAGE_STYLES
  184. elsif VIDEO_MIME_TYPES.include?(f.instance.file_content_type)
  185. VIDEO_STYLES
  186. else
  187. AUDIO_STYLES
  188. end
  189. end
  190. def file_processors(f)
  191. if f.file_content_type == 'image/gif'
  192. [:gif_transcoder, :blurhash_transcoder]
  193. elsif VIDEO_MIME_TYPES.include?(f.file_content_type)
  194. [:video_transcoder, :blurhash_transcoder, :type_corrector]
  195. elsif AUDIO_MIME_TYPES.include?(f.file_content_type)
  196. [:transcoder, :type_corrector]
  197. else
  198. [:lazy_thumbnail, :blurhash_transcoder, :type_corrector]
  199. end
  200. end
  201. end
  202. private
  203. def set_shortcode
  204. self.type = :unknown if file.blank? && !type_changed?
  205. return unless local?
  206. loop do
  207. self.shortcode = SecureRandom.urlsafe_base64(14)
  208. break if MediaAttachment.find_by(shortcode: shortcode).nil?
  209. end
  210. end
  211. def prepare_description
  212. self.description = description.strip[0...MAX_DESCRIPTION_LENGTH] unless description.nil?
  213. end
  214. def set_type_and_extension
  215. self.type = begin
  216. if VIDEO_MIME_TYPES.include?(file_content_type)
  217. :video
  218. elsif AUDIO_MIME_TYPES.include?(file_content_type)
  219. :audio
  220. else
  221. :image
  222. end
  223. end
  224. end
  225. def set_meta
  226. meta = populate_meta
  227. return if meta == {}
  228. file.instance_write :meta, meta
  229. end
  230. def populate_meta
  231. meta = file.instance_read(:meta) || {}
  232. file.queued_for_write.each do |style, file|
  233. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  234. end
  235. meta
  236. end
  237. def image_geometry(file)
  238. width, height = FastImage.size(file.path)
  239. return {} if width.nil?
  240. {
  241. width: width,
  242. height: height,
  243. size: "#{width}x#{height}",
  244. aspect: width.to_f / height,
  245. }
  246. end
  247. def video_metadata(file)
  248. movie = FFMPEG::Movie.new(file.path)
  249. return {} unless movie.valid?
  250. {
  251. width: movie.width,
  252. height: movie.height,
  253. frame_rate: movie.frame_rate,
  254. duration: movie.duration,
  255. bitrate: movie.bitrate,
  256. }.compact
  257. end
  258. def reset_parent_cache
  259. return if status_id.nil?
  260. Rails.cache.delete("statuses/#{status_id}")
  261. end
  262. end