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
|
2021-02-25 07:44:31 +01:00
|
|
|
alias PhilomenaWeb.ImageLoader
|
2019-12-24 22:14:42 +01:00
|
|
|
alias Philomena.Elasticsearch
|
2019-11-30 06:40:37 +01:00
|
|
|
alias Philomena.Images.Image
|
|
|
|
|
|
|
|
def index(conn, params) do
|
2020-05-08 04:10:54 +02:00
|
|
|
scope = ImageScope.scope(conn)
|
2019-11-30 06:40:37 +01:00
|
|
|
|
2021-02-25 07:44:31 +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
|
|
|
|
2021-02-25 07:44:31 +01:00
|
|
|
case unwrap_random_result(search_definition) do
|
|
|
|
nil ->
|
|
|
|
redirect(conn, to: Routes.image_path(conn, :index))
|
2019-11-30 06:40:37 +01:00
|
|
|
|
2021-02-25 07:44:31 +01:00
|
|
|
random_id ->
|
|
|
|
redirect(conn, to: Routes.image_path(conn, :show, random_id, scope))
|
|
|
|
end
|
2019-11-30 06:40:37 +01:00
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2021-02-25 07:44:31 +01:00
|
|
|
defp query_string(%{"q" => query}), do: query
|
|
|
|
defp query_string(_params), do: "*"
|
|
|
|
|
|
|
|
defp unwrap_random_result({:ok, {definition, _tags}}) do
|
|
|
|
definition
|
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
|
|
|
|
|
2021-02-25 07:44:31 +01:00
|
|
|
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
|
2019-12-24 22:14:42 +01:00
|
|
|
end
|