Merge branch 'refactor/locked_user_field' into 'develop'
[akkoma] / lib / pleroma / web / pleroma_api / controllers / emoji_reaction_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.PleromaAPI.EmojiReactionController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.Activity
9 alias Pleroma.Object
10 alias Pleroma.Web.CommonAPI
11 alias Pleroma.Web.MastodonAPI.StatusView
12 alias Pleroma.Web.Plugs.OAuthScopesPlug
13
14 plug(Pleroma.Web.ApiSpec.CastAndValidate)
15 plug(OAuthScopesPlug, %{scopes: ["write:statuses"]} when action in [:create, :delete])
16
17 plug(
18 OAuthScopesPlug,
19 %{scopes: ["read:statuses"], fallback: :proceed_unauthenticated}
20 when action == :index
21 )
22
23 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.EmojiReactionOperation
24
25 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
26
27 def index(%{assigns: %{user: user}} = conn, %{id: activity_id} = params) do
28 with true <- Pleroma.Config.get([:instance, :show_reactions]),
29 %Activity{} = activity <- Activity.get_by_id_with_object(activity_id),
30 %Object{data: %{"reactions" => reactions}} when is_list(reactions) <-
31 Object.normalize(activity) do
32 reactions = filter(reactions, params)
33 render(conn, "index.json", emoji_reactions: reactions, user: user)
34 else
35 _e -> json(conn, [])
36 end
37 end
38
39 defp filter(reactions, %{emoji: emoji}) when is_binary(emoji) do
40 Enum.filter(reactions, fn [e, _] -> e == emoji end)
41 end
42
43 defp filter(reactions, _), do: reactions
44
45 def create(%{assigns: %{user: user}} = conn, %{id: activity_id, emoji: emoji}) do
46 with {:ok, _activity} <- CommonAPI.react_with_emoji(activity_id, user, emoji) do
47 activity = Activity.get_by_id(activity_id)
48
49 conn
50 |> put_view(StatusView)
51 |> render("show.json", activity: activity, for: user, as: :activity)
52 end
53 end
54
55 def delete(%{assigns: %{user: user}} = conn, %{id: activity_id, emoji: emoji}) do
56 with {:ok, _activity} <- CommonAPI.unreact_with_emoji(activity_id, user, emoji) do
57 activity = Activity.get_by_id(activity_id)
58
59 conn
60 |> put_view(StatusView)
61 |> render("show.json", activity: activity, for: user, as: :activity)
62 end
63 end
64 end