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