1
0

custom_emoji.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: custom_emojis
  5. #
  6. # id :bigint(8) not null, primary key
  7. # shortcode :string default(""), not null
  8. # domain :string
  9. # image_file_name :string
  10. # image_content_type :string
  11. # image_file_size :integer
  12. # image_updated_at :datetime
  13. # created_at :datetime not null
  14. # updated_at :datetime not null
  15. # disabled :boolean default(FALSE), not null
  16. # uri :string
  17. # image_remote_url :string
  18. # visible_in_picker :boolean default(TRUE), not null
  19. #
  20. class CustomEmoji < ApplicationRecord
  21. LIMIT = 50.kilobytes
  22. SHORTCODE_RE_FRAGMENT = '[a-zA-Z0-9_]{2,}'
  23. SCAN_RE = /(?<=[^[:alnum:]:]|\n|^)
  24. :(#{SHORTCODE_RE_FRAGMENT}):
  25. (?=[^[:alnum:]:]|$)/x
  26. has_one :local_counterpart, -> { where(domain: nil) }, class_name: 'CustomEmoji', primary_key: :shortcode, foreign_key: :shortcode
  27. has_attached_file :image, styles: { static: { format: 'png', convert_options: '-coalesce -strip' } }
  28. before_validation :downcase_domain
  29. validates_attachment :image, content_type: { content_type: 'image/png' }, presence: true, size: { less_than: LIMIT }
  30. validates :shortcode, uniqueness: { scope: :domain }, format: { with: /\A#{SHORTCODE_RE_FRAGMENT}\z/ }, length: { minimum: 2 }
  31. scope :local, -> { where(domain: nil) }
  32. scope :remote, -> { where.not(domain: nil) }
  33. scope :alphabetic, -> { order(domain: :asc, shortcode: :asc) }
  34. remotable_attachment :image, LIMIT
  35. include Attachmentable
  36. after_commit :remove_entity_cache
  37. def local?
  38. domain.nil?
  39. end
  40. def object_type
  41. :emoji
  42. end
  43. class << self
  44. def from_text(text, domain)
  45. return [] if text.blank?
  46. shortcodes = text.scan(SCAN_RE).map(&:first).uniq
  47. return [] if shortcodes.empty?
  48. EntityCache.instance.emoji(shortcodes, domain)
  49. end
  50. def search(shortcode)
  51. where('"custom_emojis"."shortcode" ILIKE ?', "%#{shortcode}%")
  52. end
  53. end
  54. private
  55. def remove_entity_cache
  56. Rails.cache.delete(EntityCache.instance.to_key(:emoji, shortcode, domain))
  57. end
  58. def downcase_domain
  59. self.domain = domain.downcase unless domain.nil?
  60. end
  61. end