tag.rb 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. has_and_belongs_to_many :statuses
  23. has_and_belongs_to_many :accounts
  24. has_many :passive_relationships, class_name: 'TagFollow', inverse_of: :tag, dependent: :destroy
  25. has_many :featured_tags, dependent: :destroy, inverse_of: :tag
  26. has_many :followers, through: :passive_relationships, source: :account
  27. HASHTAG_SEPARATORS = "_\u00B7\u30FB\u200c"
  28. HASHTAG_FIRST_SEQUENCE_CHUNK_ONE = "[[:word:]_][[:word:]#{HASHTAG_SEPARATORS}]*[[:alpha:]#{HASHTAG_SEPARATORS}]"
  29. HASHTAG_FIRST_SEQUENCE_CHUNK_TWO = "[[:word:]#{HASHTAG_SEPARATORS}]*[[:word:]_]"
  30. HASHTAG_FIRST_SEQUENCE = "(#{HASHTAG_FIRST_SEQUENCE_CHUNK_ONE}#{HASHTAG_FIRST_SEQUENCE_CHUNK_TWO})"
  31. HASHTAG_LAST_SEQUENCE = '([[:word:]_]*[[:alpha:]][[:word:]_]*)'
  32. HASHTAG_NAME_PAT = "#{HASHTAG_FIRST_SEQUENCE}|#{HASHTAG_LAST_SEQUENCE}"
  33. HASHTAG_RE = %r{(?:^|[^/)\w])#(#{HASHTAG_NAME_PAT})}i
  34. HASHTAG_NAME_RE = /\A(#{HASHTAG_NAME_PAT})\z/i
  35. HASHTAG_INVALID_CHARS_RE = /[^[:alnum:]#{HASHTAG_SEPARATORS}]/
  36. validates :name, presence: true, format: { with: HASHTAG_NAME_RE }
  37. validates :display_name, format: { with: HASHTAG_NAME_RE }
  38. validate :validate_name_change, if: -> { !new_record? && name_changed? }
  39. validate :validate_display_name_change, if: -> { !new_record? && display_name_changed? }
  40. scope :reviewed, -> { where.not(reviewed_at: nil) }
  41. scope :unreviewed, -> { where(reviewed_at: nil) }
  42. scope :pending_review, -> { unreviewed.where.not(requested_review_at: nil) }
  43. scope :usable, -> { where(usable: [true, nil]) }
  44. scope :listable, -> { where(listable: [true, nil]) }
  45. scope :trendable, -> { Setting.trendable_by_default ? where(trendable: [true, nil]) : where(trendable: true) }
  46. scope :not_trendable, -> { where(trendable: false) }
  47. scope :recently_used, lambda { |account|
  48. joins(:statuses)
  49. .where(statuses: { id: account.statuses.select(:id).limit(1000) })
  50. .group(:id).order(Arel.sql('count(*) desc'))
  51. }
  52. 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
  53. update_index('tags', :self)
  54. def to_param
  55. name
  56. end
  57. def display_name
  58. attributes['display_name'] || name
  59. end
  60. def usable
  61. boolean_with_default('usable', true)
  62. end
  63. alias usable? usable
  64. def listable
  65. boolean_with_default('listable', true)
  66. end
  67. alias listable? listable
  68. def trendable
  69. boolean_with_default('trendable', Setting.trendable_by_default)
  70. end
  71. alias trendable? trendable
  72. def requires_review?
  73. reviewed_at.nil?
  74. end
  75. def reviewed?
  76. reviewed_at.present?
  77. end
  78. def requested_review?
  79. requested_review_at.present?
  80. end
  81. def requires_review_notification?
  82. requires_review? && !requested_review?
  83. end
  84. def decaying?
  85. max_score_at && max_score_at >= Trends.tags.options[:max_score_cooldown].ago && max_score_at < 1.day.ago
  86. end
  87. def history
  88. @history ||= Trends::History.new('tags', id)
  89. end
  90. class << self
  91. def find_or_create_by_names(name_or_names)
  92. names = Array(name_or_names).map { |str| [normalize(str), str] }.uniq(&:first)
  93. names.map do |(normalized_name, display_name)|
  94. tag = matching_name(normalized_name).first || create(name: normalized_name,
  95. display_name: display_name.gsub(HASHTAG_INVALID_CHARS_RE, ''))
  96. yield tag if block_given?
  97. tag
  98. end
  99. end
  100. def search_for(term, limit = 5, offset = 0, options = {})
  101. stripped_term = term.strip
  102. query = Tag.listable.matches_name(stripped_term)
  103. query = query.merge(matching_name(stripped_term).or(where.not(reviewed_at: nil))) if options[:exclude_unreviewed]
  104. query.order(Arel.sql('length(name) ASC, name ASC'))
  105. .limit(limit)
  106. .offset(offset)
  107. end
  108. def find_normalized(name)
  109. matching_name(name).first
  110. end
  111. def find_normalized!(name)
  112. find_normalized(name) || raise(ActiveRecord::RecordNotFound)
  113. end
  114. def matching_name(name_or_names)
  115. names = Array(name_or_names).map { |name| arel_table.lower(normalize(name)) }
  116. if names.size == 1
  117. where(arel_table[:name].lower.eq(names.first))
  118. else
  119. where(arel_table[:name].lower.in(names))
  120. end
  121. end
  122. def normalize(str)
  123. HashtagNormalizer.new.normalize(str)
  124. end
  125. end
  126. private
  127. def validate_name_change
  128. errors.add(:name, I18n.t('tags.does_not_match_previous_name')) unless name_was.mb_chars.casecmp(name.mb_chars).zero?
  129. end
  130. def validate_display_name_change
  131. unless HashtagNormalizer.new.normalize(display_name).casecmp(name.mb_chars).zero?
  132. errors.add(:display_name,
  133. I18n.t('tags.does_not_match_previous_name'))
  134. end
  135. end
  136. end