{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/broadcast-active-and-inactive-users","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Broadcast Active and Inactive Users\",\n  \"order\": 31,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Broadcast Active and Inactive Users\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Poison.Encoder and \\\\@derive\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Broadcast lobby_list\")), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"This event will get triggered every time a user joins the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"admin:active_users\"), \" topic so it will be up to the frontend to check whether a user is already on the\\nlist.\"), mdx(\"p\", null, \"We're also going to do a little bit of refactoring to use the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@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.\"), mdx(\"h2\", null, \"Reactor Message and RoomChannel\"), mdx(\"p\", null, \"The first thing we're going to do is add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@derive\"), \" to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Message\"), \" model. \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@derive\"), \" \", mdx(\"a\", {\n    \"href\": \"https://github.com/devinus/poison#encoding-only-some-attributes\",\n    \"parentName\": \"p\"\n  }, \"(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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Poison.Encode\"), \" to only encode certain fields and ignore the rest.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message_payload/1\"), \" function).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Message do\\n  use PhoenixChat.Web, :model\\n\\n  alias PhoenixChat.{DateTime, User, AnonymousUser}\\n\\n  @derive {Poison.Encoder, only: ~w(id body timestamp room user_id anonymous_user_id)a}\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"So now, we send message data using our API, we're only going to send \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"body\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"timestamp\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"anonymous_user_id\"), \".\"), mdx(\"p\", null, \"We should also update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AnonymousUser\"), \" to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@derive\"), \" as well to send \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"name\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"avatar\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AnonymousUser do\\n  use PhoenixChat.Web, :model\\n\\n  alias PhoenixChat.Message\\n\\n  @primary_key {:id, :binary_id, autogenerate: false}\\n  @foreign_key_type :binary_id\\n  @derive {Poison.Encoder, only: ~w(id name avatar)a}\\n\\n  ...\\n\\nend\\n\")), mdx(\"p\", null, \"Now that we've defined what data we're sending from within our model, we no longer need a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message_payload/1\"), \" function to define our message payload. Let's go ahead and delete that from our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"RoomChannel\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.RoomChannel do\\n  use PhoenixChat.Web, :channel\\n  require Logger\\n\\n  alias PhoenixChat.{Message, Repo}\\n\\n  def join(\\\"room:\\\" <> room_id, payload, socket) do\\n    authorize(payload, fn ->\\n      messages = room_id\\n        |> Message.latest_room_messages\\n        |> Repo.all\\n        |> Enum.reverse\\n      {:ok, %{messages: messages}, socket}\\n    end)\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Then let's pass \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"anonymous_user_id\"), \" as the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" instead of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from\"), \" field and remove the extra code that called our no-longer-existing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message_payload/1\"), \" function.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.RoomChannel do\\n  ...\\n\\n  def handle_in(\\\"message\\\", payload, socket) do\\n    payload = payload\\n      |> Map.put(\\\"user_id\\\", socket.assigns[:user_id])\\n      |> Map.put(\\\"anonymous_user_id\\\", socket.assigns[:uuid])\\n    changeset = Message.changeset(%Message{}, payload)\\n\\n    case Repo.insert(changeset) do\\n      {:ok, message} ->\\n        broadcast! socket, \\\"message\\\", message\\n        {:reply, :ok, socket}\\n      {:error, changeset} ->\\n        {:reply, {:error, %{errors: changeset}}, socket}\\n    end\\n  end\\nend\\n\")), mdx(\"p\", null, \"And now if you refresh your frontend, you should have a functioning app again.\"), mdx(\"h2\", null, \"Broadcast lobby_list\"), mdx(\"p\", null, \"This where we use the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Messages\"), \", finds the most recent message from each anonymous user, and returns the 20 users that have sent or received messages most recently.\"), mdx(\"p\", null, \"After we make that query, we pass the list of 20 users along with our socket.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  ...\\n\\n  @doc \\\"\\\"\\\"\\n  The `admin:active_users` topic is how we identify all users currently using the app.\\n  \\\"\\\"\\\"\\n  def join(\\\"admin:active_users\\\", payload, socket) do\\n    authorize(payload, fn ->\\n      send(self, :after_join)\\n      id = socket.assigns[:uuid] || socket.assigns[:user_id]\\n      lobby_list = AnonymousUser.recently_active_users |> Repo.all\\n      {:ok, %{id: id, lobby_list: lobby_list}, socket}\\n    end)\\n  end\\n\\n ...\\n\\nend\\n\")), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":after_join\"), \" pattern match in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_info\"), \" to add the broadcast.\"), mdx(\"p\", null, \"We should also update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ensure_user_saved/1\"), \" to return the user after the query so we can pass that user along to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"broadcast\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  ...\\n\\n  def handle_info(:after_join, %{assigns: %{uuid: uuid}} = socket) do\\n    user = ensure_user_saved!(uuid)\\n\\n    broadcast! socket, \\\"lobby_list\\\", user\\n\\n    push socket, \\\"presence_state\\\", Presence.list(socket)\\n    Logger.debug \\\"Presence for socket: #{inspect socket}\\\"\\n    {:ok, _} = Presence.track(socket, uuid, %{\\n      online_at: inspect(System.system_time(:seconds))\\n    })\\n    {:noreply, socket}\\n  end\\n\\n  defp ensure_user_saved!(uuid) do\\n    user_exists = Repo.get(AnonymousUser, uuid)\\n    if user_exists do\\n      user_exists\\n    else\\n      changeset = AnonymousUser.changeset(%AnonymousUser{}, %{id: uuid})\\n      Repo.insert!(changeset)\\n    end\\n  end\\nend\\n\")), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"intercept/1\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.Channel.html#intercept/1\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \", which allows us to hook into outgoing responses and manipulates them. In this case, we want to hook into any broadcast to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lobby_list\"), \" and only broadcast it to administrators (not anonymous users).\"), mdx(\"p\", null, \"When the intercept happens, it passes to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_out\"), \" function, in which we check if the user is an admin (has a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \"). If so, we proceed. Otherwise, we return a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{:noreply, socket}\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  ...\\n\\n  intercept ~w(lobby_list)\\n\\n  ...\\n\\n  @doc \\\"\\\"\\\"\\n  Sends the lobby_list only to admins\\n  \\\"\\\"\\\"\\n  def handle_out(\\\"lobby_list\\\", payload, socket) do\\n    assigns = socket.assigns\\n    if assigns[:user_id] do\\n      push socket, \\\"lobby_list\\\", payload\\n    end\\n    {:noreply, socket}\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"And that's all we have to change in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Broadcast Active and Inactive Users Poison.Encoder and \\@derive Broadcast lobby_list Now that we can receive messages, add anonymous users…","frontmatter":{"title":"Broadcast Active and Inactive Users","order":31,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"broadcast-active-and-inactive-users","prevNode":{"frontmatter":{"title":"Persist Anonymous Users","active":true,"free":false,"order":30,"tech":["phoenix"]},"fields":{"slug":"persist-anonymous-users"}},"nextNode":{"frontmatter":{"title":"Connect the Frontend to AdminChannel","active":true,"free":false,"order":32,"tech":["react","phoenix"]},"fields":{"slug":"connect-the-frontend-to-adminchannel"}}}},"staticQueryHashes":["1723017916"]}