Merge remote-tracking branch 'origin/develop' into reactions
[akkoma] / lib / pleroma / web / mastodon_api / controllers / suggestion_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.SuggestionController do
6 use Pleroma.Web, :controller
7
8 require Logger
9
10 alias Pleroma.Config
11 alias Pleroma.User
12 alias Pleroma.Web.MediaProxy
13
14 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
15
16 @doc "GET /api/v1/suggestions"
17 def index(%{assigns: %{user: user}} = conn, _) do
18 if Config.get([:suggestions, :enabled], false) do
19 with {:ok, data} <- fetch_suggestions(user) do
20 limit = Config.get([:suggestions, :limit], 23)
21
22 data =
23 data
24 |> Enum.slice(0, limit)
25 |> Enum.map(fn x ->
26 x
27 |> Map.put("id", fetch_suggestion_id(x))
28 |> Map.put("avatar", MediaProxy.url(x["avatar"]))
29 |> Map.put("avatar_static", MediaProxy.url(x["avatar_static"]))
30 end)
31
32 json(conn, data)
33 end
34 else
35 json(conn, [])
36 end
37 end
38
39 defp fetch_suggestions(user) do
40 api = Config.get([:suggestions, :third_party_engine], "")
41 timeout = Config.get([:suggestions, :timeout], 5000)
42 host = Config.get([Pleroma.Web.Endpoint, :url, :host])
43
44 url =
45 api
46 |> String.replace("{{host}}", host)
47 |> String.replace("{{user}}", user.nickname)
48
49 with {:ok, %{status: 200, body: body}} <-
50 Pleroma.HTTP.get(url, [], adapter: [recv_timeout: timeout, pool: :default]) do
51 Jason.decode(body)
52 else
53 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
54 end
55 end
56
57 defp fetch_suggestion_id(attrs) do
58 case User.get_or_fetch(attrs["acct"]) do
59 {:ok, %User{id: id}} -> id
60 _ -> 0
61 end
62 end
63 end