account_search_service.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # frozen_string_literal: true
  2. class AccountSearchService < BaseService
  3. attr_reader :query, :limit, :resolve, :account
  4. def call(query, limit, resolve = false, account = nil)
  5. @query = query
  6. @limit = limit
  7. @resolve = resolve
  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. [ResolveRemoteAccountService.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. 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 exact_match
  47. @_exact_match ||= begin
  48. if domain_is_local?
  49. Account.find_local(query_username)
  50. else
  51. Account.find_remote(query_username, query_domain)
  52. end
  53. end
  54. end
  55. def search_results
  56. @_search_results ||= begin
  57. if account
  58. advanced_search_results
  59. else
  60. simple_search_results
  61. end
  62. end
  63. end
  64. def advanced_search_results
  65. Account.advanced_search_for(terms_for_query, account, limit)
  66. end
  67. def simple_search_results
  68. Account.search_for(terms_for_query, limit)
  69. end
  70. def terms_for_query
  71. if domain_is_local?
  72. query_username
  73. else
  74. "#{query_username} #{query_domain}"
  75. end
  76. end
  77. end