Restricted embedding of relationships where applicable (statuses / notifications...
[akkoma] / lib / pleroma / web / mastodon_api / controllers / search_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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 import Pleroma.Web.ControllerHelper, only: [fetch_integer_param: 2, skip_relationships?: 1]
9
10 alias Pleroma.Activity
11 alias Pleroma.Plugs.OAuthScopesPlug
12 alias Pleroma.Plugs.RateLimiter
13 alias Pleroma.Repo
14 alias Pleroma.User
15 alias Pleroma.Web
16 alias Pleroma.Web.MastodonAPI.AccountView
17 alias Pleroma.Web.MastodonAPI.StatusView
18
19 require Logger
20
21 # Note: Mastodon doesn't allow unauthenticated access (requires read:accounts / read:search)
22 plug(OAuthScopesPlug, %{scopes: ["read:search"], fallback: :proceed_unauthenticated})
23
24 # Note: on private instances auth is required (EnsurePublicOrAuthenticatedPlug is not skipped)
25
26 plug(RateLimiter, [name: :search] when action in [:search, :search2, :account_search])
27
28 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
29 accounts = User.search(query, search_options(params, user))
30
31 conn
32 |> put_view(AccountView)
33 |> render("index.json", users: accounts, for: user, as: :user)
34 end
35
36 def search2(conn, params), do: do_search(:v2, conn, params)
37 def search(conn, params), do: do_search(:v1, conn, params)
38
39 defp do_search(version, %{assigns: %{user: user}} = conn, %{"q" => query} = params) do
40 options = search_options(params, user)
41 timeout = Keyword.get(Repo.config(), :timeout, 15_000)
42 default_values = %{"statuses" => [], "accounts" => [], "hashtags" => []}
43
44 result =
45 default_values
46 |> Enum.map(fn {resource, default_value} ->
47 if params["type"] in [nil, resource] do
48 {resource, fn -> resource_search(version, resource, query, options) end}
49 else
50 {resource, fn -> default_value end}
51 end
52 end)
53 |> Task.async_stream(fn {resource, f} -> {resource, with_fallback(f)} end,
54 timeout: timeout,
55 on_timeout: :kill_task
56 )
57 |> Enum.reduce(default_values, fn
58 {:ok, {resource, result}}, acc ->
59 Map.put(acc, resource, result)
60
61 _error, acc ->
62 acc
63 end)
64
65 json(conn, result)
66 end
67
68 defp search_options(params, user) do
69 [
70 skip_relationships: skip_relationships?(params),
71 resolve: params["resolve"] == "true",
72 following: params["following"] == "true",
73 limit: fetch_integer_param(params, "limit"),
74 offset: fetch_integer_param(params, "offset"),
75 type: params["type"],
76 author: get_author(params),
77 for_user: user
78 ]
79 |> Enum.filter(&elem(&1, 1))
80 end
81
82 defp resource_search(_, "accounts", query, options) do
83 accounts = with_fallback(fn -> User.search(query, options) end)
84
85 AccountView.render("index.json",
86 users: accounts,
87 for: options[:for_user],
88 as: :user,
89 skip_relationships: true
90 )
91 end
92
93 defp resource_search(_, "statuses", query, options) do
94 statuses = with_fallback(fn -> Activity.search(options[:for_user], query, options) end)
95
96 StatusView.render("index.json",
97 activities: statuses,
98 for: options[:for_user],
99 as: :activity,
100 skip_relationships: options[:skip_relationships]
101 )
102 end
103
104 defp resource_search(:v2, "hashtags", query, _options) do
105 tags_path = Web.base_url() <> "/tag/"
106
107 query
108 |> prepare_tags()
109 |> Enum.map(fn tag ->
110 tag = String.trim_leading(tag, "#")
111 %{name: tag, url: tags_path <> tag}
112 end)
113 end
114
115 defp resource_search(:v1, "hashtags", query, _options) do
116 query
117 |> prepare_tags()
118 |> Enum.map(fn tag -> String.trim_leading(tag, "#") end)
119 end
120
121 defp prepare_tags(query) do
122 query
123 |> String.split()
124 |> Enum.uniq()
125 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
126 end
127
128 defp with_fallback(f, fallback \\ []) do
129 try do
130 f.()
131 rescue
132 error ->
133 Logger.error("#{__MODULE__} search error: #{inspect(error)}")
134 fallback
135 end
136 end
137
138 defp get_author(%{"account_id" => account_id}) when is_binary(account_id),
139 do: User.get_cached_by_id(account_id)
140
141 defp get_author(_params), do: nil
142 end