Broadcast Active and Inactive Users

  • Poison.Encoder and \@derive
  • Broadcast lobby_list

Now that we can receive messages, add anonymous users to the database, and keep track of recent users based on the date of the last message they sent, we need to broadcast to our admins every time a new user joins. Our frontend will then be able to listen to this event and handle updates accordingly.

This event will get triggered every time a user joins the admin:active_users topic so it will be up to the frontend to check whether a user is already on the list.

We're also going to do a little bit of refactoring to use the @derive module attribute, which is a convenient way to customize/instruct how Protocols treat our struct (explained in detail later). This is not strictly necessary, but makes for cleaner code.

Reactor Message and RoomChannel

The first thing we're going to do is add @derive to our Message model. @derive (docs) is a module attribute that allows you to customize how the struct is treated when it interacts with a Protocol (in our case, our JSON API). We're going to instruct Poison.Encode to only encode certain fields and ignore the rest.

This will save us from writing a bunch of code for specifying which fields to include in our JSON version of our structs (which is what we're currently doing in our message_payload/1 function).

defmodule PhoenixChat.Message do
use PhoenixChat.Web, :model
alias PhoenixChat.{DateTime, User, AnonymousUser}
@derive {Poison.Encoder, only: ~w(id body timestamp room user_id anonymous_user_id)a}
...
end

So now, we send message data using our API, we're only going to send id, body, timestamp, room, user_id, and anonymous_user_id.

We should also update our AnonymousUser to use @derive as well to send id, name, and avatar.

defmodule PhoenixChat.AnonymousUser do
use PhoenixChat.Web, :model
alias PhoenixChat.Message
@primary_key {:id, :binary_id, autogenerate: false}
@foreign_key_type :binary_id
@derive {Poison.Encoder, only: ~w(id name avatar)a}
...
end

Now that we've defined what data we're sending from within our model, we no longer need a message_payload/1 function to define our message payload. Let's go ahead and delete that from our RoomChannel.

defmodule PhoenixChat.RoomChannel do
use PhoenixChat.Web, :channel
require Logger
alias PhoenixChat.{Message, Repo}
def join("room:" <> room_id, payload, socket) do
authorize(payload, fn ->
messages = room_id
|> Message.latest_room_messages
|> Repo.all
|> Enum.reverse
{:ok, %{messages: messages}, socket}
end)
end
...
end

Then let's pass anonymous_user_id as the uuid instead of the from field and remove the extra code that called our no-longer-existing message_payload/1 function.

defmodule PhoenixChat.RoomChannel do
...
def handle_in("message", payload, socket) do
payload = payload
|> Map.put("user_id", socket.assigns[:user_id])
|> Map.put("anonymous_user_id", socket.assigns[:uuid])
changeset = Message.changeset(%Message{}, payload)
case Repo.insert(changeset) do
{:ok, message} ->
broadcast! socket, "message", message
{:reply, :ok, socket}
{:error, changeset} ->
{:reply, {:error, %{errors: changeset}}, socket}
end
end
end

And now if you refresh your frontend, you should have a functioning app again.

Broadcast lobby_list

This where we use the recently_active_users/0 function we defined earlier to get the 20 most recently active anonymous users. Recall that this works by looking through our Messages, finds the most recent message from each anonymous user, and returns the 20 users that have sent or received messages most recently.

After we make that query, we pass the list of 20 users along with our socket.

defmodule PhoenixChat.AdminChannel do
...
@doc """
The `admin:active_users` topic is how we identify all users currently using the app.
"""
def join("admin:active_users", payload, socket) do
authorize(payload, fn ->
send(self, :after_join)
id = socket.assigns[:uuid] || socket.assigns[:user_id]
lobby_list = AnonymousUser.recently_active_users |> Repo.all
{:ok, %{id: id, lobby_list: lobby_list}, socket}
end)
end
...
end

Next, we need to broadcast these changes to our frontend. The best time to do this is after a new user joins the channel, so we can hook into our :after_join pattern match in handle_info to add the broadcast.

We should also update our ensure_user_saved/1 to return the user after the query so we can pass that user along to our broadcast.

defmodule PhoenixChat.AdminChannel do
...
def handle_info(:after_join, %{assigns: %{uuid: uuid}} = socket) do
user = ensure_user_saved!(uuid)
broadcast! socket, "lobby_list", user
push socket, "presence_state", Presence.list(socket)
Logger.debug "Presence for socket: #{inspect socket}"
{:ok, _} = Presence.track(socket, uuid, %{
online_at: inspect(System.system_time(:seconds))
})
{:noreply, socket}
end
defp ensure_user_saved!(uuid) do
user_exists = Repo.get(AnonymousUser, uuid)
if user_exists do
user_exists
else
changeset = AnonymousUser.changeset(%AnonymousUser{}, %{id: uuid})
Repo.insert!(changeset)
end
end
end

But at the moment, we're going to broadcast these events to everyone who is subscribed to the channel, but we actually only want to send this information to our admins. We're going to do this using intercept/1 (docs), which allows us to hook into outgoing responses and manipulates them. In this case, we want to hook into any broadcast to lobby_list and only broadcast it to administrators (not anonymous users).

When the intercept happens, it passes to the handle_out function, in which we check if the user is an admin (has a user_id). If so, we proceed. Otherwise, we return a {:noreply, socket}.

defmodule PhoenixChat.AdminChannel do
...
intercept ~w(lobby_list)
...
@doc """
Sends the lobby_list only to admins
"""
def handle_out("lobby_list", payload, socket) do
assigns = socket.assigns
if assigns[:user_id] do
push socket, "lobby_list", payload
end
{:noreply, socket}
end
...
end

And that's all we have to change in our admin_channel. We're now broadcasting the latest 20 active users on join and sending an updated list any time a new user joins. Now we should head over to the frontend to implement these changes.

Previous: Persist Anonymous UsersNext: Connect the Frontend to AdminChannel