The code powering m.abunchtell.com https://m.abunchtell.com
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

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