The code powering m.abunchtell.com https://m.abunchtell.com
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

243 wiersze
6.1 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. #
  22. class MediaAttachment < ApplicationRecord
  23. self.inheritance_column = nil
  24. enum type: [:image, :gifv, :video, :unknown]
  25. IMAGE_FILE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif'].freeze
  26. VIDEO_FILE_EXTENSIONS = ['.webm', '.mp4', '.m4v', '.mov'].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. 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. VIDEO_STYLES = {
  41. small: {
  42. convert_options: {
  43. output: {
  44. vf: 'scale=\'min(400\, iw):min(400\, ih)\':force_original_aspect_ratio=decrease',
  45. },
  46. },
  47. format: 'png',
  48. time: 0,
  49. },
  50. }.freeze
  51. VIDEO_FORMAT = {
  52. format: 'mp4',
  53. convert_options: {
  54. output: {
  55. 'loglevel' => 'fatal',
  56. 'movflags' => 'faststart',
  57. 'pix_fmt' => 'yuv420p',
  58. 'vf' => 'scale=\'trunc(iw/2)*2:trunc(ih/2)*2\'',
  59. 'vsync' => 'cfr',
  60. 'c:v' => 'h264',
  61. 'b:v' => '500K',
  62. 'maxrate' => '1300K',
  63. 'bufsize' => '1300K',
  64. 'crf' => 18,
  65. },
  66. },
  67. }.freeze
  68. IMAGE_LIMIT = 8.megabytes
  69. VIDEO_LIMIT = 40.megabytes
  70. belongs_to :account, inverse_of: :media_attachments, optional: true
  71. belongs_to :status, inverse_of: :media_attachments, optional: true
  72. belongs_to :scheduled_status, inverse_of: :media_attachments, optional: true
  73. has_attached_file :file,
  74. styles: ->(f) { file_styles f },
  75. processors: ->(f) { file_processors f },
  76. convert_options: { all: '-quality 90 -strip' }
  77. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES
  78. validates_attachment_size :file, less_than: IMAGE_LIMIT, unless: :video?
  79. validates_attachment_size :file, less_than: VIDEO_LIMIT, if: :video?
  80. remotable_attachment :file, VIDEO_LIMIT
  81. include Attachmentable
  82. validates :account, presence: true
  83. validates :description, length: { maximum: 420 }, if: :local?
  84. scope :attached, -> { where.not(status_id: nil).or(where.not(scheduled_status_id: nil)) }
  85. scope :unattached, -> { where(status_id: nil, scheduled_status_id: nil) }
  86. scope :local, -> { where(remote_url: '') }
  87. scope :remote, -> { where.not(remote_url: '') }
  88. default_scope { order(id: :asc) }
  89. def local?
  90. remote_url.blank?
  91. end
  92. def needs_redownload?
  93. file.blank? && remote_url.present?
  94. end
  95. def to_param
  96. shortcode
  97. end
  98. def focus=(point)
  99. return if point.blank?
  100. x, y = (point.is_a?(Enumerable) ? point : point.split(',')).map(&:to_f)
  101. meta = file.instance_read(:meta) || {}
  102. meta['focus'] = { 'x' => x, 'y' => y }
  103. file.instance_write(:meta, meta)
  104. end
  105. def focus
  106. x = file.meta['focus']['x']
  107. y = file.meta['focus']['y']
  108. "#{x},#{y}"
  109. end
  110. after_commit :reset_parent_cache, on: :update
  111. before_create :prepare_description, unless: :local?
  112. before_create :set_shortcode
  113. before_post_process :set_type_and_extension
  114. before_save :set_meta
  115. class << self
  116. private
  117. def file_styles(f)
  118. if f.instance.file_content_type == 'image/gif'
  119. {
  120. small: IMAGE_STYLES[:small],
  121. original: VIDEO_FORMAT,
  122. }
  123. elsif IMAGE_MIME_TYPES.include? f.instance.file_content_type
  124. IMAGE_STYLES
  125. elsif VIDEO_CONVERTIBLE_MIME_TYPES.include?(f.instance.file_content_type)
  126. {
  127. small: VIDEO_STYLES[:small],
  128. original: VIDEO_FORMAT,
  129. }
  130. else
  131. VIDEO_STYLES
  132. end
  133. end
  134. def file_processors(f)
  135. if f.file_content_type == 'image/gif'
  136. [:gif_transcoder]
  137. elsif VIDEO_MIME_TYPES.include? f.file_content_type
  138. [:video_transcoder]
  139. else
  140. [:lazy_thumbnail]
  141. end
  142. end
  143. end
  144. private
  145. def set_shortcode
  146. self.type = :unknown if file.blank? && !type_changed?
  147. return unless local?
  148. loop do
  149. self.shortcode = SecureRandom.urlsafe_base64(14)
  150. break if MediaAttachment.find_by(shortcode: shortcode).nil?
  151. end
  152. end
  153. def prepare_description
  154. self.description = description.strip[0...420] unless description.nil?
  155. end
  156. def set_type_and_extension
  157. self.type = VIDEO_MIME_TYPES.include?(file_content_type) ? :video : :image
  158. end
  159. def set_meta
  160. meta = populate_meta
  161. return if meta == {}
  162. file.instance_write :meta, meta
  163. end
  164. def populate_meta
  165. meta = file.instance_read(:meta) || {}
  166. file.queued_for_write.each do |style, file|
  167. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  168. end
  169. meta
  170. end
  171. def image_geometry(file)
  172. width, height = FastImage.size(file.path)
  173. return {} if width.nil?
  174. {
  175. width: width,
  176. height: height,
  177. size: "#{width}x#{height}",
  178. aspect: width.to_f / height.to_f,
  179. }
  180. end
  181. def video_metadata(file)
  182. movie = FFMPEG::Movie.new(file.path)
  183. return {} unless movie.valid?
  184. {
  185. width: movie.width,
  186. height: movie.height,
  187. frame_rate: movie.frame_rate,
  188. duration: movie.duration,
  189. bitrate: movie.bitrate,
  190. }
  191. end
  192. def reset_parent_cache
  193. return if status_id.nil?
  194. Rails.cache.delete("statuses/#{status_id}")
  195. end
  196. end