Add visibility check in context path (#26)
[akkoma] / lib / pleroma / web / mastodon_api / controllers / poll_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.PollController do
6 use Pleroma.Web, :controller
7
8 import Pleroma.Web.ControllerHelper, only: [try_render: 3, json_response: 3]
9
10 alias Pleroma.Activity
11 alias Pleroma.Object
12 alias Pleroma.Web.ActivityPub.Visibility
13 alias Pleroma.Web.CommonAPI
14 alias Pleroma.Web.Plugs.OAuthScopesPlug
15
16 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
17
18 plug(Pleroma.Web.ApiSpec.CastAndValidate)
19
20 plug(
21 OAuthScopesPlug,
22 %{scopes: ["read:statuses"], fallback: :proceed_unauthenticated} when action == :show
23 )
24
25 plug(OAuthScopesPlug, %{scopes: ["write:statuses"]} when action == :vote)
26
27 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.PollOperation
28
29 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
30
31 @doc "GET /api/v1/polls/:id"
32 def show(%{assigns: %{user: user}} = conn, %{id: id}) do
33 with %Object{} = object <- Object.get_by_id_and_maybe_refetch(id, interval: 60),
34 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
35 true <- Visibility.visible_for_user?(activity, user) do
36 try_render(conn, "show.json", %{object: object, for: user})
37 else
38 error when is_nil(error) or error == false ->
39 render_error(conn, :not_found, "Record not found")
40 end
41 end
42
43 @doc "POST /api/v1/polls/:id/votes"
44 def vote(%{assigns: %{user: user}, body_params: %{choices: choices}} = conn, %{id: id}) do
45 with %Object{data: %{"type" => "Question"}} = object <- Object.get_by_id(id),
46 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
47 true <- Visibility.visible_for_user?(activity, user),
48 {:ok, _activities, object} <- get_cached_vote_or_vote(user, object, choices) do
49 try_render(conn, "show.json", %{object: object, for: user})
50 else
51 nil -> render_error(conn, :not_found, "Record not found")
52 false -> render_error(conn, :not_found, "Record not found")
53 {:error, message} -> json_response(conn, :unprocessable_entity, %{error: message})
54 end
55 end
56
57 defp get_cached_vote_or_vote(user, object, choices) do
58 idempotency_key = "polls:#{user.id}:#{object.data["id"]}"
59
60 @cachex.fetch!(:idempotency_cache, idempotency_key, fn _ ->
61 case CommonAPI.vote(user, object, choices) do
62 {:error, _message} = res -> {:ignore, res}
63 res -> {:commit, res}
64 end
65 end)
66 end
67 end