2019-11-30 06:40:37 +01:00
|
|
|
defmodule PhilomenaWeb.Image.RandomController do
|
|
|
|
use PhilomenaWeb, :controller
|
|
|
|
|
2020-05-08 04:10:54 +02:00
|
|
|
alias PhilomenaWeb.ImageSorter
|
|
|
|
alias PhilomenaWeb.ImageScope
|
2019-12-24 22:14:42 +01:00
|
|
|
alias Philomena.Elasticsearch
|
2019-11-30 06:40:37 +01:00
|
|
|
alias Philomena.Images.Query
|
|
|
|
alias Philomena.Images.Image
|
|
|
|
|
|
|
|
def index(conn, params) do
|
|
|
|
user = conn.assigns.current_user
|
|
|
|
filter = conn.assigns.compiled_filter
|
|
|
|
|
2020-05-08 04:10:54 +02:00
|
|
|
scope = ImageScope.scope(conn)
|
2019-11-30 06:40:37 +01:00
|
|
|
query = query(user, params)
|
|
|
|
random_id = random_image_id(query, filter)
|
|
|
|
|
|
|
|
if random_id do
|
|
|
|
redirect(conn, to: Routes.image_path(conn, :show, random_id, scope))
|
|
|
|
else
|
|
|
|
redirect(conn, external: conn.assigns.referrer)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
defp query(user, %{"q" => q}) do
|
|
|
|
{:ok, query} = Query.compile(user, q)
|
|
|
|
|
|
|
|
query
|
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-11-30 06:40:37 +01:00
|
|
|
defp query(_user, _), do: %{match_all: %{}}
|
|
|
|
|
|
|
|
defp random_image_id(query, filter) do
|
2020-05-29 02:35:52 +02:00
|
|
|
%{query: query, sorts: sort} = ImageSorter.parse_sort(%{"sf" => "random"}, query)
|
2019-11-30 06:40:37 +01:00
|
|
|
|
2020-08-23 21:47:42 +02:00
|
|
|
Image
|
|
|
|
|> Elasticsearch.search_definition(
|
2019-11-30 06:40:37 +01:00
|
|
|
%{
|
|
|
|
query: %{
|
|
|
|
bool: %{
|
2020-05-29 01:43:17 +02:00
|
|
|
must: query,
|
2019-11-30 06:40:37 +01:00
|
|
|
must_not: [
|
|
|
|
filter,
|
|
|
|
%{term: %{hidden_from_users: true}}
|
|
|
|
]
|
|
|
|
}
|
|
|
|
},
|
2020-05-29 01:43:17 +02:00
|
|
|
sort: sort
|
2019-11-30 06:40:37 +01:00
|
|
|
},
|
2020-08-23 21:47:42 +02:00
|
|
|
%{page_size: 1}
|
2019-11-30 06:40:37 +01:00
|
|
|
)
|
2020-08-23 21:47:42 +02:00
|
|
|
|> Elasticsearch.search_records(Image)
|
2019-11-30 06:40:37 +01:00
|
|
|
|> Enum.to_list()
|
|
|
|
|> unwrap()
|
|
|
|
end
|
|
|
|
|
|
|
|
defp unwrap([image]), do: image.id
|
|
|
|
defp unwrap([]), do: nil
|
2019-12-24 22:14:42 +01:00
|
|
|
end
|