tag.rb 4.9 KB

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