The code powering m.abunchtell.com https://m.abunchtell.com
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

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