Websocket fully working

This commit is contained in:
benarc 2021-10-17 21:15:03 +01:00
parent 1d3bb016a2
commit 75ea724d12
3 changed files with 11 additions and 14 deletions

View file

@ -251,6 +251,7 @@
}
this.connection = new WebSocket(localUrl)
this.connection.onmessage = function (e) {
console.log(e)
res = e.data.split('-')
if (res[0] == 'rocket') {
addTask(['40%', '/copilot/static/rocket.gif', res[1]])

View file

@ -45,23 +45,23 @@ async def panel(request: Request):
##################WEBSOCKET ROUTES########################
# socket_relay is a list where the control panel or
# lnurl endpoints can leave a message for the compose window
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
async def connect(self, websocket: WebSocket, copilot_id: str):
await websocket.accept()
websocket.id = copilot_id
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def send_personal_message(self, message: str, copilot_id: str):
for connection in self.active_connections:
if connection.id == copilot_id:
await connection.send_text(message)
async def broadcast(self, message: str):
for connection in self.active_connections:
@ -71,21 +71,18 @@ class ConnectionManager:
manager = ConnectionManager()
@copilot_ext.websocket("/copilot/ws/{socket_id}", name="copilot.websocket_by_id")
async def websocket_endpoint(websocket: WebSocket, socket_id: str):
await manager.connect(websocket)
@copilot_ext.websocket("/copilot/ws/{copilot_id}", name="copilot.websocket_by_id")
async def websocket_endpoint(websocket: WebSocket, copilot_id: str):
await manager.connect(websocket, copilot_id)
try:
while True:
data = await websocket.receive_text()
await manager.send_personal_message(f"You wrote: {data}", websocket)
await manager.broadcast(f"Client #{socket_id} says: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"Client #{socket_id} left the chat")
async def updater(copilot_id, data, comment):
copilot = await get_copilot(copilot_id)
if not copilot:
return
manager.broadcast(f"{data + '-' + comment}")
await manager.send_personal_message(f"{data + '-' + comment}", copilot_id)

View file

@ -98,7 +98,6 @@ async def api_copilot_ws_relay(
copilot_id: str = Query(None), comment: str = Query(None), data: str = Query(None)
):
copilot = await get_copilot(copilot_id)
print(copilot)
if not copilot:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Copilot does not exist"