about summary refs log tree commit diff
path: root/app/services/process_hashtags_service.rb
blob: 15d78f6906ee5f63e100d4b2173e595067f57039 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# frozen_string_literal: true

class ProcessHashtagsService < BaseService
  def call(status, tags = [], preloaded_tags = [])
    status.tags |= preloaded_tags unless preloaded_tags.blank?

    if status.local?
      tags = Extractor.extract_hashtags(status.text) | (tags.nil? ? [] : tags)
    end
    records = []

    tags.map { |str| str.mb_chars.downcase }.uniq(&:to_s).each do |name|
      name.gsub!(/[:.]+/, '.')
      next if name.blank? || name == '.'

      component_indices = 1.upto(name.size).select { |i| name[i] == '.' }
      component_indices << name.size - 1

      component_indices.take(6).each_with_index do |i, nest|
        frag = (nest != 5) ? name[0..i] : name
        tag = Tag.where(name: frag).first_or_create(name: frag)

        next if status.tags.include?(tag)
        status.tags << tag
        next if tag.unlisted || component_indices.size > 1

        records << tag
        TrendingTags.record_use!(tag, status.account, status.created_at) if status.distributable?
      end
    end

    return unless status.distributable?

    status.account.featured_tags.where(tag_id: records.map(&:id)).each do |featured_tag|
      featured_tag.increment(status.created_at)
    end
  end
end