summaryrefslogtreecommitdiff
path: root/lib/aggiedit_web/channels/post_channel.ex
blob: 2b1c9b5aca677d3c88b76cc71019936cee15cd37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
defmodule AggieditWeb.PostChannel do
  use AggieditWeb, :channel

  alias Aggiedit.Roles
  alias Aggiedit.Repo
  alias Aggiedit.Rooms

  @impl true
  def join("post:" <> post_id, _payload, socket) do
    post = Rooms.get_post!(post_id)
    if Roles.guard?(socket.assigns.current_user, :show, post) do
      send(self(), :after_join)
      {:ok, assign(socket, %{:post => post})}
    else
      {:error, "You do not have permission to view this post."}
    end
  end

  @impl true
  def handle_info(:after_join, socket) do
    comments = socket.assigns.post
    |> Repo.preload(comments: [:user])
    |> Map.get(:comments)
    |> Enum.map(fn c -> Aggiedit.Post.Comment.serialize(c) end)
    push(socket, "initial-comments", %{:comments => comments})
    
    broadcast!(socket, "join", %{user: socket.assigns.current_user.username})
    {:noreply, socket}
  end

  @impl true
  def handle_in("send", %{"body" => comment}, socket) do
    {:ok, comment} = Rooms.comment_post(socket.assigns.post, socket.assigns.current_user, comment)
    broadcast!(socket, "shout", Aggiedit.Post.Comment.serialize(comment))
    {:reply, :ok, socket}
  end
end