philomena/lib/philomena_web/controllers/comment_controller.ex

78 lines
2 KiB
Elixir
Raw Normal View History

2019-11-12 04:10:41 +01:00
defmodule PhilomenaWeb.CommentController do
use PhilomenaWeb, :controller
2019-11-13 04:12:46 +01:00
alias Philomena.{Comments.Comment, Textile.Renderer}
2019-11-12 04:10:41 +01:00
import Ecto.Query
2019-11-17 22:30:20 +01:00
def index(conn, params) do
2019-11-12 04:10:41 +01:00
comments =
Comment.search_records(
%{
query: %{
bool: %{
2019-11-17 22:30:20 +01:00
must: parse_search(params) ++ [%{term: %{hidden_from_users: false}}]
2019-11-12 04:10:41 +01:00
}
},
2019-11-17 22:30:20 +01:00
sort: parse_sort(params)
2019-11-12 04:10:41 +01:00
},
conn.assigns.pagination,
2019-11-17 21:37:01 +01:00
Comment |> preload([image: [:tags], user: [awards: :badge]])
2019-11-12 04:10:41 +01:00
)
rendered =
comments.entries
|> Renderer.render_collection()
comments =
%{comments | entries: Enum.zip(comments.entries, rendered)}
render(conn, "index.html", comments: comments)
end
2019-11-17 22:30:20 +01:00
defp parse_search(%{"comment" => comment_params}) do
parse_author(comment_params) ++
parse_image_id(comment_params) ++
parse_body(comment_params)
end
defp parse_search(_params), do: [%{match_all: %{}}]
defp parse_author(%{"author" => author}) when author not in [nil, ""] do
case String.contains?(author, ["*", "?"]) do
true ->
[
%{wildcard: %{author: author}},
%{term: %{anonymous: false}}
]
false ->
[
%{term: %{author: author}},
%{term: %{anonymous: false}}
]
end
end
defp parse_author(_params), do: []
defp parse_image_id(%{"image_id" => image_id}) when image_id not in [nil, ""] do
case Integer.parse(image_id) do
{image_id, _rest} ->
[%{term: %{image_id: image_id}}]
_error ->
[]
end
end
defp parse_image_id(_params), do: []
defp parse_body(%{"body" => body}) when body not in [nil, ""],
do: [%{match: %{body: body}}]
defp parse_body(_params), do: []
defp parse_sort(%{"comment" => %{"sf" => sf, "sd" => sd}}) when sf in ["posted_at", "_score"] and sd in ["desc", "asc"] do
%{sf => sd}
end
defp parse_sort(_params) do
%{posted_at: :desc}
end
2019-11-12 04:10:41 +01:00
end