elie
May 8, 2017, 9:54pm
1
I have code like this in my app:
{:ok, _} = Presence.track(socket, socket.assigns.user_id, %{
online_at: inspect(System.system_time(:milli_seconds))
})
Presence.list(socket) |> IO.inspect
I’d like yo use the info from Presence.list in another module in the app. How do I go about doing this?
And will online_at be the time the user was last online?
Thanks
You can use it from anywhere else just fine. Presence.list/1 accepts a topic. It also has an override that grabs a topic out of a socket then just calls itself again as seen at:
def init(_opts) do
{:ok, %{}} # user-land state
end
def handle_metas(topic, %{joins: joins, leaves: leaves}, presences, state) do
# fetch existing presence information for the joined users and broadcast the
# event to all subscribers
for {user_id, presence} <- joins do
user_data = %{user: presence.user, metas: Map.fetch!(presences, user_id)}
msg = {MyApp.PresenceClient, {:join, user_data}}
Phoenix.PubSub.local_broadcast(MyApp.PubSub, topic, msg)
end
# fetch existing presence information for the left users and broadcast the
# event to all subscribers
for {user_id, presence} <- leaves do
metas =
case Map.fetch(presences, user_id) do
{:ok, presence_metas} -> presence_metas
:error -> []
But you can pass it the topic directly from anywhere.
You’ll have a set of those online_at’s for each one being tracked and they will each have a time based on when that code was executed (I.E. the tracking started).
elie
May 9, 2017, 3:43pm
3
So to get the latest time a user was online I’d have to do track on every action the user makes?
But if I just want to know if the user was online I can just if the user is in the list?
Well if they are still in the list at all then they ‘are’ still active.
If they are not in the presence list then they are gone
If you want to store when they were ‘last’ active instead of when they became active then store that on disconnect, like in a database.