1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MastodonAPI.SearchController do
6 use Pleroma.Web, :controller
10 alias Pleroma.Web.ControllerHelper
11 alias Pleroma.Web.Endpoint
12 alias Pleroma.Web.MastodonAPI.AccountView
13 alias Pleroma.Web.MastodonAPI.StatusView
14 alias Pleroma.Web.Plugs.OAuthScopesPlug
15 alias Pleroma.Web.Plugs.RateLimiter
21 plug(Pleroma.Web.ApiSpec.CastAndValidate, replace_params: false)
23 # Note: Mastodon doesn't allow unauthenticated access (requires read:accounts / read:search)
24 plug(OAuthScopesPlug, %{scopes: ["read:search"], fallback: :proceed_unauthenticated})
26 # Note: on private instances auth is required (EnsurePublicOrAuthenticatedPlug is not skipped)
28 plug(RateLimiter, [name: :search] when action in [:search, :search2, :account_search])
30 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.SearchOperation
33 %{assigns: %{user: user}, private: %{open_api_spex: %{params: %{q: query} = params}}} =
37 accounts = User.search(query, search_options(params, user))
40 |> put_view(AccountView)
41 |> render("index.json",
48 def search2(conn, params), do: do_search(:v2, conn, params)
49 def search(conn, params), do: do_search(:v1, conn, params)
53 %{assigns: %{user: user}, private: %{open_api_spex: %{params: %{q: query} = params}}} =
57 query = String.trim(query)
58 options = search_options(params, user)
59 timeout = Keyword.get(Repo.config(), :timeout, 15_000)
60 default_values = %{"statuses" => [], "accounts" => [], "hashtags" => []}
64 |> Enum.map(fn {resource, default_value} ->
65 if params[:type] in [nil, resource] do
66 {resource, fn -> resource_search(version, resource, query, options) end}
68 {resource, fn -> default_value end}
71 |> Task.async_stream(fn {resource, f} -> {resource, with_fallback(f)} end,
73 on_timeout: :kill_task
75 |> Enum.reduce(default_values, fn
76 {:ok, {resource, result}}, acc ->
77 Map.put(acc, resource, result)
86 defp search_options(params, user) do
88 resolve: params[:resolve],
89 following: params[:following],
90 limit: min(params[:limit], @search_limit),
91 offset: params[:offset],
93 author: get_author(params),
94 embed_relationships: ControllerHelper.embed_relationships?(params),
97 |> Enum.filter(&elem(&1, 1))
100 defp resource_search(_, "accounts", query, options) do
101 accounts = with_fallback(fn -> User.search(query, options) end)
103 AccountView.render("index.json",
105 for: options[:for_user],
106 embed_relationships: options[:embed_relationships]
110 defp resource_search(_, "statuses", query, options) do
111 statuses = with_fallback(fn -> Pleroma.Search.search(query, options) end)
113 StatusView.render("index.json",
114 activities: statuses,
115 for: options[:for_user],
120 defp resource_search(:v2, "hashtags", query, options) do
121 tags_path = Endpoint.url() <> "/tag/"
124 |> prepare_tags(options)
125 |> Enum.map(fn tag ->
126 %{name: tag, url: tags_path <> tag}
130 defp resource_search(:v1, "hashtags", query, options) do
131 prepare_tags(query, options)
134 defp prepare_tags(query, options) do
137 |> preprocess_uri_query()
138 |> String.split(~r/[^#\w]+/u, trim: true)
139 |> Enum.uniq_by(&String.downcase/1)
141 explicit_tags = Enum.filter(tags, fn tag -> String.starts_with?(tag, "#") end)
144 if Enum.any?(explicit_tags) do
150 tags = Enum.map(tags, fn tag -> String.trim_leading(tag, "#") end)
153 if Enum.empty?(explicit_tags) && !options[:skip_joined_tag] do
159 Pleroma.Pagination.paginate_list(tags, options)
162 defp add_joined_tag(tags) do
164 |> Kernel.++([joined_tag(tags)])
165 |> Enum.uniq_by(&String.downcase/1)
168 # If `query` is a URI, returns last component of its path, otherwise returns `query`
169 defp preprocess_uri_query(query) do
170 if query =~ ~r/https?:\/\// do
172 |> String.trim_trailing("/")
182 defp joined_tag(tags) do
184 |> Enum.map(fn tag -> String.capitalize(tag) end)
188 defp with_fallback(f, fallback \\ []) do
193 Logger.error("#{__MODULE__} search error: #{inspect(error)}")
198 defp get_author(%{account_id: account_id}) when is_binary(account_id),
199 do: User.get_cached_by_id(account_id)
201 defp get_author(_params), do: nil