configure presence for tracking the users listening a playlist

This commit is contained in:
Berenice Medel 2021-11-30 12:06:35 -06:00 committed by Chris McCord
parent a0f3b76f61
commit 216916817b
3 changed files with 29 additions and 2 deletions

View file

@ -17,6 +17,8 @@ defmodule LiveBeats.Application do
LiveBeatsWeb.Telemetry,
# Start the PubSub system
{Phoenix.PubSub, name: LiveBeats.PubSub},
#start presence
LiveBeatsWeb.Presence,
# Start the Endpoint (http/https)
LiveBeatsWeb.Endpoint
# Start a worker by calling: LiveBeats.Worker.start_link(arg)

View file

@ -258,6 +258,8 @@ defmodule LiveBeatsWeb.PlayerLive do
def handle_info({MediaLibrary, _}, socket), do: {:noreply, socket}
def handle_info(%{event: "presence_diff"}, socket), do: {:noreply, socket}
defp play_song(socket, %Song{} = song, elapsed) do
socket
|> push_play(song, elapsed)

View file

@ -87,6 +87,12 @@ defmodule LiveBeatsWeb.ProfileLive do
if connected?(socket) do
MediaLibrary.subscribe_to_profile(profile)
Accounts.subscribe(current_user.id)
LiveBeatsWeb.Presence.track(
self(),
topic(profile.user_id),
current_user.id,
current_user
)
end
active_song_id =
@ -169,6 +175,14 @@ defmodule LiveBeatsWeb.ProfileLive do
def handle_info({Accounts, _}, socket), do: {:noreply, socket}
def handle_info(
%{event: "presence_diff", payload: %{joins: _joins, leaves: _leaves}},
%{assigns: %{presences: _users}} = socket
) do
{:noreply, assign_presences(socket)}
end
defp stop_song(socket, song_id) do
SongRowComponent.send_status(song_id, :stopped)
@ -242,8 +256,15 @@ defmodule LiveBeatsWeb.ProfileLive do
end
defp assign_presences(socket) do
users = Accounts.lists_users_by_active_profile(socket.assigns.profile.user_id, limit: 10)
assign(socket, presences: users)
presences = socket.assigns.profile.user_id
|> topic()
|> Presence.list()
|> Enum.map(fn {_user_id, user_data} ->
user_data[:metas]
|> List.first()
end)
assign(socket, presences: presences)
end
defp url_text(nil), do: ""
@ -252,4 +273,6 @@ defmodule LiveBeatsWeb.ProfileLive do
uri = URI.parse(url_str)
uri.host <> uri.path
end
defp topic(user_id) when is_integer(user_id), do: "profile:#{user_id}"
end