Fork of Pleroma with site-specific changes and feature branches https://git.pleroma.social/pleroma/pleroma
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.5KB

  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. defmodule Pleroma.Web.MastodonAPI.PollController do
  5. use Pleroma.Web, :controller
  6. import Pleroma.Web.ControllerHelper, only: [try_render: 3, json_response: 3]
  7. alias Pleroma.Activity
  8. alias Pleroma.Object
  9. alias Pleroma.Web.ActivityPub.Visibility
  10. alias Pleroma.Web.CommonAPI
  11. alias Pleroma.Web.Plugs.OAuthScopesPlug
  12. action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
  13. plug(Pleroma.Web.ApiSpec.CastAndValidate)
  14. plug(
  15. OAuthScopesPlug,
  16. %{scopes: ["read:statuses"], fallback: :proceed_unauthenticated} when action == :show
  17. )
  18. plug(OAuthScopesPlug, %{scopes: ["write:statuses"]} when action == :vote)
  19. defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.PollOperation
  20. @doc "GET /api/v1/polls/:id"
  21. def show(%{assigns: %{user: user}} = conn, %{id: id}) do
  22. with %Object{} = object <- Object.get_by_id_and_maybe_refetch(id, interval: 60),
  23. %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
  24. true <- Visibility.visible_for_user?(activity, user) do
  25. try_render(conn, "show.json", %{object: object, for: user})
  26. else
  27. error when is_nil(error) or error == false ->
  28. render_error(conn, :not_found, "Record not found")
  29. end
  30. end
  31. @doc "POST /api/v1/polls/:id/votes"
  32. def vote(%{assigns: %{user: user}, body_params: %{choices: choices}} = conn, %{id: id}) do
  33. with %Object{data: %{"type" => "Question"}} = object <- Object.get_by_id(id),
  34. %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
  35. true <- Visibility.visible_for_user?(activity, user),
  36. {:ok, _activities, object} <- get_cached_vote_or_vote(user, object, choices) do
  37. try_render(conn, "show.json", %{object: object, for: user})
  38. else
  39. nil -> render_error(conn, :not_found, "Record not found")
  40. false -> render_error(conn, :not_found, "Record not found")
  41. {:error, message} -> json_response(conn, :unprocessable_entity, %{error: message})
  42. end
  43. end
  44. defp get_cached_vote_or_vote(user, object, choices) do
  45. idempotency_key = "polls:#{user.id}:#{object.data["id"]}"
  46. Cachex.fetch!(:idempotency_cache, idempotency_key, fn ->
  47. case CommonAPI.vote(user, object, choices) do
  48. {:error, _message} = res -> {:ignore, res}
  49. res -> {:commit, res}
  50. end
  51. end)
  52. end
  53. end