AdminChannelPresenceNow that we have the ability to send messages to our backend, we need to give our administrator the ability to respond to these messages. We're going to accomplish this by listing all of our active chats in the sidebar on the left within our phoenix-chat-frontend app.
This sidebar will connect to a new channel called admin, which will have the topic active_users, which we will use to keep track of the presence of all active sockets.
Presence is an awesome feature in Phoenix. It gives you the ability to easily discover which users are currently connected to a particular socket. For example, if you wanted to list all users that are currently active in a chatroom, you could use Presence to easily list them all rather than manipulating a list of users when people join or leave the chatroom. In other frameworks, this is a difficult problem to solve, but in Phoenix, we get it for free.
Make sure you are running at least Phoenix 1.2.0 {:phoenix, "~> 1.2.0"} within your mix.exs file. If you are not, you will get a compilation error.
Then create a Presence module in lib/phoenix_chat/presence.ex.
$ touch lib/phoenix_chat/presence.exdefmodule PhoenixChat.Presence do use Phoenix.Presence, otp_app: :phoenix_chat, pubsub_server: PhoenixChat.PubSubendAnd finally add Presence to your supervision tree within lib/phoenix_chat.ex:
... def start(_type, _args) do import Supervisor.Spec children = [ # Start the endpoint when the application starts supervisor(PhoenixChat.Endpoint, []), # Start the Ecto repository supervisor(PhoenixChat.Repo, []), supervisor(PhoenixChat.Presence, []) ] ... endPresence is now set up and ready for action.
The first thing we need is the AdminChannel, which we will use to give the administrator access to the list of active users. An explanation of each function is below the code block.
$ touch web/channels/admin_channel.exdefmodule PhoenixChat.AdminChannel do @moduledoc """ The channel used to give the administrator access to all users. """ use PhoenixChat.Web, :channel require Logger alias PhoenixChat.{Presence} @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) {:ok, socket} end) end @doc """ This handles the `:after_join` event and tracks the presence of the socket that has subscribed to the `admin:active_users` topic. """ def handle_info(:after_join, socket) do push socket, "presence_state", Presence.list(socket) Logger.debug "Presence for socket: #{inspect socket}" id = socket.assigns.user_id || socket.assigns.uuid {:ok, _} = Presence.track(socket, id, %{ online_at: inspect(System.system_time(:seconds)) }) {:noreply, socket} endendOur join/3 function should look familiar, as it's mostly the same as our join/3 function in our room channel. The difference here is that we've included a new function: send(self, :after_join).
This send/2 function (docs) sends a message to a process, in our case back to the AdminChannel (self). We want this to happen when a user joins for the first time. It calls the send/2 function with an arbitrary atom used for pattern matching. Since we want to run an action after user joins for the first time, we'll call our message :after_join.
Then we use the handle_info/2 function (docs) to pattern match against messages sent by send/2. If the message matches the pattern :after_join, we run the handle_info function above. This function is a little bit complicated, so we'll go over it line-by-line.
The first line is push socket, "presence_state", Presence.list(socket), which triggers a presence_state event in the client. presence_state is an arbitrary name that we are giving this event and we will use it later when we connect this to our phoenix-chat-frontend app.
The next line simply logs the socket for debugging purposes.
The third line sets id to either the user_id, if the user is an admin (and therefore has a user_id in the database), or sets it to the uuid of the anonymous user (which we are not storing in the database).
Then we use pattern matching to make sure that Presence.track is working properly. If the response is :ok, we tell Presence to track (docs) the socket, using the id as the identifier and a map that contains the online_at metadata letting Presence know when the user joined the socket.
Otherwise, we send :noreply and return the socket unchanged.
Let's also add this channel to our UserSocket.
... ## Channels channel "room:*", PhoenixChat.RoomChannel channel "admin:*", PhoenixChat.AdminChannel ...And that's all we need to do to set up Presence. The next step is to handle incoming messages and persist them to the database.