Merge remote-tracking branch 'origin/develop' into feature/embeddable-posts
[akkoma] / lib / pleroma / web / mastodon_api / controllers / poll_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.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.Plugs.OAuthScopesPlug
13 alias Pleroma.Web.ActivityPub.Visibility
14 alias Pleroma.Web.CommonAPI
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 @doc "GET /api/v1/polls/:id"
30 def show(%{assigns: %{user: user}} = conn, %{id: id}) do
31 with %Object{} = object <- Object.get_by_id_and_maybe_refetch(id, interval: 60),
32 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
33 true <- Visibility.visible_for_user?(activity, user) do
34 try_render(conn, "show.json", %{object: object, for: user})
35 else
36 error when is_nil(error) or error == false ->
37 render_error(conn, :not_found, "Record not found")
38 end
39 end
40
41 @doc "POST /api/v1/polls/:id/votes"
42 def vote(%{assigns: %{user: user}, body_params: %{choices: choices}} = conn, %{id: id}) do
43 with %Object{data: %{"type" => "Question"}} = object <- Object.get_by_id(id),
44 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
45 true <- Visibility.visible_for_user?(activity, user),
46 {:ok, _activities, object} <- get_cached_vote_or_vote(user, object, choices) do
47 try_render(conn, "show.json", %{object: object, for: user})
48 else
49 nil -> render_error(conn, :not_found, "Record not found")
50 false -> render_error(conn, :not_found, "Record not found")
51 {:error, message} -> json_response(conn, :unprocessable_entity, %{error: message})
52 end
53 end
54
55 defp get_cached_vote_or_vote(user, object, choices) do
56 idempotency_key = "polls:#{user.id}:#{object.data["id"]}"
57
58 Cachex.fetch!(:idempotency_cache, idempotency_key, fn ->
59 case CommonAPI.vote(user, object, choices) do
60 {:error, _message} = res -> {:ignore, res}
61 res -> {:commit, res}
62 end
63 end)
64 end
65 end