philomena/lib/philomena_web/controllers/search_controller.ex

107 lines
2.5 KiB
Elixir
Raw Normal View History

2019-08-29 03:33:58 +02:00
defmodule PhilomenaWeb.SearchController do
use PhilomenaWeb, :controller
alias Philomena.Images.{Image, Query}
2019-11-17 03:20:33 +01:00
alias Philomena.Interactions
2019-08-29 03:33:58 +02:00
2019-08-29 03:35:01 +02:00
import Ecto.Query
2019-08-29 03:33:58 +02:00
def index(conn, params) do
2019-11-17 03:20:33 +01:00
filter = conn.assigns.compiled_filter
user = conn.assigns.current_user
2019-08-29 03:33:58 +02:00
with {:ok, query} <- Query.compile(user, params["q"]) do
2019-11-18 15:14:26 +01:00
sd = parse_sd(params)
sf = parse_sf(params, sd)
2019-08-29 03:35:01 +02:00
images =
2019-08-29 03:33:58 +02:00
Image.search_records(
2019-08-29 03:35:01 +02:00
%{
2019-11-18 15:14:26 +01:00
query: %{bool: %{must: [query | sf.query], must_not: [filter, %{term: %{hidden_from_users: true}}]}},
sort: sf.sort
2019-08-29 03:35:01 +02:00
},
2019-10-09 01:19:57 +02:00
conn.assigns.pagination,
2019-08-29 03:35:01 +02:00
Image |> preload(:tags)
2019-08-29 03:33:58 +02:00
)
2019-11-17 03:20:33 +01:00
interactions =
Interactions.user_interactions(images, user)
2019-08-29 03:44:15 +02:00
conn
2019-11-17 23:51:14 +01:00
|> render("index.html", images: images, search_query: params["q"], interactions: interactions, layout_class: "layout--wide")
2019-08-29 03:35:01 +02:00
else
2019-11-15 16:40:10 +01:00
{:error, msg} ->
2019-08-29 03:44:15 +02:00
conn
|> render("index.html",
2019-08-29 03:35:01 +02:00
images: [],
2019-11-15 16:40:10 +01:00
error: msg,
2019-08-29 03:35:01 +02:00
search_query: params["q"]
)
end
2019-08-29 03:33:58 +02:00
end
2019-11-18 15:14:26 +01:00
defp parse_sd(%{"sd" => sd}) when sd in ~W(asc desc),
do: sd
defp parse_sd(_params), do: :desc
defp parse_sf(%{"sf" => sf}, sd) when
sf in ~W(created_at updated_at first_seen_at width height score comment_count tag_count wilson_score _score)
do
%{query: [], sort: %{sf => sd}}
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} ->
%{
query: [],
sort: %{
"galleries.position": %{
order: sd,
nested_path: :galleries,
nested_filter: %{
term: %{
"galleries.id": gallery
}
}
}
}
}
_ ->
%{query: [], sort: %{match_none: %{}}}
end
end
defp parse_sf(_params, sd) do
%{query: [], sort: %{created_at: sd}}
end
defp random_query(seed, sd) do
%{
query: [%{
function_score: %{
query: %{match_all: %{}},
random_score: %{seed: seed},
boost_mode: :replace
}
}],
sort: %{_score: sd}
}
end
2019-08-29 03:33:58 +02:00
end