141 строка
2.8 KiB
Python
141 строка
2.8 KiB
Python
import asyncio
|
|
|
|
from fastapi import FastAPI, Response, Body
|
|
from fastapi.websockets import WebSocket, WebSocketDisconnect
|
|
from fastapi.responses import JSONResponse
|
|
|
|
import config
|
|
|
|
|
|
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,
|
|
data: any,
|
|
):
|
|
for connection in self.connections:
|
|
asyncio.ensure_future(connection.send_json(data))
|
|
|
|
|
|
api = FastAPI(
|
|
title=config.Main.app_name,
|
|
)
|
|
|
|
scripts = [
|
|
{
|
|
'id': 1,
|
|
'name': 'Текущее состояние сотрудников',
|
|
'time': '0 11 * * 1-5',
|
|
'messageNumber': '1 вопрос',
|
|
'isEnabled': True,
|
|
},
|
|
{
|
|
'id': 2,
|
|
'name': 'Планы на обед',
|
|
'time': '45 11 * * 1-5',
|
|
'messageNumber': '2 вопроса',
|
|
'isEnabled': False,
|
|
},
|
|
]
|
|
|
|
|
|
scripts_cm = ConnectionManager()
|
|
|
|
|
|
# TODO(Development-only headers)
|
|
cors = {
|
|
'Access-Control-Allow-Methods': '*',
|
|
'Access-Control-Allow-Headers': '*',
|
|
'Access-Control-Allow-Origin': '*',
|
|
}
|
|
|
|
|
|
@api.options(
|
|
path='/api/scripts',
|
|
)
|
|
async def _():
|
|
return Response(
|
|
headers=cors,
|
|
)
|
|
|
|
|
|
@api.get(
|
|
path='/api/scripts',
|
|
)
|
|
async def _():
|
|
return JSONResponse(
|
|
content=scripts,
|
|
status_code=200,
|
|
headers=cors,
|
|
)
|
|
|
|
|
|
@api.put(
|
|
path='/api/scripts',
|
|
)
|
|
async def _(
|
|
script_id: int = Body(
|
|
alias='id',
|
|
validation_alias='id',
|
|
serialization_alias='id',
|
|
),
|
|
name: str = Body(),
|
|
time: str = Body(),
|
|
message_number: str = Body(
|
|
alias='messageNumber',
|
|
validation_alias='messageNumber',
|
|
serialization_alias='messageNumber',
|
|
),
|
|
is_enabled: bool = Body(
|
|
alias='isEnabled',
|
|
validation_alias='isEnabled',
|
|
serialization_alias='isEnabled',
|
|
),
|
|
):
|
|
i = script_id - 1
|
|
scripts[i]['name'] = name
|
|
scripts[i]['time'] = time
|
|
scripts[i]['messageNumber'] = message_number
|
|
scripts[i]['isEnabled'] = is_enabled
|
|
return Response(
|
|
status_code=201,
|
|
headers=cors,
|
|
)
|
|
|
|
|
|
@api.websocket(
|
|
path='/ws/scripts',
|
|
)
|
|
async def _(
|
|
websocket: WebSocket,
|
|
):
|
|
await scripts_cm.connect(websocket)
|
|
try:
|
|
await scripts_cm.broadcast(scripts)
|
|
while True:
|
|
await websocket.receive_json()
|
|
except WebSocketDisconnect:
|
|
scripts_cm.disconnect(websocket)
|