Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Agent - Phoenix Presence - WebSocket
defmodule MyAppWeb.AgentChannel do
use Phoenix.Channel
alias MyApp.Presence
@doc """
Used by backend agent
"""
def join("agent:" <> _agent_topic, _message, socket) do
send(self(), :after_agent_joined)
{:ok, socket}
end
def handle_info(:after_agent_joined, socket) do
agent = socket.assigns.agent
{:ok, _} = Presence.track(socket, "agent_status:#{agent.id}", %{})
{:noreply, socket}
end
end
defmodule MyApp.Agents do
@moduledoc """
The Agents context.
"""
alias MyApp.Presence
@doc """
Returns true if agent is registered under Phoenix Presence.
"""
def online?(nil), do: false
def online?(agent_id) do
agent = get_agent!(agent_id)
topic = "agent:#{agent.topic}"
case Presence.get_by_key(topic, "agent_status:#{agent.id}") do
[] -> false
%{metas: _metas} ->
# The _metas would contain a list of connections in the channel,
# having a phx reference to each of them, suggesting we have an agent live.
# but the metas as such currently is of no use.
true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.