1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 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.ActivityPub.Visibility
13 alias Pleroma.Web.CommonAPI
14 alias Pleroma.Web.Plugs.OAuthScopesPlug
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 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
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})
38 error when is_nil(error) or error == false ->
39 render_error(conn, :not_found, "Record not found")
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})
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})
57 defp get_cached_vote_or_vote(user, object, choices) do
58 idempotency_key = "polls:#{user.id}:#{object.data["id"]}"
60 @cachex.fetch!(:idempotency_cache, idempotency_key, fn _ ->
61 case CommonAPI.vote(user, object, choices) do
62 {:error, _message} = res -> {:ignore, res}