search_controller.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # frozen_string_literal: true
  2. class Api::V1::Peers::SearchController < Api::BaseController
  3. before_action :require_enabled_api!
  4. before_action :set_domains
  5. skip_before_action :require_authenticated_user!, unless: :limited_federation_mode?
  6. skip_around_action :set_locale
  7. vary_by ''
  8. def index
  9. cache_even_if_authenticated!
  10. render json: @domains
  11. end
  12. private
  13. def require_enabled_api!
  14. head 404 unless Setting.peers_api_enabled && !limited_federation_mode?
  15. end
  16. def set_domains
  17. return if params[:q].blank?
  18. if Chewy.enabled?
  19. @domains = InstancesIndex.query(function_score: {
  20. query: {
  21. prefix: {
  22. domain: TagManager.instance.normalize_domain(params[:q].strip),
  23. },
  24. },
  25. field_value_factor: {
  26. field: 'accounts_count',
  27. modifier: 'log2p',
  28. },
  29. }).limit(10).pluck(:domain)
  30. else
  31. domain = params[:q].strip
  32. domain = TagManager.instance.normalize_domain(domain)
  33. @domains = Instance.searchable.where(Instance.arel_table[:domain].matches("#{Instance.sanitize_sql_like(domain)}%", false, true)).limit(10).pluck(:domain)
  34. end
  35. rescue Addressable::URI::InvalidURIError
  36. @domains = []
  37. end
  38. end