tag.rb 5.5 KB

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