forked from ArchismitaS/Study-Session-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
81 lines (63 loc) · 2.23 KB
/
main.py
File metadata and controls
81 lines (63 loc) · 2.23 KB
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
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends
from jose import jwt, JWTError
from typing import Dict, List
import uuid
app = FastAPI()
SECRET_KEY = "secret"
ALGORITHM = "HS256"
sessions: Dict[str, dict] = {}
def verify_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except JWTError:
raise HTTPException(status_code=401, detail="Invalid Token")
@app.post("/create-session")
def create_session(token: str):
user = verify_token(token)
session_code = str(uuid.uuid4())[:6]
sessions[session_code] = {
"host_id": user["id"],
"members": [],
"connections": {}
}
return {"session_code": session_code}
@app.websocket("/ws/{session_code}")
async def websocket_endpoint(websocket: WebSocket, session_code: str, token: str):
user = verify_token(token)
await websocket.accept()
if session_code not in sessions:
await websocket.close()
return
session = sessions[session_code]
session["members"].append(user["id"])
session["connections"][user["id"]] = websocket
for connection in session["connections"].values():
await connection.send_json({
"event": "member-joined",
"user_id": user["id"]
})
try:
while True:
data = await websocket.receive_json()
for connection in session["connections"].values():
await connection.send_json({
"event": "receive-message",
"sender": user["id"],
"message": data["message"]
})
except WebSocketDisconnect:
session["members"].remove(user["id"])
del session["connections"][user["id"]]
if user["id"] == session["host_id"]:
for connection in session["connections"].values():
await connection.send_json({
"event": "session-ended"
})
del sessions[session_code]
return
for connection in session["connections"].values():
await connection.send_json({
"event": "member-left",
"user_id": user["id"]
})