Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / web / mastodon_api / controllers / poll_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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 plug(Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug)
26
27 @doc "GET /api/v1/polls/:id"
28 def show(%{assigns: %{user: user}} = conn, %{"id" => id}) do
29 with %Object{} = object <- Object.get_by_id_and_maybe_refetch(id, interval: 60),
30 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
31 true <- Visibility.visible_for_user?(activity, user) do
32 try_render(conn, "show.json", %{object: object, for: user})
33 else
34 error when is_nil(error) or error == false ->
35 render_error(conn, :not_found, "Record not found")
36 end
37 end
38
39 @doc "POST /api/v1/polls/:id/votes"
40 def vote(%{assigns: %{user: user}} = conn, %{"id" => id, "choices" => choices}) do
41 with %Object{data: %{"type" => "Question"}} = object <- Object.get_by_id(id),
42 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
43 true <- Visibility.visible_for_user?(activity, user),
44 {:ok, _activities, object} <- get_cached_vote_or_vote(user, object, choices) do
45 try_render(conn, "show.json", %{object: object, for: user})
46 else
47 nil -> render_error(conn, :not_found, "Record not found")
48 false -> render_error(conn, :not_found, "Record not found")
49 {:error, message} -> json_response(conn, :unprocessable_entity, %{error: message})
50 end
51 end
52
53 defp get_cached_vote_or_vote(user, object, choices) do
54 idempotency_key = "polls:#{user.id}:#{object.data["id"]}"
55
56 Cachex.fetch!(:idempotency_cache, idempotency_key, fn ->
57 case CommonAPI.vote(user, object, choices) do
58 {:error, _message} = res -> {:ignore, res}
59 res -> {:commit, res}
60 end
61 end)
62 end
63 end