main.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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-count")
  22. async def user_count(sid):
  23. print("user-count", sid)
  24. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  25. @sio.event
  26. async def disconnect(sid):
  27. if sid in USER_POOL:
  28. disconnected_user = USER_POOL.pop(sid)
  29. print(f"user {disconnected_user} disconnected with session ID {sid}")
  30. await sio.emit("user-count", {"count": len(USER_POOL)})
  31. else:
  32. print(f"Unknown session ID {sid} disconnected")