闭社主体 forked from https://github.com/tootsuite/mastodon
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.

63 lines
1.4 KiB

  1. class MediaAttachment < ApplicationRecord
  2. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  3. VIDEO_MIME_TYPES = ['video/webm', 'video/mp4'].freeze
  4. belongs_to :account, inverse_of: :media_attachments
  5. belongs_to :status, inverse_of: :media_attachments
  6. has_attached_file :file,
  7. styles: -> (f) { file_styles f },
  8. processors: -> (f) { f.video? ? [:transcoder] : [:thumbnail] },
  9. convert_options: { all: "-strip" }
  10. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES
  11. validates_attachment_size :file, less_than: 4.megabytes
  12. validates :account, presence: true
  13. def local?
  14. remote_url.blank?
  15. end
  16. def file_remote_url=(url)
  17. self.file = URI.parse(url)
  18. end
  19. def image?
  20. IMAGE_MIME_TYPES.include? file_content_type
  21. end
  22. def video?
  23. VIDEO_MIME_TYPES.include? file_content_type
  24. end
  25. def type
  26. image? ? 'image' : 'video'
  27. end
  28. private
  29. def self.file_styles(f)
  30. if f.instance.image?
  31. {
  32. original: '100%',
  33. small: '510x680>'
  34. }
  35. else
  36. {
  37. original: {
  38. convert_options: {},
  39. format: 'webm'
  40. },
  41. small: {
  42. convert_options: {
  43. output: {
  44. vf: 'scale=\'min(510\, iw):min(680\, ih)\':force_original_aspect_ratio=decrease'
  45. }
  46. },
  47. format: 'png',
  48. time: 1
  49. }
  50. }
  51. end
  52. end
  53. end