tag.rb 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: tags
  5. #
  6. # id :bigint(8) not null, primary key
  7. # name :string default(""), not null
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. # usable :boolean
  11. # trendable :boolean
  12. # listable :boolean
  13. # reviewed_at :datetime
  14. # requested_review_at :datetime
  15. # last_status_at :datetime
  16. # max_score :float
  17. # max_score_at :datetime
  18. # display_name :string
  19. #
  20. class Tag < ApplicationRecord
  21. include Paginable
  22. include Reviewable
  23. # rubocop:disable Rails/HasAndBelongsToMany
  24. has_and_belongs_to_many :statuses
  25. has_and_belongs_to_many :accounts
  26. # rubocop:enable Rails/HasAndBelongsToMany
  27. has_many :passive_relationships, class_name: 'TagFollow', inverse_of: :tag, dependent: :destroy
  28. has_many :featured_tags, dependent: :destroy, inverse_of: :tag
  29. has_many :followers, through: :passive_relationships, source: :account
  30. HASHTAG_SEPARATORS = "_\u00B7\u30FB\u200c"
  31. HASHTAG_FIRST_SEQUENCE_CHUNK_ONE = "[[:word:]_][[:word:]#{HASHTAG_SEPARATORS}]*[[:alpha:]#{HASHTAG_SEPARATORS}]"
  32. HASHTAG_FIRST_SEQUENCE_CHUNK_TWO = "[[:word:]#{HASHTAG_SEPARATORS}]*[[:word:]_]"
  33. HASHTAG_FIRST_SEQUENCE = "(#{HASHTAG_FIRST_SEQUENCE_CHUNK_ONE}#{HASHTAG_FIRST_SEQUENCE_CHUNK_TWO})"
  34. HASHTAG_LAST_SEQUENCE = '([[:word:]_]*[[:alpha:]][[:word:]_]*)'
  35. HASHTAG_NAME_PAT = "#{HASHTAG_FIRST_SEQUENCE}|#{HASHTAG_LAST_SEQUENCE}"
  36. HASHTAG_RE = %r{(?<![=/)\p{Alnum}])#(#{HASHTAG_NAME_PAT})}
  37. HASHTAG_NAME_RE = /\A(#{HASHTAG_NAME_PAT})\z/i
  38. HASHTAG_INVALID_CHARS_RE = /[^[:alnum:]\u0E47-\u0E4E#{HASHTAG_SEPARATORS}]/
  39. RECENT_STATUS_LIMIT = 1000
  40. validates :name, presence: true, format: { with: HASHTAG_NAME_RE }
  41. validates :display_name, format: { with: HASHTAG_NAME_RE }
  42. validate :validate_name_change, if: -> { !new_record? && name_changed? }
  43. validate :validate_display_name_change, if: -> { !new_record? && display_name_changed? }
  44. scope :pending_review, -> { unreviewed.where.not(requested_review_at: nil) }
  45. scope :usable, -> { where(usable: [true, nil]) }
  46. scope :not_usable, -> { where(usable: false) }
  47. scope :listable, -> { where(listable: [true, nil]) }
  48. scope :trendable, -> { Setting.trendable_by_default ? where(trendable: [true, nil]) : where(trendable: true) }
  49. scope :not_trendable, -> { where(trendable: false) }
  50. scope :suggestions_for_account, ->(account) { recently_used(account).not_featured_by(account) }
  51. scope :not_featured_by, ->(account) { where.not(id: account.featured_tags.select(:tag_id)) }
  52. scope :recently_used, lambda { |account|
  53. joins(:statuses)
  54. .where(statuses: { id: account.statuses.select(:id).limit(RECENT_STATUS_LIMIT) })
  55. .group(:id).order(Arel.sql('count(*) desc'))
  56. }
  57. scope :matches_name, ->(term) { where(arel_table[:name].lower.matches(arel_table.lower("#{sanitize_sql_like(Tag.normalize(term))}%"), nil, true)) } # Search with case-sensitive to use B-tree index
  58. update_index('tags', :self)
  59. def to_param
  60. name
  61. end
  62. def display_name
  63. attributes['display_name'] || name
  64. end
  65. def formatted_name
  66. "##{display_name}"
  67. end
  68. def usable
  69. boolean_with_default('usable', true)
  70. end
  71. alias usable? usable
  72. def listable
  73. boolean_with_default('listable', true)
  74. end
  75. alias listable? listable
  76. def trendable
  77. boolean_with_default('trendable', Setting.trendable_by_default)
  78. end
  79. alias trendable? trendable
  80. def decaying?
  81. max_score_at && max_score_at >= Trends.tags.options[:max_score_cooldown].ago && max_score_at < 1.day.ago
  82. end
  83. def history
  84. @history ||= Trends::History.new('tags', id)
  85. end
  86. class << self
  87. def find_or_create_by_names(name_or_names)
  88. names = Array(name_or_names).map { |str| [normalize(str), str] }.uniq(&:first)
  89. names.map do |(normalized_name, display_name)|
  90. tag = matching_name(normalized_name).first || create(name: normalized_name,
  91. display_name: display_name.gsub(HASHTAG_INVALID_CHARS_RE, ''))
  92. yield tag if block_given?
  93. tag
  94. end
  95. end
  96. def search_for(term, limit = 5, offset = 0, options = {})
  97. stripped_term = term.strip
  98. options.reverse_merge!({ exclude_unlistable: true, exclude_unreviewed: false })
  99. query = Tag.matches_name(stripped_term)
  100. query = query.merge(Tag.listable) if options[:exclude_unlistable]
  101. query = query.merge(matching_name(stripped_term).or(reviewed)) if options[:exclude_unreviewed]
  102. query.order(Arel.sql('length(name) ASC, name ASC'))
  103. .limit(limit)
  104. .offset(offset)
  105. end
  106. def find_normalized(name)
  107. matching_name(name).first
  108. end
  109. def find_normalized!(name)
  110. find_normalized(name) || raise(ActiveRecord::RecordNotFound)
  111. end
  112. def matching_name(name_or_names)
  113. names = Array(name_or_names).map { |name| arel_table.lower(normalize(name)) }
  114. if names.size == 1
  115. where(arel_table[:name].lower.eq(names.first))
  116. else
  117. where(arel_table[:name].lower.in(names))
  118. end
  119. end
  120. def normalize(str)
  121. HashtagNormalizer.new.normalize(str)
  122. end
  123. end
  124. private
  125. def validate_name_change
  126. errors.add(:name, I18n.t('tags.does_not_match_previous_name')) unless name_was.mb_chars.casecmp(name.mb_chars).zero?
  127. end
  128. def validate_display_name_change
  129. unless HashtagNormalizer.new.normalize(display_name).casecmp(name.mb_chars).zero?
  130. errors.add(:display_name,
  131. I18n.t('tags.does_not_match_previous_name'))
  132. end
  133. end
  134. end