Skip to content

Instantly share code, notes, and snippets.

@sreecodeslayer
Last active August 19, 2019 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sreecodeslayer/b8565c7ff04ef6b1b93807fbe5eec317 to your computer and use it in GitHub Desktop.
Save sreecodeslayer/b8565c7ff04ef6b1b93807fbe5eec317 to your computer and use it in GitHub Desktop.
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