philomena/lib/philomena_web/controllers/image/random_controller.ex

45 lines
1.1 KiB
Elixir
Raw Normal View History

2019-11-30 06:40:37 +01:00
defmodule PhilomenaWeb.Image.RandomController do
use PhilomenaWeb, :controller
alias PhilomenaWeb.ImageSorter
alias PhilomenaWeb.ImageScope
alias PhilomenaWeb.ImageLoader
alias PhilomenaQuery.Search
2019-11-30 06:40:37 +01:00
alias Philomena.Images.Image
def index(conn, params) do
scope = ImageScope.scope(conn)
2019-11-30 06:40:37 +01:00
search_definition =
ImageLoader.search_string(
conn,
query_string(params),
pagination: %{page_size: 1},
sorts: &ImageSorter.parse_sort(%{"sf" => "random"}, &1)
)
2019-11-30 06:40:37 +01:00
case unwrap_random_result(search_definition) do
nil ->
redirect(conn, to: ~p"/images")
2019-11-30 06:40:37 +01:00
random_id ->
redirect(conn, to: ~p"/images/#{random_id}?#{scope}")
end
2019-11-30 06:40:37 +01:00
end
2020-01-11 05:20:19 +01:00
defp query_string(%{"q" => query}), do: query
defp query_string(_params), do: "*"
defp unwrap_random_result({:ok, {definition, _tags}}) do
definition
|> Search.search_records(Image)
2019-11-30 06:40:37 +01:00
|> Enum.to_list()
|> unwrap()
end
defp unwrap_random_result(_definition), do: nil
2019-11-30 06:40:37 +01:00
defp unwrap([image]), do: image.id
defp unwrap([]), do: nil
end