FE
[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.Plugs.OAuthScopesPlug
12 alias Pleroma.User
13 alias Pleroma.Web.MediaProxy
14
15 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
16
17 plug(OAuthScopesPlug, %{scopes: ["read"]} when action == :index)
18
19 plug(Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug)
20
21 @doc "GET /api/v1/suggestions"
22 def index(%{assigns: %{user: user}} = conn, _) do
23 if Config.get([:suggestions, :enabled], false) do
24 with {:ok, data} <- fetch_suggestions(user) do
25 limit = Config.get([:suggestions, :limit], 23)
26
27 data =
28 data
29 |> Enum.slice(0, limit)
30 |> Enum.map(fn x ->
31 x
32 |> Map.put("id", fetch_suggestion_id(x))
33 |> Map.put("avatar", MediaProxy.url(x["avatar"]))
34 |> Map.put("avatar_static", MediaProxy.url(x["avatar_static"]))
35 end)
36
37 json(conn, data)
38 end
39 else
40 json(conn, [])
41 end
42 end
43
44 defp fetch_suggestions(user) do
45 api = Config.get([:suggestions, :third_party_engine], "")
46 timeout = Config.get([:suggestions, :timeout], 5000)
47 host = Config.get([Pleroma.Web.Endpoint, :url, :host])
48
49 url =
50 api
51 |> String.replace("{{host}}", host)
52 |> String.replace("{{user}}", user.nickname)
53
54 with {:ok, %{status: 200, body: body}} <-
55 Pleroma.HTTP.get(url, [], adapter: [recv_timeout: timeout, pool: :default]) do
56 Jason.decode(body)
57 else
58 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
59 end
60 end
61
62 defp fetch_suggestion_id(attrs) do
63 case User.get_or_fetch(attrs["acct"]) do
64 {:ok, %User{id: id}} -> id
65 _ -> 0
66 end
67 end
68 end