Hi, I’m struggling with case of tracking online users. I went through LiveView book where topic was covered but from other perspective than I need (or I just do not understand yet this). In book it’s written how to track users being on specific page (here: product show page) and only on this page.
I’m creating learning project with admin panel where I put List of all users and one column I just want to leave to Green/Red circle showing if specific user is online or offline.
I found out that Presence/PubSub is really good handling similar cases, but almost all of posts/videos are about tracking users watching specific page what doesnt please me. I didnt find anything about tracking users right after being logged in.
If its important auth system I use is built in phx.gen.auth so It works with conn.
I’m thinking if its possible to use user_socket.ex for it. There is automatically created function:
@impl true
def connect(_params, socket, _connect_info) do
{:ok, socket}
end
I tried put in params session token and then pass it into Presence.track, but while debugging it seems nothing happens.
Another way I was thinking was putting Presence.track in every mount function if session token is present and then publish it and after that broadcast list of active users in admin panel. I tried to avoid putting it in every function and use it once on > connect but if there is not another way I will do it.
Example:
@topic "users_online"
@impl true
def mount(_params, %{"user_token" => user_token}, socket) do
user = Accounts.get_user_by_session_token(user_token)
Presence.track(socket, @topic, user.id, %{online_at: inspect(System.system_time(:second))})
{:ok,
socket
|> assign(:current_user, user)
|> assign(:products, Catalog.list_available_products())
|> assign(:brands, Catalog.list_brands())
|> assign(:categories, Catalog.list_categories())}
end
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:products, Catalog.list_available_products())
|> assign(:brands, Catalog.list_brands())
|> assign(:categories, Catalog.list_categories())
}
end