api/endpoints/xc.py

88 lines
2.5 KiB
Python
Raw Normal View History

2024-08-19 11:42:23 -04:00
#!/usr/bin/env python3.12
2025-01-11 20:59:10 -05:00
# pylint: disable=invalid-name
2024-08-19 11:42:23 -04:00
2025-01-11 20:59:10 -05:00
from fastapi import FastAPI, Request, HTTPException
2024-08-19 11:42:23 -04:00
from pydantic import BaseModel
from aiohttp import ClientSession, ClientTimeout
class ValidXCRequest(BaseModel):
"""
- **key**: valid XC API key
- **bid**: bot id
- **cmd**: bot command
- **data**: command data
"""
key: str
bid: int
cmd: str
2024-08-19 12:45:56 -04:00
data: dict | None = None
2024-08-19 11:42:23 -04:00
2024-11-29 15:33:12 -05:00
2024-08-19 11:42:23 -04:00
class XC(FastAPI):
"""XC (CrossComm) Endpoints"""
def __init__(self, app: FastAPI, util, constants, glob_state): # pylint: disable=super-init-not-called
self.app = app
self.util = util
self.constants = constants
self.glob_state = glob_state
2024-11-29 15:33:12 -05:00
self.ws_endpoints = {
# "aces_ws_put": self.put_ws_handler,
}
2024-08-19 11:42:23 -04:00
self.endpoints = {
"xc": self.xc_handler,
#tbd
}
2024-11-29 15:33:12 -05:00
for endpoint, handler in self.ws_endpoints.items():
app.add_api_websocket_route(f"/{endpoint}/", handler)
2024-08-19 11:42:23 -04:00
for endpoint, handler in self.endpoints.items():
app.add_api_route(f"/{endpoint}/", handler, methods=["POST"])
2024-11-29 15:33:12 -05:00
# async def put_ws_handler(self, ws: WebSocket):
# await ws.accept()
# await self.audio_streamer.handle_client(ws)
2024-08-19 11:42:23 -04:00
async def xc_handler(self, data: ValidXCRequest, request: Request):
"""
/xc/
Handle XC Commands
"""
key = data.key
bid = data.bid
cmd = data.cmd
cmd_data = data.data
2024-08-27 20:47:29 -04:00
req_type = 0
2024-08-19 11:42:23 -04:00
2024-08-27 20:47:29 -04:00
if bid in [1]:
req_type = 2
if not self.util.check_key(path=request.url.path, req_type=req_type, key=key):
2024-08-19 11:42:23 -04:00
raise HTTPException(status_code=403, detail="Unauthorized")
BID_ADDR_MAP = {
2024-08-27 20:47:29 -04:00
0: '10.10.10.101:5991', # Thomas/Aces
1: '10.10.10.100:5992' # MS & Waleed Combo
2024-08-19 11:42:23 -04:00
}
2025-01-11 20:59:10 -05:00
if not bid in BID_ADDR_MAP:
2024-08-19 11:42:23 -04:00
return {
'err': True,
'errorText': 'Invalid bot id'
}
bot_api_url = f'http://{BID_ADDR_MAP[bid]}/'
async with ClientSession() as session:
async with session.post(f"{bot_api_url}{cmd}", json=cmd_data, headers={
'Content-Type': 'application/json; charset=utf-8'
}, timeout=ClientTimeout(connect=5, sock_read=5)) as request:
response = await request.json()
return {
'success': True,
'response': response
}