1 defmodule Pleroma.Search.Builtin do
2 @behaviour Pleroma.Search
7 alias Pleroma.Web.MastodonAPI.AccountView
8 alias Pleroma.Web.MastodonAPI.StatusView
9 alias Pleroma.Web.Endpoint
14 def search(_conn, %{q: query} = params, options) do
15 version = Keyword.get(options, :version)
16 timeout = Keyword.get(Repo.config(), :timeout, 15_000)
17 default_values = %{"statuses" => [], "accounts" => [], "hashtags" => []}
20 |> Enum.map(fn {resource, default_value} ->
21 if params[:type] in [nil, resource] do
22 {resource, fn -> resource_search(version, resource, query, options) end}
24 {resource, fn -> default_value end}
27 |> Task.async_stream(fn {resource, f} -> {resource, with_fallback(f)} end,
29 on_timeout: :kill_task
31 |> Enum.reduce(default_values, fn
32 {:ok, {resource, result}}, acc ->
33 Map.put(acc, resource, result)
40 defp resource_search(_, "accounts", query, options) do
41 accounts = with_fallback(fn -> User.search(query, options) end)
43 AccountView.render("index.json",
45 for: options[:for_user],
46 embed_relationships: options[:embed_relationships]
50 defp resource_search(_, "statuses", query, options) do
51 statuses = with_fallback(fn -> Activity.search(options[:for_user], query, options) end)
53 StatusView.render("index.json",
55 for: options[:for_user],
60 defp resource_search(:v2, "hashtags", query, options) do
61 tags_path = Endpoint.url() <> "/tag/"
64 |> prepare_tags(options)
66 %{name: tag, url: tags_path <> tag}
70 defp resource_search(:v1, "hashtags", query, options) do
71 prepare_tags(query, options)
74 defp prepare_tags(query, options) do
77 |> preprocess_uri_query()
78 |> String.split(~r/[^#\w]+/u, trim: true)
79 |> Enum.uniq_by(&String.downcase/1)
81 explicit_tags = Enum.filter(tags, fn tag -> String.starts_with?(tag, "#") end)
84 if Enum.any?(explicit_tags) do
90 tags = Enum.map(tags, fn tag -> String.trim_leading(tag, "#") end)
93 if Enum.empty?(explicit_tags) && !options[:skip_joined_tag] do
99 Pleroma.Pagination.paginate(tags, options)
102 # If `query` is a URI, returns last component of its path, otherwise returns `query`
103 defp preprocess_uri_query(query) do
104 if query =~ ~r/https?:\/\// do
106 |> String.trim_trailing("/")
116 defp add_joined_tag(tags) do
118 |> Kernel.++([joined_tag(tags)])
119 |> Enum.uniq_by(&String.downcase/1)
122 defp joined_tag(tags) do
124 |> Enum.map(fn tag -> String.capitalize(tag) end)
128 defp with_fallback(f, fallback \\ []) do
133 Logger.error("#{__MODULE__} search error: #{inspect(error)}")