闭社主体 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.

42 lines
917 B

  1. # frozen_string_literal: true
  2. class StatusLengthValidator < ActiveModel::Validator
  3. MAX_CHARS = 500
  4. URL_PATTERN = %r{
  5. (?:
  6. (#{Twitter::TwitterText::Regex[:valid_url_preceding_chars]})
  7. (#{FetchLinkCardService::URL_PATTERN})
  8. )
  9. }iox
  10. URL_PLACEHOLDER = "\1#{'x' * 23}"
  11. def validate(status)
  12. return unless status.local? && !status.reblog?
  13. @status = status
  14. status.errors.add(:text, I18n.t('statuses.over_character_limit', max: MAX_CHARS)) if too_long?
  15. end
  16. private
  17. def too_long?
  18. countable_length > MAX_CHARS
  19. end
  20. def countable_length
  21. total_text.mb_chars.grapheme_length
  22. end
  23. def total_text
  24. [@status.spoiler_text, countable_text].join
  25. end
  26. def countable_text
  27. return '' if @status.text.nil?
  28. @status.text.dup.tap do |new_text|
  29. new_text.gsub!(URL_PATTERN, URL_PLACEHOLDER)
  30. new_text.gsub!(Account::MENTION_RE, '@\2')
  31. end
  32. end
  33. end