remove all endpoints marked as deprecated (#91)
[akkoma] / lib / pleroma / web / mastodon_api / controllers / search_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.SearchController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.Repo
9 alias Pleroma.User
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
16
17 require Logger
18
19 @search_limit 40
20
21 plug(Pleroma.Web.ApiSpec.CastAndValidate)
22
23 # Note: Mastodon doesn't allow unauthenticated access (requires read:accounts / read:search)
24 plug(OAuthScopesPlug, %{scopes: ["read:search"], fallback: :proceed_unauthenticated})
25
26 # Note: on private instances auth is required (EnsurePublicOrAuthenticatedPlug is not skipped)
27
28 plug(RateLimiter, [name: :search] when action in [:search2, :account_search])
29
30 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.SearchOperation
31
32 def account_search(%{assigns: %{user: user}} = conn, %{q: query} = params) do
33 accounts = User.search(query, search_options(params, user))
34
35 conn
36 |> put_view(AccountView)
37 |> render("index.json",
38 users: accounts,
39 for: user,
40 as: :user
41 )
42 end
43
44 def search2(conn, params), do: do_search(:v2, conn, params)
45
46 defp do_search(version, %{assigns: %{user: user}} = conn, %{q: query} = params) do
47 query = String.trim(query)
48 options = search_options(params, user)
49 timeout = Keyword.get(Repo.config(), :timeout, 15_000)
50 default_values = %{"statuses" => [], "accounts" => [], "hashtags" => []}
51
52 result =
53 default_values
54 |> Enum.map(fn {resource, default_value} ->
55 if params[:type] in [nil, resource] do
56 {resource, fn -> resource_search(version, resource, query, options) end}
57 else
58 {resource, fn -> default_value end}
59 end
60 end)
61 |> Task.async_stream(fn {resource, f} -> {resource, with_fallback(f)} end,
62 timeout: timeout,
63 on_timeout: :kill_task
64 )
65 |> Enum.reduce(default_values, fn
66 {:ok, {resource, result}}, acc ->
67 Map.put(acc, resource, result)
68
69 _error, acc ->
70 acc
71 end)
72
73 json(conn, result)
74 end
75
76 defp search_options(params, user) do
77 [
78 resolve: params[:resolve],
79 following: params[:following],
80 limit: min(params[:limit], @search_limit),
81 offset: params[:offset],
82 type: params[:type],
83 author: get_author(params),
84 embed_relationships: ControllerHelper.embed_relationships?(params),
85 for_user: user
86 ]
87 |> Enum.filter(&elem(&1, 1))
88 end
89
90 defp resource_search(_, "accounts", query, options) do
91 accounts = with_fallback(fn -> User.search(query, options) end)
92
93 AccountView.render("index.json",
94 users: accounts,
95 for: options[:for_user],
96 embed_relationships: options[:embed_relationships]
97 )
98 end
99
100 defp resource_search(_, "statuses", query, options) do
101 statuses = with_fallback(fn -> Pleroma.Search.search(query, options) end)
102
103 StatusView.render("index.json",
104 activities: statuses,
105 for: options[:for_user],
106 as: :activity
107 )
108 end
109
110 defp resource_search(:v2, "hashtags", query, options) do
111 tags_path = Endpoint.url() <> "/tag/"
112
113 query
114 |> prepare_tags(options)
115 |> Enum.map(fn tag ->
116 %{name: tag, url: tags_path <> tag}
117 end)
118 end
119
120 defp prepare_tags(query, options) do
121 tags =
122 query
123 |> preprocess_uri_query()
124 |> String.split(~r/[^#\w]+/u, trim: true)
125 |> Enum.uniq_by(&String.downcase/1)
126
127 explicit_tags = Enum.filter(tags, fn tag -> String.starts_with?(tag, "#") end)
128
129 tags =
130 if Enum.any?(explicit_tags) do
131 explicit_tags
132 else
133 tags
134 end
135
136 tags = Enum.map(tags, fn tag -> String.trim_leading(tag, "#") end)
137
138 tags =
139 if Enum.empty?(explicit_tags) && !options[:skip_joined_tag] do
140 add_joined_tag(tags)
141 else
142 tags
143 end
144
145 Pleroma.Pagination.paginate(tags, options)
146 end
147
148 defp add_joined_tag(tags) do
149 tags
150 |> Kernel.++([joined_tag(tags)])
151 |> Enum.uniq_by(&String.downcase/1)
152 end
153
154 # If `query` is a URI, returns last component of its path, otherwise returns `query`
155 defp preprocess_uri_query(query) do
156 if query =~ ~r/https?:\/\// do
157 query
158 |> String.trim_trailing("/")
159 |> URI.parse()
160 |> Map.get(:path)
161 |> String.split("/")
162 |> Enum.at(-1)
163 else
164 query
165 end
166 end
167
168 defp joined_tag(tags) do
169 tags
170 |> Enum.map(fn tag -> String.capitalize(tag) end)
171 |> Enum.join()
172 end
173
174 defp with_fallback(f, fallback \\ []) do
175 try do
176 f.()
177 rescue
178 error ->
179 Logger.error("#{__MODULE__} search error: #{inspect(error)}")
180 fallback
181 end
182 end
183
184 defp get_author(%{account_id: account_id}) when is_binary(account_id),
185 do: User.get_cached_by_id(account_id)
186
187 defp get_author(_params), do: nil
188 end