forked from altamino/websocket
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
53 lines (45 loc) · 1.59 KB
/
Copy pathmain.py
File metadata and controls
53 lines (45 loc) · 1.59 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
from contextlib import asynccontextmanager
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from helpers.middleware import CheckRequest
from objects.errors import Errors
from handlers import handle_message
from helpers.connection_manager import ConnectionManager
manager = ConnectionManager()
@asynccontextmanager
async def lifespan(app: FastAPI):
await manager.start()
yield
await manager.stop()
app = FastAPI(lifespan=lifespan)
@app.get("/")
async def index():
return Errors.InvalidRequest()
@app.get("/health")
async def health():
return {"alive": True}
@app.websocket("/")
async def websocket_endpoint(ws: WebSocket):
admin, uid, error = await CheckRequest(ws)
if error:
print(f"WebSocket connection rejected: {error['message']}")
await ws.close(code=error.get("code", 1008), reason=error.get("message", "Unauthorized"))
return
await manager.connect(ws, uid)
try:
while True:
try:
data = await ws.receive_json()
except Exception as e:
print(f"failed receive json: {e}")
break # соединение мертво — выходим, finally сделает disconnect
if data.get("t") and data.get("o"):
try:
await handle_message(data, manager, uid, admin, ws)
except Exception as e:
print(f"handle_message error: {e}")
except WebSocketDisconnect:
pass
except Exception as e:
print(f"WebSocket error: {e}")
finally:
manager.disconnect(ws, uid)