You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

172 lines
5.0 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  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 :recently_used, ->(account) { joins(:statuses).where(statuses: { id: account.statuses.select(:id).limit(1000) }).group(:id).order(Arel.sql('count(*) desc')) }
  38. # Search with case-sensitive to use B-tree index.
  39. scope :matches_name, ->(term) { where(arel_table[:name].lower.matches(arel_table.lower("#{sanitize_sql_like(Tag.normalize(term))}%"), nil, true)) }
  40. delegate :accounts_count,
  41. :accounts_count=,
  42. :increment_count!,
  43. :decrement_count!,
  44. to: :account_tag_stat
  45. after_save :save_account_tag_stat
  46. update_index('tags#tag', :self)
  47. def account_tag_stat
  48. super || build_account_tag_stat
  49. end
  50. def cached_sample_accounts
  51. Rails.cache.fetch("#{cache_key}/sample_accounts", expires_in: 12.hours) { sample_accounts }
  52. end
  53. def to_param
  54. name
  55. end
  56. def usable
  57. boolean_with_default('usable', true)
  58. end
  59. alias usable? usable
  60. def listable
  61. boolean_with_default('listable', true)
  62. end
  63. alias listable? listable
  64. def trendable
  65. boolean_with_default('trendable', Setting.trendable_by_default)
  66. end
  67. alias trendable? trendable
  68. def requires_review?
  69. reviewed_at.nil?
  70. end
  71. def reviewed?
  72. reviewed_at.present?
  73. end
  74. def requested_review?
  75. requested_review_at.present?
  76. end
  77. def trending?
  78. TrendingTags.trending?(self)
  79. end
  80. def history
  81. days = []
  82. 7.times do |i|
  83. day = i.days.ago.beginning_of_day.to_i
  84. days << {
  85. day: day.to_s,
  86. uses: Redis.current.get("activity:tags:#{id}:#{day}") || '0',
  87. accounts: Redis.current.pfcount("activity:tags:#{id}:#{day}:accounts").to_s,
  88. }
  89. end
  90. days
  91. end
  92. class << self
  93. def find_or_create_by_names(name_or_names)
  94. Array(name_or_names).map(&method(:normalize)).uniq { |str| str.mb_chars.downcase.to_s }.map do |normalized_name|
  95. tag = matching_name(normalized_name).first || create(name: normalized_name)
  96. yield tag if block_given?
  97. tag
  98. end
  99. end
  100. def search_for(term, limit = 5, offset = 0, options = {})
  101. striped_term = term.strip
  102. query = Tag.listable.matches_name(striped_term)
  103. query = query.merge(matching_name(striped_term).or(where.not(reviewed_at: 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| arel_table.lower(normalize(name)) }
  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. def normalize(str)
  123. str.gsub(/\A#/, '')
  124. end
  125. end
  126. private
  127. def save_account_tag_stat
  128. return unless account_tag_stat&.changed?
  129. account_tag_stat.save
  130. end
  131. def validate_name_change
  132. errors.add(:name, I18n.t('tags.does_not_match_previous_name')) unless name_was.mb_chars.casecmp(name.mb_chars).zero?
  133. end
  134. end