search_controller.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # frozen_string_literal: true
  2. class Api::V2::SearchController < Api::BaseController
  3. include Authorization
  4. RESULTS_LIMIT = 20
  5. before_action -> { authorize_if_got_token! :read, :'read:search' }
  6. before_action :validate_search_params!
  7. with_options unless: :user_signed_in? do
  8. before_action :query_pagination_error, if: :pagination_requested?
  9. before_action :remote_resolve_error, if: :remote_resolve_requested?
  10. end
  11. def index
  12. @search = Search.new(search_results)
  13. render json: @search, serializer: REST::SearchSerializer
  14. rescue Mastodon::SyntaxError
  15. unprocessable_entity
  16. rescue ActiveRecord::RecordNotFound
  17. not_found
  18. end
  19. private
  20. def validate_search_params!
  21. params.require(:q)
  22. end
  23. def query_pagination_error
  24. render json: { error: 'Search queries pagination is not supported without authentication' }, status: 401
  25. end
  26. def remote_resolve_error
  27. render json: { error: 'Search queries that resolve remote resources are not supported without authentication' }, status: 401
  28. end
  29. def remote_resolve_requested?
  30. truthy_param?(:resolve)
  31. end
  32. def pagination_requested?
  33. params[:offset].present?
  34. end
  35. def search_results
  36. SearchService.new.call(
  37. params[:q],
  38. current_account,
  39. limit_param(RESULTS_LIMIT),
  40. combined_search_params
  41. )
  42. end
  43. def combined_search_params
  44. search_params.merge(
  45. resolve: truthy_param?(:resolve),
  46. exclude_unreviewed: truthy_param?(:exclude_unreviewed),
  47. following: truthy_param?(:following)
  48. )
  49. end
  50. def search_params
  51. params.permit(:type, :offset, :min_id, :max_id, :account_id, :following)
  52. end
  53. end