statuses_search_service.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # frozen_string_literal: true
  2. class StatusesSearchService < BaseService
  3. def call(query, account = nil, options = {})
  4. MastodonOTELTracer.in_span('StatusesSearchService#call') do |span|
  5. @query = query&.strip
  6. @account = account
  7. @options = options
  8. @limit = options[:limit].to_i
  9. @offset = options[:offset].to_i
  10. convert_deprecated_options!
  11. span.add_attributes(
  12. 'search.offset' => @offset,
  13. 'search.limit' => @limit,
  14. 'search.backend' => Chewy.enabled? ? 'elasticsearch' : 'database'
  15. )
  16. status_search_results.tap do |results|
  17. span.set_attribute('search.results.count', results.size)
  18. end
  19. end
  20. end
  21. private
  22. def status_search_results
  23. request = parsed_query.request
  24. results = request.collapse(field: :id).order(id: { order: :desc }).limit(@limit).offset(@offset).objects.compact
  25. account_ids = results.map(&:account_id)
  26. account_domains = results.map(&:account_domain)
  27. preloaded_relations = @account.relations_map(account_ids, account_domains)
  28. results.reject { |status| StatusFilter.new(status, @account, preloaded_relations).filtered? }
  29. rescue Faraday::ConnectionFailed, Parslet::ParseFailed
  30. []
  31. end
  32. def parsed_query
  33. SearchQueryTransformer.new.apply(SearchQueryParser.new.parse(@query), current_account: @account)
  34. end
  35. def convert_deprecated_options!
  36. syntax_options = []
  37. if @options[:account_id]
  38. username = Account.select(:username, :domain).find(@options[:account_id]).acct
  39. syntax_options << "from:@#{username}"
  40. end
  41. if @options[:min_id]
  42. timestamp = Mastodon::Snowflake.to_time(@options[:min_id].to_i)
  43. syntax_options << "after:\"#{timestamp.iso8601}\""
  44. end
  45. if @options[:max_id]
  46. timestamp = Mastodon::Snowflake.to_time(@options[:max_id].to_i)
  47. syntax_options << "before:\"#{timestamp.iso8601}\""
  48. end
  49. @query = "#{@query} #{syntax_options.join(' ')}".strip if syntax_options.any?
  50. end
  51. end