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