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.

28 lines
934 B

  1. # frozen_string_literal: true
  2. class ReactionValidator < ActiveModel::Validator
  3. SUPPORTED_EMOJIS = Oj.load(File.read(Rails.root.join('app', 'javascript', 'mastodon', 'features', 'emoji', 'emoji_map.json'))).keys.freeze
  4. LIMIT = 8
  5. def validate(reaction)
  6. return if reaction.name.blank?
  7. reaction.errors.add(:name, I18n.t('reactions.errors.unrecognized_emoji')) if reaction.custom_emoji_id.blank? && !unicode_emoji?(reaction.name)
  8. reaction.errors.add(:base, I18n.t('reactions.errors.limit_reached')) if new_reaction?(reaction) && limit_reached?(reaction)
  9. end
  10. private
  11. def unicode_emoji?(name)
  12. SUPPORTED_EMOJIS.include?(name)
  13. end
  14. def new_reaction?(reaction)
  15. !reaction.announcement.announcement_reactions.where(name: reaction.name).exists?
  16. end
  17. def limit_reached?(reaction)
  18. reaction.announcement.announcement_reactions.where.not(name: reaction.name).count('distinct name') >= LIMIT
  19. end
  20. end