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.

75 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. end
  31. def perform_hashtags_search!
  32. Tag.search_for(query.gsub(/\A#/, ''), limit)
  33. end
  34. def default_results
  35. { accounts: [], hashtags: [], statuses: [] }
  36. end
  37. def url_query?
  38. query =~ /\Ahttps?:\/\//
  39. end
  40. def url_resource_results
  41. { url_resource_symbol => [url_resource] }
  42. end
  43. def url_resource
  44. @_url_resource ||= ResolveURLService.new.call(query)
  45. end
  46. def url_resource_symbol
  47. url_resource.class.name.downcase.pluralize.to_sym
  48. end
  49. def full_text_searchable?
  50. return false unless Chewy.enabled?
  51. !account.nil? && !((query.start_with?('#') || query.include?('@')) && !query.include?(' '))
  52. end
  53. def account_searchable?
  54. !(query.include?('@') && query.include?(' '))
  55. end
  56. def hashtag_searchable?
  57. !query.include?('@')
  58. end
  59. end