1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MastodonAPI.PollController do
6 use Pleroma.Web, :controller
8 import Pleroma.Web.ControllerHelper, only: [try_render: 3, json_response: 3]
10 alias Pleroma.Activity
12 alias Pleroma.Web.Plugs.OAuthScopesPlug
13 alias Pleroma.Web.ActivityPub.Visibility
14 alias Pleroma.Web.CommonAPI
16 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
18 plug(Pleroma.Web.ApiSpec.CastAndValidate)
22 %{scopes: ["read:statuses"], fallback: :proceed_unauthenticated} when action == :show
25 plug(OAuthScopesPlug, %{scopes: ["write:statuses"]} when action == :vote)
27 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.PollOperation
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})
36 error when is_nil(error) or error == false ->
37 render_error(conn, :not_found, "Record not found")
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})
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})
55 defp get_cached_vote_or_vote(user, object, choices) do
56 idempotency_key = "polls:#{user.id}:#{object.data["id"]}"
58 Cachex.fetch!(:idempotency_cache, idempotency_key, fn ->
59 case CommonAPI.vote(user, object, choices) do
60 {:error, _message} = res -> {:ignore, res}