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.

100 lines
2.2 KiB

  1. # frozen_string_literal: true
  2. class AccountSearchService < BaseService
  3. attr_reader :query, :limit, :options, :account
  4. def call(query, limit, account = nil, options = {})
  5. @query = query.strip
  6. @limit = limit
  7. @options = options
  8. @account = account
  9. search_service_results
  10. end
  11. private
  12. def search_service_results
  13. return [] if query_blank_or_hashtag? || limit < 1
  14. if resolving_non_matching_remote_account?
  15. [ResolveAccountService.new.call("#{query_username}@#{query_domain}")].compact
  16. else
  17. search_results_and_exact_match.compact.uniq.slice(0, limit)
  18. end
  19. end
  20. def resolving_non_matching_remote_account?
  21. options[:resolve] && !exact_match && !domain_is_local?
  22. end
  23. def search_results_and_exact_match
  24. exact = [exact_match]
  25. return exact if !exact[0].nil? && limit == 1
  26. exact + search_results.to_a
  27. end
  28. def query_blank_or_hashtag?
  29. query.blank? || query.start_with?('#')
  30. end
  31. def split_query_string
  32. @_split_query_string ||= query.gsub(/\A@/, '').split('@')
  33. end
  34. def query_username
  35. @_query_username ||= split_query_string.first || ''
  36. end
  37. def query_domain
  38. @_query_domain ||= query_without_split? ? nil : split_query_string.last
  39. end
  40. def query_without_split?
  41. split_query_string.size == 1
  42. end
  43. def domain_is_local?
  44. @_domain_is_local ||= TagManager.instance.local_domain?(query_domain)
  45. end
  46. def search_from
  47. options[:following] && account ? account.following : Account
  48. end
  49. def exact_match
  50. @_exact_match ||= begin
  51. if domain_is_local?
  52. search_from.find_local(query_username)
  53. else
  54. search_from.find_remote(query_username, query_domain)
  55. end
  56. end
  57. end
  58. def search_results
  59. @_search_results ||= begin
  60. if account
  61. advanced_search_results
  62. else
  63. simple_search_results
  64. end
  65. end
  66. end
  67. def advanced_search_results
  68. Account.advanced_search_for(terms_for_query, account, limit, options[:following])
  69. end
  70. def simple_search_results
  71. Account.search_for(terms_for_query, limit)
  72. end
  73. def terms_for_query
  74. if domain_is_local?
  75. query_username
  76. else
  77. "#{query_username} #{query_domain}"
  78. end
  79. end
  80. end