Spaces:
Build error
Build error
File size: 5,257 Bytes
b7a7f32 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
import enum
import json
from datetime import datetime
from typing import Dict, List, Optional
from fastapi import WebSocket, websockets
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from core.db.redis_session import redis_chat_client
from core.security import get_uid_hash
from models import User
class ChatMessageTypes(enum.Enum):
MESSAGE_HISTORY: int = 1
PUBLIC_MESSAGE: int = 2
ANON_MESSAGE: int = 3
USER_JOINED: int = 4
USER_LEFT: int = 5
ACTIVE_USER_LIST: int = 6
class Message(BaseModel):
msg_type: int
data: Optional[str]
user: Optional[str]
time: datetime
class WebSocketManager:
def __init__(self):
self.connections: Dict = {}
async def update(self, data, key):
msg = await redis_chat_client.client.get(key)
if msg:
msg = json.loads(msg)
else:
msg = []
msg.append(data)
await redis_chat_client.client.set(
key, json.dumps(msg, separators=(",", ":")), expire=60 * 60 * 1000
)
async def send_history(self, websocket: WebSocket, class_session_id: int):
chat_history = await redis_chat_client.client.get(
f"chat_class_sess_{class_session_id}", encoding="UTF-8"
)
msg_history_instance = Message(
msg_type=ChatMessageTypes.MESSAGE_HISTORY.value,
data=chat_history,
time=datetime.utcnow(),
)
await websocket.send_json(
jsonable_encoder(msg_history_instance.dict(exclude_none=True))
)
async def connect(self, websocket: WebSocket, user_id: int, class_session_id: int):
await websocket.accept()
try:
self.connections[class_session_id].append(websocket)
except:
self.connections.update({class_session_id: [websocket]})
msg_instance = Message(
msg_type=ChatMessageTypes.USER_JOINED.value,
time=datetime.utcnow(),
user=user_id,
)
# self.send_history(websocket=websocket, class_session_id=class_session_id)
await self.broadcast(
msg_instance.dict(exclude_none=True), user_id, class_session_id, save=False
)
pre_status = await redis_chat_client.client.get(
f"active_status_{class_session_id}", encoding="UTF-8"
)
active_user_instance = Message(
msg_type=ChatMessageTypes.ACTIVE_USER_LIST.value,
data=pre_status,
time=datetime.utcnow(),
)
# print(active_user_instance.dict(exclude_none=True))
await websocket.send_json(
jsonable_encoder(active_user_instance.dict(exclude_none=True))
)
if not pre_status:
pre_status_obj = []
else:
pre_status_obj = json.loads(pre_status)
pre_status_obj.append(user_id)
pre_status_obj = list(set(pre_status_obj))
await redis_chat_client.client.set(
f"active_status_{class_session_id}",
json.dumps(pre_status_obj, separators=(",", ":")),
)
await redis_chat_client.client.expire(
f"active_status_{class_session_id}",
60 * 60 * 1000,
)
async def disconnect(
self, websocket: WebSocket, user_id: int, class_session_id: int
):
self.connections[class_session_id].remove(websocket)
msg_instance = Message(
msg_type=ChatMessageTypes.USER_LEFT.value,
time=datetime.utcnow(),
user=user_id,
)
await self.broadcast(msg_instance, user_id, class_session_id, save=False)
pre_status = json.loads(
await redis_chat_client.client.get(f"active_status_{class_session_id}")
)
pre_status.remove(user_id)
await redis_chat_client.client.set(
f"active_status_{class_session_id}",
json.dumps(pre_status, separators=(",", ":")),
)
await redis_chat_client.client.expire(
f"active_status_{class_session_id}",
60 * 60 * 1000,
)
async def broadcast(
self, data: any, user_id: int, class_session_id: int, save: bool = True
):
encoded_data = jsonable_encoder(data)
for connection in self.connections.get(class_session_id):
try:
await connection.send_json(encoded_data)
except Exception as e:
pass
if save:
await self.update(encoded_data, f"chat_class_sess_{class_session_id}")
async def message(
self,
websocket: WebSocket,
message: str,
user_id: int,
class_session_id: int,
anon: bool = False,
):
msg_type = ChatMessageTypes.PUBLIC_MESSAGE.value
user = user_id
if anon:
msg_type = ChatMessageTypes.ANON_MESSAGE.value
user = get_uid_hash(user_id)
msg_instance = Message(
msg_type=msg_type,
data=message,
user=user,
time=datetime.utcnow(),
)
await self.broadcast(
msg_instance.dict(exclude_none=True), user_id, class_session_id
)
ws = WebSocketManager()
|