about summary refs log tree commit diff
path: root/app/services/search_service.rb
blob: fe98566866d9493241eb6032f6e283e710e4ca30 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# frozen_string_literal: true

class SearchService < BaseService
  attr_accessor :query, :account, :limit, :resolve

  def call(query, limit, resolve = false, account = nil)
    @query   = query
    @account = account
    @limit   = limit
    @resolve = resolve

    default_results.tap do |results|
      if url_query?
        results.merge!(url_resource_results) unless url_resource.nil?
      elsif query.present?
        results[:accounts] = perform_accounts_search! if account_searchable?
        results[:statuses] = perform_statuses_search! if full_text_searchable?
        results[:hashtags] = perform_hashtags_search! if hashtag_searchable?
      end
    end
  end

  private

  def perform_accounts_search!
    AccountSearchService.new.call(query, limit, account, resolve: resolve)
  end

  def perform_statuses_search!
    statuses = StatusesIndex.filter(term: { searchable_by: account.id })
                            .query(multi_match: { type: 'most_fields', query: query, operator: 'and', fields: %w(text text.stemmed) })
                            .limit(limit).objects

    statuses.reject { |status| StatusFilter.new(status, account).filtered? }
  end

  def perform_hashtags_search!
    Tag.search_for(query.gsub(/\A#/, ''), limit)
  end

  def default_results
    { accounts: [], hashtags: [], statuses: [] }
  end

  def url_query?
    query =~ /\Ahttps?:\/\//
  end

  def url_resource_results
    { url_resource_symbol => [url_resource] }
  end

  def url_resource
    @_url_resource ||= ResolveURLService.new.call(query)
  end

  def url_resource_symbol
    url_resource.class.name.downcase.pluralize.to_sym
  end

  def full_text_searchable?
    return false unless Chewy.enabled?
    !account.nil? && !((query.start_with?('#') || query.include?('@')) && !query.include?(' '))
  end

  def account_searchable?
    !(query.include?('@') && query.include?(' '))
  end

  def hashtag_searchable?
    !query.include?('@')
  end
end