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.

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