tag.rb 4.3 KB

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