Last active
August 19, 2019 07:45
-
-
Save sreecodeslayer/b8565c7ff04ef6b1b93807fbe5eec317 to your computer and use it in GitHub Desktop.
Agent - Phoenix Presence - WebSocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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