tag.rb 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. #
  19. class Tag < ApplicationRecord
  20. has_and_belongs_to_many :statuses
  21. has_and_belongs_to_many :accounts
  22. has_and_belongs_to_many :sample_accounts, -> { local.discoverable.popular.limit(3) }, class_name: 'Account'
  23. has_many :featured_tags, dependent: :destroy, inverse_of: :tag
  24. has_one :account_tag_stat, dependent: :destroy
  25. HASHTAG_SEPARATORS = "_\u00B7\u200c"
  26. HASHTAG_NAME_RE = "([[:word:]_][[:word:]#{HASHTAG_SEPARATORS}]*[[:alpha:]#{HASHTAG_SEPARATORS}][[:word:]#{HASHTAG_SEPARATORS}]*[[:word:]_])|([[:word:]_]*[[:alpha:]][[:word:]_]*)"
  27. HASHTAG_RE = /(?:^|[^\/\)\w])#(#{HASHTAG_NAME_RE})/i
  28. validates :name, presence: true, format: { with: /\A(#{HASHTAG_NAME_RE})\z/i }
  29. validate :validate_name_change, if: -> { !new_record? && name_changed? }
  30. scope :reviewed, -> { where.not(reviewed_at: nil) }
  31. scope :unreviewed, -> { where(reviewed_at: nil) }
  32. scope :pending_review, -> { unreviewed.where.not(requested_review_at: nil) }
  33. scope :usable, -> { where(usable: [true, nil]) }
  34. scope :listable, -> { where(listable: [true, nil]) }
  35. scope :trendable, -> { Setting.trendable_by_default ? where(trendable: [true, nil]) : where(trendable: true) }
  36. scope :discoverable, -> { listable.joins(:account_tag_stat).where(AccountTagStat.arel_table[:accounts_count].gt(0)).order(Arel.sql('account_tag_stats.accounts_count desc')) }
  37. scope :most_used, ->(account) { joins(:statuses).where(statuses: { account: account }).group(:id).order(Arel.sql('count(*) desc')) }
  38. scope :matches_name, ->(value) { where(arel_table[:name].matches("#{value}%")) }
  39. delegate :accounts_count,
  40. :accounts_count=,
  41. :increment_count!,
  42. :decrement_count!,
  43. to: :account_tag_stat
  44. after_save :save_account_tag_stat
  45. update_index('tags#tag', :self)
  46. def account_tag_stat
  47. super || build_account_tag_stat
  48. end
  49. def cached_sample_accounts
  50. Rails.cache.fetch("#{cache_key}/sample_accounts", expires_in: 12.hours) { sample_accounts }
  51. end
  52. def to_param
  53. name
  54. end
  55. def usable
  56. boolean_with_default('usable', true)
  57. end
  58. alias usable? usable
  59. def listable
  60. boolean_with_default('listable', true)
  61. end
  62. alias listable? listable
  63. def trendable
  64. boolean_with_default('trendable', Setting.trendable_by_default)
  65. end
  66. alias trendable? trendable
  67. def requires_review?
  68. reviewed_at.nil?
  69. end
  70. def reviewed?
  71. reviewed_at.present?
  72. end
  73. def requested_review?
  74. requested_review_at.present?
  75. end
  76. def trending?
  77. TrendingTags.trending?(self)
  78. end
  79. def history
  80. days = []
  81. 7.times do |i|
  82. day = i.days.ago.beginning_of_day.to_i
  83. days << {
  84. day: day.to_s,
  85. uses: Redis.current.get("activity:tags:#{id}:#{day}") || '0',
  86. accounts: Redis.current.pfcount("activity:tags:#{id}:#{day}:accounts").to_s,
  87. }
  88. end
  89. days
  90. end
  91. class << self
  92. def find_or_create_by_names(name_or_names)
  93. Array(name_or_names).map(&method(:normalize)).uniq { |str| str.mb_chars.downcase.to_s }.map do |normalized_name|
  94. tag = matching_name(normalized_name).first || create(name: normalized_name)
  95. yield tag if block_given?
  96. tag
  97. end
  98. end
  99. def search_for(term, limit = 5, offset = 0, options = {})
  100. normalized_term = normalize(term.strip).mb_chars.downcase.to_s
  101. pattern = sanitize_sql_like(normalized_term) + '%'
  102. query = Tag.listable.where(arel_table[:name].lower.matches(pattern))
  103. query = query.where(arel_table[:name].lower.eq(normalized_term).or(arel_table[:reviewed_at].not_eq(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| normalize(name).mb_chars.downcase.to_s }
  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. private
  123. def normalize(str)
  124. str.gsub(/\A#/, '')
  125. end
  126. end
  127. private
  128. def save_account_tag_stat
  129. return unless account_tag_stat&.changed?
  130. account_tag_stat.save
  131. end
  132. def validate_name_change
  133. errors.add(:name, I18n.t('tags.does_not_match_previous_name')) unless name_was.mb_chars.casecmp(name.mb_chars).zero?
  134. end
  135. end