2016-11-15 15:56:29 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-11-12 13:33:21 +00:00
|
|
|
class SearchService < BaseService
|
2018-02-09 22:04:47 +00:00
|
|
|
attr_accessor :query, :account, :limit, :resolve
|
2017-05-05 16:26:04 +01:00
|
|
|
|
2017-03-17 19:47:38 +00:00
|
|
|
def call(query, limit, resolve = false, account = nil)
|
2018-02-09 22:04:47 +00:00
|
|
|
@query = query
|
|
|
|
@account = account
|
|
|
|
@limit = limit
|
|
|
|
@resolve = resolve
|
2016-11-12 13:33:21 +00:00
|
|
|
|
2017-05-05 16:26:04 +01:00
|
|
|
default_results.tap do |results|
|
|
|
|
if url_query?
|
2018-01-22 13:24:22 +00:00
|
|
|
results.merge!(url_resource_results) unless url_resource.nil?
|
2017-05-05 16:26:04 +01:00
|
|
|
elsif query.present?
|
2018-02-09 22:04:47 +00:00
|
|
|
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?
|
2017-05-05 16:26:04 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2017-03-31 21:44:12 +01:00
|
|
|
|
2018-02-09 22:04:47 +00:00
|
|
|
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
|
|
|
|
|
2017-05-05 16:26:04 +01:00
|
|
|
def default_results
|
|
|
|
{ accounts: [], hashtags: [], statuses: [] }
|
|
|
|
end
|
2016-11-12 13:33:21 +00:00
|
|
|
|
2017-05-05 16:26:04 +01:00
|
|
|
def url_query?
|
|
|
|
query =~ /\Ahttps?:\/\//
|
|
|
|
end
|
|
|
|
|
2018-01-22 13:24:22 +00:00
|
|
|
def url_resource_results
|
|
|
|
{ url_resource_symbol => [url_resource] }
|
2017-05-05 16:26:04 +01:00
|
|
|
end
|
|
|
|
|
2018-01-22 13:24:22 +00:00
|
|
|
def url_resource
|
|
|
|
@_url_resource ||= ResolveURLService.new.call(query)
|
2017-05-05 16:26:04 +01:00
|
|
|
end
|
2016-11-12 13:33:21 +00:00
|
|
|
|
2018-01-22 13:24:22 +00:00
|
|
|
def url_resource_symbol
|
|
|
|
url_resource.class.name.downcase.pluralize.to_sym
|
2016-11-12 13:33:21 +00:00
|
|
|
end
|
2018-02-09 22:04:47 +00:00
|
|
|
|
|
|
|
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
|
2016-11-12 13:33:21 +00:00
|
|
|
end
|