1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MastodonAPI.PollView do
8 alias Pleroma.Web.CommonAPI.Utils
10 def render("show.json", %{object: object, multiple: multiple, options: options} = params) do
11 {end_time, expired} = end_time_and_expired(object)
12 {options, votes_count} = options_and_votes_count(options)
13 {voted, own_votes} = voted_and_own_votes(params, options)
16 # Mastodon uses separate ids for polls, but an object can't have
17 # more than one poll embedded so object id is fine
18 id: to_string(object.id),
22 votes_count: votes_count,
23 voters_count: voters_count(object),
27 emojis: Pleroma.Web.MastodonAPI.StatusView.build_emojis(object.data["emoji"])
31 def render("show.json", %{object: object} = params) do
33 %{"anyOf" => [_ | _] = options} ->
34 render(__MODULE__, "show.json", Map.merge(params, %{multiple: true, options: options}))
36 %{"oneOf" => [_ | _] = options} ->
37 render(__MODULE__, "show.json", Map.merge(params, %{multiple: false, options: options}))
44 defp end_time_and_expired(object) do
45 if object.data["closed"] do
46 end_time = NaiveDateTime.from_iso8601!(object.data["closed"])
47 expired = NaiveDateTime.compare(end_time, NaiveDateTime.utc_now()) == :lt
49 {Utils.to_masto_date(end_time), expired}
55 defp options_and_votes_count(options) do
56 Enum.map_reduce(options, 0, fn %{"name" => name} = option, count ->
57 current_count = option["replies"]["totalItems"] || 0
61 votes_count: current_count
62 }, current_count + count}
66 defp voters_count(%{data: %{"voters" => [_ | _] = voters}}) do
70 defp voters_count(_), do: 0
72 defp voted_and_own_votes(%{object: object} = params, options) do
73 options = options |> Enum.map(fn x -> Map.get(x, :title) end)
77 Pleroma.Web.ActivityPub.Utils.get_existing_votes(params[:for].ap_id, object)
80 for vote <- existing_votes do
81 data = Map.get(vote, :object) |> Map.get(:data)
83 Enum.find_index(options, fn x -> x == data["name"] end)
86 voted = existing_votes != [] or params[:for].ap_id == object.data["actor"]