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.

68 lines
2.0 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: custom_emojis
  5. #
  6. # id :integer 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. validates_attachment :image, content_type: { content_type: 'image/png' }, presence: true, size: { less_than: LIMIT }
  29. validates :shortcode, uniqueness: { scope: :domain }, format: { with: /\A#{SHORTCODE_RE_FRAGMENT}\z/ }, length: { minimum: 2 }
  30. scope :local, -> { where(domain: nil) }
  31. scope :remote, -> { where.not(domain: nil) }
  32. scope :alphabetic, -> { order(domain: :asc, shortcode: :asc) }
  33. remotable_attachment :image, LIMIT
  34. include Attachmentable
  35. def local?
  36. domain.nil?
  37. end
  38. def object_type
  39. :emoji
  40. end
  41. class << self
  42. def from_text(text, domain)
  43. return [] if text.blank?
  44. shortcodes = text.scan(SCAN_RE).map(&:first).uniq
  45. return [] if shortcodes.empty?
  46. where(shortcode: shortcodes, domain: domain, disabled: false)
  47. end
  48. def search(shortcode)
  49. where('"custom_emojis"."shortcode" ILIKE ?', "%#{shortcode}%")
  50. end
  51. end
  52. end