Fix multiple-choice poll detection

This commit is contained in:
Haelwenn (lanodan) Monnier 2020-06-15 00:30:45 +02:00
parent 10bd08ef07
commit 4644a8bd10
No known key found for this signature in database
GPG Key ID: D5B7A8E43C997DEE
3 changed files with 19 additions and 11 deletions

View File

@ -255,6 +255,12 @@ def increase_replies_count(ap_id) do
end
end
defp poll_is_multiple?(%Object{data: %{"anyOf" => anyOf}}) do
!Enum.empty?(anyOf)
end
defp poll_is_multiple?(_), do: false
def decrease_replies_count(ap_id) do
Object
|> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
@ -281,10 +287,10 @@ def decrease_replies_count(ap_id) do
def increase_vote_count(ap_id, name, actor) do
with %Object{} = object <- Object.normalize(ap_id),
"Question" <- object.data["type"] do
multiple = Map.has_key?(object.data, "anyOf")
key = if poll_is_multiple?(object), do: "anyOf", else: "oneOf"
options =
(object.data["anyOf"] || object.data["oneOf"] || [])
object.data[key]
|> Enum.map(fn
%{"name" => ^name} = option ->
Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
@ -296,11 +302,8 @@ def increase_vote_count(ap_id, name, actor) do
voters = [actor | object.data["voters"] || []] |> Enum.uniq()
data =
if multiple do
Map.put(object.data, "anyOf", options)
else
Map.put(object.data, "oneOf", options)
end
object.data
|> Map.put(key, options)
|> Map.put("voters", voters)
object

View File

@ -340,8 +340,13 @@ defp validate_existing_votes(%{ap_id: ap_id}, object) do
end
end
defp get_options_and_max_count(%{data: %{"anyOf" => any_of}}), do: {any_of, Enum.count(any_of)}
defp get_options_and_max_count(%{data: %{"oneOf" => one_of}}), do: {one_of, 1}
defp get_options_and_max_count(%{data: %{"anyOf" => any_of}})
when is_list(any_of) and any_of != [],
do: {any_of, Enum.count(any_of)}
defp get_options_and_max_count(%{data: %{"oneOf" => one_of}})
when is_list(one_of) and one_of != [],
do: {one_of, 1}
defp normalize_and_validate_choices(choices, object) do
choices = Enum.map(choices, fn i -> if is_binary(i), do: String.to_integer(i), else: i end)

View File

@ -28,10 +28,10 @@ def render("show.json", %{object: object, multiple: multiple, options: options}
def render("show.json", %{object: object} = params) do
case object.data do
%{"anyOf" => options} when is_list(options) ->
%{"anyOf" => options} when is_list(options) and options != [] ->
render(__MODULE__, "show.json", Map.merge(params, %{multiple: true, options: options}))
%{"oneOf" => options} when is_list(options) ->
%{"oneOf" => options} when is_list(options) and options != [] ->
render(__MODULE__, "show.json", Map.merge(params, %{multiple: false, options: options}))
_ ->