tag.rb 4.9 KB

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