2024-08-15 00:57:30 +03:00
|
|
|
import asyncio
|
2024-08-14 01:09:41 +03:00
|
|
|
import os
|
|
|
|
|
2024-08-13 23:57:26 +03:00
|
|
|
from fastapi import FastAPI
|
2024-08-14 01:09:41 +03:00
|
|
|
from fastapi.responses import HTMLResponse
|
2024-08-15 00:57:30 +03:00
|
|
|
from fastapi.websockets import WebSocket, WebSocketDisconnect
|
2024-08-13 23:57:26 +03:00
|
|
|
|
|
|
|
import config
|
|
|
|
|
|
|
|
|
2024-08-15 00:57:30 +03:00
|
|
|
class ConnectionManager:
|
|
|
|
connections: list[WebSocket]
|
|
|
|
|
|
|
|
class StateError(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
):
|
|
|
|
self.connections = []
|
|
|
|
|
|
|
|
async def connect(
|
|
|
|
self,
|
|
|
|
websocket: WebSocket,
|
|
|
|
):
|
|
|
|
await websocket.accept()
|
|
|
|
self.connections.append(websocket)
|
|
|
|
|
|
|
|
def disconnect(
|
|
|
|
self,
|
|
|
|
websocket: WebSocket,
|
|
|
|
):
|
|
|
|
self.connections.remove(websocket)
|
|
|
|
|
|
|
|
async def broadcast(
|
|
|
|
self,
|
2024-08-26 17:20:13 +03:00
|
|
|
data: any,
|
2024-08-15 00:57:30 +03:00
|
|
|
):
|
|
|
|
for connection in self.connections:
|
|
|
|
asyncio.ensure_future(connection.send_json(data))
|
|
|
|
|
|
|
|
|
|
|
|
connection_manager = ConnectionManager()
|
|
|
|
|
|
|
|
|
2024-08-17 15:29:45 +03:00
|
|
|
api = FastAPI(
|
2024-08-14 01:09:41 +03:00
|
|
|
title=config.Main.app_name,
|
|
|
|
)
|
|
|
|
|
2024-08-26 17:20:13 +03:00
|
|
|
scripts = [
|
2024-08-17 00:52:52 +03:00
|
|
|
{
|
|
|
|
'id': 1,
|
|
|
|
'name': 'Текущее состояние сотрудников',
|
2024-08-26 17:20:13 +03:00
|
|
|
'time': '0 11 * * 1-5',
|
|
|
|
'messageNumber': '1 вопрос',
|
2024-08-17 15:29:45 +03:00
|
|
|
'isEnabled': True,
|
2024-08-17 00:52:52 +03:00
|
|
|
},
|
|
|
|
{
|
|
|
|
'id': 2,
|
|
|
|
'name': 'Планы на обед',
|
2024-08-26 17:20:13 +03:00
|
|
|
'time': '45 11 * * 1-5',
|
|
|
|
'messageNumber': '2 вопроса',
|
2024-08-17 15:29:45 +03:00
|
|
|
'isEnabled': False,
|
2024-08-17 00:52:52 +03:00
|
|
|
},
|
|
|
|
]
|
|
|
|
|
|
|
|
|
2024-08-26 17:20:13 +03:00
|
|
|
@api.websocket(
|
|
|
|
path='/ws/scripts',
|
2024-08-15 00:57:30 +03:00
|
|
|
)
|
|
|
|
async def _(
|
2024-08-26 17:20:13 +03:00
|
|
|
websocket: WebSocket,
|
2024-08-15 00:57:30 +03:00
|
|
|
):
|
2024-08-26 17:20:13 +03:00
|
|
|
await connection_manager.connect(websocket)
|
|
|
|
try:
|
|
|
|
await connection_manager.broadcast(scripts)
|
|
|
|
while True:
|
|
|
|
await connection_manager.broadcast(await websocket.receive_json())
|
|
|
|
except WebSocketDisconnect:
|
|
|
|
connection_manager.disconnect(websocket)
|