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.

77 lines
2.0 KiB

  1. # frozen_string_literal: true
  2. class SearchService < BaseService
  3. attr_accessor :query, :account, :limit, :resolve
  4. def call(query, limit, resolve = false, account = nil)
  5. @query = query.strip
  6. @account = account
  7. @limit = limit
  8. @resolve = resolve
  9. default_results.tap do |results|
  10. if url_query?
  11. results.merge!(url_resource_results) unless url_resource.nil?
  12. elsif query.present?
  13. results[:accounts] = perform_accounts_search! if account_searchable?
  14. results[:statuses] = perform_statuses_search! if full_text_searchable?
  15. results[:hashtags] = perform_hashtags_search! if hashtag_searchable?
  16. end
  17. end
  18. end
  19. private
  20. def perform_accounts_search!
  21. AccountSearchService.new.call(query, limit, account, resolve: resolve)
  22. end
  23. def perform_statuses_search!
  24. statuses = StatusesIndex.filter(term: { searchable_by: account.id })
  25. .query(multi_match: { type: 'most_fields', query: query, operator: 'and', fields: %w(text text.stemmed) })
  26. .limit(limit)
  27. .objects
  28. .compact
  29. statuses.reject { |status| StatusFilter.new(status, account).filtered? }
  30. rescue Faraday::ConnectionFailed
  31. []
  32. end
  33. def perform_hashtags_search!
  34. Tag.search_for(query.gsub(/\A#/, ''), limit)
  35. end
  36. def default_results
  37. { accounts: [], hashtags: [], statuses: [] }
  38. end
  39. def url_query?
  40. query =~ /\Ahttps?:\/\//
  41. end
  42. def url_resource_results
  43. { url_resource_symbol => [url_resource] }
  44. end
  45. def url_resource
  46. @_url_resource ||= ResolveURLService.new.call(query, on_behalf_of: @account)
  47. end
  48. def url_resource_symbol
  49. url_resource.class.name.downcase.pluralize.to_sym
  50. end
  51. def full_text_searchable?
  52. return false unless Chewy.enabled?
  53. !account.nil? && !((query.start_with?('#') || query.include?('@')) && !query.include?(' '))
  54. end
  55. def account_searchable?
  56. !(query.include?('@') && query.include?(' '))
  57. end
  58. def hashtag_searchable?
  59. !query.include?('@')
  60. end
  61. end