open-webui/backend/apps/socket/main.py

69 lines
1.8 KiB
Python
Raw Normal View History

2024-06-04 06:39:52 +00:00
import socketio
from apps.webui.models.users import Users
from utils.utils import decode_token
sio = socketio.AsyncServer(cors_allowed_origins=[], async_mode="asgi")
app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io")
# Dictionary to maintain the user pool
2024-06-04 08:10:31 +00:00
2024-06-04 06:39:52 +00:00
USER_POOL = {}
@sio.event
async def connect(sid, environ, auth):
print("connect ", sid)
user = None
2024-06-04 07:45:56 +00:00
if auth and "token" in auth:
data = decode_token(auth["token"])
if data is not None and "id" in data:
user = Users.get_user_by_id(data["id"])
if user:
2024-06-04 08:10:31 +00:00
USER_POOL[sid] = user.id
2024-06-04 07:45:56 +00:00
print(f"user {user.name}({user.id}) connected with session ID {sid}")
2024-06-04 06:39:52 +00:00
2024-06-04 08:10:31 +00:00
print(len(set(USER_POOL)))
await sio.emit("user-count", {"count": len(set(USER_POOL))})
2024-06-04 16:52:27 +00:00
@sio.on("user-join")
async def user_join(sid, data):
print("user-join", sid, data)
auth = data["auth"] if "auth" in data else None
if auth and "token" in auth:
data = decode_token(auth["token"])
if data is not None and "id" in data:
user = Users.get_user_by_id(data["id"])
if user:
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))})
2024-06-04 08:10:31 +00:00
@sio.on("user-count")
async def user_count(sid):
print("user-count", sid)
await sio.emit("user-count", {"count": len(set(USER_POOL))})
2024-06-04 06:39:52 +00:00
@sio.event
2024-06-04 08:10:31 +00:00
async def disconnect(sid):
2024-06-04 06:39:52 +00:00
if sid in USER_POOL:
disconnected_user = USER_POOL.pop(sid)
print(f"user {disconnected_user} disconnected with session ID {sid}")
2024-06-04 08:10:31 +00:00
await sio.emit("user-count", {"count": len(USER_POOL)})
2024-06-04 06:39:52 +00:00
else:
print(f"Unknown session ID {sid} disconnected")