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 query = String.trim(query)
18 default_values = %{"statuses" => [], "accounts" => [], "hashtags" => []}
21 |> Enum.map(fn {resource, default_value} ->
22 if params[:type] in [nil, resource] do
23 {resource, fn -> resource_search(version, resource, query, options) end}
25 {resource, fn -> default_value end}
28 |> Task.async_stream(fn {resource, f} -> {resource, with_fallback(f)} end,
30 on_timeout: :kill_task
32 |> Enum.reduce(default_values, fn
33 {:ok, {resource, result}}, acc ->
34 Map.put(acc, resource, result)
41 defp resource_search(_, "accounts", query, options) do
42 accounts = with_fallback(fn -> User.search(query, options) end)
44 AccountView.render("index.json",
46 for: options[:for_user],
47 embed_relationships: options[:embed_relationships]
51 defp resource_search(_, "statuses", query, options) do
52 statuses = with_fallback(fn -> Activity.search(options[:for_user], query, options) end)
54 StatusView.render("index.json",
56 for: options[:for_user],
61 defp resource_search(:v2, "hashtags", query, options) do
62 tags_path = Endpoint.url() <> "/tag/"
65 |> prepare_tags(options)
67 %{name: tag, url: tags_path <> tag}
71 defp resource_search(:v1, "hashtags", query, options) do
72 prepare_tags(query, options)
75 defp prepare_tags(query, options) do
78 |> preprocess_uri_query()
79 |> String.split(~r/[^#\w]+/u, trim: true)
80 |> Enum.uniq_by(&String.downcase/1)
82 explicit_tags = Enum.filter(tags, fn tag -> String.starts_with?(tag, "#") end)
85 if Enum.any?(explicit_tags) do
91 tags = Enum.map(tags, fn tag -> String.trim_leading(tag, "#") end)
94 if Enum.empty?(explicit_tags) && !options[:skip_joined_tag] do
100 Pleroma.Pagination.paginate(tags, options)
103 # If `query` is a URI, returns last component of its path, otherwise returns `query`
104 defp preprocess_uri_query(query) do
105 if query =~ ~r/https?:\/\// do
107 |> String.trim_trailing("/")
117 defp add_joined_tag(tags) do
119 |> Kernel.++([joined_tag(tags)])
120 |> Enum.uniq_by(&String.downcase/1)
123 defp joined_tag(tags) do
125 |> Enum.map(fn tag -> String.capitalize(tag) end)
129 defp with_fallback(f, fallback \\ []) do
134 Logger.error("#{__MODULE__} search error: #{inspect(error)}")