a002912f33be2d7da1831bd510cb427c2273cab7
[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.Plugs.OAuthScopesPlug
11 alias Pleroma.Web.CommonAPI
12 alias Pleroma.Web.MastodonAPI.StatusView
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 def index(%{assigns: %{user: user}} = conn, %{id: activity_id} = params) do
26 with %Activity{} = activity <- Activity.get_by_id_with_object(activity_id),
27 %Object{data: %{"reactions" => reactions}} when is_list(reactions) <-
28 Object.normalize(activity) do
29 reactions = filter(reactions, params)
30 render(conn, "index.json", emoji_reactions: reactions, user: user)
31 else
32 _e -> json(conn, [])
33 end
34 end
35
36 defp filter(reactions, %{emoji: emoji}) when is_binary(emoji) do
37 Enum.filter(reactions, fn [e, _] -> e == emoji end)
38 end
39
40 defp filter(reactions, _), do: reactions
41
42 def create(%{assigns: %{user: user}} = conn, %{id: activity_id, emoji: emoji}) do
43 with {:ok, _activity} <- CommonAPI.react_with_emoji(activity_id, user, emoji) do
44 activity = Activity.get_by_id(activity_id)
45
46 conn
47 |> put_view(StatusView)
48 |> render("show.json", activity: activity, for: user, as: :activity)
49 end
50 end
51
52 def delete(%{assigns: %{user: user}} = conn, %{id: activity_id, emoji: emoji}) do
53 with {:ok, _activity} <- CommonAPI.unreact_with_emoji(activity_id, user, emoji) do
54 activity = Activity.get_by_id(activity_id)
55
56 conn
57 |> put_view(StatusView)
58 |> render("show.json", activity: activity, for: user, as: :activity)
59 end
60 end
61 end