philomena/lib/philomena_web/image_sorter.ex

95 lines
2 KiB
Elixir
Raw Normal View History

defmodule PhilomenaWeb.ImageSorter do
2019-12-25 02:17:27 +01:00
@allowed_fields ~W(
created_at
updated_at
first_seen_at
aspect_ratio
faves
id
downvotes
upvotes
width
height
score
comment_count
tag_count
wilson_score
2020-07-06 20:00:02 +02:00
pixels
size
duration
2019-12-25 02:17:27 +01:00
)
2020-05-29 01:43:17 +02:00
def parse_sort(params, query) do
2019-11-30 03:33:15 +01:00
sd = parse_sd(params)
2020-05-29 01:43:17 +02:00
parse_sf(params, sd, query)
2019-11-30 03:33:15 +01:00
end
defp parse_sd(%{"sd" => sd}) when sd in ~W(asc desc), do: sd
defp parse_sd(_params), do: "desc"
2020-05-29 01:43:17 +02:00
defp parse_sf(%{"sf" => sf}, sd, query) when sf in @allowed_fields do
%{query: query, sorts: [%{sf => sd}]}
2019-12-26 23:43:32 +01:00
end
2020-05-29 01:43:17 +02:00
defp parse_sf(%{"sf" => "_score"}, sd, query) do
%{query: query, sorts: [%{"_score" => sd}]}
2019-11-30 03:33:15 +01:00
end
2020-05-29 01:43:17 +02:00
defp parse_sf(%{"sf" => "random"}, sd, query) do
random_query(:rand.uniform(4_294_967_296), sd, query)
2019-11-30 03:33:15 +01:00
end
2020-05-29 01:43:17 +02:00
defp parse_sf(%{"sf" => <<"random:", seed::binary>>}, sd, query) do
2019-11-30 03:33:15 +01:00
case Integer.parse(seed) do
{seed, _rest} ->
2020-05-29 01:43:17 +02:00
random_query(seed, sd, query)
2019-11-30 03:33:15 +01:00
_ ->
2020-05-29 01:43:17 +02:00
random_query(:rand.uniform(4_294_967_296), sd, query)
2019-11-30 03:33:15 +01:00
end
end
2020-05-29 01:43:17 +02:00
defp parse_sf(%{"sf" => <<"gallery_id:", gallery::binary>>}, sd, query) do
2019-11-30 03:33:15 +01:00
case Integer.parse(gallery) do
{gallery, _rest} ->
%{
2020-05-29 01:43:17 +02:00
query: query,
2020-01-11 05:20:19 +01:00
sorts: [
%{
"galleries.position" => %{
order: sd,
nested: %{
path: :galleries,
filter: %{
term: %{"galleries.id" => gallery}
}
2019-11-30 03:33:15 +01:00
}
}
}
]
2019-11-30 03:33:15 +01:00
}
_ ->
2020-05-29 01:43:17 +02:00
%{query: query, sorts: []}
2019-11-30 03:33:15 +01:00
end
end
2020-05-29 01:43:17 +02:00
defp parse_sf(_params, sd, query) do
%{query: query, sorts: [%{"created_at" => sd}]}
2019-11-30 03:33:15 +01:00
end
2020-05-29 01:43:17 +02:00
defp random_query(seed, sd, query) do
2019-11-30 03:33:15 +01:00
%{
2020-05-29 01:43:17 +02:00
query: %{
function_score: %{
query: query,
random_score: %{seed: seed, field: :id},
boost_mode: :replace
2019-11-30 03:33:15 +01:00
}
2020-05-29 01:43:17 +02:00
},
sorts: [%{"_score" => sd}]
2019-11-30 03:33:15 +01:00
}
end
2019-12-25 02:17:27 +01:00
end