{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/use-presence-to-list-active-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\": \"Use Presence to List Active Users\",\n  \"order\": 27,\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, \"Use Presence to List Active Users\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Creating an \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"AdminChannel\")), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Using \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"Presence\"))), mdx(\"p\", null, \"Now 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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat-frontend\"), \" app.\"), mdx(\"p\", null, \"This sidebar will connect to a new channel called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"admin\"), \", which will have the topic \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"active_users\"), \", which we will use to keep track of the presence of all active sockets.\"), mdx(\"h2\", null, \"Basics of Phoenix Presence\"), mdx(\"p\", null, mdx(\"a\", {\n    \"href\": \"https://dockyard.com/blog/2016/03/25/what-makes-phoenix-presence-special-sneak-peek\",\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, mdx(\"strong\", {\n    \"parentName\": \"p\"\n  }, \"Make sure you are running at least Phoenix 1.2.0 \", mdx(\"inlineCode\", {\n    \"parentName\": \"strong\"\n  }, \"{:phoenix, \\\"~> 1.2.0\\\"}\"), \" within your \", mdx(\"inlineCode\", {\n    \"parentName\": \"strong\"\n  }, \"mix.exs\"), \" file. If you are not, you will get a compilation error.\")), mdx(\"p\", null, \"Then create a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Presence\"), \" module in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lib/phoenix_chat/presence.ex\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch lib/phoenix_chat/presence.ex\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Presence do\\n  use Phoenix.Presence, otp_app: :phoenix_chat,\\n                        pubsub_server: PhoenixChat.PubSub\\nend\\n\")), mdx(\"p\", null, \"And finally add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Presence\"), \" to your supervision tree within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lib/phoenix_chat.ex\"), \":\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n\\n  def start(_type, _args) do\\n    import Supervisor.Spec\\n\\n    children = [\\n      # Start the endpoint when the application starts\\n      supervisor(PhoenixChat.Endpoint, []),\\n      # Start the Ecto repository\\n      supervisor(PhoenixChat.Repo, []),\\n      supervisor(PhoenixChat.Presence, [])\\n    ]\\n\\n    ...\\n  end\\n\")), mdx(\"p\", null, \"Presence is now set up and ready for action.\"), mdx(\"h2\", null, \"Creating the AdminChannel\"), mdx(\"p\", null, \"The first thing we need is the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch web/channels/admin_channel.ex\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  @moduledoc \\\"\\\"\\\"\\n  \\b\\bThe channel used to give the administrator access to all users.\\n  \\\"\\\"\\\"\\n\\n  use PhoenixChat.Web, :channel\\n  require Logger\\n\\n  alias PhoenixChat.{Presence}\\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      {:ok, socket}\\n    end)\\n  end\\n\\n  @doc \\\"\\\"\\\"\\n  \\b\\bThis handles the `:after_join` event and tracks the presence of the socket that has subscribed to the `admin:active_users` topic.\\n  \\\"\\\"\\\"\\n  def handle_info(:after_join, socket) do\\n    push socket, \\\"presence_state\\\", Presence.list(socket)\\n    Logger.debug \\\"Presence for socket: #{inspect socket}\\\"\\n    id = socket.assigns.user_id || socket.assigns.uuid\\n    {:ok, _} = Presence.track(socket, id, %{\\n      online_at: inspect(System.system_time(:seconds))\\n    })\\n    {:noreply, socket}\\n  end\\nend\\n\")), mdx(\"p\", null, \"Our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"join/3\"), \" function should look familiar, as it's mostly the same as our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"join/3\"), \" function in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room\"), \" channel. The difference here is that we've included a new function: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"send(self, :after_join)\"), \".\"), mdx(\"p\", null, \"This \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"send/2\"), \" function \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/docs/master/elixir/Kernel.html#send/2\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" sends a message to a process, in our case back to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AdminChannel\"), \" (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"self\"), \"). We want this to happen when a user joins for the first time. It calls the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":after_join\"), \".\"), mdx(\"p\", null, \"Then we use the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_info/2\"), \" function \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.Channel.html#c:handle_info/2\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" to pattern match against messages sent by \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"send/2\"), \". If the message matches the pattern \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":after_join\"), \", we run the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_info\"), \" function above. This function is a little bit complicated, so we'll go over it line-by-line.\"), mdx(\"p\", null, \"The first line is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"push socket, \\\"presence_state\\\", Presence.list(socket)\"), \", which triggers a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"presence_state\"), \" event in the client. \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"presence_state\"), \" is an arbitrary name that we are giving this event and we will use it later when we connect this to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat-frontend\"), \" app.\"), mdx(\"p\", null, \"The next line simply logs the socket for debugging purposes.\"), mdx(\"p\", null, \"The third line sets \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" to either the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \", if the user is an admin (and therefore has a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" in the database), or sets it to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" of the anonymous user (which we are not storing in the database).\"), mdx(\"p\", null, \"Then we use pattern matching to make sure that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Presence.track\"), \" is working properly. If the response is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":ok\"), \", we tell \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Presence\"), \" to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"track\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.Presence.html#c:track/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" the socket, using the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" as the identifier and a map that contains the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"online_at\"), \" metadata letting \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Presence\"), \" know when the user joined the socket.\"), mdx(\"p\", null, \"Otherwise, we send \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":noreply\"), \" and return the socket unchanged.\"), mdx(\"p\", null, \"Let's also add this channel to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserSocket\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n\\n  ## Channels\\n  channel \\\"room:*\\\", PhoenixChat.RoomChannel\\n  channel \\\"admin:*\\\", PhoenixChat.AdminChannel\\n\\n  ...\\n\")), mdx(\"p\", null, \"And that's all we need to do to set up \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Presence\"), \". The next step is to handle incoming messages and persist them to the database.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Use Presence to List Active Users Creating an  AdminChannel Using  Presence Now that we have the ability to send messages to our backend, we…","frontmatter":{"title":"Use Presence to List Active Users","order":27,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"use-presence-to-list-active-users","prevNode":{"frontmatter":{"title":"Connect React to Channels","active":true,"free":false,"order":26,"tech":["react","phoenix"]},"fields":{"slug":"connect-react-to-channels"}},"nextNode":{"frontmatter":{"title":"Persist Messages to the Database","active":true,"free":false,"order":28,"tech":["phoenix","postgres"]},"fields":{"slug":"persist-messages-to-the-database"}}}},"staticQueryHashes":["1723017916"]}