philomena/lib/philomena_web/controllers/topic_controller.ex

64 lines
1.7 KiB
Elixir
Raw Normal View History

2019-10-06 23:31:48 +02:00
defmodule PhilomenaWeb.TopicController do
use PhilomenaWeb, :controller
2019-11-18 04:31:28 +01:00
alias Philomena.{Forums.Forum, Topics, Topics.Topic, Posts, Posts.Post, Textile.Renderer}
2019-10-06 23:31:48 +02:00
alias Philomena.Repo
import Ecto.Query
plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true
2019-11-11 18:57:02 +01:00
def show(conn, %{"id" => slug} = params) do
2019-10-06 23:59:47 +02:00
forum = conn.assigns.forum
topic =
Topic
|> where(forum_id: ^forum.id, slug: ^slug, hidden_from_users: false)
2019-11-18 19:11:32 +01:00
|> preload([:user, poll: :options])
2019-10-06 23:59:47 +02:00
|> Repo.one()
conn = conn |> assign(:topic, topic)
2019-10-09 01:40:26 +02:00
%{page_number: page} = conn.assigns.pagination
2019-10-06 23:59:47 +02:00
2019-11-11 18:57:02 +01:00
page =
with {post_id, _extra} <- Integer.parse(params["post_id"] || ""),
[post] <- Post |> where(id: ^post_id) |> Repo.all()
do
div(post.topic_position, 25) + 1
else
_ ->
page
end
2019-10-06 23:31:48 +02:00
posts =
Post
|> where(topic_id: ^conn.assigns.topic.id)
2019-10-09 01:37:14 +02:00
|> where([p], p.topic_position >= ^(25 * (page - 1)) and p.topic_position < ^(25 * page))
2019-10-07 00:06:22 +02:00
|> order_by(asc: :created_at)
2019-11-12 03:53:19 +01:00
|> preload([topic: :forum, user: [awards: :badge]])
2019-10-09 01:40:26 +02:00
|> Repo.all()
2019-11-11 00:35:52 +01:00
rendered =
Renderer.render_collection(posts)
posts =
Enum.zip(posts, rendered)
2019-10-09 01:40:26 +02:00
posts =
%Scrivener.Page{
entries: posts,
page_number: page,
page_size: 25,
total_entries: topic.post_count,
total_pages: div(topic.post_count + 25 - 1, 25)
}
2019-10-06 23:31:48 +02:00
2019-11-17 19:05:50 +01:00
watching =
Topics.subscribed?(topic, conn.assigns.current_user)
2019-11-18 04:31:28 +01:00
changeset =
%Post{}
|> Posts.change_post()
render(conn, "show.html", posts: posts, changeset: changeset, watching: watching)
2019-10-06 23:31:48 +02:00
end
end