The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

86 lines
2.4 KiB

  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. # category_id :bigint(8)
  20. #
  21. class CustomEmoji < ApplicationRecord
  22. LIMIT = 50.kilobytes
  23. SHORTCODE_RE_FRAGMENT = '[a-zA-Z0-9_]{2,}'
  24. SCAN_RE = /(?<=[^[:alnum:]:]|\n|^)
  25. :(#{SHORTCODE_RE_FRAGMENT}):
  26. (?=[^[:alnum:]:]|$)/x
  27. belongs_to :category, class_name: 'CustomEmojiCategory', optional: true
  28. has_one :local_counterpart, -> { where(domain: nil) }, class_name: 'CustomEmoji', primary_key: :shortcode, foreign_key: :shortcode
  29. has_attached_file :image, styles: { static: { format: 'png', convert_options: '-coalesce -strip' } }
  30. before_validation :downcase_domain
  31. validates_attachment :image, content_type: { content_type: 'image/png' }, presence: true, size: { less_than: LIMIT }
  32. validates :shortcode, uniqueness: { scope: :domain }, format: { with: /\A#{SHORTCODE_RE_FRAGMENT}\z/ }, length: { minimum: 2 }
  33. scope :local, -> { where(domain: nil) }
  34. scope :remote, -> { where.not(domain: nil) }
  35. scope :alphabetic, -> { order(domain: :asc, shortcode: :asc) }
  36. scope :by_domain_and_subdomains, ->(domain) { where(domain: domain).or(where(arel_table[:domain].matches('%.' + domain))) }
  37. remotable_attachment :image, LIMIT
  38. include Attachmentable
  39. after_commit :remove_entity_cache
  40. def local?
  41. domain.nil?
  42. end
  43. def object_type
  44. :emoji
  45. end
  46. class << self
  47. def from_text(text, domain)
  48. return [] if text.blank?
  49. shortcodes = text.scan(SCAN_RE).map(&:first).uniq
  50. return [] if shortcodes.empty?
  51. EntityCache.instance.emoji(shortcodes, domain)
  52. end
  53. def search(shortcode)
  54. where('"custom_emojis"."shortcode" ILIKE ?', "%#{shortcode}%")
  55. end
  56. end
  57. private
  58. def remove_entity_cache
  59. Rails.cache.delete(EntityCache.instance.to_key(:emoji, shortcode, domain))
  60. end
  61. def downcase_domain
  62. self.domain = domain.downcase unless domain.nil?
  63. end
  64. end