main.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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] = {
  18. "id": user.id,
  19. "name": user.name,
  20. "email": user.email,
  21. "role": user.role,
  22. }
  23. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  24. @sio.event
  25. def disconnect(sid):
  26. if sid in USER_POOL:
  27. disconnected_user = USER_POOL.pop(sid)
  28. print(f"user {disconnected_user} disconnected with session ID {sid}")
  29. else:
  30. print(f"Unknown session ID {sid} disconnected")
  31. @sio.event
  32. def disconnect(sid):
  33. print("disconnect", sid)