main.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import socketio
  2. from apps.webui.models.users import Users
  3. from utils.utils import decode_token
  4. sio = socketio.AsyncServer(cors_allowed_origins=[], async_mode="asgi")
  5. app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io")
  6. # Dictionary to maintain the user pool
  7. USER_POOL = {}
  8. @sio.event
  9. async def connect(sid, environ, auth):
  10. print("connect ", sid)
  11. user = None
  12. if auth and "token" in auth:
  13. data = decode_token(auth["token"])
  14. if data is not None and "id" in data:
  15. user = Users.get_user_by_id(data["id"])
  16. if user:
  17. USER_POOL[sid] = user.id
  18. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  19. print(len(set(USER_POOL)))
  20. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  21. @sio.on("user-join")
  22. async def user_join(sid, data):
  23. print("user-join", sid, data)
  24. auth = data["auth"] if "auth" in data else None
  25. if auth and "token" in auth:
  26. data = decode_token(auth["token"])
  27. if data is not None and "id" in data:
  28. user = Users.get_user_by_id(data["id"])
  29. if user:
  30. USER_POOL[sid] = user.id
  31. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  32. print(len(set(USER_POOL)))
  33. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  34. @sio.on("user-count")
  35. async def user_count(sid):
  36. print("user-count", sid)
  37. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  38. @sio.event
  39. async def disconnect(sid):
  40. if sid in USER_POOL:
  41. disconnected_user = USER_POOL.pop(sid)
  42. print(f"user {disconnected_user} disconnected with session ID {sid}")
  43. await sio.emit("user-count", {"count": len(USER_POOL)})
  44. else:
  45. print(f"Unknown session ID {sid} disconnected")