Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / web / mastodon_api / views / poll_view.ex
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
5 defmodule Pleroma.Web.MastodonAPI.PollView do
6 use Pleroma.Web, :view
7
8 alias Pleroma.Web.CommonAPI.Utils
9
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
14 %{
15 # Mastodon uses separate ids for polls, but an object can't have
16 # more than one poll embedded so object id is fine
17 id: to_string(object.id),
18 expires_at: end_time,
19 expired: expired,
20 multiple: multiple,
21 votes_count: votes_count,
22 options: options,
23 voted: voted?(params),
24 emojis: Pleroma.Web.MastodonAPI.StatusView.build_emojis(object.data["emoji"])
25 }
26 end
27
28 def render("show.json", %{object: object} = params) do
29 case object.data do
30 %{"anyOf" => options} when is_list(options) ->
31 render(__MODULE__, "show.json", Map.merge(params, %{multiple: true, options: options}))
32
33 %{"oneOf" => options} when is_list(options) ->
34 render(__MODULE__, "show.json", Map.merge(params, %{multiple: false, options: options}))
35
36 _ ->
37 nil
38 end
39 end
40
41 defp end_time_and_expired(object) do
42 case object.data["closed"] || object.data["endTime"] do
43 end_time when is_binary(end_time) ->
44 end_time = NaiveDateTime.from_iso8601!(end_time)
45 expired = NaiveDateTime.compare(end_time, NaiveDateTime.utc_now()) == :lt
46
47 {Utils.to_masto_date(end_time), expired}
48
49 _ ->
50 {nil, false}
51 end
52 end
53
54 defp options_and_votes_count(options) do
55 Enum.map_reduce(options, 0, fn %{"name" => name} = option, count ->
56 current_count = option["replies"]["totalItems"] || 0
57
58 {%{
59 title: name,
60 votes_count: current_count
61 }, current_count + count}
62 end)
63 end
64
65 defp voted?(%{object: object} = opts) do
66 if opts[:for] do
67 existing_votes = Pleroma.Web.ActivityPub.Utils.get_existing_votes(opts[:for].ap_id, object)
68 existing_votes != [] or opts[:for].ap_id == object.data["actor"]
69 else
70 false
71 end
72 end
73 end