Merge branch 'feature/1710-consolidate-instance-info' into 'develop'
[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(
19 OAuthScopesPlug,
20 %{scopes: ["read:statuses"], fallback: :proceed_unauthenticated} when action == :show
21 )
22
23 plug(OAuthScopesPlug, %{scopes: ["write:statuses"]} when action == :vote)
24
25 @doc "GET /api/v1/polls/:id"
26 def show(%{assigns: %{user: user}} = conn, %{"id" => id}) do
27 with %Object{} = object <- Object.get_by_id_and_maybe_refetch(id, interval: 60),
28 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
29 true <- Visibility.visible_for_user?(activity, user) do
30 try_render(conn, "show.json", %{object: object, for: user})
31 else
32 error when is_nil(error) or error == false ->
33 render_error(conn, :not_found, "Record not found")
34 end
35 end
36
37 @doc "POST /api/v1/polls/:id/votes"
38 def vote(%{assigns: %{user: user}} = conn, %{"id" => id, "choices" => choices}) do
39 with %Object{data: %{"type" => "Question"}} = object <- Object.get_by_id(id),
40 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
41 true <- Visibility.visible_for_user?(activity, user),
42 {:ok, _activities, object} <- get_cached_vote_or_vote(user, object, choices) do
43 try_render(conn, "show.json", %{object: object, for: user})
44 else
45 nil -> render_error(conn, :not_found, "Record not found")
46 false -> render_error(conn, :not_found, "Record not found")
47 {:error, message} -> json_response(conn, :unprocessable_entity, %{error: message})
48 end
49 end
50
51 defp get_cached_vote_or_vote(user, object, choices) do
52 idempotency_key = "polls:#{user.id}:#{object.data["id"]}"
53
54 Cachex.fetch!(:idempotency_cache, idempotency_key, fn ->
55 case CommonAPI.vote(user, object, choices) do
56 {:error, _message} = res -> {:ignore, res}
57 res -> {:commit, res}
58 end
59 end)
60 end
61 end