live_beats/lib/live_beats_web/live/nav.ex

63 lines
1.7 KiB
Elixir
Raw Normal View History

2021-10-29 16:12:23 +00:00
defmodule LiveBeatsWeb.Nav do
import Phoenix.LiveView
2022-01-31 19:27:06 +00:00
alias LiveBeats.{Accounts, MediaLibrary}
2021-11-22 14:57:24 +00:00
alias LiveBeatsWeb.{ProfileLive, SettingsLive}
2021-11-12 15:10:04 +00:00
2021-11-22 15:31:30 +00:00
def on_mount(:default, _params, _session, socket) do
{:cont,
socket
|> assign(active_users: MediaLibrary.list_active_profiles(limit: 20))
2022-01-31 13:21:27 +00:00
|> assign(:region, System.get_env("FLY_REGION") || "iad")
2022-01-28 01:42:36 +00:00
|> attach_hook(:active_tab, :handle_params, &handle_active_tab_params/3)
|> attach_hook(:ping, :handle_event, &handle_event/3)}
end
2021-11-24 03:06:48 +00:00
defp handle_active_tab_params(params, _url, socket) do
2021-11-19 19:50:36 +00:00
active_tab =
2021-11-22 15:31:30 +00:00
case {socket.view, socket.assigns.live_action} do
2021-11-24 03:06:48 +00:00
{ProfileLive, _} ->
2021-11-30 15:03:08 +00:00
if params["profile_username"] == current_user_profile_username(socket) do
2021-11-24 03:06:48 +00:00
:profile
end
{SettingsLive, _} ->
:settings
{_, _} ->
nil
2021-11-22 14:57:24 +00:00
end
2021-11-19 19:50:36 +00:00
{:cont, assign(socket, active_tab: active_tab)}
2021-10-29 16:12:23 +00:00
end
2021-11-24 03:06:48 +00:00
2022-01-29 01:40:48 +00:00
defp handle_event("ping", %{"rtt" => rtt}, socket) do
2022-01-31 19:27:06 +00:00
{:halt,
socket
|> rate_limited_ping_broadcast(socket.assigns.current_user, rtt)
|> push_event("pong", %{})}
end
2022-01-29 01:40:48 +00:00
2022-02-01 14:33:04 +00:00
defp handle_event(_, _, socket), do: {:cont, socket}
2022-01-31 19:27:06 +00:00
defp rate_limited_ping_broadcast(socket, %Accounts.User{} = user, rtt) when is_integer(rtt) do
now = System.system_time(:millisecond)
last_ping_at = socket.assigns[:last_ping_at]
2022-01-29 01:40:48 +00:00
2022-01-31 19:27:06 +00:00
if is_nil(last_ping_at) || now - last_ping_at > 1000 do
MediaLibrary.broadcast_ping(user, rtt, socket.assigns.region)
assign(socket, :last_ping_at, now)
else
socket
end
2022-01-28 01:42:36 +00:00
end
2022-01-31 19:27:06 +00:00
defp rate_limited_ping_broadcast(socket, _user, _rtt), do: socket
2021-11-30 15:03:08 +00:00
defp current_user_profile_username(socket) do
2021-11-24 03:06:48 +00:00
if user = socket.assigns.current_user do
user.username
end
end
2021-10-29 16:12:23 +00:00
end