From bbfa54a6b9d097342ea9458ef10db90697c71dfd Mon Sep 17 00:00:00 2001 From: "Timothy J. Baek" Date: Tue, 4 Jun 2024 01:10:31 -0700 Subject: [PATCH] feat: active user count --- backend/apps/socket/main.py | 27 +++++++++-------- .../components/layout/Sidebar/UserMenu.svelte | 30 +++++++++++++++++-- src/lib/stores/index.ts | 1 + src/routes/+layout.svelte | 9 ++++-- 4 files changed, 50 insertions(+), 17 deletions(-) diff --git a/backend/apps/socket/main.py b/backend/apps/socket/main.py index 3fbfb8ae8..a8fc50efa 100644 --- a/backend/apps/socket/main.py +++ b/backend/apps/socket/main.py @@ -7,6 +7,8 @@ sio = socketio.AsyncServer(cors_allowed_origins=[], async_mode="asgi") app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io") # Dictionary to maintain the user pool + + USER_POOL = {} @@ -22,24 +24,25 @@ async def connect(sid, environ, auth): user = Users.get_user_by_id(data["id"]) if user: - USER_POOL[sid] = { - "id": user.id, - "name": user.name, - "email": user.email, - "role": user.role, - } + USER_POOL[sid] = user.id print(f"user {user.name}({user.id}) connected with session ID {sid}") + print(len(set(USER_POOL))) + await sio.emit("user-count", {"count": len(set(USER_POOL))}) + + +@sio.on("user-count") +async def user_count(sid): + print("user-count", sid) + await sio.emit("user-count", {"count": len(set(USER_POOL))}) + @sio.event -def disconnect(sid): +async def disconnect(sid): if sid in USER_POOL: disconnected_user = USER_POOL.pop(sid) print(f"user {disconnected_user} disconnected with session ID {sid}") + + await sio.emit("user-count", {"count": len(USER_POOL)}) else: print(f"Unknown session ID {sid} disconnected") - - -@sio.event -def disconnect(sid): - print("disconnect", sid) diff --git a/src/lib/components/layout/Sidebar/UserMenu.svelte b/src/lib/components/layout/Sidebar/UserMenu.svelte index 7d571555d..1525727c0 100644 --- a/src/lib/components/layout/Sidebar/UserMenu.svelte +++ b/src/lib/components/layout/Sidebar/UserMenu.svelte @@ -1,11 +1,11 @@