2021-12-09 05:33:29 +00:00
|
|
|
defmodule LiveBeats.PresenceClient do
|
|
|
|
@behaviour Phoenix.Presence.Client
|
|
|
|
|
2021-12-09 07:29:00 +00:00
|
|
|
@presence LiveBeatsWeb.Presence
|
|
|
|
@pubsub LiveBeats.PubSub
|
2021-12-09 05:33:29 +00:00
|
|
|
|
|
|
|
def list(topic) do
|
|
|
|
@presence.list(topic)
|
|
|
|
end
|
|
|
|
|
2021-12-16 18:30:21 +00:00
|
|
|
@impl Phoenix.Presence.Client
|
2021-12-09 05:33:29 +00:00
|
|
|
def init(_opts) do
|
|
|
|
# user-land state
|
|
|
|
{:ok, %{}}
|
|
|
|
end
|
|
|
|
|
2021-12-16 18:30:21 +00:00
|
|
|
@impl Phoenix.Presence.Client
|
2022-01-11 19:57:06 +00:00
|
|
|
def handle_join(topic, _key, presence, state) do
|
2021-12-09 07:29:00 +00:00
|
|
|
active_users_topic =
|
|
|
|
topic
|
|
|
|
|> profile_identifier()
|
|
|
|
|> active_users_topic()
|
|
|
|
|
2022-01-11 19:57:06 +00:00
|
|
|
Phoenix.PubSub.local_broadcast(
|
|
|
|
@pubsub,
|
|
|
|
active_users_topic,
|
|
|
|
{__MODULE__, %{user_joined: presence}}
|
|
|
|
)
|
2021-12-09 07:29:00 +00:00
|
|
|
|
2021-12-09 05:33:29 +00:00
|
|
|
{:ok, state}
|
|
|
|
end
|
|
|
|
|
2021-12-16 18:30:21 +00:00
|
|
|
@impl Phoenix.Presence.Client
|
2022-01-11 19:57:06 +00:00
|
|
|
def handle_leave(topic, _key, presence, state) do
|
2021-12-09 07:29:00 +00:00
|
|
|
active_users_topic =
|
|
|
|
topic
|
|
|
|
|> profile_identifier()
|
|
|
|
|> active_users_topic()
|
|
|
|
|
2022-01-11 19:57:06 +00:00
|
|
|
Phoenix.PubSub.local_broadcast(
|
|
|
|
@pubsub,
|
|
|
|
active_users_topic,
|
|
|
|
{__MODULE__, %{user_left: presence}}
|
|
|
|
)
|
|
|
|
|
2021-12-09 05:33:29 +00:00
|
|
|
{:ok, state}
|
|
|
|
end
|
2021-12-09 07:29:00 +00:00
|
|
|
|
|
|
|
defp active_users_topic(user_id) do
|
|
|
|
"active_users:#{user_id}"
|
|
|
|
end
|
|
|
|
|
|
|
|
defp profile_identifier(topic) do
|
|
|
|
"active_profile:" <> identifier = topic
|
|
|
|
identifier
|
|
|
|
end
|
2021-12-09 05:33:29 +00:00
|
|
|
end
|