philomena/lib/philomena_web/image_sorter.ex

96 lines
2.1 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
)
2019-11-30 03:33:15 +01:00
def parse_sort(params) do
sd = parse_sd(params)
parse_sf(params, sd)
end
defp parse_sd(%{"sd" => sd}) when sd in ~W(asc desc), do: sd
defp parse_sd(_params), do: "desc"
2019-12-25 02:17:27 +01:00
defp parse_sf(%{"sf" => sf}, sd) when sf in @allowed_fields do
2019-12-26 23:43:32 +01:00
%{queries: [], sorts: [%{sf => sd}], constant_score: true}
end
defp parse_sf(%{"sf" => "_score"}, sd) do
%{queries: [], sorts: [%{"_score" => sd}], constant_score: false}
2019-11-30 03:33:15 +01:00
end
defp parse_sf(%{"sf" => "random"}, sd) do
random_query(:rand.uniform(4_294_967_296), sd)
end
defp parse_sf(%{"sf" => <<"random:", seed::binary>>}, sd) do
case Integer.parse(seed) do
{seed, _rest} ->
random_query(seed, sd)
_ ->
random_query(:rand.uniform(4_294_967_296), sd)
end
end
defp parse_sf(%{"sf" => <<"gallery_id:", gallery::binary>>}, sd) do
case Integer.parse(gallery) do
{gallery, _rest} ->
%{
queries: [],
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
}
}
}
2020-01-11 05:20:19 +01:00
],
2019-12-26 23:43:32 +01:00
constant_score: true
2019-11-30 03:33:15 +01:00
}
_ ->
2019-12-26 23:43:32 +01:00
%{queries: [%{match_none: %{}}], sorts: [], constant_score: true}
2019-11-30 03:33:15 +01:00
end
end
defp parse_sf(_params, sd) do
2019-12-26 23:43:32 +01:00
%{queries: [], sorts: [%{"created_at" => sd}], constant_score: true}
2019-11-30 03:33:15 +01:00
end
defp random_query(seed, sd) do
%{
2020-01-11 05:20:19 +01:00
queries: [
%{
function_score: %{
query: %{match_all: %{}},
random_score: %{seed: seed, field: :id},
boost_mode: :replace
}
2019-11-30 03:33:15 +01:00
}
2020-01-11 05:20:19 +01:00
],
2019-12-26 23:43:32 +01:00
sorts: [%{"_score" => sd}],
constant_score: true
2019-11-30 03:33:15 +01:00
}
end
2019-12-25 02:17:27 +01:00
end